code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* 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.ArrayList;
import java.util.List;
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.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
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;
/**
* 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;
List<SelectChoice> mItems;
private ArrayList<CheckBox> mCheckboxes;
@SuppressWarnings("unchecked")
public SelectMultiWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mPrompt = prompt;
mCheckboxes = new ArrayList<CheckBox>();
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
setOrientation(LinearLayout.VERTICAL);
List<Selection> ve = new ArrayList<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (List<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.get(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;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
} else {
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() {
List<Selection> vc = new ArrayList<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();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/SelectMultiWidget.java
|
Java
|
asf20
| 7,517
|
/*
* 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.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
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.preferences.PreferencesActivity;
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.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
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;
/**
* 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 static final boolean DEFAULT_HIGH_RESOLUTION = true;
private static final String NEXUS7 = "Nexus 7";
private static final String DIRECTORY_PICTURES = "Pictures";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri nexus7Uri;
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) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect
.getInstance());
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(VideoWidget.this, "captureButton",
"click", mPrompt.getIndex());
Intent i = new Intent(
android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
// Need to have this ugly code to account for
// a bug in the Nexus 7 on 4.3 not returning the mediaUri in the data
// of the intent - using the MediaStore.EXTRA_OUTPUT to get the data
// Have it saving to an intermediate location instead of final destination
// to allow the current location to catch issues with the intermediate file
Log.i(t, "The build of this device is " + android.os.Build.MODEL);
if (NEXUS7.equals(android.os.Build.MODEL) && Build.VERSION.SDK_INT == 18) {
nexus7Uri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, nexus7Uri);
} else {
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Video.Media.EXTERNAL_CONTENT_URI.toString());
}
// request high resolution if configured for that...
boolean high_resolution = settings.getBoolean(PreferencesActivity.KEY_HIGH_RESOLUTION,
VideoWidget.DEFAULT_HIGH_RESOLUTION);
if(high_resolution) {
i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY,1);
}
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;
}
}
@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 = MediaUtils.getPathFromUri(this.getContext(), (Uri) binaryuri, Video.Media.DATA);
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);
// Need to have this ugly code to account for
// a bug in the Nexus 7 on 4.3 not returning the mediaUri in the data
// of the intent - uri in this case is a file
if (NEXUS7.equals(android.os.Build.MODEL) && Build.VERSION.SDK_INT == 18) {
Uri mediaUri = (Uri)binaryuri;
File fileToDelete = new File(mediaUri.getPath());
int delCount = fileToDelete.delete() ? 1 : 0;
Log.i(t, "Deleting original capture of file: " + mediaUri.toString() + " count: " + delCount);
}
}
@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();
}
/*
* Create a file Uri for saving an image or video
* For Nexus 7 fix ...
* See http://developer.android.com/guide/topics/media/camera.html for more info
*/
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* Create a File for saving an image or video
* For Nexus 7 fix ...
* See http://developer.android.com/guide/topics/media/camera.html for more info
*/
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), DIRECTORY_PICTURES);
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d(t, "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSSZ", Locale.US).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/VideoWidget.java
|
Java
|
asf20
| 13,540
|
/*
* 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.List;
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.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
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;
List<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);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
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;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) sc).getImage();
} else {
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.get(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();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/GridWidget.java
|
Java
|
asf20
| 16,055
|
/*
* 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();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/AnnotateWidget.java
|
Java
|
asf20
| 13,069
|
/*
* 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();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/BarcodeWidget.java
|
Java
|
asf20
| 5,208
|
/*
* 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.activities.GeoPointMapActivitySdk7;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.CompatibilityUtils;
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 String READ_ONLY = "readOnly";
public static final double DEFAULT_LOCATION_ACCURACY = 5.0;
private Button mGetLocationButton;
private Button mViewButton;
private TextView mStringAnswer;
private TextView mAnswerDisplay;
private final boolean mReadOnly;
private final boolean mUseMapsV2;
private boolean mUseMaps;
private String mAppearance;
private double mAccuracyThreshold;
public GeoPointWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
// Determine the activity threshold to use
String acc = prompt.getQuestion().getAdditionalAttribute(null, ACCURACY_THRESHOLD);
if ( acc != null && acc.length() != 0 ) {
mAccuracyThreshold = Double.parseDouble(acc);
} else {
mAccuracyThreshold = DEFAULT_LOCATION_ACCURACY;
}
// Determine whether or not to use the plain, maps, or mapsV2 activity
mAppearance = prompt.getAppearanceHint();
boolean requestV2 = false;
boolean requestMaps = false;
if ( mAppearance != null && mAppearance.equalsIgnoreCase("placement-map") ) {
requestV2 = true;
requestMaps = true;
}
if (mAppearance != null && mAppearance.equalsIgnoreCase("maps")) {
requestMaps = true;
}
// use mapsV2 if it is available and was requested
mUseMapsV2 = requestV2 && CompatibilityUtils.useMapsV2(context);
if ( mUseMapsV2 ) {
// if we are using mapsV2, we are using maps...
mUseMaps = true;
} else if ( requestMaps ) {
// using the legacy maps widget... if MapActivity is available
// otherwise just use the plain widget
try {
// do google maps exist on the device
Class.forName("com.google.android.maps.MapActivity");
mUseMaps = true;
} catch (ClassNotFoundException e) {
// use the plain geolocation activity
mUseMaps = false;
}
} else {
// use the plain geolocation activity
mUseMaps = false;
}
mReadOnly = prompt.isReadOnly();
// assemble the widget...
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
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);
// 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());
Intent i;
if (mUseMapsV2 ) {
i = new Intent(getContext(), GeoPointMapActivity.class);
} else {
i = new Intent(getContext(), GeoPointMapActivitySdk7.class);
}
String s = mStringAnswer.getText().toString();
if ( s.length() != 0 ) {
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();
i.putExtra(LOCATION, gp);
}
i.putExtra(READ_ONLY, true);
i.putExtra(ACCURACY_THRESHOLD, mAccuracyThreshold);
((Activity) getContext()).startActivity(i);
}
});
mGetLocationButton = new Button(getContext());
mGetLocationButton.setId(QuestionWidget.newUniqueId());
mGetLocationButton.setPadding(20, 20, 20, 20);
mGetLocationButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mGetLocationButton.setEnabled(!prompt.isReadOnly());
mGetLocationButton.setLayoutParams(params);
// 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 ( mUseMapsV2 ) {
i = new Intent(getContext(), GeoPointMapActivity.class);
} else if (mUseMaps) {
i = new Intent(getContext(), GeoPointMapActivitySdk7.class);
} else {
i = new Intent(getContext(), GeoPointActivity.class);
}
String s = mStringAnswer.getText().toString();
if ( s.length() != 0 ) {
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();
i.putExtra(LOCATION, gp);
}
i.putExtra(READ_ONLY, mReadOnly);
i.putExtra(ACCURACY_THRESHOLD, mAccuracyThreshold);
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.LOCATION_CAPTURE);
}
});
// finish complex layout
// control what gets shown with setVisibility(View.GONE)
addView(mGetLocationButton);
addView(mViewButton);
addView(mAnswerDisplay);
// figure out what text and buttons to enable or to show...
boolean dataAvailable = false;
String s = prompt.getAnswerText();
if (s != null && !s.equals("")) {
dataAvailable = true;
setBinaryData(s);
}
updateButtonLabelsAndVisibility(dataAvailable);
}
private void updateButtonLabelsAndVisibility(boolean dataAvailable) {
// BUT for mapsV2, we only show the mGetLocationButton, altering its text.
// for maps, we show the view button.
if ( mUseMapsV2 ) {
// show the GetLocation button
mGetLocationButton.setVisibility(View.VISIBLE);
// hide the view button
mViewButton.setVisibility(View.GONE);
if ( mReadOnly ) {
mGetLocationButton.setText(getContext()
.getString(R.string.show_location));
} else {
mGetLocationButton.setText(getContext()
.getString(R.string.view_change_location));
}
} else {
// if it is read-only, hide the get-location button...
if ( mReadOnly ) {
mGetLocationButton.setVisibility(View.GONE);
} else {
mGetLocationButton.setVisibility(View.VISIBLE);
mGetLocationButton.setText(getContext()
.getString(dataAvailable ?
R.string.replace_location : R.string.get_location));
}
if (mUseMaps) {
// show the view button
mViewButton.setVisibility(View.VISIBLE);
mViewButton.setEnabled(dataAvailable);
} else {
mViewButton.setVisibility(View.GONE);
}
}
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mAnswerDisplay.setText(null);
updateButtonLabelsAndVisibility(false);
}
@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);
updateButtonLabelsAndVisibility(true);
}
@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();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/GeoPointWidget.java
|
Java
|
asf20
| 12,527
|
/*
* 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.List;
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.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
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 multiple selection 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. This is almost identical to GridWidget, except multiple
* icons can be selected simultaneously.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class GridMultiWidget 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;
List<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;
// need to remember the last click position for audio treatment
int lastClickPosition = 0;
// The number of columns in the grid, can be user defined (<= 0 if unspecified)
int numColumns;
int resizeWidth;
@SuppressWarnings("unchecked")
public GridMultiWidget(Context context, FormEntryPrompt prompt, int numColumns) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
mPrompt = prompt;
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());
}
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;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) sc).getImage();
} else {
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("GridMultiWidget", "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("GridMultiWidget", errorMsg);
missingImage.setText(errorMsg);
}
if ( numColumns > 0 ) {
maxColumnWidth = resizeWidth;
// force the max width to find the 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) {
if (selected[position]) {
selected[position] = false;
if ( audioHandlers[position] != null) {
audioHandlers[position].stopPlaying();
}
imageViews[position].setBackgroundColor(Color.WHITE);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get(position).getValue(), mPrompt.getIndex());
} else {
selected[position] = true;
if ( audioHandlers[lastClickPosition] != null) {
audioHandlers[lastClickPosition].stopPlaying();
}
imageViews[position].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
orangeBlueVal));
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get(position).getValue(), mPrompt.getIndex());
if ( audioHandlers[position] != null) {
audioHandlers[position].playAudio(getContext());
}
lastClickPosition = position;
}
}
});
// Fill in answer
IAnswerData answer = prompt.getAnswerValue();
List<Selection> ve;
if ((answer == null) || (answer.getValue() == null)) {
ve = new ArrayList<Selection>();
} else {
ve = (List<Selection>) answer.getValue();
}
for (int i = 0; i < choices.length; ++i) {
String value = mItems.get(i).getValue();
boolean found = false;
for (Selection s : ve) {
if (value.equals(s.getValue())) {
found = true;
break;
}
}
selected[i] = found;
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() {
List<Selection> vc = new ArrayList<Selection>();
for (int i = 0; i < mItems.size(); i++) {
if (selected[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() {
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();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/GridMultiWidget.java
|
Java
|
asf20
| 16,482
|
/*
* 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.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.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore.Audio;
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;
/**
* 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 AudioWidget 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 AudioWidget(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_audio));
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());
Intent i = new Intent(
android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
i.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
.toString());
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.AUDIO_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"audio capture"), 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_sound));
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());
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("audio/*");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.AUDIO_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"choose audio"), 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_audio));
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(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), "audio/*");
try {
((Activity) getContext()).startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"play audio"), 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.deleteAudioFileFromMediaProvider(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;
}
}
@Override
public void setBinaryData(Object binaryuri) {
// when replacing an answer. remove the current media.
if (mBinaryName != null) {
deleteMedia();
}
// get the file path and create a copy in the instance folder
String binaryPath = MediaUtils.getPathFromUri(this.getContext(), (Uri) binaryuri, Audio.Media.DATA);
String extension = binaryPath.substring(binaryPath.lastIndexOf("."));
String destAudioPath = mInstanceFolder + File.separator
+ System.currentTimeMillis() + extension;
File source = new File(binaryPath);
File newAudio = new File(destAudioPath);
FileUtils.copyFile(source, newAudio);
if (newAudio.exists()) {
// Add the copy to the content provier
ContentValues values = new ContentValues(6);
values.put(Audio.Media.TITLE, newAudio.getName());
values.put(Audio.Media.DISPLAY_NAME, newAudio.getName());
values.put(Audio.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Audio.Media.DATA, newAudio.getAbsolutePath());
Uri AudioURI = getContext().getContentResolver().insert(
Audio.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting AUDIO returned uri = " + AudioURI.toString());
mBinaryName = newAudio.getName();
Log.i(t, "Setting current answer to " + newAudio.getName());
} else {
Log.e(t, "Inserting Audio file FAILED");
}
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();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/AudioWidget.java
|
Java
|
asf20
| 9,789
|
/*
* 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.List;
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.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
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.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* ListWidget handles select-one fields using radio buttons. The radio buttons 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.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class ListWidget extends QuestionWidget implements OnCheckedChangeListener {
private static final String t = "ListWidget";
// 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;
List<SelectChoice> mItems; // may take a while to compute
ArrayList<RadioButton> buttons;
public ListWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
buttons = new ArrayList<RadioButton>();
// Layout holds the horizontal list of buttons
LinearLayout buttonLayout = new LinearLayout(context);
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
RadioButton r = new RadioButton(getContext());
r.setId(QuestionWidget.newUniqueId());
r.setTag(Integer.valueOf(i));
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
r.setOnCheckedChangeListener(this);
String imageURI;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
} else {
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(r, 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 is created and populated with the question text in the
// super() constructor via a call to addQuestionText
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.get(i);
return new SelectOneData(new Selection(sc));
}
}
@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);
}
public int getCheckedId() {
for (int i=0; i < buttons.size(); ++i ) {
RadioButton button = buttons.get(i);
if (button.isChecked()) {
return i;
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : this.buttons) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
// 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.
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 (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton r : buttons) {
r.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ListWidget.java
|
Java
|
asf20
| 14,763
|
/*
* 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.util.ArrayList;
import java.util.List;
import java.util.Locale;
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.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.external.ExternalDataUtil;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
/**
* AutoCompleteWidget handles select-one fields using an autocomplete text box. The user types part
* of the desired selection and suggestions appear in a list below. The full list of possible
* answers is not displayed to the user. The goal is to be more compact; this question type is best
* suited for select one questions with a large number of possible answers. If images, audio, or
* video are specified in the select answers they are ignored.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class AutoCompleteWidget extends QuestionWidget {
AutoCompleteAdapter choices;
AutoCompleteTextView autocomplete;
List<SelectChoice> mItems;
// Defines which filter to use to display autocomplete possibilities
String filterType;
// The various filter types
String match_substring = "substring";
String match_prefix = "prefix";
String match_chars = "chars";
public AutoCompleteWidget(Context context, FormEntryPrompt prompt, String filterType) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
mPrompt = prompt;
choices = new AutoCompleteAdapter(getContext(), android.R.layout.simple_list_item_1);
autocomplete = new AutoCompleteTextView(getContext());
// Default to matching substring
if (filterType != null) {
this.filterType = filterType;
} else {
this.filterType = match_substring;
}
for (SelectChoice sc : mItems) {
choices.add(prompt.getSelectChoiceText(sc));
}
choices.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
autocomplete.setAdapter(choices);
autocomplete.setTextColor(Color.BLACK);
setGravity(Gravity.LEFT);
// Fill in answer
String s = null;
if (mPrompt.getAnswerValue() != null) {
s = ((Selection) mPrompt.getAnswerValue().getValue()).getValue();
}
for (int i = 0; i < mItems.size(); ++i) {
String sMatch = mItems.get(i).getValue();
if (sMatch.equals(s)) {
autocomplete.setText(mItems.get(i).getLabelInnerText());
}
}
addView(autocomplete);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String response = autocomplete.getText().toString();
for (SelectChoice sc : mItems) {
if (response.equals(mPrompt.getSelectChoiceText(sc))) {
return new SelectOneData(new Selection(sc));
}
}
// If the user has typed text into the autocomplete box that doesn't match any answer, warn
// them that their
// solution didn't count.
if (!response.equals("")) {
Toast.makeText(getContext(),
"Warning: \"" + response + "\" does not match any answers. No answer recorded.",
Toast.LENGTH_LONG).show();
}
return null;
}
@Override
public void clearAnswer() {
autocomplete.setText("");
}
@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);
}
private class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ItemsFilter mFilter;
public ArrayList<String> mItems;
public AutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mItems = new ArrayList<String>();
}
@Override
public void add(String toAdd) {
super.add(toAdd);
mItems.add(toAdd);
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public String getItem(int position) {
return mItems.get(position);
}
@Override
public int getPosition(String item) {
return mItems.indexOf(item);
}
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemsFilter(mItems);
}
return mFilter;
}
@Override
public long getItemId(int position) {
return position;
}
private class ItemsFilter extends Filter {
final ArrayList<String> mItemsArray;
public ItemsFilter(ArrayList<String> list) {
if (list == null) {
mItemsArray = new ArrayList<String>();
} else {
mItemsArray = new ArrayList<String>(list);
}
}
@Override
protected FilterResults performFiltering(CharSequence prefix) {
// Initiate our results object
FilterResults results = new FilterResults();
// If the adapter array is empty, check the actual items array and use it
if (mItems == null) {
mItems = new ArrayList<String>(mItemsArray);
}
// No prefix is sent to filter by so we're going to send back the original array
if (prefix == null || prefix.length() == 0) {
results.values = mItemsArray;
results.count = mItemsArray.size();
} else {
// Compare lower case strings
String prefixString = prefix.toString().toLowerCase(Locale.getDefault());
// Local to here so we're not changing actual array
final ArrayList<String> items = mItems;
final int count = items.size();
final ArrayList<String> newItems = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
final String item = items.get(i);
String item_compare = item.toLowerCase(Locale.getDefault());
// Match the strings using the filter specified
if (filterType.equals(match_substring)
&& (item_compare.startsWith(prefixString) || item_compare
.contains(prefixString))) {
newItems.add(item);
} else if (filterType.equals(match_prefix)
&& item_compare.startsWith(prefixString)) {
newItems.add(item);
} else if (filterType.equals(match_chars)) {
char[] toMatch = prefixString.toCharArray();
boolean matches = true;
for (int j = 0; j < toMatch.length; j++) {
int index = item_compare.indexOf(toMatch[j]);
if (index > -1) {
item_compare =
item_compare.substring(0, index)
+ item_compare.substring(index + 1);
} else {
matches = false;
break;
}
}
if (matches) {
newItems.add(item);
}
} else {
// Default to substring
if (item_compare.startsWith(prefixString)
|| item_compare.contains(prefixString)) {
newItems.add(item);
}
}
}
// Set and return
results.values = newItems;
results.count = newItems.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mItems = (ArrayList<String>) results.values;
// Let the adapter know about the updated list
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
autocomplete.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
autocomplete.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/AutoCompleteWidget.java
|
Java
|
asf20
| 10,712
|
/*
* 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.application.Collect;
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Widget that allows user to scan barcodes and add them to the form.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class TriggerWidget extends QuestionWidget {
private CheckBox mTriggerButton;
private TextView mStringAnswer;
private static final String mOK = "OK";
private FormEntryPrompt mPrompt;
public FormEntryPrompt getPrompt() {
return mPrompt;
}
public TriggerWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mPrompt = prompt;
this.setOrientation(LinearLayout.VERTICAL);
mTriggerButton = new CheckBox(getContext());
mTriggerButton.setId(QuestionWidget.newUniqueId());
mTriggerButton.setText(getContext().getString(R.string.trigger));
mTriggerButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
// mActionButton.setPadding(20, 20, 20, 20);
mTriggerButton.setEnabled(!prompt.isReadOnly());
mTriggerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mTriggerButton.isChecked()) {
mStringAnswer.setText(mOK);
Collect.getInstance().getActivityLogger().logInstanceAction(TriggerWidget.this, "triggerButton",
"OK", mPrompt.getIndex());
} else {
mStringAnswer.setText(null);
Collect.getInstance().getActivityLogger().logInstanceAction(TriggerWidget.this, "triggerButton",
"null", mPrompt.getIndex());
}
}
});
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) {
if (s.equals(mOK)) {
mTriggerButton.setChecked(true);
} else {
mTriggerButton.setChecked(false);
}
mStringAnswer.setText(s);
}
// finish complex layout
this.addView(mTriggerButton);
// this.addView(mStringAnswer);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mTriggerButton.setChecked(false);
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
@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) {
mTriggerButton.setOnLongClickListener(l);
mStringAnswer.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mTriggerButton.cancelLongPress();
mStringAnswer.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/TriggerWidget.java
|
Java
|
asf20
| 4,498
|
/*
* 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.List;
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.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
/**
* SpinnerWidget handles select-one fields. Instead of a list of buttons it uses a spinner, wherein
* the user clicks a button and the choices pop up in a dialogue box. The goal is to be more
* compact. If images, audio, or video are specified in the select answers they are ignored.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class SpinnerWidget extends QuestionWidget {
List<SelectChoice> mItems;
Spinner spinner;
String[] choices;
private static final int BROWN = 0xFF936931;
public SpinnerWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
spinner = new Spinner(context);
choices = new String[mItems.size()+1];
for (int i = 0; i < mItems.size(); i++) {
choices[i] = prompt.getSelectChoiceText(mItems.get(i));
}
choices[mItems.size()] = getContext().getString(R.string.select_one);
// The spinner requires a custom adapter. It is defined below
SpinnerAdapter adapter =
new SpinnerAdapter(getContext(), android.R.layout.simple_spinner_item, choices,
TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
spinner.setAdapter(adapter);
spinner.setPrompt(prompt.getQuestionText());
spinner.setEnabled(!prompt.isReadOnly());
spinner.setFocusable(!prompt.isReadOnly());
// Fill in previous answer
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
spinner.setSelection(mItems.size());
if (s != null) {
for (int i = 0; i < mItems.size(); ++i) {
String sMatch = mItems.get(i).getValue();
if (sMatch.equals(s)) {
spinner.setSelection(i);
}
}
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if ( position == mItems.size() ) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged.clearValue",
"", mPrompt.getIndex());
} else {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
mItems.get(position).getValue(), mPrompt.getIndex());
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
addView(spinner);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
int i = spinner.getSelectedItemPosition();
if (i == -1 || i == mItems.size()) {
return null;
} else {
SelectChoice sc = mItems.get(i);
return new SelectOneData(new Selection(sc));
}
}
@Override
public void clearAnswer() {
// It seems that spinners cannot return a null answer. This resets the answer
// to its original value, but it is not null.
spinner.setSelection(mItems.size());
}
@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);
}
// Defines how to display the select answers
private class SpinnerAdapter extends ArrayAdapter<String> {
Context context;
String[] items = new String[] {};
int textUnit;
float textSize;
public SpinnerAdapter(final Context context, final int textViewResourceId,
final String[] objects, int textUnit, float textSize) {
super(context, textViewResourceId, objects);
this.items = objects;
this.context = context;
this.textUnit = textUnit;
this.textSize = textSize;
}
@Override
// Defines the text view parameters for the drop down list entries
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.custom_spinner_item, parent, false);
}
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
tv.setTextSize(textUnit, textSize);
tv.setBackgroundColor(Color.WHITE);
tv.setPadding(10, 10, 10, 10); // Are these values OK?
if (position == items.length-1) {
tv.setText(parent.getContext().getString(R.string.clear_answer));
tv.setTextColor(BROWN);
tv.setTypeface(null, Typeface.NORMAL);
if (spinner.getSelectedItemPosition() == position) {
tv.setBackgroundColor(Color.LTGRAY);
}
} else {
tv.setText(items[position]);
tv.setTextColor(Color.BLACK);
tv.setTypeface(null, (spinner.getSelectedItemPosition() == position)
? Typeface.BOLD : Typeface.NORMAL);
}
return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
}
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
tv.setText(items[position]);
tv.setTextSize(textUnit, textSize);
tv.setTextColor(Color.BLACK);
tv.setTypeface(null, Typeface.BOLD);
if (position == items.length-1) {
tv.setTextColor(BROWN);
tv.setTypeface(null, Typeface.NORMAL);
}
return convertView;
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
spinner.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
spinner.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/SpinnerWidget.java
|
Java
|
asf20
| 8,322
|
/*
* 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.ArrayList;
import java.util.List;
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.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
import org.odk.collect.android.views.MediaLayout;
import android.content.Context;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
/**
* SelectOneWidgets handles select-one fields using radio buttons.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SelectOneWidget extends QuestionWidget implements
OnCheckedChangeListener {
List<SelectChoice> mItems; // may take a while to compute
ArrayList<RadioButton> buttons;
public SelectOneWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
buttons = new ArrayList<RadioButton>();
// Layout holds the vertical list of buttons
LinearLayout buttonLayout = new LinearLayout(context);
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
RadioButton r = new RadioButton(getContext());
r.setText(prompt.getSelectChoiceText(mItems.get(i)));
r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
r.setTag(Integer.valueOf(i));
r.setId(QuestionWidget.newUniqueId());
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
r.setOnCheckedChangeListener(this);
String audioURI = null;
audioURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
} else {
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), r, audioURI, imageURI,
videoURI, bigImageURI);
if (i != mItems.size() - 1) {
// Last, add the dividing line (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
mediaLayout.addDivider(divider);
}
buttonLayout.addView(mediaLayout);
}
}
buttonLayout.setOrientation(LinearLayout.VERTICAL);
// The buttons take up the right half of the screen
LayoutParams buttonParams = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
addView(buttonLayout, buttonParams);
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.get(i);
return new SelectOneData(new Selection(sc));
}
}
@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);
}
public int getCheckedId() {
for (int i = 0; i < buttons.size(); ++i) {
RadioButton button = buttons.get(i);
if (button.isChecked()) {
return i;
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : buttons ) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
SelectChoice choice = mItems.get((Integer)buttonView.getTag());
if ( choice != null ) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
choice.getValue(), mPrompt.getIndex());
} else {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
"<no matching choice>", mPrompt.getIndex());
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton button : this.buttons) {
button.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/SelectOneWidget.java
|
Java
|
asf20
| 6,594
|
/*
* Copyright (C) 2013 Nafundi LLC
*
* 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.application.Collect;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
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 open URLs from within the form
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class UrlWidget extends QuestionWidget {
private Button mOpenUrlButton;
private TextView mStringAnswer;
public UrlWidget(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
mOpenUrlButton = new Button(getContext());
mOpenUrlButton.setId(QuestionWidget.newUniqueId());
mOpenUrlButton.setText(getContext().getString(R.string.open_url));
mOpenUrlButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mOpenUrlButton.setPadding(20, 20, 20, 20);
mOpenUrlButton.setEnabled(!prompt.isReadOnly());
mOpenUrlButton.setLayoutParams(params);
mOpenUrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "openUrl", "click",
mPrompt.getIndex());
if (mStringAnswer != null & mStringAnswer.getText() != null
&& !"".equalsIgnoreCase((String) mStringAnswer.getText())) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse((String) mStringAnswer.getText()));
getContext().startActivity(i);
} else {
Toast.makeText(getContext(), "No URL set", Toast.LENGTH_SHORT).show();
}
}
});
// 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) {
mStringAnswer.setText(s);
}
// finish complex layout
addView(mOpenUrlButton);
addView(mStringAnswer);
}
@Override
public void clearAnswer() {
Toast.makeText(getContext(), "URL is readonly", Toast.LENGTH_SHORT).show();
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
@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) {
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mOpenUrlButton.cancelLongPress();
mStringAnswer.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/UrlWidget.java
|
Java
|
asf20
| 4,534
|
/*
* 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.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.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 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 ImageWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "MediaWidget";
private Button mCaptureButton;
private Button mChooseButton;
private ImageView mImageView;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
public ImageWidget(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);
}
}
});
// 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();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ImageWidget.java
|
Java
|
asf20
| 12,835
|
/*
* 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.IntegerData;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.text.InputFilter;
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 IntegerWidget extends StringWidget {
private Integer getIntegerAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Integer d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Double){
d = Integer.valueOf(((Double) dataValue).intValue());
} else {
d = (Integer)dataValue;
}
}
}
return d;
}
public IntegerWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) {
super(context, prompt, readOnlyOverride, 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);
// only allows numbers and no periods
mAnswer.setKeyListener(new DigitsKeyListener(true, false));
// ints can only hold 2,147,483,648. we allow 999,999,999
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(9);
mAnswer.setFilters(fa);
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
Integer i = getIntegerAnswerValue();
if (i != null) {
mAnswer.setText(i.toString());
}
setupChangeListener();
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new IntegerData(Integer.parseInt(s));
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/IntegerWidget.java
|
Java
|
asf20
| 3,062
|
/*
* 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.DateTimeData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.odk.collect.android.application.Collect;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TimePicker;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.Date;
/**
* Displays a DatePicker widget. DateWidget handles leap years and does not allow dates that do not
* exist.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class DateTimeWidget extends QuestionWidget {
private DatePicker mDatePicker;
private TimePicker mTimePicker;
private DatePicker.OnDateChangedListener mDateListener;
private boolean hideDay = false;
private boolean hideMonth = false;
private boolean showCalendar = false;
private HorizontalScrollView scrollView = null;
public DateTimeWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mDatePicker = new DatePicker(getContext());
mDatePicker.setId(QuestionWidget.newUniqueId());
mDatePicker.setFocusable(!prompt.isReadOnly());
mDatePicker.setEnabled(!prompt.isReadOnly());
mTimePicker = new TimePicker(getContext());
mTimePicker.setId(QuestionWidget.newUniqueId());
mTimePicker.setFocusable(!prompt.isReadOnly());
mTimePicker.setEnabled(!prompt.isReadOnly());
mTimePicker.setPadding(0, 20, 0, 0);
String clockType =
android.provider.Settings.System.getString(context.getContentResolver(),
android.provider.Settings.System.TIME_12_24);
if (clockType == null || clockType.equalsIgnoreCase("24")) {
mTimePicker.setIs24HourView(true);
}
hideDayFieldIfNotInFormat(prompt);
mDateListener = new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
if (mPrompt.isReadOnly()) {
setAnswer();
} else {
// handle leap years and number of days in month
// TODO
// http://code.google.com/p/android/issues/detail?id=2081
// in older versions of android (1.6ish) the datepicker lets you pick bad dates
// in newer versions, calling updateDate() calls onDatechangedListener(), causing an
// endless loop.
Calendar c = Calendar.getInstance();
c.set(year, month, 1);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
if (day > max) {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateTimeWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, max), mPrompt.getIndex());
mDatePicker.updateDate(year, month, max);
}
} else {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateTimeWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, day), mPrompt.getIndex());
mDatePicker.updateDate(year, month, day);
}
}
}
}
};
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateTimeWidget.this, "onTimeChanged",
String.format("%1$02d:%2$02d",hourOfDay, minute), mPrompt.getIndex());
}
});
setGravity(Gravity.LEFT);
if ( showCalendar ) {
scrollView = new HorizontalScrollView(context);
LinearLayout ll = new LinearLayout(context);
ll.addView(mDatePicker);
ll.setPadding(10, 10, 10, 10);
scrollView.addView(ll);
addView(scrollView);
} else {
addView(mDatePicker);
}
addView(mTimePicker);
// If there's an answer, use it.
setAnswer();
}
/**
* Shared between DateWidget and DateTimeWidget.
* There are extra appearance settings that do not apply for dateTime...
* TODO: move this into utilities or base class?
*
* @param prompt
*/
@SuppressLint("NewApi")
private void hideDayFieldIfNotInFormat(FormEntryPrompt prompt) {
String appearance = prompt.getQuestion().getAppearanceAttr();
if ( appearance == null ) {
if ( Build.VERSION.SDK_INT >= 11 ) {
showCalendar = true;
this.mDatePicker.setCalendarViewShown(true);
if ( Build.VERSION.SDK_INT >= 12 ) {
CalendarView cv = this.mDatePicker.getCalendarView();
cv.setShowWeekNumber(false);
}
this.mDatePicker.setSpinnersShown(true);
hideDay = true;
hideMonth = false;
} else {
return;
}
} else if ( "month-year".equals(appearance) ) {
hideDay = true;
if ( Build.VERSION.SDK_INT >= 11 ) {
this.mDatePicker.setCalendarViewShown(false);
this.mDatePicker.setSpinnersShown(true);
}
} else if ( "year".equals(appearance) ) {
hideMonth = true;
if ( Build.VERSION.SDK_INT >= 11 ) {
this.mDatePicker.setCalendarViewShown(false);
this.mDatePicker.setSpinnersShown(true);
}
} else if ("no-calendar".equals(appearance) ) {
if ( Build.VERSION.SDK_INT >= 11 ) {
this.mDatePicker.setCalendarViewShown(false);
this.mDatePicker.setSpinnersShown(true);
}
} else {
if ( Build.VERSION.SDK_INT >= 11 ) {
showCalendar = true;
this.mDatePicker.setCalendarViewShown(true);
if ( Build.VERSION.SDK_INT >= 12 ) {
CalendarView cv = this.mDatePicker.getCalendarView();
cv.setShowWeekNumber(false);
}
this.mDatePicker.setSpinnersShown(true);
hideDay = true;
hideMonth = false;
}
}
if ( hideMonth || hideDay ) {
for (Field datePickerDialogField : this.mDatePicker.getClass().getDeclaredFields()) {
if ("mDayPicker".equals(datePickerDialogField.getName()) ||
"mDaySpinner".equals(datePickerDialogField.getName())) {
datePickerDialogField.setAccessible(true);
Object dayPicker = new Object();
try {
dayPicker = datePickerDialogField.get(this.mDatePicker);
} catch (Exception e) {
e.printStackTrace();
}
((View) dayPicker).setVisibility(View.GONE);
}
if ( hideMonth ) {
if ("mMonthPicker".equals(datePickerDialogField.getName()) ||
"mMonthSpinner".equals(datePickerDialogField.getName())) {
datePickerDialogField.setAccessible(true);
Object monthPicker = new Object();
try {
monthPicker = datePickerDialogField.get(this.mDatePicker);
} catch (Exception e) {
e.printStackTrace();
}
((View) monthPicker).setVisibility(View.GONE);
}
}
}
}
}
private void setAnswer() {
if (mPrompt.getAnswerValue() != null) {
DateTime ldt =
new DateTime(
((Date) ((DateTimeData) mPrompt.getAnswerValue()).getValue()).getTime());
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
} else {
// create time widget with current time as of right now
clearAnswer();
}
}
/**
* Resets date to today.
*/
@Override
public void clearAnswer() {
DateTime ldt = new DateTime();
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
}
@Override
public IAnswerData getAnswer() {
if ( showCalendar ) {
scrollView.clearChildFocus(mDatePicker);
}
clearFocus();
DateTime ldt =
new DateTime(mDatePicker.getYear(), mDatePicker.getMonth() + 1,
mDatePicker.getDayOfMonth(), mTimePicker.getCurrentHour(),
mTimePicker.getCurrentMinute(), 0);
//DateTime utc = ldt.withZone(DateTimeZone.forID("UTC"));
return new DateTimeData(ldt.toDate());
}
@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) {
mDatePicker.setOnLongClickListener(l);
mTimePicker.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mDatePicker.cancelLongPress();
mTimePicker.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/DateTimeWidget.java
|
Java
|
asf20
| 11,014
|
/*
* 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.TimeData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.TimePicker;
import java.util.Date;
/**
* Displays a TimePicker widget.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class TimeWidget extends QuestionWidget {
private TimePicker mTimePicker;
public TimeWidget(Context context, final FormEntryPrompt prompt) {
super(context, prompt);
mTimePicker = new TimePicker(getContext());
mTimePicker.setId(QuestionWidget.newUniqueId());
mTimePicker.setFocusable(!prompt.isReadOnly());
mTimePicker.setEnabled(!prompt.isReadOnly());
String clockType =
android.provider.Settings.System.getString(context.getContentResolver(),
android.provider.Settings.System.TIME_12_24);
if (clockType == null || clockType.equalsIgnoreCase("24")) {
mTimePicker.setIs24HourView(true);
}
// If there's an answer, use it.
if (prompt.getAnswerValue() != null) {
// create a new date time from date object using default time zone
DateTime ldt =
new DateTime(((Date) ((TimeData) prompt.getAnswerValue()).getValue()).getTime());
System.out.println("retrieving:" + ldt);
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
} else {
// create time widget with current time as of right now
clearAnswer();
}
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Collect.getInstance().getActivityLogger().logInstanceAction(TimeWidget.this, "onTimeChanged",
String.format("%1$02d:%2$02d",hourOfDay, minute), mPrompt.getIndex());
}
});
setGravity(Gravity.LEFT);
addView(mTimePicker);
}
/**
* Resets time to today.
*/
@Override
public void clearAnswer() {
DateTime ldt = new DateTime();
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
}
@Override
public IAnswerData getAnswer() {
clearFocus();
// use picker time, convert to today's date, store as utc
DateTime ldt =
(new DateTime()).withTime(mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute(),
0, 0);
//DateTime utc = ldt.withZone(DateTimeZone.forID("UTC"));
System.out.println("storing:" + ldt);
return new TimeData(ldt.toDate());
}
@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) {
mTimePicker.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mTimePicker.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/TimeWidget.java
|
Java
|
asf20
| 4,184
|
/*
* 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.NumberFormat;
import org.javarosa.core.model.data.DecimalData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
/**
* A widget that restricts values to floating point numbers.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class DecimalWidget extends StringWidget {
private Double getDoubleAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Double d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Integer){
d = Double.valueOf(((Integer)dataValue).intValue());
} else {
d = (Double) dataValue;
}
}
}
return d;
}
public DecimalWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) {
super(context, prompt, readOnlyOverride, true);
// formatting
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
// needed to make long readonly text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
// only numbers are allowed
mAnswer.setKeyListener(new DigitsKeyListener(true, true));
// only 15 characters allowed
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(15);
mAnswer.setFilters(fa);
Double d = getDoubleAnswerValue();
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(15);
nf.setMaximumIntegerDigits(15);
nf.setGroupingUsed(false);
if (d != null) {
// truncate to 15 digits max...
String dString = nf.format(d);
d = Double.parseDouble(dString.replace(',', '.'));
mAnswer.setText(d.toString());
}
// disable if read only
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
setupChangeListener();
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new DecimalData(Double.valueOf(s).doubleValue());
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/DecimalWidget.java
|
Java
|
asf20
| 3,467
|
/*
* 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.lang.reflect.Field;
import java.util.Calendar;
import java.util.Date;
import org.javarosa.core.model.data.DateData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.odk.collect.android.application.Collect;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
/**
* Displays a DatePicker widget. DateWidget handles leap years and does not allow dates that do not
* exist.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class DateWidget extends QuestionWidget {
private DatePicker mDatePicker;
private DatePicker.OnDateChangedListener mDateListener;
private boolean hideDay = false;
private boolean hideMonth = false;
private boolean showCalendar = false;
private HorizontalScrollView scrollView = null;
public DateWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mDatePicker = new DatePicker(getContext());
mDatePicker.setId(QuestionWidget.newUniqueId());
mDatePicker.setFocusable(!prompt.isReadOnly());
mDatePicker.setEnabled(!prompt.isReadOnly());
hideDayFieldIfNotInFormat(prompt);
mDateListener = new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
if (mPrompt.isReadOnly()) {
setAnswer();
} else {
// TODO support dates <1900 >2100
// handle leap years and number of days in month
// http://code.google.com/p/android/issues/detail?id=2081
Calendar c = Calendar.getInstance();
c.set(year, month, 1);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
// in older versions of android (1.6ish) the datepicker lets you pick bad dates
// in newer versions, calling updateDate() calls onDatechangedListener(), causing an
// endless loop.
if (day > max) {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, max), mPrompt.getIndex());
mDatePicker.updateDate(year, month, max);
}
} else {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, day), mPrompt.getIndex());
mDatePicker.updateDate(year, month, day);
}
}
}
}
};
setGravity(Gravity.LEFT);
if ( showCalendar ) {
scrollView = new HorizontalScrollView(context);
LinearLayout ll = new LinearLayout(context);
ll.addView(mDatePicker);
ll.setPadding(10, 10, 10, 10);
scrollView.addView(ll);
addView(scrollView);
} else {
addView(mDatePicker);
}
// If there's an answer, use it.
setAnswer();
}
/**
* Shared between DateWidget and DateTimeWidget.
* There are extra appearance settings that do not apply for dateTime...
* TODO: move this into utilities or base class?
*
* @param prompt
*/
@SuppressLint("NewApi")
private void hideDayFieldIfNotInFormat(FormEntryPrompt prompt) {
String appearance = prompt.getQuestion().getAppearanceAttr();
if ( appearance == null ) {
if ( Build.VERSION.SDK_INT >= 11 ) {
showCalendar = true;
this.mDatePicker.setCalendarViewShown(true);
if ( Build.VERSION.SDK_INT >= 12 ) {
CalendarView cv = this.mDatePicker.getCalendarView();
cv.setShowWeekNumber(false);
}
this.mDatePicker.setSpinnersShown(true);
hideDay = true;
hideMonth = false;
} else {
return;
}
} else if ( "month-year".equals(appearance) ) {
hideDay = true;
if ( Build.VERSION.SDK_INT >= 11 ) {
this.mDatePicker.setCalendarViewShown(false);
this.mDatePicker.setSpinnersShown(true);
}
} else if ( "year".equals(appearance) ) {
hideMonth = true;
if ( Build.VERSION.SDK_INT >= 11 ) {
this.mDatePicker.setCalendarViewShown(false);
this.mDatePicker.setSpinnersShown(true);
}
} else if ("no-calendar".equals(appearance) ) {
if ( Build.VERSION.SDK_INT >= 11 ) {
this.mDatePicker.setCalendarViewShown(false);
this.mDatePicker.setSpinnersShown(true);
}
} else {
if ( Build.VERSION.SDK_INT >= 11 ) {
showCalendar = true;
this.mDatePicker.setCalendarViewShown(true);
if ( Build.VERSION.SDK_INT >= 12 ) {
CalendarView cv = this.mDatePicker.getCalendarView();
cv.setShowWeekNumber(false);
}
this.mDatePicker.setSpinnersShown(true);
hideDay = true;
hideMonth = false;
}
}
if ( hideMonth || hideDay ) {
for (Field datePickerDialogField : this.mDatePicker.getClass().getDeclaredFields()) {
if ("mDayPicker".equals(datePickerDialogField.getName()) ||
"mDaySpinner".equals(datePickerDialogField.getName())) {
datePickerDialogField.setAccessible(true);
Object dayPicker = new Object();
try {
dayPicker = datePickerDialogField.get(this.mDatePicker);
} catch (Exception e) {
e.printStackTrace();
}
((View) dayPicker).setVisibility(View.GONE);
}
if ( hideMonth ) {
if ("mMonthPicker".equals(datePickerDialogField.getName()) ||
"mMonthSpinner".equals(datePickerDialogField.getName())) {
datePickerDialogField.setAccessible(true);
Object monthPicker = new Object();
try {
monthPicker = datePickerDialogField.get(this.mDatePicker);
} catch (Exception e) {
e.printStackTrace();
}
((View) monthPicker).setVisibility(View.GONE);
}
}
}
}
}
private void setAnswer() {
if (mPrompt.getAnswerValue() != null) {
DateTime ldt =
new DateTime(((Date) ((DateData) mPrompt.getAnswerValue()).getValue()).getTime());
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
} else {
// create date widget with current time as of right now
clearAnswer();
}
}
/**
* Resets date to today.
*/
@Override
public void clearAnswer() {
DateTime ldt = new DateTime();
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
}
@Override
public IAnswerData getAnswer() {
if ( showCalendar ) {
scrollView.clearChildFocus(mDatePicker);
}
clearFocus();
DateTime ldt =
new DateTime(mDatePicker.getYear(), (!showCalendar && hideMonth) ? 1 : mDatePicker.getMonth() + 1,
(!showCalendar && (hideMonth || hideDay)) ? 1 : mDatePicker.getDayOfMonth(), 0, 0);
// DateTime utc = ldt.withZone(DateTimeZone.forID("UTC"));
return new DateData(ldt.toDate());
}
@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) {
mDatePicker.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mDatePicker.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/DateWidget.java
|
Java
|
asf20
| 9,617
|
/*
* 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.odk.collect.android.external.ExternalAppsUtils;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.IntegerData;
import org.javarosa.form.api.FormEntryPrompt;
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.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
/**
* Launch an external app to supply an integer value. If the app
* does not launch, enable the text area for regular data entry.
*
* See {@link org.odk.collect.android.widgets.ExStringWidget} for usage.
*
* @author mitchellsundt@gmail.com
*
*/
public class ExIntegerWidget extends ExStringWidget {
private Integer getIntegerAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Integer d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Double){
d = Integer.valueOf(((Double) dataValue).intValue());
} else {
d = (Integer)dataValue;
}
}
}
return d;
}
public ExIntegerWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
// only allows numbers and no periods
mAnswer.setKeyListener(new DigitsKeyListener(true, false));
// ints can only hold 2,147,483,648. we allow 999,999,999
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(9);
mAnswer.setFilters(fa);
Integer i = getIntegerAnswerValue();
if (i != null) {
mAnswer.setText(i.toString());
}
}
@Override
protected void fireActivity(Intent i) throws ActivityNotFoundException {
i.putExtra("value", getIntegerAnswerValue());
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchIntent",
i.getAction(), mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.EX_INT_CAPTURE);
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new IntegerData(Integer.parseInt(s));
} catch (Exception NumberFormatException) {
return null;
}
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
IntegerData integerData = ExternalAppsUtils.asIntegerData(answer);
mAnswer.setText( integerData == null ? null : integerData.getValue().toString());
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ExIntegerWidget.java
|
Java
|
asf20
| 3,782
|
/*
* 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.util.ArrayList;
import java.util.List;
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.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.views.MediaLayout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
/**
* SelectOneWidgets handles select-one fields using radio buttons. Unlike the classic
* SelectOneWidget, when a user clicks an option they are then immediately advanced to the next
* question.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class SelectOneAutoAdvanceWidget extends QuestionWidget implements OnCheckedChangeListener {
List<SelectChoice> mItems; // may take a while to compute
ArrayList<RadioButton> buttons;
AdvanceToNextListener listener;
public SelectOneAutoAdvanceWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
LayoutInflater inflater = LayoutInflater.from(getContext());
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
buttons = new ArrayList<RadioButton>();
listener = (AdvanceToNextListener) context;
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
// use this for recycle
Bitmap b = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.expander_ic_right);
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
RelativeLayout thisParentLayout =
(RelativeLayout) inflater.inflate(R.layout.quick_select_layout, null);
LinearLayout questionLayout = (LinearLayout) thisParentLayout.getChildAt(0);
ImageView rightArrow = (ImageView) thisParentLayout.getChildAt(1);
RadioButton r = new RadioButton(getContext());
r.setText(prompt.getSelectChoiceText(mItems.get(i)));
r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
r.setTag(Integer.valueOf(i));
r.setId(QuestionWidget.newUniqueId());
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
rightArrow.setImageBitmap(b);
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
r.setOnCheckedChangeListener(this);
String audioURI = null;
audioURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
} else {
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(), "", r, audioURI, imageURI, videoURI, bigImageURI);
if (i != mItems.size() - 1) {
// Last, add the dividing line (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
mediaLayout.addDivider(divider);
}
questionLayout.addView(mediaLayout);
addView(thisParentLayout);
}
}
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.get(i);
return new SelectOneData(new Selection(sc));
}
}
@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);
}
public int getCheckedId() {
for (int i = 0; i < buttons.size(); ++i) {
RadioButton button = buttons.get(i);
if (button.isChecked()) {
return i;
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!buttonView.isPressed()) {
return;
}
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : this.buttons) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
listener.advance();
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton r : buttons) {
r.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/SelectOneAutoAdvanceWidget.java
|
Java
|
asf20
| 7,933
|
/*
* 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 java.util.Date;
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.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
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 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 ImageWebViewWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "MediaWidget";
private Button mCaptureButton;
private Button mChooseButton;
private WebView mImageDisplay;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
private String constructImageElement() {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
// int screenHeight = display.getHeight();
String imgElement = f.exists() ? ("<img align=\"middle\" src=\"file:///"
+ f.getAbsolutePath()
+
// Appending the time stamp to the filename is a hack to prevent
// caching.
"?"
+ new Date().getTime()
+ "\" width=\""
+ Integer.toString(screenWidth - 10) + "\" >")
: "";
return imgElement;
}
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if (mImageDisplay == null
|| mImageDisplay.getVisibility() != View.VISIBLE) {
return false;
}
Rect rect = new Rect();
mImageDisplay.getHitRect(rect);
// Log.i(t, "hitRect: " + rect.left + "," + rect.top + " : " +
// rect.right + "," + rect.bottom );
// Log.i(t, "e1 Raw, Clean: " + e1.getRawX() + "," + e1.getRawY() +
// " : " + e1.getX() + "," + e1.getY());
// Log.i(t, "e2 Raw, Clean: " + e2.getRawX() + "," + e2.getRawY() +
// " : " + e2.getX() + "," + e2.getY());
// starts in WebView
if (rect.contains((int) e1.getRawX(), (int) e1.getRawY())) {
return true;
}
// ends in WebView
if (rect.contains((int) e2.getRawX(), (int) e2.getRawY())) {
return true;
}
// transits WebView
if (rect.contains((int) ((e1.getRawX() + e2.getRawX()) / 2.0),
(int) ((e1.getRawY() + e2.getRawY()) / 2.0))) {
return true;
}
// Log.i(t, "NOT SUPPRESSED");
return false;
}
public ImageWebViewWidget(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);
}
}
});
// 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) {
mImageDisplay = new WebView(getContext());
mImageDisplay.setId(QuestionWidget.newUniqueId());
mImageDisplay.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mImageDisplay.getSettings().setBuiltInZoomControls(true);
mImageDisplay.getSettings().setDefaultZoom(
WebSettings.ZoomDensity.FAR);
mImageDisplay.setVisibility(View.VISIBLE);
mImageDisplay.setLayoutParams(params);
// HTML is used to display the image.
String html = "<body>" + constructImageElement() + "</body>";
mImageDisplay.loadDataWithBaseURL("file:///" + mInstanceFolder
+ File.separator, html, "text/html", "utf-8", "");
addView(mImageDisplay);
}
}
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();
if (mImageDisplay != null) {
// update HTML to not hold image file reference.
String html = "<body></body>";
mImageDisplay.loadDataWithBaseURL("file:///" + mInstanceFolder
+ File.separator, html, "text/html", "utf-8", "");
mImageDisplay.setVisibility(View.INVISIBLE);
}
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);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ImageWebViewWidget.java
|
Java
|
asf20
| 12,261
|
/*
* 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.util.ArrayList;
import java.util.List;
import org.javarosa.core.model.data.IAnswerData;
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.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public abstract class QuestionWidget extends LinearLayout {
@SuppressWarnings("unused")
private final static String t = "QuestionWidget";
private static int idGenerator = 1211322;
/**
* Generate a unique ID to keep Android UI happy when the screen orientation
* changes.
*
* @return
*/
public static int newUniqueId() {
return ++idGenerator;
}
private LinearLayout.LayoutParams mLayout;
protected FormEntryPrompt mPrompt;
protected final int mQuestionFontsize;
protected final int mAnswerFontsize;
private TextView mQuestionText;
private MediaLayout mediaLayout;
private TextView mHelpText;
public QuestionWidget(Context context, FormEntryPrompt p) {
super(context);
mQuestionFontsize = Collect.getQuestionFontsize();
mAnswerFontsize = mQuestionFontsize + 2;
mPrompt = p;
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.TOP);
setPadding(0, 7, 0, 0);
mLayout =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mLayout.setMargins(10, 0, 10, 0);
addQuestionText(p);
addHelpText(p);
}
public void playAudio() {
mediaLayout.playAudio();
}
public void playVideo() {
mediaLayout.playVideo();
}
public FormEntryPrompt getPrompt() {
return mPrompt;
}
// http://code.google.com/p/android/issues/detail?id=8488
private void recycleDrawablesRecursive(ViewGroup viewGroup, List<ImageView> images) {
int childCount = viewGroup.getChildCount();
for(int index = 0; index < childCount; index++)
{
View child = viewGroup.getChildAt(index);
if ( child instanceof ImageView ) {
images.add((ImageView)child);
} else if ( child instanceof ViewGroup ) {
recycleDrawablesRecursive((ViewGroup) child, images);
}
}
viewGroup.destroyDrawingCache();
}
// http://code.google.com/p/android/issues/detail?id=8488
public void recycleDrawables() {
List<ImageView> images = new ArrayList<ImageView>();
// collect all the image views
recycleDrawablesRecursive(this, images);
for ( ImageView imageView : images ) {
imageView.destroyDrawingCache();
Drawable d = imageView.getDrawable();
if ( d != null && d instanceof BitmapDrawable) {
imageView.setImageDrawable(null);
BitmapDrawable bd = (BitmapDrawable) d;
Bitmap bmp = bd.getBitmap();
if ( bmp != null ) {
bmp.recycle();
}
}
}
}
// Abstract methods
public abstract IAnswerData getAnswer();
public abstract void clearAnswer();
public abstract void setFocus(Context context);
public abstract void setOnLongClickListener(OnLongClickListener l);
/**
* Override this to implement fling gesture suppression (e.g. for embedded WebView treatments).
* @param e1
* @param e2
* @param velocityX
* @param velocityY
* @return true if the fling gesture should be suppressed
*/
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
/**
* Add a Views containing the question text, audio (if applicable), and image (if applicable).
* To satisfy the RelativeLayout constraints, we add the audio first if it exists, then the
* TextView to fit the rest of the space, then the image if applicable.
*/
protected void addQuestionText(FormEntryPrompt p) {
String imageURI = p.getImageText();
String audioURI = p.getAudioText();
String videoURI = p.getSpecialFormQuestionText("video");
// shown when image is clicked
String bigImageURI = p.getSpecialFormQuestionText("big-image");
String promptText = p.getLongText();
// Add the text view. Textview always exists, regardless of whether there's text.
mQuestionText = new TextView(getContext());
mQuestionText.setText(promptText == null ? "" : promptText);
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 (promptText == null || promptText.length() == 0) {
mQuestionText.setVisibility(GONE);
}
// Create the layout for audio, image, text
mediaLayout = new MediaLayout(getContext());
mediaLayout.setAVT(p.getIndex(), "", mQuestionText, audioURI, imageURI, videoURI, bigImageURI);
addView(mediaLayout, mLayout);
}
/**
* Add a TextView containing the help text.
*/
private void addHelpText(FormEntryPrompt p) {
String s = p.getHelpText();
if (s != null && !s.equals("")) {
mHelpText = new TextView(getContext());
mHelpText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize - 3);
mHelpText.setPadding(0, -5, 0, 7);
// wrap to the widget of view
mHelpText.setHorizontallyScrolling(false);
mHelpText.setText(s);
mHelpText.setTypeface(null, Typeface.ITALIC);
addView(mHelpText, mLayout);
}
}
/**
* Every subclassed widget should override this, adding any views they may contain, and calling
* super.cancelLongPress()
*/
public void cancelLongPress() {
super.cancelLongPress();
if (mQuestionText != null) {
mQuestionText.cancelLongPress();
}
if (mHelpText != null) {
mHelpText.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/QuestionWidget.java
|
Java
|
asf20
| 7,289
|
/*
* 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.text.NumberFormat;
import org.odk.collect.android.external.ExternalAppsUtils;
import org.javarosa.core.model.data.DecimalData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
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.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
/**
* Launch an external app to supply a decimal value. If the app
* does not launch, enable the text area for regular data entry.
*
* See {@link org.odk.collect.android.widgets.ExStringWidget} for usage.
*
* @author mitchellsundt@gmail.com
*
*/
public class ExDecimalWidget extends ExStringWidget {
private Double getDoubleAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Double d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Integer){
d = Double.valueOf(((Integer)dataValue).intValue());
} else {
d = (Double) dataValue;
}
}
}
return d;
}
public ExDecimalWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
// only allows numbers and no periods
mAnswer.setKeyListener(new DigitsKeyListener(true, true));
// only 15 characters allowed
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(15);
mAnswer.setFilters(fa);
Double d = getDoubleAnswerValue();
// apparently an attempt at rounding to no more than 15 digit precision???
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(15);
nf.setMaximumIntegerDigits(15);
nf.setGroupingUsed(false);
if (d != null) {
// truncate to 15 digits max...
String dString = nf.format(d);
d = Double.parseDouble(dString.replace(',', '.')); // in case , is decimal pt
mAnswer.setText(d.toString());
}
}
@Override
protected void fireActivity(Intent i) throws ActivityNotFoundException {
i.putExtra("value", getDoubleAnswerValue());
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchIntent",
i.getAction(), mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.EX_DECIMAL_CAPTURE);
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new DecimalData(Double.valueOf(s).doubleValue());
} catch (Exception NumberFormatException) {
return null;
}
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
DecimalData decimalData = ExternalAppsUtils.asDecimalData(answer);
mAnswer.setText( decimalData == null ? null : decimalData.getValue().toString());
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ExDecimalWidget.java
|
Java
|
asf20
| 4,238
|
/*
* Copyright (C) 2013 Nafundi
*
* 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.BearingActivity;
import org.odk.collect.android.activities.FormEntryActivity;
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;
/**
* BearingWidget is the widget that allows the user to get a compass heading.
*
* @author Carl Hartung (chartung@nafundi.com)
*/
public class BearingWidget extends QuestionWidget implements IBinaryWidget {
private Button mGetBearingButton;
private TextView mStringAnswer;
private TextView mAnswerDisplay;
public BearingWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mGetBearingButton = new Button(getContext());
mGetBearingButton.setId(QuestionWidget.newUniqueId());
mGetBearingButton.setPadding(20, 20, 20, 20);
mGetBearingButton.setText(getContext()
.getString(R.string.get_bearing));
mGetBearingButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mGetBearingButton.setEnabled(!prompt.isReadOnly());
mGetBearingButton.setLayoutParams(params);
if (prompt.isReadOnly()) {
mGetBearingButton.setVisibility(View.GONE);
}
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("")) {
mGetBearingButton.setText(getContext().getString(
R.string.replace_bearing));
setBinaryData(s);
}
// when you press the button
mGetBearingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "recordBearing", "click",
mPrompt.getIndex());
Intent i = null;
i = new Intent(getContext(), BearingActivity.class);
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.BEARING_CAPTURE);
}
});
addView(mGetBearingButton);
addView(mAnswerDisplay);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mAnswerDisplay.setText(null);
mGetBearingButton.setText(getContext()
.getString(R.string.get_bearing));
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
@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);
mAnswerDisplay.setText(s);
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) {
mGetBearingButton.setOnLongClickListener(l);
mStringAnswer.setOnLongClickListener(l);
mAnswerDisplay.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mGetBearingButton.cancelLongPress();
mStringAnswer.cancelLongPress();
mAnswerDisplay.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/BearingWidget.java
|
Java
|
asf20
| 5,847
|
/*
* Copyright (C) 2014 Nafundi
*
* 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.tasks;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.FormException;
import org.odk.collect.android.exception.GeoPointNotFoundException;
import org.odk.collect.android.picasa.AlbumEntry;
import org.odk.collect.android.picasa.AlbumFeed;
import org.odk.collect.android.picasa.PhotoEntry;
import org.odk.collect.android.picasa.PicasaClient;
import org.odk.collect.android.picasa.PicasaUrl;
import org.odk.collect.android.picasa.UserFeed;
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.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.Xml;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
*
* @author carlhartung (chartung@nafundi.com)
*
*/
public abstract class GoogleMapsEngineAbstractUploader<Params, Progress, Result>
extends GoogleMapsEngineTask<Long, Integer, HashMap<String, String>> {
private final static String tag = "GoogleMapsEngineInstanceUploaderTask";
protected HashMap<String, String> mResults;
protected static final String picasa_fail = "Picasa Error: ";
protected static final String oauth_fail = "OAUTH Error: ";
protected static final String form_fail = "Form Error: ";
private final static String PROJECT_ID = "projectid";
/*
* By default, GME has a rate limit of 1 request/sec, so we've added GME_SLEEP_TIME
* to make sure we stay within that limit
* The production version of ODK Collect is not rate limited by GME, and is reflected
* in the code below.
* You should change this if working on a non Google Play version of Collect.
*/
// dev
//private static final int GME_SLEEP_TIME = 1100;
// prod
private static final int GME_SLEEP_TIME = 1;
// As of August 2014 there was a known issue in GME that returns an error
// if a request comes in too soon after creating a table.
// This delay prevents that error
// see "known issues at the bottom of this page:
// https://developers.google.com/maps-engine/documentation/table-create
private static final int GME_CREATE_TABLE_DELAY = 4000;
/**
* @param selection
* @param selectionArgs
* @param token
*/
protected void uploadInstances(String selection, String[] selectionArgs,
String token) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(Collect.getInstance()
.getApplicationContext());
Cursor c = null;
try {
c = Collect
.getInstance()
.getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
if (isCancelled()) {
return;
}
String instance = c
.getString(c
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c
.getColumnIndex(InstanceColumns._ID));
String jrformid = c.getString(c
.getColumnIndex(InstanceColumns.JR_FORM_ID));
Uri toUpdate = Uri.withAppendedPath(
InstanceColumns.CONTENT_URI, id);
ContentValues cv = new ContentValues();
String formSelection = FormsColumns.JR_FORM_ID + "=?";
String[] formSelectionArgs = { jrformid };
Cursor formcursor = Collect
.getInstance()
.getContentResolver()
.query(FormsColumns.CONTENT_URI, null,
formSelection, formSelectionArgs, null);
String md5 = null;
String formFilePath = null;
if (formcursor.getCount() > 0) {
formcursor.moveToFirst();
md5 = formcursor.getString(formcursor
.getColumnIndex(FormsColumns.MD5_HASH));
formFilePath = formcursor.getString(formcursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
}
if (md5 == null) {
// fail and exit
Log.e(tag, "no md5");
return;
}
// get projectID and draftaccesslist from preferences
// these may get overwritten per form
// so pull the value each time
HashMap<String, String> gmeFormValues = new HashMap<String, String>();
String projectid = appSharedPrefs.getString(
PreferencesActivity.KEY_GME_PROJECT_ID, null);
gmeFormValues.put(PROJECT_ID, projectid);
publishProgress(c.getPosition() + 1, c.getCount());
if (!uploadOneSubmission(id, instance, jrformid, token,
gmeFormValues, md5, formFilePath)) {
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return;
} else {
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
}
}
}
} finally {
if (c != null) {
c.close();
}
}
}
private boolean uploadOneSubmission(String id, String instanceFilePath,
String jrFormId, String token,
HashMap<String, String> gmeFormValues, String md5,
String formFilePath) {
// if the token is null fail immediately
if (token == null) {
mResults.put(
id,
oauth_fail
+ Collect.getInstance().getString(
R.string.invalid_oauth));
return false;
}
HashMap<String, String> answersToUpload = new HashMap<String, String>();
HashMap<String, String> photosToUpload = new HashMap<String, String>();
HashMap<String, PhotoEntry> uploadedPhotos = new HashMap<String, PhotoEntry>();
HttpTransport h = AndroidHttp.newCompatibleTransport();
GoogleCredential gc = new GoogleCredential();
gc.setAccessToken(token);
PicasaClient client = new PicasaClient(h.createRequestFactory(gc));
String gmeTableId = null;
// get instance file
File instanceFile = new File(instanceFilePath);
// parses the instance file and populates the answers and photos
// hashmaps. Also extracts the projectid and draftaccess list if
// defined
try {
processXMLFile(instanceFile, answersToUpload, photosToUpload,
gmeFormValues);
} catch (XmlPullParserException e) {
e.printStackTrace();
mResults.put(id, form_fail + e.getMessage());
return false;
} catch (FormException e) {
mResults.put(
id,
form_fail
+ Collect.getInstance().getString(
R.string.gme_repeat_error));
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
mResults.put(id, form_fail + e.getMessage());
return false;
} catch (IOException e) {
e.printStackTrace();
mResults.put(id, form_fail + e.getMessage());
return false;
}
// at this point, we should have a projectid either from
// the settings or the form
// if not, fail
if (gmeFormValues.get(PROJECT_ID) == null) {
mResults.put(
id,
form_fail
+ Collect.getInstance().getString(
R.string.gme_project_id_error));
return false;
}
// check to see if a table already exists in GME that
// matches the given md5
try {
gmeTableId = getGmeTableID(gmeFormValues.get(PROJECT_ID), jrFormId,
token, md5);
} catch (IOException e2) {
e2.printStackTrace();
mResults.put(id, form_fail + e2.getMessage());
return false;
}
// GME limit is 1/s, so sleep for 1 second after each GME query
try {
Thread.sleep(GME_SLEEP_TIME);
} catch (InterruptedException e3) {
e3.printStackTrace();
}
// didn't exist, so try to create it
boolean newTable = false;
if (gmeTableId == null) {
try {
gmeTableId = createTable(jrFormId,
gmeFormValues.get(PROJECT_ID), md5, token, formFilePath);
newTable = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
mResults.put(id, form_fail + e.getMessage());
return false;
} catch (XmlPullParserException e) {
e.printStackTrace();
mResults.put(id, form_fail + e.getMessage());
return false;
} catch (IOException e) {
e.printStackTrace();
mResults.put(id, form_fail + e.getMessage());
return false;
} catch (FormException e) {
e.printStackTrace();
mResults.put(id, form_fail + e.getMessage());
return false;
}
}
// GME has 1q/s limit
// but needs a few extra seconds after a create table
try {
int sleepTime = GME_SLEEP_TIME;
if (newTable) {
sleepTime += GME_CREATE_TABLE_DELAY;
}
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
// at this point, we should have a valid gme table id to
// submit this instance to
if (gmeTableId == null) {
mResults.put(
id,
form_fail
+ Collect.getInstance().getString(
R.string.gme_table_error));
return false;
}
// if we have any photos to upload,
// get the picasa album or create a new one
// then upload the photos
if (photosToUpload.size() > 0) {
// First set up a picasa album to upload to:
// maybe we should move this, because if we don't have any
// photos we don't care...
AlbumEntry albumToUse = null;
try {
albumToUse = getOrCreatePicasaAlbum(client, jrFormId);
} catch (IOException e) {
e.printStackTrace();
GoogleAuthUtil.invalidateToken(Collect.getInstance(), token);
mResults.put(id, picasa_fail + e.getMessage());
return false;
}
try {
uploadPhotosToPicasa(photosToUpload, uploadedPhotos, client,
albumToUse, instanceFile);
} catch (IOException e1) {
e1.printStackTrace();
mResults.put(id, picasa_fail + e1.getMessage());
return false;
}
}
// All photos have been sent to picasa (if there were any)
// now upload data to GME
String jsonSubmission = null;
try {
jsonSubmission = buildJSONSubmission(answersToUpload,
uploadedPhotos);
} catch (GeoPointNotFoundException e2) {
e2.printStackTrace();
mResults.put(id, form_fail + e2.getMessage());
return false;
}
URL gmeuri = null;
try {
gmeuri = new URL("https://www.googleapis.com/mapsengine/v1/tables/"
+ gmeTableId + "/features/batchInsert");
} catch (MalformedURLException e) {
mResults.put(id, gme_fail + e.getMessage());
return false;
}
// try to upload the submission
// if not successful, in case of error results will already be
// populated
return uploadSubmission(gmeuri, token, jsonSubmission, gmeTableId, id,
newTable);
}
private boolean uploadSubmission(URL gmeuri, String token,
String jsonSubmission, String gmeTableId, String id,
boolean newTable) {
HttpURLConnection conn = null;
int status = -1;
try {
conn = (HttpURLConnection) gmeuri.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(jsonSubmission.getBytes().length);
// make some HTTP header nicety
conn.setRequestProperty("Content-Type",
"application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.addRequestProperty("Authorization", "OAuth " + token);
// setup send
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(jsonSubmission.getBytes());
// clean up
os.flush();
status = conn.getResponseCode();
if (status / 100 == 2) {
mResults.put(id,
Collect.getInstance().getString(R.string.success));
// GME has 1q/s limit
try {
Thread.sleep(GME_SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
} else {
String errorString = getErrorMesssage(conn.getErrorStream());
if (status == 400) {
// BAD REQUEST
if (newTable) {
mResults.put(
id,
gme_fail
+ Collect.getInstance().getString(
R.string.gme_create_400));
} else {
mResults.put(id, gme_fail + errorString);
}
} else if (status == 403 || status == 401) {
// 403 == forbidden
// 401 == invalid token (should work on next try)
GoogleAuthUtil
.invalidateToken(Collect.getInstance(), token);
mResults.put(id, gme_fail + errorString);
}
return false;
}
} catch (Exception e) {
e.printStackTrace();
String errorString = getErrorMesssage(conn.getErrorStream());
mResults.put(id, gme_fail + errorString);
return false;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private String buildJSONSubmission(HashMap<String, String> answersToUpload,
HashMap<String, PhotoEntry> uploadedPhotos)
throws GeoPointNotFoundException {
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Feature.class, new FeatureSerializer());
gsonBuilder.registerTypeAdapter(ArrayList.class,
new FeatureListSerializer());
final Gson gson = gsonBuilder.create();
Map<String, String> properties = new HashMap<String, String>();
properties.put("gx_id", String.valueOf(System.currentTimeMillis()));
// there has to be a geo point, else we can't upload
boolean foundGeo = false;
PointGeometry pg = null;
Iterator<String> answerIterator = answersToUpload.keySet().iterator();
while (answerIterator.hasNext()) {
String path = answerIterator.next();
String answer = answersToUpload.get(path);
// the instances don't have data types, so we try to match a
// fairly specific pattern to determine geo coordinates, so we
// pattern match against our answer
// [-]#.# [-]#.# #.# #.#
if (!foundGeo) {
Pattern p = Pattern
.compile("^-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s[0-9]+\\.[0-9]+$");
Matcher m = p.matcher(answer);
if (m.matches()) {
foundGeo = true;
// split on spaces, take the first two, which are lat
// long
String[] tokens = answer.split(" ");
pg = new PointGeometry();
pg.type = "Point";
pg.setCoordinates(Double.parseDouble(tokens[1]),
Double.parseDouble(tokens[0]));
}
}
// geo or not, add to properties
properties.put(path, answer);
}
if (!foundGeo) {
throw new GeoPointNotFoundException(
"Instance has no Coordinates! Unable to upload");
}
// then add the urls for photos
Iterator<String> photoIterator = uploadedPhotos.keySet().iterator();
while (photoIterator.hasNext()) {
String path = photoIterator.next();
String url = uploadedPhotos.get(path).getImageLink();
properties.put(path, url);
}
Feature f = new Feature();
f.geometry = pg;
f.properties = properties;
// gme expects an array of features for uploads, even though we only
// send one
ArrayList<Feature> features = new ArrayList<Feature>();
features.add(f);
return gson.toJson(features);
}
private void uploadPhotosToPicasa(HashMap<String, String> photos,
HashMap<String, PhotoEntry> uploaded, PicasaClient client,
AlbumEntry albumToUse, File instanceFile) throws IOException {
Iterator<String> itr = photos.keySet().iterator();
while (itr.hasNext()) {
String key = itr.next();
String filename = instanceFile.getParentFile() + "/"
+ photos.get(key);
File toUpload = new File(filename);
// first check the local content provider
// to see if this photo already has a picasa_id
String selection = Images.Media.DATA + "=?";
String[] selectionArgs = { filename };
Cursor c = Collect
.getInstance()
.getContentResolver()
.query(Images.Media.EXTERNAL_CONTENT_URI, null, selection,
selectionArgs, null);
if (c.getCount() != 1) {
c.close();
throw new FileNotFoundException(picasa_fail
+ Collect.getInstance().getString(
R.string.picasa_upload_error, filename));
}
// assume it's not already in picasa
boolean inPicasa = false;
// this will contain the link to the photo
PhotoEntry picasaPhoto = null;
c.moveToFirst();
String picasa_id = c.getString(c
.getColumnIndex(Images.Media.PICASA_ID));
if (picasa_id == null || picasa_id.equalsIgnoreCase("")) {
// not in picasa, so continue
} else {
// got a picasa ID, make sure it exists in this
// particular album online
// if it does, go on
// if it doesn't, upload it and update the picasa_id
if (albumToUse.numPhotos != 0) {
PicasaUrl photosUrl = new PicasaUrl(
albumToUse.getFeedLink());
AlbumFeed albumFeed = client.executeGetAlbumFeed(photosUrl);
for (PhotoEntry photo : albumFeed.photos) {
if (picasa_id.equals(photo.id)) {
// already in picasa, no need to upload
inPicasa = true;
picasaPhoto = photo;
}
}
}
}
// wasn't already there, so upload a new copy and update the
// content provder with its picasa_id
if (!inPicasa) {
String fileName = toUpload.getAbsolutePath();
File file = new File(fileName);
String mimetype = URLConnection.guessContentTypeFromName(file
.getName());
InputStreamContent content = new InputStreamContent(mimetype,
new FileInputStream(file));
picasaPhoto = client.executeInsertPhotoEntry(new PicasaUrl(
albumToUse.getFeedLink()), content, toUpload.getName());
ContentValues cv = new ContentValues();
cv.put(Images.Media.PICASA_ID, picasaPhoto.id);
// update the content provider picasa_id once we upload
String where = Images.Media.DATA + "=?";
String[] whereArgs = { toUpload.getAbsolutePath() };
Collect.getInstance()
.getContentResolver()
.update(Images.Media.EXTERNAL_CONTENT_URI, cv, where,
whereArgs);
}
// uploadedPhotos keeps track of the uploaded URL
// relative to the path
uploaded.put(key, picasaPhoto);
}
}
private AlbumEntry getOrCreatePicasaAlbum(PicasaClient client,
String jrFormId) throws IOException {
AlbumEntry albumToUse = null;
PicasaUrl url = PicasaUrl.relativeToRoot("feed/api/user/default");
UserFeed feed = null;
feed = client.executeGetUserFeed(url);
// Find an album with a title matching the form_id
// Technically there could be multiple albums that match
// We just use the first one that matches
if (feed.albums != null) {
for (AlbumEntry album : feed.albums) {
if (jrFormId.equals(album.title)) {
albumToUse = album;
break;
}
}
}
// no album exited, so create one
if (albumToUse == null) {
AlbumEntry newAlbum = new AlbumEntry();
newAlbum.access = "private";
newAlbum.title = jrFormId;
newAlbum.summary = "Images for form: " + jrFormId;
albumToUse = client.executeInsert(feed, newAlbum);
}
return albumToUse;
}
private String getGmeTableID(String projectid, String jrformid,
String token, String md5) throws IOException {
String gmetableid = null;
// first check to see if form exists.
// if a project ID has been defined
String url = "https://www.googleapis.com/mapsengine/v1/tables";
if (projectid != null) {
url = url + "?projectId=" + projectid;
}
HttpURLConnection conn = null;
TablesListResponse tables = null;
boolean found = false;
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
// keep fetching while nextToken exists
// and we haven't found a matching table
findtableloop: while (tables == null || tables.nextPageToken != null) {
String openUrl = url + "&where=Name=" + jrformid;
if (tables != null && tables.nextPageToken != null) {
openUrl = url + "&pageToken=" + tables.nextPageToken;
} else {
openUrl = url;
}
Log.i(tag, "trying to open url: " + openUrl);
URL fullUrl = new URL(openUrl);
conn = (HttpURLConnection) fullUrl.openConnection();
conn.setRequestMethod("GET");
conn.addRequestProperty("Authorization", "OAuth " + token);
conn.connect();
if (conn.getResponseCode() != 200) {
String errorString = getErrorMesssage(conn.getErrorStream());
throw new IOException(errorString);
}
BufferedReader br = null;
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
if (tables != null) {
tables.nextPageToken = null;
tables = null;
}
tables = gson.fromJson(br, TablesListResponse.class);
for (int i = 0; i < tables.tables.length; i++) {
Table t = tables.tables[i];
for (int j = 0; j < t.tags.length; j++) {
if (md5.equalsIgnoreCase(t.tags[j])) {
found = true;
gmetableid = t.id;
break findtableloop;
}
}
}
br.close();
// GME has 1q/s limit
try {
Thread.sleep(GME_SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!found) {
return null;
} else {
return gmetableid;
}
}
private String createTable(String jrformid, String projectid, String md5,
String token, String formFilePath) throws FileNotFoundException,
XmlPullParserException, IOException, FormException {
ArrayList<String> columnNames = new ArrayList<String>();
getColumns(formFilePath, columnNames);
String gmetableid = null;
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
Table t = new Table();
t.name = jrformid;
Log.i(tag, "Using GME projectid : " + projectid);
t.projectId = projectid;
Column first = new Column();
first.name = "geometry";
first.type = "points";
Column[] columns = new Column[columnNames.size() + 1];
columns[0] = first;
for (int i = 0; i < columnNames.size(); i++) {
Column c = new Column();
c.name = columnNames.get(i);
c.type = "string";
columns[i + 1] = c;
}
Schema s = new Schema();
s.columns = columns;
t.schema = s;
String[] tags = { md5 };
t.tags = tags;
t.description = "auto-created by ODK Collect for formid " + jrformid;
URL createTableUrl = new URL(
"https://www.googleapis.com/mapsengine/v1/tables");
HttpURLConnection sendConn = null;
int status = -1;
final String json = gson.toJson(t);
sendConn = (HttpURLConnection) createTableUrl.openConnection();
sendConn.setReadTimeout(10000 /* milliseconds */);
sendConn.setConnectTimeout(15000 /* milliseconds */);
sendConn.setRequestMethod("POST");
sendConn.setDoInput(true);
sendConn.setDoOutput(true);
sendConn.setFixedLengthStreamingMode(json.getBytes().length);
// make some HTTP header nicety
sendConn.setRequestProperty("Content-Type",
"application/json;charset=utf-8");
sendConn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
sendConn.addRequestProperty("Authorization", "OAuth " + token);
// setup send
OutputStream os = new BufferedOutputStream(sendConn.getOutputStream());
os.write(json.getBytes());
// clean up
os.flush();
status = sendConn.getResponseCode();
if (status != 200) {
String errorString = getErrorMesssage(sendConn.getErrorStream());
throw new IOException(errorString);
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(
sendConn.getInputStream()));
Table table = gson.fromJson(br, Table.class);
Log.i(tag, "found table id :: " + table.id);
gmetableid = table.id;
}
return gmetableid;
}
private void getColumns(String filePath, ArrayList<String> columns)
throws FileNotFoundException, XmlPullParserException, IOException,
FormException {
File formFile = new File(filePath);
FileInputStream in = null;
in = new FileInputStream(formFile);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
readForm(parser, columns);
in.close();
}
private void readForm(XmlPullParser parser, ArrayList<String> columns)
throws XmlPullParserException, IOException, FormException {
ArrayList<String> path = new ArrayList<String>();
// we put path names in here as we go, and if we hit a duplicate we
// blow up
ArrayList<String> repeatCheck = new ArrayList<String>();
boolean getPaths = false;
int event = parser.next();
int depth = 0;
int lastpush = 0;
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
if (getPaths) {
path.add(parser.getName());
depth++;
lastpush = depth;
if (repeatCheck.contains(getPath(path))) {
throw new FormException(Collect.getInstance()
.getString(R.string.gme_repeat_error));
} else {
repeatCheck.add(getPath(path));
}
}
if (parser.getName().equals("instance")) {
getPaths = true;
}
break;
case XmlPullParser.TEXT:
// skip it
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("instance")) {
return;
}
if (getPaths) {
if (depth == lastpush) {
columns.add(getPath(path));
} else {
lastpush--;
}
path.remove(path.size() - 1);
depth--;
}
break;
default:
Log.i(tag,
"DEFAULTING: " + parser.getName() + " :: "
+ parser.getEventType());
break;
}
event = parser.next();
}
}
private void processXMLFile(File instanceFile,
HashMap<String, String> answersToUpload,
HashMap<String, String> photosToUpload,
HashMap<String, String> gmeFormValues)
throws FileNotFoundException, XmlPullParserException, IOException,
FormException {
FileInputStream in = null;
in = new FileInputStream(instanceFile);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
readFeed(parser, answersToUpload, photosToUpload, gmeFormValues);
in.close();
}
private void readFeed(XmlPullParser parser,
HashMap<String, String> answersToUpload,
HashMap<String, String> photosToUpload,
HashMap<String, String> gmeFormValues)
throws XmlPullParserException, IOException, FormException {
ArrayList<String> path = new ArrayList<String>();
// we put path names in here as we go, and if we hit a duplicate we
// blow up
ArrayList<String> repeatCheck = new ArrayList<String>();
int event = parser.next();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
path.add(parser.getName());
if (repeatCheck.contains(getPath(path))) {
throw new FormException(Collect.getInstance().getString(
R.string.gme_repeat_error));
} else {
repeatCheck.add(getPath(path));
}
// check the start tag for project ID
for (int i = 0; i < parser.getAttributeCount(); i++) {
String attr = parser.getAttributeName(i);
if ("projectId".equals(attr)) {
gmeFormValues.put("projectId",
parser.getAttributeValue(i));
break;
}
}
break;
case XmlPullParser.TEXT:
String answer = parser.getText();
if (answer.endsWith(".jpg") || answer.endsWith(".png")) {
photosToUpload.put(getPath(path), answer);
} else {
answersToUpload.put(getPath(path), answer);
}
break;
case XmlPullParser.END_TAG:
path.remove(path.size() - 1);
break;
default:
Log.i(tag,
"DEFAULTING: " + parser.getName() + " :: "
+ parser.getEventType());
break;
}
event = parser.next();
}
}
private String getPath(ArrayList<String> path) {
String currentPath = "";
for (String node : path) {
currentPath += "/" + node;
}
return currentPath;
}
@Override
protected void onPostExecute(HashMap<String, String> results) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.uploadingComplete(results);
StringBuilder selection = new StringBuilder();
Set<String> keys = results.keySet();
Iterator<String> it = keys.iterator();
String[] selectionArgs = new String[keys.size() + 1];
int i = 0;
selection.append("(");
while (it.hasNext()) {
String id = it.next();
selection.append(InstanceColumns._ID + "=?");
selectionArgs[i++] = id;
if (i != keys.size()) {
selection.append(" or ");
}
}
selection.append(") and status=?");
selectionArgs[i] = InstanceProviderAPI.STATUS_SUBMITTED;
Cursor uploadResults = null;
try {
uploadResults = Collect
.getInstance()
.getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection.toString(),
selectionArgs, null);
if (uploadResults.getCount() > 0) {
Long[] toDelete = new Long[uploadResults.getCount()];
uploadResults.moveToPosition(-1);
int cnt = 0;
while (uploadResults.moveToNext()) {
toDelete[cnt] = uploadResults.getLong(uploadResults
.getColumnIndex(InstanceColumns._ID));
cnt++;
}
boolean deleteFlag = PreferenceManager.getDefaultSharedPreferences(
Collect.getInstance().getApplicationContext()).getBoolean(
PreferencesActivity.KEY_DELETE_AFTER_SEND, false);
if (deleteFlag) {
DeleteInstancesTask dit = new DeleteInstancesTask();
dit.setContentResolver(Collect.getInstance().getContentResolver());
dit.execute(toDelete);
}
}
} finally {
if (uploadResults != null) {
uploadResults.close();
}
}
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0].intValue(),
values[1].intValue());
}
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/GoogleMapsEngineAbstractUploader.java
|
Java
|
asf20
| 31,984
|
/*
* 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.tasks;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Element;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.TaskCancelledException;
import org.odk.collect.android.listeners.FormDownloaderListener;
import org.odk.collect.android.logic.FormDetails;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.utilities.DocumentFetchResult;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.WebUtils;
import org.opendatakit.httpclientandroidlib.Header;
import org.opendatakit.httpclientandroidlib.HttpEntity;
import org.opendatakit.httpclientandroidlib.HttpResponse;
import org.opendatakit.httpclientandroidlib.HttpStatus;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.client.methods.HttpGet;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for downloading a given list of forms. We assume right now that the forms are
* coming from the same server that presented the form list, but theoretically that won't always be
* true.
*
* @author msundt
* @author carlhartung
*/
public class DownloadFormsTask extends
AsyncTask<ArrayList<FormDetails>, String, HashMap<FormDetails, String>> {
private static final String t = "DownloadFormsTask";
private static final String MD5_COLON_PREFIX = "md5:";
private static final String TEMP_DOWNLOAD_EXTENSION = ".tempDownload";
private FormDownloaderListener mStateListener;
private static final String NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_MANIFEST =
"http://openrosa.org/xforms/xformsManifest";
private boolean isXformsManifestNamespacedElement(Element e) {
return e.getNamespace().equalsIgnoreCase(NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_MANIFEST);
}
@Override
protected HashMap<FormDetails, String> doInBackground(ArrayList<FormDetails>... values) {
ArrayList<FormDetails> toDownload = values[0];
int total = toDownload.size();
int count = 1;
Collect.getInstance().getActivityLogger().logAction(this, "downloadForms", String.valueOf(total));
HashMap<FormDetails, String> result = new HashMap<FormDetails, String>();
for (FormDetails fd : toDownload) {
publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total)
.toString());
String message = "";
if (isCancelled()) {
break;
}
String tempMediaPath = null;
String finalMediaPath = null;
FileResult fileResult = null;
try {
// get the xml file
// if we've downloaded a duplicate, this gives us the file
fileResult = downloadXform(fd.formName, fd.downloadUrl);
if (fd.manifestUrl != null) {
// use a temporary media path until everything is ok.
tempMediaPath = new File(Collect.CACHE_PATH, String.valueOf(System.currentTimeMillis())).getAbsolutePath();
finalMediaPath = FileUtils.constructMediaPath(fileResult.getFile().getAbsolutePath());
String error = downloadManifestAndMediaFiles(tempMediaPath, finalMediaPath, fd, count, total);
if (error != null) {
message += error;
}
} else {
Log.i(t, "No Manifest for: " + fd.formName);
}
} catch (TaskCancelledException e) {
Log.e(t, e.getMessage());
cleanUp(fileResult, e.getFile(), tempMediaPath);
// do not download additional forms.
break;
} catch (Exception e) {
String msg = e.getMessage();
if ( msg == null ) {
msg = e.toString();
}
Log.e(t, msg);
if (e.getCause() != null) {
msg = e.getCause().getMessage();
if ( msg == null ) {
msg = e.getCause().toString();
}
}
message += msg;
}
if (!isCancelled() && message.length() == 0 && fileResult != null) {
// install everything
UriResult uriResult = null;
try {
uriResult = findExistingOrCreateNewUri(fileResult.getFile());
Log.w(t, "Form uri = " + uriResult.getUri() + ", isNew = " + uriResult.isNew());
// move the media files in the media folder
if (tempMediaPath != null) {
File formMediaPath = new File(uriResult.getMediaPath());
FileUtils.moveMediaFiles(tempMediaPath, formMediaPath);
}
} catch (IOException e) {
Log.e(t, e.getMessage());
if (uriResult != null && uriResult.isNew() && fileResult.isNew()) {
// this means we should delete the entire form together with the metadata
Uri uri = uriResult.getUri();
Log.w(t, "The form is new. We should delete the entire form.");
int deletedCount = Collect.getInstance().getContentResolver().delete(uri, null, null);
Log.w(t, "Deleted " + deletedCount + " rows using uri " + uri);
}
cleanUp(fileResult, null, tempMediaPath);
} catch (TaskCancelledException e) {
Log.e(t, e.getMessage());
cleanUp(fileResult, e.getFile(), tempMediaPath);
}
} else {
cleanUp(fileResult, null, tempMediaPath);
}
count++;
saveResult(result, fd, message);
}
return result;
}
private void saveResult(HashMap<FormDetails, String> result, FormDetails fd, String message) {
if (message.equalsIgnoreCase("")) {
message = Collect.getInstance().getString(R.string.success);
}
result.put(fd, message);
}
/**
* Some clean up
*
* @param fileResult
* @param fileOnCancel
* @param tempMediaPath
*/
private void cleanUp(FileResult fileResult, File fileOnCancel, String tempMediaPath) {
if (fileResult == null) {
Log.w(t, "The user cancelled (or an exception happened) the download of a form at the very beginning.");
} else {
if (fileResult.getFile() != null) {
FileUtils.deleteAndReport(fileResult.getFile());
}
}
if (fileOnCancel != null) {
FileUtils.deleteAndReport(fileOnCancel);
}
if ( tempMediaPath != null ) {
FileUtils.purgeMediaPath(tempMediaPath);
}
}
/**
* Checks a form file whether it is a new one or if it matches an old one.
*
* @param formFile the form definition file
* @return a {@link org.odk.collect.android.tasks.DownloadFormsTask.UriResult} object
* @throws TaskCancelledException if the user cancels the task during the download.
*/
private UriResult findExistingOrCreateNewUri(File formFile) throws TaskCancelledException {
Cursor cursor = null;
Uri uri = null;
String mediaPath;
boolean isNew;
String formFilePath = formFile.getAbsolutePath();
mediaPath = FileUtils.constructMediaPath(formFilePath);
FileUtils.checkMediaPath(new File(mediaPath));
try {
String[] selectionArgs = {
formFile.getAbsolutePath()
};
String selection = FormsColumns.FORM_FILE_PATH + "=?";
cursor = Collect.getInstance()
.getContentResolver()
.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs,
null);
isNew = cursor.getCount() <= 0;
if (isNew) {
// doesn't exist, so insert it
ContentValues v = new ContentValues();
v.put(FormsColumns.FORM_FILE_PATH, formFilePath);
v.put(FormsColumns.FORM_MEDIA_PATH, mediaPath);
Log.w(t, "Parsing document " + formFile.getAbsolutePath());
HashMap<String, String> formInfo = FileUtils.parseXML(formFile);
if (isCancelled()) {
throw new TaskCancelledException(formFile, "Form " + formFile.getName() + " was cancelled while it was being parsed.");
}
v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE));
v.put(FormsColumns.JR_VERSION, formInfo.get(FileUtils.VERSION));
v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID));
v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI));
v.put(FormsColumns.BASE64_RSA_PUBLIC_KEY, formInfo.get(FileUtils.BASE64_RSA_PUBLIC_KEY));
uri =
Collect.getInstance().getContentResolver()
.insert(FormsColumns.CONTENT_URI, v);
Collect.getInstance().getActivityLogger().logAction(this, "insert", formFile.getAbsolutePath());
} else {
cursor.moveToFirst();
uri =
Uri.withAppendedPath(FormsColumns.CONTENT_URI,
cursor.getString(cursor.getColumnIndex(FormsColumns._ID)));
mediaPath = cursor.getString(cursor.getColumnIndex(FormsColumns.FORM_MEDIA_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "refresh", formFile.getAbsolutePath());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return new UriResult(uri, mediaPath, isNew);
}
/**
* Takes the formName and the URL and attempts to download the specified file. Returns a file
* object representing the downloaded file.
*
* @param formName
* @param url
* @return
* @throws Exception
*/
private FileResult downloadXform(String formName, String url) throws Exception {
// clean up friendly form name...
String rootName = formName.replaceAll("[^\\p{L}\\p{Digit}]", " ");
rootName = rootName.replaceAll("\\p{javaWhitespace}+", " ");
rootName = rootName.trim();
// proposed name of xml file...
String path = Collect.FORMS_PATH + File.separator + rootName + ".xml";
int i = 2;
File f = new File(path);
while (f.exists()) {
path = Collect.FORMS_PATH + File.separator + rootName + "_" + i + ".xml";
f = new File(path);
i++;
}
downloadFile(f, url);
boolean isNew = true;
// we've downloaded the file, and we may have renamed it
// make sure it's not the same as a file we already have
String[] projection = {
FormsColumns.FORM_FILE_PATH
};
String[] selectionArgs = {
FileUtils.getMd5Hash(f)
};
String selection = FormsColumns.MD5_HASH + "=?";
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver()
.query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null);
if (c.getCount() > 0) {
// Should be at most, 1
c.moveToFirst();
isNew = false;
// delete the file we just downloaded, because it's a duplicate
Log.w(t, "A duplicate file has been found, we need to remove the downloaded file and return the other one.");
FileUtils.deleteAndReport(f);
// set the file returned to the file we already had
String existingPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
f = new File(existingPath);
Log.w(t, "Will use " + existingPath);
}
} finally {
if (c != null) {
c.close();
}
}
return new FileResult(f, isNew);
}
/**
* Common routine to download a document from the downloadUrl and save the contents in the file
* 'file'. Shared by media file download and form file download.
*
* SurveyCTO: The file is saved into a temp folder and is moved to the final place if everything is okay,
* so that garbage is not left over on cancel.
*
* @param file the final file
* @param downloadUrl the url to get the contents from.
* @throws Exception
*/
private void downloadFile(File file, String downloadUrl) throws Exception {
File tempFile = File.createTempFile(file.getName(), TEMP_DOWNLOAD_EXTENSION, new File(Collect.CACHE_PATH));
URI uri;
try {
// assume the downloadUrl is escaped properly
URL url = new URL(downloadUrl);
uri = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
throw e;
} catch (URISyntaxException e) {
e.printStackTrace();
throw e;
}
// WiFi network connections can be renegotiated during a large form download sequence.
// This will cause intermittent download failures. Silently retry once after each
// failure. Only if there are two consecutive failures, do we abort.
boolean success = false;
int attemptCount = 0;
final int MAX_ATTEMPT_COUNT = 2;
while ( !success && ++attemptCount <= MAX_ATTEMPT_COUNT ) {
if (isCancelled()) {
throw new TaskCancelledException(tempFile, "Cancelled before requesting " + tempFile.getAbsolutePath());
} else {
Log.i(t, "Started downloading to " + tempFile.getAbsolutePath() + " from " + downloadUrl);
}
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
// set up request...
HttpGet req = WebUtils.createOpenRosaHttpGet(uri);
req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);
HttpResponse response;
try {
response = httpclient.execute(req, localContext);
int statusCode = response.getStatusLine().getStatusCode();
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 errMsg =
Collect.getInstance().getString(R.string.file_fetch_failed, downloadUrl,
response.getStatusLine().getReasonPhrase(), statusCode);
Log.e(t, errMsg);
throw new Exception(errMsg);
}
// write connection to file
InputStream is = null;
OutputStream os = null;
try {
HttpEntity entity = response.getEntity();
is = entity.getContent();
Header contentEncoding = entity.getContentEncoding();
if ( contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING) ) {
is = new GZIPInputStream(is);
}
os = new FileOutputStream(tempFile);
byte buf[] = new byte[4096];
int len;
while ((len = is.read(buf)) > 0 && !isCancelled()) {
os.write(buf, 0, len);
}
os.flush();
success = true;
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
}
}
if (is != null) {
try {
// ensure stream is consumed...
final long count = 1024L;
while (is.skip(count) == count)
;
} catch (Exception e) {
// no-op
}
try {
is.close();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
Log.e(t, e.toString());
// silently retry unless this is the last attempt,
// in which case we rethrow the exception.
FileUtils.deleteAndReport(tempFile);
if ( attemptCount == MAX_ATTEMPT_COUNT ) {
throw e;
}
}
if (isCancelled()) {
FileUtils.deleteAndReport(tempFile);
throw new TaskCancelledException(tempFile, "Cancelled downloading of " + tempFile.getAbsolutePath());
}
}
Log.d(t, "Completed downloading of " + tempFile.getAbsolutePath() + ". It will be moved to the proper path...");
FileUtils.deleteAndReport(file);
String errorMessage = FileUtils.copyFile(tempFile, file);
if (file.exists()) {
Log.w(t, "Copied " + tempFile.getAbsolutePath() + " over " + file.getAbsolutePath());
FileUtils.deleteAndReport(tempFile);
} else {
String msg = Collect.getInstance().getString(R.string.fs_file_copy_error, tempFile.getAbsolutePath(), file.getAbsolutePath(), errorMessage);
Log.w(t, msg);
throw new RuntimeException(msg);
}
}
private static class UriResult {
private final Uri uri;
private final String mediaPath;
private final boolean isNew;
private UriResult(Uri uri, String mediaPath, boolean aNew) {
this.uri = uri;
this.mediaPath = mediaPath;
this.isNew = aNew;
}
private Uri getUri() {
return uri;
}
private String getMediaPath() {
return mediaPath;
}
private boolean isNew() {
return isNew;
}
}
private static class FileResult {
private final File file;
private final boolean isNew;
private FileResult(File file, boolean aNew) {
this.file = file;
isNew = aNew;
}
private File getFile() {
return file;
}
private boolean isNew() {
return isNew;
}
}
private static class MediaFile {
final String filename;
final String hash;
final String downloadUrl;
MediaFile(String filename, String hash, String downloadUrl) {
this.filename = filename;
this.hash = hash;
this.downloadUrl = downloadUrl;
}
}
private String downloadManifestAndMediaFiles(String tempMediaPath, String finalMediaPath, FormDetails fd, int count,
int total) throws Exception {
if (fd.manifestUrl == null)
return null;
publishProgress(Collect.getInstance().getString(R.string.fetching_manifest, fd.formName),
Integer.valueOf(count).toString(), Integer.valueOf(total).toString());
List<MediaFile> files = new ArrayList<MediaFile>();
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
DocumentFetchResult result =
WebUtils.getXmlDocument(fd.manifestUrl, localContext, httpclient);
if (result.errorMessage != null) {
return result.errorMessage;
}
String errMessage = Collect.getInstance().getString(R.string.access_error, fd.manifestUrl);
if (!result.isOpenRosaResponse) {
errMessage += Collect.getInstance().getString(R.string.manifest_server_error);
Log.e(t, errMessage);
return errMessage;
}
// Attempt OpenRosa 1.0 parsing
Element manifestElement = result.doc.getRootElement();
if (!manifestElement.getName().equals("manifest")) {
errMessage +=
Collect.getInstance().getString(R.string.root_element_error,
manifestElement.getName());
Log.e(t, errMessage);
return errMessage;
}
String namespace = manifestElement.getNamespace();
if (!isXformsManifestNamespacedElement(manifestElement)) {
errMessage += Collect.getInstance().getString(R.string.root_namespace_error, namespace);
Log.e(t, errMessage);
return errMessage;
}
int nElements = manifestElement.getChildCount();
for (int i = 0; i < nElements; ++i) {
if (manifestElement.getType(i) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element mediaFileElement = manifestElement.getElement(i);
if (!isXformsManifestNamespacedElement(mediaFileElement)) {
// someone else's extension?
continue;
}
String name = mediaFileElement.getName();
if (name.equalsIgnoreCase("mediaFile")) {
String filename = null;
String hash = null;
String downloadUrl = null;
// don't process descriptionUrl
int childCount = mediaFileElement.getChildCount();
for (int j = 0; j < childCount; ++j) {
if (mediaFileElement.getType(j) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element child = mediaFileElement.getElement(j);
if (!isXformsManifestNamespacedElement(child)) {
// someone else's extension?
continue;
}
String tag = child.getName();
if (tag.equals("filename")) {
filename = XFormParser.getXMLText(child, true);
if (filename != null && filename.length() == 0) {
filename = null;
}
} else if (tag.equals("hash")) {
hash = XFormParser.getXMLText(child, true);
if (hash != null && hash.length() == 0) {
hash = null;
}
} else if (tag.equals("downloadUrl")) {
downloadUrl = XFormParser.getXMLText(child, true);
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
}
}
if (filename == null || downloadUrl == null || hash == null) {
errMessage +=
Collect.getInstance().getString(R.string.manifest_tag_error,
Integer.toString(i));
Log.e(t, errMessage);
return errMessage;
}
files.add(new MediaFile(filename, hash, downloadUrl));
}
}
// OK we now have the full set of files to download...
Log.i(t, "Downloading " + files.size() + " media files.");
int mediaCount = 0;
if (files.size() > 0) {
File tempMediaDir = new File(tempMediaPath);
File finalMediaDir = new File(finalMediaPath);
FileUtils.checkMediaPath(tempMediaDir);
FileUtils.checkMediaPath(finalMediaDir);
for (MediaFile toDownload : files) {
++mediaCount;
publishProgress(
Collect.getInstance().getString(R.string.form_download_progress, fd.formName,
mediaCount, files.size()), Integer.valueOf(count).toString(), Integer
.valueOf(total).toString());
// try {
File finalMediaFile = new File(finalMediaDir, toDownload.filename);
File tempMediaFile = new File(tempMediaDir, toDownload.filename);
if (!finalMediaFile.exists()) {
downloadFile(tempMediaFile, toDownload.downloadUrl);
} else {
String currentFileHash = FileUtils.getMd5Hash(finalMediaFile);
String downloadFileHash = toDownload.hash.substring(MD5_COLON_PREFIX.length());
if (!currentFileHash.contentEquals(downloadFileHash)) {
// if the hashes match, it's the same file
// otherwise delete our current one and replace it with the new one
FileUtils.deleteAndReport(finalMediaFile);
downloadFile(tempMediaFile, toDownload.downloadUrl);
} else {
// exists, and the hash is the same
// no need to download it again
Log.i(t, "Skipping media file fetch -- file hashes identical: " + finalMediaFile.getAbsolutePath());
}
}
// } catch (Exception e) {
// return e.getLocalizedMessage();
// }
}
}
return null;
}
@Override
protected void onPostExecute(HashMap<FormDetails, String> value) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.formsDownloadingComplete(value);
}
}
}
@Override
protected void onProgressUpdate(String... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0],
Integer.valueOf(values[1]),
Integer.valueOf(values[2]));
}
}
}
public void setDownloaderListener(FormDownloaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/DownloadFormsTask.java
|
Java
|
asf20
| 28,203
|
/*
* 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.tasks;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.instance.InstanceInitializationFactory;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.instance.utils.DefaultAnswerResolver;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.RootTranslator;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.debug.Event;
import org.javarosa.debug.EventNotifier;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryModel;
import org.javarosa.xform.parse.XFormParseException;
import org.javarosa.xform.parse.XFormParser;
import org.javarosa.xform.util.XFormUtils;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ItemsetDbAdapter;
import org.odk.collect.android.external.ExternalAnswerResolver;
import org.odk.collect.android.external.ExternalDataHandler;
import org.odk.collect.android.external.ExternalDataManager;
import org.odk.collect.android.external.ExternalDataManagerImpl;
import org.odk.collect.android.external.ExternalDataReader;
import org.odk.collect.android.external.ExternalDataReaderImpl;
import org.odk.collect.android.external.handler.ExternalDataHandlerPull;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.logic.FileReferenceFactory;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.preferences.AdminPreferencesActivity;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.ZipUtils;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.util.Log;
import au.com.bytecode.opencsv.CSVReader;
/**
* Background task for loading a form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class FormLoaderTask extends AsyncTask<String, String, FormLoaderTask.FECWrapper> {
private final static String t = "FormLoaderTask";
private static final String ITEMSETS_CSV = "itemsets.csv";
private FormLoaderListener mStateListener;
private String mErrorMsg;
private String mInstancePath;
private final String mXPath;
private final String mWaitingXPath;
private boolean pendingActivityResult = false;
private int requestCode = 0;
private int resultCode = 0;
private Intent intent = null;
private ExternalDataManager externalDataManager;
protected class FECWrapper {
FormController controller;
boolean usedSavepoint;
protected FECWrapper(FormController controller, boolean usedSavepoint) {
this.controller = controller;
this.usedSavepoint = usedSavepoint;
}
protected FormController getController() {
return controller;
}
protected boolean hasUsedSavepoint() {
return usedSavepoint;
}
protected void free() {
controller = null;
}
}
FECWrapper data;
public FormLoaderTask(String instancePath, String XPath, String waitingXPath) {
mInstancePath = instancePath;
mXPath = XPath;
mWaitingXPath = waitingXPath;
}
/**
* Initialize {@link FormEntryController} with {@link FormDef} from binary or
* from XML. If given an instance, it will be used to fill the {@link FormDef}
* .
*/
@Override
protected FECWrapper doInBackground(String... path) {
FormEntryController fec = null;
FormDef fd = null;
FileInputStream fis = null;
mErrorMsg = null;
String formPath = path[0];
File formXml = new File(formPath);
String formHash = FileUtils.getMd5Hash(formXml);
File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");
publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));
FormDef.EvalBehavior mode = AdminPreferencesActivity.getConfiguredFormProcessingLogic(Collect.getInstance());
FormDef.setEvalBehavior(mode);
// FormDef.setDefaultEventNotifier(new EventNotifier() {
//
// @Override
// public void publishEvent(Event event) {
// Log.d("FormDef", event.asLogLine());
// }
// });
if (formBin.exists()) {
// if we have binary, deserialize binary
Log.i(
t,
"Attempting to load " + formXml.getName() + " from cached file: "
+ formBin.getAbsolutePath());
fd = deserializeFormDef(formBin);
if (fd == null) {
// some error occured with deserialization. Remove the file, and make a
// new .formdef
// from xml
Log.w(t, "Deserialization FAILED! Deleting cache file: " + formBin.getAbsolutePath());
formBin.delete();
}
}
if (fd == null) {
// no binary, read from xml
try {
Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
fis = new FileInputStream(formXml);
fd = XFormUtils.getFormFromInputStream(fis);
if (fd == null) {
mErrorMsg = "Error reading XForm file";
} else {
serializeFormDef(fd, formPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
mErrorMsg = e.getMessage();
} catch (XFormParseException e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} catch (Exception e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} finally {
IOUtils.closeQuietly(fis);
}
}
if (mErrorMsg != null || fd == null) {
return null;
}
// set paths to /sdcard/odk/forms/formfilename-media/
String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
File formMediaDir = new File(formXml.getParent(), formFileName + "-media");
externalDataManager = new ExternalDataManagerImpl(formMediaDir);
// add external data function handlers
ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
fd.getEvaluationContext().addFunctionHandler(externalDataHandlerPull);
try {
loadExternalData(formMediaDir);
} catch (Exception e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
return null;
}
if (isCancelled()) {
// that means that the user has cancelled, so no need to go further
return null;
}
// create FormEntryController from formdef
FormEntryModel fem = new FormEntryModel(fd);
fec = new FormEntryController(fem);
boolean usedSavepoint = false;
try {
// import existing data into formdef
if (mInstancePath != null) {
File instance = new File(mInstancePath);
File shadowInstance = SaveToDiskTask.savepointFile(instance);
if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
// the savepoint is newer than the saved value of the instance.
// use it.
usedSavepoint = true;
instance = shadowInstance;
Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
}
if (instance.exists()) {
// This order is important. Import data, then initialize.
try {
importData(instance, fec);
fd.initialize(false, new InstanceInitializationFactory());
} catch (RuntimeException e) {
Log.e(t, e.getMessage(), e);
// SCTO-633
if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
// this means that the .save file is corrupted or 0-sized, so
// don't use it.
usedSavepoint = false;
mInstancePath = null;
fd.initialize(true, new InstanceInitializationFactory());
} else {
// this means that the saved instance is corrupted.
throw e;
}
}
} else {
fd.initialize(true, new InstanceInitializationFactory());
}
} else {
fd.initialize(true, new InstanceInitializationFactory());
}
} catch (RuntimeException e) {
Log.e(t, e.getMessage(), e);
if (e.getCause() instanceof XPathTypeMismatchException) {
// this is a case of
// https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
// the data are imported, the survey will be unusable
// but we should give the option to the user to edit the form
// otherwise the survey will be TOTALLY inaccessible.
Log.w(
t,
"We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
} else {
mErrorMsg = e.getMessage();
return null;
}
}
// Remove previous forms
ReferenceManager._().clearSession();
// for itemsets.csv, we only check to see if the itemset file has been
// updated
File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
String csvmd5 = null;
if (csv.exists()) {
csvmd5 = FileUtils.getMd5Hash(csv);
boolean readFile = false;
ItemsetDbAdapter ida = new ItemsetDbAdapter();
ida.open();
// get the database entry (if exists) for this itemsets.csv, based
// on the path
Cursor c = ida.getItemsets(csv.getAbsolutePath());
if (c != null) {
if (c.getCount() == 1) {
c.moveToFirst(); // should be only one, ever, if any
String oldmd5 = c.getString(c.getColumnIndex("hash"));
if (oldmd5.equals(csvmd5)) {
// they're equal, do nothing
} else {
// the csv has been updated, delete the old entries
ida.dropTable(ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()),
csv.getAbsolutePath());
// and read the new
readFile = true;
}
} else {
// new csv, add it
readFile = true;
}
c.close();
}
ida.close();
if (readFile) {
readCSV(csv, csvmd5, ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()));
}
}
// This should get moved to the Application Class
if (ReferenceManager._().getFactories().length == 0) {
// this is /sdcard/odk
ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
}
// Set jr://... to point to /sdcard/odk/forms/filename-media/
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));
// clean up vars
fis = null;
fd = null;
formBin = null;
formXml = null;
formPath = null;
FormController fc = new FormController(formMediaDir, fec, mInstancePath == null ? null
: new File(mInstancePath));
if (mXPath != null) {
// we are resuming after having terminated -- set index to this
// position...
FormIndex idx = fc.getIndexFromXPath(mXPath);
fc.jumpToIndex(idx);
}
if (mWaitingXPath != null) {
FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
fc.setIndexWaitingForData(idx);
}
data = new FECWrapper(fc, usedSavepoint);
return data;
}
@SuppressWarnings("unchecked")
private void loadExternalData(File mediaFolder) {
// SCTO-594
File[] zipFiles = mediaFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".zip");
}
});
if (zipFiles != null) {
ZipUtils.unzip(zipFiles);
for (File zipFile : zipFiles) {
boolean deleted = zipFile.delete();
if (!deleted) {
Log.w(t, "Cannot delete " + zipFile + ". It will be re-unzipped next time. :(");
}
}
}
File[] csvFiles = mediaFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
String lowerCaseName = file.getName().toLowerCase();
return lowerCaseName.endsWith(".csv") && !lowerCaseName.equalsIgnoreCase(ITEMSETS_CSV);
}
});
Map<String, File> externalDataMap = new HashMap<String, File>();
if (csvFiles != null) {
for (File csvFile : csvFiles) {
String dataSetName = csvFile.getName().substring(0, csvFile.getName().lastIndexOf("."));
externalDataMap.put(dataSetName, csvFile);
}
if (externalDataMap.size() > 0) {
publishProgress(Collect.getInstance()
.getString(R.string.survey_loading_reading_csv_message));
ExternalDataReader externalDataReader = new ExternalDataReaderImpl(this);
externalDataReader.doImport(externalDataMap);
}
}
}
public void publishExternalDataLoadingProgress(String message) {
publishProgress(message);
}
@Override
protected void onProgressUpdate(String... values) {
synchronized (this) {
if (mStateListener != null && values != null) {
if (values.length == 1) {
mStateListener.onProgressStep(values[0]);
}
}
}
}
public boolean importData(File instanceFile, FormEntryController fec) {
publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_data_message));
// convert files into a byte array
byte[] fileBytes = FileUtils.getFileAsBytes(instanceFile);
// get the root of the saved and template instances
TreeElement savedRoot = XFormParser.restoreDataModel(fileBytes, null).getRoot();
TreeElement templateRoot = fec.getModel().getForm().getInstance().getRoot().deepCopy(true);
// weak check for matching forms
if (!savedRoot.getName().equals(templateRoot.getName()) || savedRoot.getMult() != 0) {
Log.e(t, "Saved form instance does not match template form definition");
return false;
} else {
// populate the data model
TreeReference tr = TreeReference.rootRef();
tr.add(templateRoot.getName(), TreeReference.INDEX_UNBOUND);
// Here we set the Collect's implementation of the IAnswerResolver.
// We set it back to the default after select choices have been populated.
XFormParser.setAnswerResolver(new ExternalAnswerResolver());
templateRoot.populate(savedRoot, fec.getModel().getForm());
XFormParser.setAnswerResolver(new DefaultAnswerResolver());
// populated model to current form
fec.getModel().getForm().getInstance().setRoot(templateRoot);
// fix any language issues
// :
// http://bitbucket.org/javarosa/main/issue/5/itext-n-appearing-in-restored-instances
if (fec.getModel().getLanguages() != null) {
fec.getModel().getForm()
.localeChanged(fec.getModel().getLanguage(), fec.getModel().getForm().getLocalizer());
}
return true;
}
}
/**
* Read serialized {@link FormDef} from file and recreate as object.
*
* @param formDef
* serialized FormDef file
* @return {@link FormDef} object
*/
public FormDef deserializeFormDef(File formDef) {
// TODO: any way to remove reliance on jrsp?
FileInputStream fis = null;
FormDef fd = null;
try {
// create new form def
fd = new FormDef();
fis = new FileInputStream(formDef);
DataInputStream dis = new DataInputStream(fis);
// read serialized formdef into new formdef
fd.readExternal(dis, ExtUtil.defaultPrototypes());
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
fd = null;
} catch (IOException e) {
e.printStackTrace();
fd = null;
} catch (DeserializationException e) {
e.printStackTrace();
fd = null;
} catch (Exception e) {
e.printStackTrace();
fd = null;
}
return fd;
}
/**
* Write the FormDef to the file system as a binary blog.
*
* @param filepath
* path to the form file
*/
public void serializeFormDef(FormDef fd, String filepath) {
// calculate unique md5 identifier
String hash = FileUtils.getMd5Hash(new File(filepath));
File formDef = new File(Collect.CACHE_PATH + File.separator + hash + ".formdef");
// formdef does not exist, create one.
if (!formDef.exists()) {
FileOutputStream fos;
try {
fos = new FileOutputStream(formDef);
DataOutputStream dos = new DataOutputStream(fos);
fd.writeExternal(dos);
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void onCancelled() {
super.onCancelled();
if (externalDataManager != null) {
externalDataManager.close();
}
}
@Override
protected void onPostExecute(FECWrapper wrapper) {
synchronized (this) {
try {
if (mStateListener != null) {
if (wrapper == null) {
mStateListener.loadingError(mErrorMsg);
} else {
mStateListener.loadingComplete(this);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void setFormLoaderListener(FormLoaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
public FormController getFormController() {
return (data != null) ? data.getController() : null;
}
public ExternalDataManager getExternalDataManager() {
return externalDataManager;
}
public boolean hasUsedSavepoint() {
return (data != null) ? data.hasUsedSavepoint() : false;
}
public void destroy() {
if (data != null) {
data.free();
data = null;
}
}
public boolean hasPendingActivityResult() {
return pendingActivityResult;
}
public int getRequestCode() {
return requestCode;
}
public int getResultCode() {
return resultCode;
}
public Intent getIntent() {
return intent;
}
public void setActivityResult(int requestCode, int resultCode, Intent intent) {
this.pendingActivityResult = true;
this.requestCode = requestCode;
this.resultCode = resultCode;
this.intent = intent;
}
private void readCSV(File csv, String formHash, String pathHash) {
CSVReader reader;
ItemsetDbAdapter ida = new ItemsetDbAdapter();
ida.open();
boolean withinTransaction = false;
try {
reader = new CSVReader(new FileReader(csv));
String[] nextLine;
String[] columnHeaders = null;
int lineNumber = 0;
while ((nextLine = reader.readNext()) != null) {
lineNumber++;
if (lineNumber == 1) {
// first line of csv is column headers
columnHeaders = nextLine;
ida.createTable(formHash, pathHash, columnHeaders,
csv.getAbsolutePath());
continue;
}
// add the rest of the lines to the specified database
// nextLine[] is an array of values from the line
// System.out.println(nextLine[4] + "etc...");
if (lineNumber == 2) {
// start a transaction for the inserts
withinTransaction = true;
ida.beginTransaction();
}
ida.addRow(pathHash, columnHeaders, nextLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if ( withinTransaction ) {
ida.commit();
}
ida.close();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/FormLoaderTask.java
|
Java
|
asf20
| 21,390
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.tasks;
/**
*
* Author: Meletis Margaritis
* Date: 15/3/2013
* Time: 2:53 μμ
*/
public class SaveResult {
private int saveResult;
private String saveErrorMessage;
public int getSaveResult() {
return saveResult;
}
public void setSaveResult(int saveResult) {
this.saveResult = saveResult;
}
public void setSaveErrorMessage(String saveErrorMessage) {
this.saveErrorMessage = saveErrorMessage;
}
public String getSaveErrorMessage() {
return saveErrorMessage;
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/SaveResult.java
|
Java
|
asf20
| 1,299
|
/*
* 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.tasks;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteInstancesListener;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.content.ContentResolver;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Task responsible for deleting selected instances.
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*
*/
public class DeleteInstancesTask extends AsyncTask<Long, Void, Integer> {
private static final String t = "DeleteInstancesTask";
private ContentResolver cr;
private DeleteInstancesListener dl;
private int successCount = 0;
@Override
protected Integer doInBackground(Long... params) {
int deleted = 0;
if (params == null ||cr == null || dl == null) {
return deleted;
}
// delete files from database and then from file system
for (int i = 0; i < params.length; i++) {
if ( isCancelled() ) {
break;
}
try {
Uri deleteForm =
Uri.withAppendedPath(InstanceColumns.CONTENT_URI, params[i].toString());
int wasDeleted = cr.delete(deleteForm, null, null);
deleted += wasDeleted;
if (wasDeleted > 0) {
Collect.getInstance().getActivityLogger().logAction(this, "delete", deleteForm.toString());
}
} catch ( Exception ex ) {
Log.e(t,"Exception during delete of: " + params[i].toString() + " exception: " + ex.toString());
}
}
successCount = deleted;
return deleted;
}
@Override
protected void onPostExecute(Integer result) {
cr = null;
if (dl != null) {
dl.deleteComplete(result);
}
super.onPostExecute(result);
}
@Override
protected void onCancelled() {
cr = null;
if (dl != null) {
dl.deleteComplete(successCount);
}
}
public void setDeleteListener(DeleteInstancesListener listener) {
dl = listener;
}
public void setContentResolver(ContentResolver resolver){
cr = resolver;
}
public int getDeleteCount() {
return successCount;
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/DeleteInstancesTask.java
|
Java
|
asf20
| 2,910
|
/*
* 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.tasks;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
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.utilities.FileUtils;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for adding to the forms content provider, any forms that have been added to the
* sdcard manually. Returns immediately if it detects an error.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class DiskSyncTask extends AsyncTask<Void, String, String> {
private final static String t = "DiskSyncTask";
private static int counter = 0;
int instance;
DiskSyncListener mListener;
String statusMessage;
private static class UriFile {
public final Uri uri;
public final File file;
UriFile(Uri uri, File file) {
this.uri = uri;
this.file = file;
}
}
@Override
protected String doInBackground(Void... params) {
instance = ++counter; // roughly track the scan # we're on... logging use only
Log.i(t, "["+instance+"] doInBackground begins!");
try {
// Process everything then report what didn't work.
StringBuffer errors = new StringBuffer();
File formDir = new File(Collect.FORMS_PATH);
if (formDir.exists() && formDir.isDirectory()) {
// Get all the files in the /odk/foms directory
List<File> xFormsToAdd = new LinkedList<File>();
// Step 1: assemble the candidate form files
// discard files beginning with "."
// discard files not ending with ".xml" or ".xhtml"
{
File[] formDefs = formDir.listFiles();
for ( File addMe: formDefs ) {
// Ignore invisible files that start with periods.
if (!addMe.getName().startsWith(".")
&& (addMe.getName().endsWith(".xml") || addMe.getName().endsWith(".xhtml"))) {
xFormsToAdd.add(addMe);
} else {
Log.i(t, "["+instance+"] Ignoring: " + addMe.getAbsolutePath());
}
}
}
// Step 2: quickly run through and figure out what files we need to
// parse and update; this is quick, as we only calculate the md5
// and see if it has changed.
List<UriFile> uriToUpdate = new ArrayList<UriFile>();
Cursor mCursor = null;
// open the cursor within a try-catch block so it can always be closed.
try {
mCursor = Collect.getInstance().getContentResolver()
.query(FormsColumns.CONTENT_URI, null, null, null, null);
if (mCursor == null) {
Log.e(t, "["+instance+"] Forms Content Provider returned NULL");
errors.append("Internal Error: Unable to access Forms content provider").append("\r\n");
return errors.toString();
}
mCursor.moveToPosition(-1);
while (mCursor.moveToNext()) {
// For each element in the provider, see if the file already exists
String sqlFilename =
mCursor.getString(mCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
String md5 = mCursor.getString(mCursor.getColumnIndex(FormsColumns.MD5_HASH));
File sqlFile = new File(sqlFilename);
if (sqlFile.exists()) {
// remove it from the list of forms (we only want forms
// we haven't added at the end)
xFormsToAdd.remove(sqlFile);
if (!FileUtils.getMd5Hash(sqlFile).contentEquals(md5)) {
// Probably someone overwrite the file on the sdcard
// So re-parse it and update it's information
String id = mCursor.getString(mCursor.getColumnIndex(FormsColumns._ID));
Uri updateUri = Uri.withAppendedPath(FormsColumns.CONTENT_URI, id);
uriToUpdate.add(new UriFile(updateUri, sqlFile));
}
} else {
Log.w(t, "["+instance+"] file referenced by content provider does not exist " + sqlFile);
}
}
} finally {
if ( mCursor != null ) {
mCursor.close();
}
}
// Step3: go through uriToUpdate to parse and update each in turn.
// This is slow because buildContentValues(...) is slow.
Collections.shuffle(uriToUpdate); // Big win if multiple DiskSyncTasks running
for ( UriFile entry : uriToUpdate ) {
Uri updateUri = entry.uri;
File formDefFile = entry.file;
// Probably someone overwrite the file on the sdcard
// So re-parse it and update it's information
ContentValues values;
try {
values = buildContentValues(formDefFile);
} catch ( IllegalArgumentException e) {
errors.append(e.getMessage()).append("\r\n");
File badFile = new File(formDefFile.getParentFile(), formDefFile.getName() + ".bad");
badFile.delete();
formDefFile.renameTo(badFile);
continue;
}
// update in content provider
int count =
Collect.getInstance().getContentResolver()
.update(updateUri, values, null, null);
Log.i(t, "["+instance+"] " + count + " records successfully updated");
}
uriToUpdate.clear();
// Step 4: go through the newly-discovered files in xFormsToAdd and add them.
// This is slow because buildContentValues(...) is slow.
//
Collections.shuffle(xFormsToAdd); // Big win if multiple DiskSyncTasks running
while ( !xFormsToAdd.isEmpty() ) {
File formDefFile = xFormsToAdd.remove(0);
// Since parsing is so slow, if there are multiple tasks,
// they may have already updated the database.
// Skip this file if that is the case.
if ( isAlreadyDefined(formDefFile) ) {
Log.i(t, "["+instance+"] skipping -- definition already recorded: " + formDefFile.getAbsolutePath());
continue;
}
// Parse it for the first time...
ContentValues values;
try {
values = buildContentValues(formDefFile);
} catch ( IllegalArgumentException e) {
errors.append(e.getMessage()).append("\r\n");
File badFile = new File(formDefFile.getParentFile(), formDefFile.getName() + ".bad");
badFile.delete();
formDefFile.renameTo(badFile);
continue;
}
// insert into content provider
try {
// insert failures are OK and expected if multiple
// DiskSync scanners are active.
Collect.getInstance().getContentResolver()
.insert(FormsColumns.CONTENT_URI, values);
} catch ( SQLException e ) {
Log.i(t, "["+instance+"] " + e.toString());
}
}
}
if ( errors.length() != 0 ) {
statusMessage = errors.toString();
} else {
statusMessage = Collect.getInstance().getString(R.string.finished_disk_scan);
}
return statusMessage;
} finally {
Log.i(t, "["+instance+"] doInBackground ends!");
}
}
private boolean isAlreadyDefined(File formDefFile) {
// first try to see if a record with this filename already exists...
String[] projection = {
FormsColumns._ID, FormsColumns.FORM_FILE_PATH
};
String[] selectionArgs = { formDefFile.getAbsolutePath() };
String selection = FormsColumns.FORM_FILE_PATH + "=?";
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver()
.query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null);
return ( c.getCount() > 0 );
} finally {
if ( c != null ) {
c.close();
}
}
}
public String getStatusMessage() {
return statusMessage;
}
/**
* Attempts to parse the formDefFile as an XForm.
* This is slow because FileUtils.parseXML is slow
*
* @param formDefFile
* @return key-value list to update or insert into the content provider
* @throws IllegalArgumentException if the file failed to parse or was missing fields
*/
public ContentValues buildContentValues(File formDefFile) throws IllegalArgumentException {
// Probably someone overwrite the file on the sdcard
// So re-parse it and update it's information
ContentValues updateValues = new ContentValues();
HashMap<String, String> fields = null;
try {
fields = FileUtils.parseXML(formDefFile);
} catch (RuntimeException e) {
throw new IllegalArgumentException(formDefFile.getName() + " :: " + e.toString());
}
String title = fields.get(FileUtils.TITLE);
String version = fields.get(FileUtils.VERSION);
String formid = fields.get(FileUtils.FORMID);
String submission = fields.get(FileUtils.SUBMISSIONURI);
String base64RsaPublicKey = fields.get(FileUtils.BASE64_RSA_PUBLIC_KEY);
// update date
Long now = Long.valueOf(System.currentTimeMillis());
updateValues.put(FormsColumns.DATE, now);
if (title != null) {
updateValues.put(FormsColumns.DISPLAY_NAME, title);
} else {
throw new IllegalArgumentException(Collect.getInstance().getString(R.string.xform_parse_error,
formDefFile.getName(), "title"));
}
if (formid != null) {
updateValues.put(FormsColumns.JR_FORM_ID, formid);
} else {
throw new IllegalArgumentException(Collect.getInstance().getString(R.string.xform_parse_error,
formDefFile.getName(), "id"));
}
if (version != null) {
updateValues.put(FormsColumns.JR_VERSION, version);
}
if (submission != null) {
updateValues.put(FormsColumns.SUBMISSION_URI, submission);
}
if (base64RsaPublicKey != null) {
updateValues.put(FormsColumns.BASE64_RSA_PUBLIC_KEY, base64RsaPublicKey);
}
// Note, the path doesn't change here, but it needs to be included so the
// update will automatically update the .md5 and the cache path.
updateValues.put(FormsColumns.FORM_FILE_PATH, formDefFile.getAbsolutePath());
return updateValues;
}
public void setDiskSyncListener(DiskSyncListener l) {
mListener = l;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (mListener != null) {
mListener.SyncComplete(result);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/DiskSyncTask.java
|
Java
|
asf20
| 12,436
|
/*
* 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.tasks;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Element;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
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.utilities.DocumentFetchResult;
import org.odk.collect.android.utilities.WebUtils;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.HashMap;
/**
* Background task for downloading forms from urls or a formlist from a url. We overload this task a
* bit so that we don't have to keep track of two separate downloading tasks and it simplifies
* interfaces. If LIST_URL is passed to doInBackground(), we fetch a form list. If a hashmap
* containing form/url pairs is passed, we download those forms.
*
* @author carlhartung
*/
public class DownloadFormListTask extends AsyncTask<Void, String, HashMap<String, FormDetails>> {
private static final String t = "DownloadFormsTask";
// used to store error message if one occurs
public static final String DL_ERROR_MSG = "dlerrormessage";
public static final String DL_AUTH_REQUIRED = "dlauthrequired";
private FormListDownloaderListener mStateListener;
private static final String NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_LIST =
"http://openrosa.org/xforms/xformsList";
private boolean isXformsListNamespacedElement(Element e) {
return e.getNamespace().equalsIgnoreCase(NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_LIST);
}
@Override
protected HashMap<String, FormDetails> doInBackground(Void... values) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getBaseContext());
String downloadListUrl =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
Collect.getInstance().getString(R.string.default_server_url));
// NOTE: /formlist must not be translated! It is the well-known path on the server.
String formListUrl = Collect.getInstance().getApplicationContext().getString(R.string.default_odk_formlist);
String downloadPath = settings.getString(PreferencesActivity.KEY_FORMLIST_URL, formListUrl);
downloadListUrl += downloadPath;
Collect.getInstance().getActivityLogger().logAction(this, formListUrl, downloadListUrl);
// We populate this with available forms from the specified server.
// <formname, details>
HashMap<String, FormDetails> formList = new HashMap<String, FormDetails>();
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
DocumentFetchResult result =
WebUtils.getXmlDocument(downloadListUrl, localContext, httpclient);
// If we can't get the document, return the error, cancel the task
if (result.errorMessage != null) {
if (result.responseCode == 401) {
formList.put(DL_AUTH_REQUIRED, new FormDetails(result.errorMessage));
} else {
formList.put(DL_ERROR_MSG, new FormDetails(result.errorMessage));
}
return formList;
}
if (result.isOpenRosaResponse) {
// Attempt OpenRosa 1.0 parsing
Element xformsElement = result.doc.getRootElement();
if (!xformsElement.getName().equals("xforms")) {
String error = "root element is not <xforms> : " + xformsElement.getName();
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
String namespace = xformsElement.getNamespace();
if (!isXformsListNamespacedElement(xformsElement)) {
String error = "root element namespace is incorrect:" + namespace;
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
int nElements = xformsElement.getChildCount();
for (int i = 0; i < nElements; ++i) {
if (xformsElement.getType(i) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element xformElement = (Element) xformsElement.getElement(i);
if (!isXformsListNamespacedElement(xformElement)) {
// someone else's extension?
continue;
}
String name = xformElement.getName();
if (!name.equalsIgnoreCase("xform")) {
// someone else's extension?
continue;
}
// this is something we know how to interpret
String formId = null;
String formName = null;
String version = null;
String majorMinorVersion = null;
String description = null;
String downloadUrl = null;
String manifestUrl = null;
// don't process descriptionUrl
int fieldCount = xformElement.getChildCount();
for (int j = 0; j < fieldCount; ++j) {
if (xformElement.getType(j) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = xformElement.getElement(j);
if (!isXformsListNamespacedElement(child)) {
// someone else's extension?
continue;
}
String tag = child.getName();
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
} else if (tag.equals("name")) {
formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
} else if (tag.equals("version")) {
version = XFormParser.getXMLText(child, true);
if (version != null && version.length() == 0) {
version = null;
}
} else if (tag.equals("majorMinorVersion")) {
majorMinorVersion = XFormParser.getXMLText(child, true);
if (majorMinorVersion != null && majorMinorVersion.length() == 0) {
majorMinorVersion = null;
}
} else if (tag.equals("descriptionText")) {
description = XFormParser.getXMLText(child, true);
if (description != null && description.length() == 0) {
description = null;
}
} else if (tag.equals("downloadUrl")) {
downloadUrl = XFormParser.getXMLText(child, true);
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
} else if (tag.equals("manifestUrl")) {
manifestUrl = XFormParser.getXMLText(child, true);
if (manifestUrl != null && manifestUrl.length() == 0) {
manifestUrl = null;
}
}
}
if (formId == null || downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing one or more tags: formId, name, or downloadUrl";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
formList.put(formId, new FormDetails(formName, downloadUrl, manifestUrl, formId, (version != null) ? version : majorMinorVersion));
}
} else {
// Aggregate 0.9.x mode...
// populate HashMap with form names and urls
Element formsElement = result.doc.getRootElement();
int formsCount = formsElement.getChildCount();
String formId = null;
for (int i = 0; i < formsCount; ++i) {
if (formsElement.getType(i) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = formsElement.getElement(i);
String tag = child.getName();
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
}
if (tag.equalsIgnoreCase("form")) {
String formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
String downloadUrl = child.getAttributeValue(null, "url");
downloadUrl = downloadUrl.trim();
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
if (downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing form name or url attribute";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_legacy_formlist_failed, error)));
return formList;
}
formList.put(formName, new FormDetails(formName, downloadUrl, null, formId, null));
formId = null;
}
}
}
return formList;
}
@Override
protected void onPostExecute(HashMap<String, FormDetails> value) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.formListDownloadingComplete(value);
}
}
}
public void setDownloaderListener(FormListDownloaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/DownloadFormListTask.java
|
Java
|
asf20
| 12,643
|
/*
* 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.tasks;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.javarosa.form.api.FormEntryController;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.EncryptionException;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.logic.FormController;
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.utilities.EncryptionUtils;
import org.odk.collect.android.utilities.EncryptionUtils.EncryptedFormInformation;
import org.odk.collect.android.utilities.FileUtils;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for loading a form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SaveToDiskTask extends AsyncTask<Void, String, SaveResult> {
private final static String t = "SaveToDiskTask";
private FormSavedListener mSavedListener;
private Boolean mSave;
private Boolean mMarkCompleted;
private Uri mUri;
private String mInstanceName;
public static final int SAVED = 500;
public static final int SAVE_ERROR = 501;
public static final int VALIDATE_ERROR = 502;
public static final int VALIDATED = 503;
public static final int SAVED_AND_EXIT = 504;
public SaveToDiskTask(Uri uri, Boolean saveAndExit, Boolean markCompleted, String updatedName) {
mUri = uri;
mSave = saveAndExit;
mMarkCompleted = markCompleted;
mInstanceName = updatedName;
}
/**
* Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
* an instance, it will be used to fill the {@link FormDef}.
*/
@Override
protected SaveResult doInBackground(Void... nothing) {
SaveResult saveResult = new SaveResult();
FormController formController = Collect.getInstance().getFormController();
publishProgress(Collect.getInstance().getString(R.string.survey_saving_validating_message));
try {
int validateStatus = formController.validateAnswers(mMarkCompleted);
if (validateStatus != FormEntryController.ANSWER_OK) {
// validation failed, pass specific failure
saveResult.setSaveResult(validateStatus);
return saveResult;
}
} catch (Exception e) {
Log.e(t, e.getMessage(), e);
// SCTO-825
// that means that we have a bad design
// save the exception to be used in the error dialog.
saveResult.setSaveErrorMessage(e.getMessage());
saveResult.setSaveResult(SAVE_ERROR);
return saveResult;
}
// check if the "Cancel" was hit and exit.
if (isCancelled()) {
return null;
}
if (mMarkCompleted) {
formController.postProcessInstance();
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "save", Boolean.toString(mMarkCompleted));
// close all open databases of external data.
Collect.getInstance().getExternalDataManager().close();
// if there is a meta/instanceName field, be sure we are using the latest value
// just in case the validate somehow triggered an update.
String updatedSaveName = formController.getSubmissionMetadata().instanceName;
if ( updatedSaveName != null ) {
mInstanceName = updatedSaveName;
}
try {
exportData(mMarkCompleted);
// attempt to remove any scratch file
File shadowInstance = savepointFile(formController.getInstancePath());
if (shadowInstance.exists()) {
FileUtils.deleteAndReport(shadowInstance);
}
saveResult.setSaveResult(mSave ? SAVED_AND_EXIT : SAVED);
} catch (Exception e) {
Log.e(t, e.getMessage(), e);
saveResult.setSaveErrorMessage(e.getMessage());
saveResult.setSaveResult(SAVE_ERROR);
}
return saveResult;
}
private void updateInstanceDatabase(boolean incomplete, boolean canEditAfterCompleted) {
FormController formController = Collect.getInstance().getFormController();
// Update the instance database...
ContentValues values = new ContentValues();
if (mInstanceName != null) {
values.put(InstanceColumns.DISPLAY_NAME, mInstanceName);
}
if (incomplete || !mMarkCompleted) {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
} else {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_COMPLETE);
}
// update this whether or not the status is complete...
values.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, Boolean.toString(canEditAfterCompleted));
// If FormEntryActivity was started with an Instance, just update that instance
if (Collect.getInstance().getContentResolver().getType(mUri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) {
int updated = Collect.getInstance().getContentResolver().update(mUri, values, null, null);
if (updated > 1) {
Log.w(t, "Updated more than one entry, that's not good: " + mUri.toString());
} else if (updated == 1) {
Log.i(t, "Instance successfully updated");
} else {
Log.e(t, "Instance doesn't exist but we have its Uri!! " + mUri.toString());
}
} else if (Collect.getInstance().getContentResolver().getType(mUri).equals(FormsColumns.CONTENT_ITEM_TYPE)) {
// If FormEntryActivity was started with a form, then it's likely the first time we're
// saving.
// However, it could be a not-first time saving if the user has been using the manual
// 'save data' option from the menu. So try to update first, then make a new one if that
// fails.
String instancePath = formController.getInstancePath().getAbsolutePath();
String where = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] whereArgs = {
instancePath
};
int updated =
Collect.getInstance().getContentResolver()
.update(InstanceColumns.CONTENT_URI, values, where, whereArgs);
if (updated > 1) {
Log.w(t, "Updated more than one entry, that's not good: " + instancePath);
} else if (updated == 1) {
Log.i(t, "Instance found and successfully updated: " + instancePath);
// already existed and updated just fine
} else {
Log.i(t, "No instance found, creating");
// Entry didn't exist, so create it.
Cursor c = null;
try {
// retrieve the form definition...
c = Collect.getInstance().getContentResolver().query(mUri, null, null, null, null);
c.moveToFirst();
String jrformid = c.getString(c.getColumnIndex(FormsColumns.JR_FORM_ID));
String jrversion = c.getString(c.getColumnIndex(FormsColumns.JR_VERSION));
String formname = c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME));
String submissionUri = null;
if ( !c.isNull(c.getColumnIndex(FormsColumns.SUBMISSION_URI)) ) {
submissionUri = c.getString(c.getColumnIndex(FormsColumns.SUBMISSION_URI));
}
// add missing fields into values
values.put(InstanceColumns.INSTANCE_FILE_PATH, instancePath);
values.put(InstanceColumns.SUBMISSION_URI, submissionUri);
if (mInstanceName != null) {
values.put(InstanceColumns.DISPLAY_NAME, mInstanceName);
} else {
values.put(InstanceColumns.DISPLAY_NAME, formname);
}
values.put(InstanceColumns.JR_FORM_ID, jrformid);
values.put(InstanceColumns.JR_VERSION, jrversion);
} finally {
if ( c != null ) {
c.close();
}
}
mUri = Collect.getInstance().getContentResolver()
.insert(InstanceColumns.CONTENT_URI, values);
}
}
}
/**
* Return the name of the savepoint file for a given instance.
*
* @param instancePath
* @return
*/
public static File savepointFile(File instancePath) {
File tempDir = new File(Collect.CACHE_PATH);
return new File(tempDir, instancePath.getName() + ".save");
}
/**
* Write's the data to the sdcard, and updates the instances content provider.
* In theory we don't have to write to disk, and this is where you'd add
* other methods.
*
* @param markCompleted
* @return
*/
private void exportData(boolean markCompleted) throws IOException, EncryptionException {
FormController formController = Collect.getInstance().getFormController();
publishProgress(Collect.getInstance().getString(R.string.survey_saving_collecting_message));
ByteArrayPayload payload = formController.getFilledInFormXml();
// write out xml
String instancePath = formController.getInstancePath().getAbsolutePath();
publishProgress(Collect.getInstance().getString(R.string.survey_saving_saving_message));
exportXmlFile(payload, instancePath);
// update the mUri. We have exported the reloadable instance, so update status...
// Since we saved a reloadable instance, it is flagged as re-openable so that if any error
// occurs during the packaging of the data for the server fails (e.g., encryption),
// we can still reopen the filled-out form and re-save it at a later time.
updateInstanceDatabase(true, true);
if ( markCompleted ) {
// now see if the packaging of the data for the server would make it
// non-reopenable (e.g., encryption or send an SMS or other fraction of the form).
boolean canEditAfterCompleted = formController.isSubmissionEntireForm();
boolean isEncrypted = false;
// build a submission.xml to hold the data being submitted
// and (if appropriate) encrypt the files on the side
// pay attention to the ref attribute of the submission profile...
File instanceXml = formController.getInstancePath();
File submissionXml = new File(instanceXml.getParentFile(), "submission.xml");
payload = formController.getSubmissionXml();
// write out submission.xml -- the data to actually submit to aggregate
publishProgress(Collect.getInstance().getString(R.string.survey_saving_finalizing_message));
exportXmlFile(payload, submissionXml.getAbsolutePath());
// see if the form is encrypted and we can encrypt it...
EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(mUri,
formController.getSubmissionMetadata());
if ( formInfo != null ) {
// if we are encrypting, the form cannot be reopened afterward
canEditAfterCompleted = false;
// and encrypt the submission (this is a one-way operation)...
publishProgress(Collect.getInstance().getString(R.string.survey_saving_encrypting_message));
EncryptionUtils.generateEncryptedSubmission(instanceXml, submissionXml, formInfo);
isEncrypted = true;
}
// At this point, we have:
// 1. the saved original instanceXml,
// 2. all the plaintext attachments
// 2. the submission.xml that is the completed xml (whether encrypting or not)
// 3. all the encrypted attachments if encrypting (isEncrypted = true).
//
// NEXT:
// 1. Update the instance database (with status complete).
// 2. Overwrite the instanceXml with the submission.xml
// and remove the plaintext attachments if encrypting
updateInstanceDatabase(false, canEditAfterCompleted);
if ( !canEditAfterCompleted ) {
// AT THIS POINT, there is no going back. We are committed
// to returning "success" (true) whether or not we can
// rename "submission.xml" to instanceXml and whether or
// not we can delete the plaintext media files.
//
// Handle the fall-out for a failed "submission.xml" rename
// in the InstanceUploader task. Leftover plaintext media
// files are handled during form deletion.
// delete the restore Xml file.
if ( !instanceXml.delete() ) {
String msg = "Error deleting " + instanceXml.getAbsolutePath()
+ " prior to renaming submission.xml";
Log.e(t, msg);
throw new IOException(msg);
}
// rename the submission.xml to be the instanceXml
if ( !submissionXml.renameTo(instanceXml) ) {
String msg = "Error renaming submission.xml to " + instanceXml.getAbsolutePath();
Log.e(t, msg);
throw new IOException(msg);
}
} else {
// try to delete the submissionXml file, since it is
// identical to the existing instanceXml file
// (we don't need to delete and rename anything).
if ( !submissionXml.delete() ) {
String msg = "Error deleting " + submissionXml.getAbsolutePath()
+ " (instance is re-openable)";
Log.w(t, msg);
}
}
// if encrypted, delete all plaintext files
// (anything not named instanceXml or anything not ending in .enc)
if ( isEncrypted ) {
if ( !EncryptionUtils.deletePlaintextFiles(instanceXml) ) {
Log.e(t, "Error deleting plaintext files for " + instanceXml.getAbsolutePath());
}
}
}
}
/**
* This method actually writes the xml to disk.
* @param payload
* @param path
* @return
*/
static void exportXmlFile(ByteArrayPayload payload, String path) throws IOException {
File file = new File(path);
if (file.exists() && !file.delete()) {
throw new IOException("Cannot overwrite " + path + ". Perhaps the file is locked?");
}
// create data stream
InputStream is = payload.getPayloadStream();
int len = (int) payload.getLength();
// read from data stream
byte[] data = new byte[len];
// try {
int read = is.read(data, 0, len);
if (read > 0) {
// write xml file
RandomAccessFile randomAccessFile = null;
try {
// String filename = path + File.separator +
// path.substring(path.lastIndexOf(File.separator) + 1) + ".xml";
randomAccessFile = new RandomAccessFile(file, "rws");
randomAccessFile.write(data);
} finally {
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
Log.e(t, "Error closing RandomAccessFile: " + path, e);
}
}
}
}
// } catch (IOException e) {
// Log.e(t, "Error reading from payload data stream");
// e.printStackTrace();
// return false;
// }
//
// return false;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (mSavedListener != null && values != null) {
if (values.length == 1) {
mSavedListener.onProgressStep(values[0]);
}
}
}
@Override
protected void onPostExecute(SaveResult result) {
synchronized (this) {
if (mSavedListener != null && result != null) {
mSavedListener.savingComplete(result);
}
}
}
public void setFormSavedListener(FormSavedListener fsl) {
synchronized (this) {
mSavedListener = fsl;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/SaveToDiskTask.java
|
Java
|
asf20
| 17,909
|
/*
* Copyright (C) 2014 Nafundi
*
* 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.tasks;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/**
*
* @author carlhartung (chartung@nafundi.com)
*
*/
public abstract class GoogleMapsEngineTask<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {
private static String tag = "GoogleMapsEngineTask";
public final static int PLAYSTORE_REQUEST_CODE = 55551;
public final static int USER_RECOVERABLE_REQUEST_CODE = 55552;
protected static final String gme_fail = "GME Error: ";
protected String mGoogleUserName = null;
protected InstanceUploaderListener mStateListener;
public void setUserName(String username) {
mGoogleUserName = username;
}
public void setUploaderListener(InstanceUploaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
protected String authenticate(Context context, String mGoogleUserName)
throws IOException, GoogleAuthException,
GooglePlayServicesAvailabilityException,
UserRecoverableAuthException {
// use google auth utils to get oauth2 token
String scope = "oauth2:https://www.googleapis.com/auth/mapsengine https://picasaweb.google.com/data/";
String token = null;
if (mGoogleUserName == null) {
Log.e(tag, "Google user not set");
return null;
}
token = GoogleAuthUtil.getToken(context, mGoogleUserName, scope);
return token;
}
protected static class Backoff {
private static final long INITIAL_WAIT = 1000 + new Random()
.nextInt(1000);
private static final long MAX_BACKOFF = 1800 * 1000;
private long mWaitInterval = INITIAL_WAIT;
private boolean mBackingOff = true;
public boolean shouldRetry() {
return mBackingOff;
}
private void noRetry() {
mBackingOff = false;
}
public void backoff() {
if (mWaitInterval > MAX_BACKOFF) {
noRetry();
} else if (mWaitInterval > 0) {
try {
Thread.sleep(mWaitInterval);
} catch (InterruptedException e) {
}
}
mWaitInterval = (mWaitInterval == 0) ? INITIAL_WAIT
: mWaitInterval * 2;
}
}
protected static byte[] readStream(InputStream in) throws IOException {
final byte[] buf = new byte[1024];
int count = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
while ((count = in.read(buf)) != -1) {
out.write(buf, 0, count);
}
in.close();
return out.toByteArray();
}
protected String getErrorMesssage(InputStream is) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder jsonResponseBuilder = new StringBuilder();
String line = null;
try {
while ((line = br.readLine()) != null) {
jsonResponseBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String jsonResponse = jsonResponseBuilder.toString();
Log.i(tag, "GME json response : " + jsonResponse);
GMEErrorResponse errResp = gson.fromJson(jsonResponse, GMEErrorResponse.class);
StringBuilder sb = new StringBuilder();
sb.append(gme_fail + "\n");
if (errResp.error.errors != null) {
for (int i = 0; i < errResp.error.errors.length; i++) {
sb.append(errResp.error.errors[i].message + "\n");
}
} else {
sb.append(errResp.error.message + "\n");
}
return sb.toString();
}
// FOR JSON
public static class FeaturesListResponse {
public Feature[] features;
}
public static class Feature {
public Geometry geometry;
public Map<String, String> properties;
}
public static class Geometry {
public String type;
}
public static class PointGeometry extends Geometry {
public double[] coordinates;
public void setCoordinates(double lat, double lon) {
coordinates = new double[2];
coordinates[0] = lat;
coordinates[1] = lon;
}
}
public class GMEErrorResponse {
public GMEError error;
}
public class GMEError {
public GMEInnerError[] errors;
public String code;
public String message;
public String extendedHelp;
}
public class GMEInnerError {
public String domain;
public String reason;
public String message;
public String locationType;
public String location;
}
public static class Table {
public String id;
public String name;
public String description;
public String projectId;
public String tags[];
public String sourceEncoding;
public String draftAccessList;
public String publishedAccessList;
public String processingStatus;
public Schema schema;
}
public static class Schema {
public Column[] columns;
public String primaryGeometry;
public String primaryKey;
}
public static class Column {
public String name;
public String type;
}
public static class TablesListResponse {
public Table[] tables;
public String nextPageToken;
}
public static class FeatureSerializer implements JsonSerializer<Feature> {
@Override
public JsonElement serialize(final Feature feature,
final Type typeOfSrc, final JsonSerializationContext context) {
final JsonObject json = new JsonObject();
json.addProperty("type", "Feature");
JsonElement geoElement = context.serialize(feature.geometry);
json.add("geometry", geoElement);
JsonElement propElement = context.serialize(feature.properties);
json.add("properties", propElement);
return json;
}
}
public static class FeatureListSerializer implements
JsonSerializer<ArrayList<Feature>> {
@Override
public JsonElement serialize(final ArrayList<Feature> features,
final Type typeOfSrc, final JsonSerializationContext context) {
final JsonObject json = new JsonObject();
final JsonArray jsonArray = new JsonArray();
for (final Feature feature : features) {
final JsonElement element = context.serialize(feature);
jsonArray.add(element);
}
json.add("features", jsonArray);
return json;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/GoogleMapsEngineTask.java
|
Java
|
asf20
| 7,475
|
/*
* 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.tasks;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteFormsListener;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import android.content.ContentResolver;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Task responsible for deleting selected forms.
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*
*/
public class DeleteFormsTask extends AsyncTask<Long, Void, Integer> {
private static final String t = "DeleteFormsTask";
private ContentResolver cr;
private DeleteFormsListener dl;
private int successCount = 0;
@Override
protected Integer doInBackground(Long... params) {
int deleted = 0;
if (params == null ||cr == null || dl == null) {
return deleted;
}
// delete files from database and then from file system
for (int i = 0; i < params.length; i++) {
if ( isCancelled() ) {
break;
}
try {
Uri deleteForm =
Uri.withAppendedPath(FormsColumns.CONTENT_URI, params[i].toString());
int wasDeleted = cr.delete(deleteForm, null, null);
deleted += wasDeleted;
if (wasDeleted > 0) {
Collect.getInstance().getActivityLogger().logAction(this, "delete", deleteForm.toString());
}
} catch ( Exception ex ) {
Log.e(t,"Exception during delete of: " + params[i].toString() + " exception: " + ex.toString());
}
}
successCount = deleted;
return deleted;
}
@Override
protected void onPostExecute(Integer result) {
cr = null;
if (dl != null) {
dl.deleteComplete(result);
}
super.onPostExecute(result);
}
@Override
protected void onCancelled() {
cr = null;
if (dl != null) {
dl.deleteComplete(successCount);
}
}
public void setDeleteListener(DeleteFormsListener listener) {
dl = listener;
}
public void setContentResolver(ContentResolver resolver){
cr = resolver;
}
public int getDeleteCount() {
return successCount;
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/DeleteFormsTask.java
|
Java
|
asf20
| 2,878
|
/*
* 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.tasks;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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.logic.PropertyManager;
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.utilities.WebUtils;
import org.opendatakit.httpclientandroidlib.Header;
import org.opendatakit.httpclientandroidlib.HttpResponse;
import org.opendatakit.httpclientandroidlib.HttpStatus;
import org.opendatakit.httpclientandroidlib.client.ClientProtocolException;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.client.methods.HttpHead;
import org.opendatakit.httpclientandroidlib.client.methods.HttpPost;
import org.opendatakit.httpclientandroidlib.conn.ConnectTimeoutException;
import org.opendatakit.httpclientandroidlib.conn.HttpHostConnectException;
import org.opendatakit.httpclientandroidlib.entity.mime.MultipartEntity;
import org.opendatakit.httpclientandroidlib.entity.mime.content.FileBody;
import org.opendatakit.httpclientandroidlib.entity.mime.content.StringBody;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.webkit.MimeTypeMap;
/**
* Background task for uploading completed forms.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class InstanceUploaderTask extends AsyncTask<Long, Integer, InstanceUploaderTask.Outcome> {
private static final String t = "InstanceUploaderTask";
// it can take up to 27 seconds to spin up Aggregate
private static final int CONNECTION_TIMEOUT = 60000;
private static final String fail = "Error: ";
private InstanceUploaderListener mStateListener;
public static class Outcome {
public Uri mAuthRequestingServer = null;
public HashMap<String, String> mResults = new HashMap<String,String>();
}
/**
* Uploads to urlString the submission identified by id with filepath of instance
* @param urlString destination URL
* @param id
* @param instanceFilePath
* @param toUpdate - Instance URL for recording status update.
* @param httpclient - client connection
* @param localContext - context (e.g., credentials, cookies) for client connection
* @param uriRemap - mapping of Uris to avoid redirects on subsequent invocations
* @return false if credentials are required and we should terminate immediately.
*/
private boolean uploadOneSubmission(String urlString, String id, String instanceFilePath,
Uri toUpdate, HttpContext localContext, Map<Uri, Uri> uriRemap, Outcome outcome) {
Collect.getInstance().getActivityLogger().logAction(this, urlString, instanceFilePath);
File instanceFile = new File(instanceFilePath);
ContentValues cv = new ContentValues();
Uri u = Uri.parse(urlString);
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
// if https then enable preemptive basic auth...
if ( u.getScheme().equals("https") ) {
WebUtils.enablePreemptiveBasicAuth(localContext, u.getHost());
}
Log.i(t, "Using Uri remap for submission " + id + ". Now: " + u.toString());
} else {
// if https then enable preemptive basic auth...
if ( u.getScheme() != null && u.getScheme().equals("https") ) {
WebUtils.enablePreemptiveBasicAuth(localContext, u.getHost());
}
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
Log.i(t, "Issuing HEAD request for " + id + " to: " + u.toString());
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
// clear the cookies -- should not be necessary?
Collect.getInstance().getCookieStore().clear();
WebUtils.discardEntityBytes(response);
// we need authentication, so stop and return what we've
// done so far.
outcome.mAuthRequestingServer = u;
return false;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
WebUtils.discardEntityBytes(response);
if (locations != null && locations.length == 1) {
try {
Uri uNew = Uri.parse(URLDecoder.decode(locations[0].getValue(), "utf-8"));
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
outcome.mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
} catch (Exception e) {
e.printStackTrace();
outcome.mResults.put(id, fail + urlString + " " + e.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
}
} else {
// may be a server that does not handle
WebUtils.discardEntityBytes(response);
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES) {
outcome.mResults.put(
id,
fail
+ "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Client Protocol Exception");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Connection Timeout");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + e.toString() + " :: Network Connection Failed");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (SocketTimeoutException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Connection Timeout");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (HttpHostConnectException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Network Connection Refused");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (Exception e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
String msg = e.getMessage();
if (msg == null) {
msg = e.toString();
}
outcome.mResults.put(id, fail + "Generic Exception: " + msg);
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
// Under normal operations, we upload the instanceFile to
// the server. However, during the save, there is a failure
// window that may mark the submission as complete but leave
// the file-to-be-uploaded with the name "submission.xml" and
// the plaintext submission files on disk. In this case,
// upload the submission.xml and all the files in the directory.
// This means the plaintext files and the encrypted files
// will be sent to the server and the server will have to
// figure out what to do with them.
File submissionFile = new File(instanceFile.getParentFile(), "submission.xml");
if ( submissionFile.exists() ) {
Log.w(t, "submission.xml will be uploaded instead of " + instanceFile.getAbsolutePath());
} else {
submissionFile = instanceFile;
}
if (!instanceFile.exists() && !submissionFile.exists()) {
outcome.mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (fileName.equals(submissionFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
int lastJ;
while (j < files.size() || first) {
lastJ = j;
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(submissionFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + submissionFile.getName());
byteCount += submissionFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (f.getName().endsWith(".amr")) {
fb = new FileBody(f, "audio/amr");
entity.addPart(f.getName(), fb);
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if ((j-lastJ+1 > 100) || (byteCount + files.get(j + 1).length() > 10000000L)) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
Log.i(t, "Issuing POST request for " + id + " to: " + u.toString());
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
WebUtils.discardEntityBytes(response);
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) {
if (responseCode == HttpStatus.SC_OK) {
outcome.mResults.put(id, fail + "Network login failure? Again?");
} else if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
// clear the cookies -- should not be necessary?
Collect.getInstance().getCookieStore().clear();
outcome.mResults.put(id, fail + response.getStatusLine().getReasonPhrase()
+ " (" + responseCode + ") at " + urlString);
} else {
outcome.mResults.put(id, fail + response.getStatusLine().getReasonPhrase()
+ " (" + responseCode + ") at " + urlString);
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
String msg = e.getMessage();
if (msg == null) {
msg = e.toString();
}
outcome.mResults.put(id, fail + "Generic Exception: " + msg);
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
}
// if it got here, it must have worked
outcome.mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
// TODO: This method is like 350 lines long, down from 400.
// still. ridiculous. make it smaller.
protected Outcome doInBackground(Long... values) {
Outcome outcome = new Outcome();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[(values == null) ? 0 : values.length];
if ( values != null ) {
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
}
String deviceId = new PropertyManager(Collect.getInstance().getApplicationContext())
.getSingularProperty(PropertyManager.OR_DEVICE_ID_PROPERTY);
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
Map<Uri, Uri> uriRemap = new HashMap<Uri, Uri>();
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
if (isCancelled()) {
return outcome;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
int subIdx = c.getColumnIndex(InstanceColumns.SUBMISSION_URI);
String urlString = c.isNull(subIdx) ? null : c.getString(subIdx);
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL,
Collect.getInstance().getString(R.string.default_server_url));
if ( urlString.charAt(urlString.length()-1) == '/') {
urlString = urlString.substring(0, urlString.length()-1);
}
// NOTE: /submission must not be translated! It is the well-known path on the server.
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL,
Collect.getInstance().getString(R.string.default_odk_submission));
if ( submissionUrl.charAt(0) != '/') {
submissionUrl = "/" + submissionUrl;
}
urlString = urlString + submissionUrl;
}
// add the deviceID to the request...
try {
urlString += "?deviceID=" + URLEncoder.encode(deviceId, "UTF-8");
} catch (UnsupportedEncodingException e) {
// unreachable...
}
if ( !uploadOneSubmission(urlString, id, instance, toUpdate, localContext, uriRemap, outcome) ) {
return outcome; // get credentials...
}
}
}
} finally {
if (c != null) {
c.close();
}
}
return outcome;
}
@Override
protected void onPostExecute(Outcome outcome) {
synchronized (this) {
if (mStateListener != null) {
if (outcome.mAuthRequestingServer != null) {
mStateListener.authRequest(outcome.mAuthRequestingServer, outcome.mResults);
} else {
mStateListener.uploadingComplete(outcome.mResults);
StringBuilder selection = new StringBuilder();
Set<String> keys = outcome.mResults.keySet();
Iterator<String> it = keys.iterator();
String[] selectionArgs = new String[keys.size()+1];
int i = 0;
selection.append("(");
while (it.hasNext()) {
String id = it.next();
selection.append(InstanceColumns._ID + "=?");
selectionArgs[i++] = id;
if (i != keys.size()) {
selection.append(" or ");
}
}
selection.append(") and status=?");
selectionArgs[i] = InstanceProviderAPI.STATUS_SUBMITTED;
Cursor results = null;
try {
results = Collect
.getInstance()
.getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection.toString(),
selectionArgs, null);
if (results.getCount() > 0) {
Long[] toDelete = new Long[results.getCount()];
results.moveToPosition(-1);
int cnt = 0;
while (results.moveToNext()) {
toDelete[cnt] = results.getLong(results
.getColumnIndex(InstanceColumns._ID));
cnt++;
}
boolean deleteFlag = PreferenceManager.getDefaultSharedPreferences(
Collect.getInstance().getApplicationContext()).getBoolean(
PreferencesActivity.KEY_DELETE_AFTER_SEND, false);
if (deleteFlag) {
DeleteInstancesTask dit = new DeleteInstancesTask();
dit.setContentResolver(Collect.getInstance().getContentResolver());
dit.execute(toDelete);
}
}
} finally {
if (results != null) {
results.close();
}
}
}
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0].intValue(), values[1].intValue());
}
}
}
public void setUploaderListener(InstanceUploaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
public static void copyToBytes(InputStream input, OutputStream output,
int bufferSize) throws IOException {
byte[] buf = new byte[bufferSize];
int bytesRead = input.read(buf);
while (bytesRead != -1) {
output.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
}
output.flush();
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/InstanceUploaderTask.java
|
Java
|
asf20
| 30,569
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.tasks;
/**
*
* Author: Meletis Margaritis
* Date: 19/10/2013
* Time: 12:17 μμ
*/
public interface ProgressNotifier {
void onProgressStep(String stepMessage);
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/ProgressNotifier.java
|
Java
|
asf20
| 912
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.tasks;
import android.os.AsyncTask;
import android.util.Log;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.SavePointListener;
import org.odk.collect.android.logic.FormController;
import java.io.File;
/**
* Author: Meletis Margaritis
* Date: 27/6/2013
* Time: 6:46 μμ
*/
public class SavePointTask extends AsyncTask<Void, Void, String> {
private final static String t = "SavePointTask";
private static final Object lock = new Object();
private static int lastPriorityUsed = 0;
private final SavePointListener listener;
private int priority;
public SavePointTask(SavePointListener listener) {
this.listener = listener;
this.priority = ++lastPriorityUsed;
}
@Override
protected String doInBackground(Void... params) {
synchronized (lock) {
if (priority < lastPriorityUsed) {
Log.w(t, "Savepoint thread (p=" + priority + ") was cancelled (a) because another one is waiting (p=" + lastPriorityUsed + ")");
return null;
}
long start = System.currentTimeMillis();
try {
FormController formController = Collect.getInstance().getFormController();
File temp = SaveToDiskTask.savepointFile(formController.getInstancePath());
ByteArrayPayload payload = formController.getFilledInFormXml();
if (priority < lastPriorityUsed) {
Log.w(t, "Savepoint thread (p=" + priority + ") was cancelled (b) because another one is waiting (p=" + lastPriorityUsed + ")");
return null;
}
// write out xml
SaveToDiskTask.exportXmlFile(payload, temp.getAbsolutePath());
long end = System.currentTimeMillis();
Log.i(t, "Savepoint ms: " + Long.toString(end - start) + " to " + temp);
return null;
} catch (Exception e) {
String msg = e.getMessage();
Log.e(t, msg, e);
return msg;
}
}
}
@Override
protected void onPostExecute(String errorMessage) {
super.onPostExecute(errorMessage);
if (listener != null && errorMessage != null) {
listener.onSavePointError(errorMessage);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/tasks/SavePointTask.java
|
Java
|
asf20
| 3,254
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.exception;
/**
* Author: Meletis Margaritis
* Date: 01/05/13
* Time: 10:57
*/
public class ExternalDataException extends RuntimeException {
public ExternalDataException(String detailMessage) {
super(detailMessage);
}
public ExternalDataException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/ExternalDataException.java
|
Java
|
asf20
| 1,111
|
package org.odk.collect.android.exception;
public class GeoPointNotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public GeoPointNotFoundException (String msg) {
super(msg);
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/GeoPointNotFoundException.java
|
Java
|
asf20
| 240
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.exception;
/**
*
* Author: Meletis Margaritis
* Date: 30/07/13
* Time: 12:27
*/
public class ExternalParamsException extends Exception {
public ExternalParamsException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/ExternalParamsException.java
|
Java
|
asf20
| 1,014
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.exception;
/**
*
* Author: Meletis Margaritis
* Date: 30/09/13
* Time: 11:39
*/
public class EncryptionException extends Exception {
public EncryptionException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/EncryptionException.java
|
Java
|
asf20
| 1,006
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.exception;
import java.io.File;
/**
* Author: Meletis Margaritis
* Date: 3/6/2013
* Time: 11:57 μμ
*/
public class TaskCancelledException extends Exception {
private File file;
public TaskCancelledException(File file, String detailMessage) {
super(detailMessage);
this.file = file;
}
public File getFile() {
return file;
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/TaskCancelledException.java
|
Java
|
asf20
| 1,129
|
package org.odk.collect.android.exception;
public class FormException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public FormException (String msg) {
super(msg);
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/FormException.java
|
Java
|
asf20
| 216
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.exception;
/**
* This exception wraps all exceptions that come from JR.
*
* Author: Meletis Margaritis
* Date: 2/13/14
* Time: 11:39 AM
*/
public class JavaRosaException extends Exception {
public JavaRosaException(Throwable throwable) {
super(throwable.getMessage() == null ? throwable.getClass().getSimpleName() : throwable.getMessage(), throwable);
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/JavaRosaException.java
|
Java
|
asf20
| 1,089
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.exception;
/**
* Author: Meletis Margaritis
* Date: 16/5/2013
* Time: 2:15 πμ
*/
public class InvalidSyntaxException extends RuntimeException {
public InvalidSyntaxException(String detailMessage) {
super(detailMessage);
}
public InvalidSyntaxException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}
|
0nima0-f
|
src/org/odk/collect/android/exception/InvalidSyntaxException.java
|
Java
|
asf20
| 1,119
|
package org.odk.collect.android.receivers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.NotificationActivity;
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;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.GoogleMapsEngineAbstractUploader;
import org.odk.collect.android.tasks.InstanceUploaderTask;
import org.odk.collect.android.utilities.WebUtils;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
public class NetworkReceiver extends BroadcastReceiver implements InstanceUploaderListener {
// turning on wifi often gets two CONNECTED events. we only want to run one thread at a time
public static boolean running = false;
InstanceUploaderTask mInstanceUploaderTask;
GoogleMapsEngineAutoUploadTask mGoogleMapsEngineUploadTask;
@Override
public void onReceive(Context context, Intent intent) {
// make sure sd card is ready, if not don't try to send
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
String action = intent.getAction();
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo currentNetworkInfo = manager.getActiveNetworkInfo();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (currentNetworkInfo != null && currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
if (interfaceIsEnabled(context, currentNetworkInfo)) {
uploadForms(context);
}
}
} else if (action.equals("org.odk.collect.android.FormSaved")) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni == null || !ni.isConnected()) {
// not connected, do nothing
} else {
if (interfaceIsEnabled(context, ni)) {
uploadForms(context);
}
}
}
}
private boolean interfaceIsEnabled(Context context,
NetworkInfo currentNetworkInfo) {
// make sure autosend is enabled on the given connected interface
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
boolean sendwifi = sharedPreferences.getBoolean(
PreferencesActivity.KEY_AUTOSEND_WIFI, false);
boolean sendnetwork = sharedPreferences.getBoolean(
PreferencesActivity.KEY_AUTOSEND_NETWORK, false);
return (currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
&& sendwifi || currentNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE
&& sendnetwork);
}
private void uploadForms(Context context) {
if (!running) {
running = true;
String selection = InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS + "=?";
String selectionArgs[] =
{
InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED
};
ArrayList<Long> toUpload = new ArrayList<Long>();
Cursor c = context.getContentResolver().query(InstanceColumns.CONTENT_URI, null,
selection, selectionArgs, null);
try {
if (c != null && c.getCount() > 0) {
c.move(-1);
while (c.moveToNext()) {
Long l = c.getLong(c.getColumnIndex(InstanceColumns._ID));
toUpload.add(Long.valueOf(l));
}
}
} finally {
if (c != null) {
c.close();
}
}
if (toUpload.size() < 1) {
running = false;
return;
}
Long[] toSendArray = new Long[toUpload.size()];
toUpload.toArray(toSendArray);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
String protocol = settings.getString(PreferencesActivity.KEY_PROTOCOL,
context.getString(R.string.protocol_odk_default));
if (protocol.equals(context.getString(R.string.protocol_google_maps_engine))) {
mGoogleMapsEngineUploadTask = new GoogleMapsEngineAutoUploadTask(context);
String googleUsername = settings.getString(
PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null);
if (googleUsername == null || googleUsername.equalsIgnoreCase("")) {
// just quit if there's no username
running = false;
return;
}
mGoogleMapsEngineUploadTask.setUserName(googleUsername);
mGoogleMapsEngineUploadTask.setUploaderListener(this);
mGoogleMapsEngineUploadTask.execute(toSendArray);
} else {
// get the username, password, and server from preferences
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
String server = settings.getString(PreferencesActivity.KEY_SERVER_URL,
context.getString(R.string.default_server_url));
String url = server
+ settings.getString(PreferencesActivity.KEY_FORMLIST_URL,
context.getString(R.string.default_odk_formlist));
Uri u = Uri.parse(url);
WebUtils.addCredentials(storedUsername, storedPassword, u.getHost());
mInstanceUploaderTask = new InstanceUploaderTask();
mInstanceUploaderTask.setUploaderListener(this);
mInstanceUploaderTask.execute(toSendArray);
}
}
}
@Override
public void uploadingComplete(HashMap<String, String> result) {
// task is done
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(null);
}
if (mGoogleMapsEngineUploadTask != null) {
mGoogleMapsEngineUploadTask.setUploaderListener(null);
}
running = false;
StringBuilder message = new StringBuilder();
message.append(Collect.getInstance().getString(R.string.odk_auto_note) + " :: \n\n");
if (result == null) {
message.append(Collect.getInstance().getString(R.string.odk_auth_auth_fail));
} else {
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 ");
}
}
{
Cursor results = null;
try {
results = Collect
.getInstance()
.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");
}
}
} finally {
if (results != null) {
results.close();
}
}
}
}
Intent notifyIntent = new Intent(Collect.getInstance(), NotificationActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notifyIntent.putExtra(NotificationActivity.NOTIFICATION_KEY, message.toString().trim());
PendingIntent pendingNotify = PendingIntent.getActivity(Collect.getInstance(), 0,
notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(Collect.getInstance())
.setSmallIcon(R.drawable.notes)
.setContentTitle(Collect.getInstance().getString(R.string.odk_auto_note))
.setContentIntent(pendingNotify)
.setContentText(message.toString().trim())
.setAutoCancel(true)
.setLargeIcon(
BitmapFactory.decodeResource(Collect.getInstance().getResources(),
android.R.drawable.ic_dialog_info));
NotificationManager mNotificationManager = (NotificationManager)Collect.getInstance()
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1328974928, mBuilder.build());
}
@Override
public void progressUpdate(int progress, int total) {
// do nothing
}
@Override
public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
// if we get an auth request, just fail
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(null);
}
if (mGoogleMapsEngineUploadTask != null) {
mGoogleMapsEngineUploadTask.setUploaderListener(null);
}
running = false;
}
private class GoogleMapsEngineAutoUploadTask extends
GoogleMapsEngineAbstractUploader<Long, Integer, HashMap<String, String>> {
private Context mContext;
public GoogleMapsEngineAutoUploadTask(Context c) {
mContext = c;
}
@Override
protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[(values == null) ? 0 : values.length];
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
}
String token = null;
try {
token = authenticate(mContext, mGoogleUserName);
} catch (IOException e) {
// network or server error, the call is expected to succeed if
// you try again later. Don't attempt to call again immediately
// - the request is likely to fail, you'll hit quotas or
// back-off.
return null;
} catch (GooglePlayServicesAvailabilityException playEx) {
return null;
} catch (UserRecoverableAuthException e) {
e.printStackTrace();
return null;
} catch (GoogleAuthException e) {
// Failure. The call is not expected to ever succeed so it
// should not be retried.
return null;
}
mContext = null;
if (token == null) {
// failed, so just return
return null;
}
uploadInstances(selection, selectionArgs, token);
return mResults;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/receivers/NetworkReceiver.java
|
Java
|
asf20
| 13,033
|
/*
* 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.application;
import java.io.File;
import org.odk.collect.android.R;
import org.odk.collect.android.database.ActivityLogger;
import org.odk.collect.android.external.ExternalDataManager;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.utilities.AgingCredentialsProvider;
import org.opendatakit.httpclientandroidlib.client.CookieStore;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
import org.opendatakit.httpclientandroidlib.client.protocol.ClientContext;
import org.opendatakit.httpclientandroidlib.impl.client.BasicCookieStore;
import org.opendatakit.httpclientandroidlib.protocol.BasicHttpContext;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.preference.PreferenceManager;
/**
* Extends the Application class to implement
*
* @author carlhartung
*/
public class Collect extends Application {
// Storage paths
public static final String ODK_ROOT = Environment.getExternalStorageDirectory()
+ File.separator + "odk";
public static final String FORMS_PATH = ODK_ROOT + File.separator + "forms";
public static final String INSTANCES_PATH = ODK_ROOT + File.separator + "instances";
public static final String CACHE_PATH = ODK_ROOT + File.separator + ".cache";
public static final String METADATA_PATH = ODK_ROOT + File.separator + "metadata";
public static final String TMPFILE_PATH = CACHE_PATH + File.separator + "tmp.jpg";
public static final String TMPDRAWFILE_PATH = CACHE_PATH + File.separator + "tmpDraw.jpg";
public static final String TMPXML_PATH = CACHE_PATH + File.separator + "tmp.xml";
public static final String LOG_PATH = ODK_ROOT + File.separator + "log";
public static final String DEFAULT_FONTSIZE = "21";
// share all session cookies across all sessions...
private CookieStore cookieStore = new BasicCookieStore();
// retain credentials for 7 minutes...
private CredentialsProvider credsProvider = new AgingCredentialsProvider(7 * 60 * 1000);
private ActivityLogger mActivityLogger;
private FormController mFormController = null;
private ExternalDataManager externalDataManager;
private static Collect singleton = null;
public static Collect getInstance() {
return singleton;
}
public ActivityLogger getActivityLogger() {
return mActivityLogger;
}
public FormController getFormController() {
return mFormController;
}
public void setFormController(FormController controller) {
mFormController = controller;
}
public ExternalDataManager getExternalDataManager() {
return externalDataManager;
}
public void setExternalDataManager(ExternalDataManager externalDataManager) {
this.externalDataManager = externalDataManager;
}
public static int getQuestionFontsize() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect
.getInstance());
String question_font = settings.getString(PreferencesActivity.KEY_FONT_SIZE,
Collect.DEFAULT_FONTSIZE);
int questionFontsize = Integer.valueOf(question_font);
return questionFontsize;
}
public String getVersionedAppName() {
String versionDetail = "";
try {
PackageInfo pinfo;
pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int versionNumber = pinfo.versionCode;
String versionName = pinfo.versionName;
versionDetail = " " + versionName + " (" + versionNumber + ")";
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getString(R.string.app_name) + versionDetail;
}
/**
* Creates required directories on the SDCard (or other external storage)
*
* @throws RuntimeException if there is no SDCard or the directory exists as a non directory
*/
public static void createODKDirs() throws RuntimeException {
String cardstatus = Environment.getExternalStorageState();
if (!cardstatus.equals(Environment.MEDIA_MOUNTED)) {
throw new RuntimeException(Collect.getInstance().getString(R.string.sdcard_unmounted, cardstatus));
}
String[] dirs = {
ODK_ROOT, FORMS_PATH, INSTANCES_PATH, CACHE_PATH, METADATA_PATH
};
for (String dirName : dirs) {
File dir = new File(dirName);
if (!dir.exists()) {
if (!dir.mkdirs()) {
RuntimeException e =
new RuntimeException("ODK reports :: Cannot create directory: "
+ dirName);
throw e;
}
} else {
if (!dir.isDirectory()) {
RuntimeException e =
new RuntimeException("ODK reports :: " + dirName
+ " exists, but is not a directory");
throw e;
}
}
}
}
/**
* Predicate that tests whether a directory path might refer to an
* ODK Tables instance data directory (e.g., for media attachments).
*
* @param directory
* @return
*/
public static boolean isODKTablesInstanceDataDirectory(File directory) {
/**
* Special check to prevent deletion of files that
* could be in use by ODK Tables.
*/
String dirPath = directory.getAbsolutePath();
if ( dirPath.startsWith(Collect.ODK_ROOT) ) {
dirPath = dirPath.substring(Collect.ODK_ROOT.length());
String[] parts = dirPath.split(File.separator);
// [appName, instances, tableId, instanceId ]
if ( parts.length == 4 && parts[1].equals("instances") ) {
return true;
}
}
return false;
}
/**
* Construct and return a session context with shared cookieStore and credsProvider so a user
* does not have to re-enter login information.
*
* @return
*/
public synchronized HttpContext getHttpContext() {
// context holds authentication state machine, so it cannot be
// shared across independent activities.
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
return localContext;
}
public CredentialsProvider getCredentialsProvider() {
return credsProvider;
}
public CookieStore getCookieStore() {
return cookieStore;
}
@Override
public void onCreate() {
singleton = this;
// // set up logging defaults for apache http component stack
// Log log;
// log = LogFactory.getLog("org.opendatakit.httpclientandroidlib");
// log.enableError(true);
// log.enableWarn(true);
// log.enableInfo(true);
// log.enableDebug(true);
// log = LogFactory.getLog("org.opendatakit.httpclientandroidlib.wire");
// log.enableError(true);
// log.enableWarn(false);
// log.enableInfo(false);
// log.enableDebug(false);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
super.onCreate();
PropertyManager mgr = new PropertyManager(this);
FormController.initializeJavaRosa(mgr);
mActivityLogger = new ActivityLogger(
mgr.getSingularProperty(PropertyManager.DEVICE_ID_PROPERTY));
}
}
|
0nima0-f
|
src/org/odk/collect/android/application/Collect.java
|
Java
|
asf20
| 8,632
|
/*
* Copyright (C) 2014 Nafundi
*
* 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.preferences;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
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.tasks.GoogleMapsEngineTask;
import org.odk.collect.android.views.DynamicListPreference;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Handles GME specific preferences.
*
* @author Carl Hartung (chartung@nafundi.com)
*/
public class GMEPreferencesActivity extends PreferenceActivity implements
InstanceUploaderListener {
private DynamicListPreference mGMEProjectIDPreference;
private static String GME_ERROR = "gme_error";
private boolean partnerListDialogShowing;
private final static int PROGRESS_DIALOG = 1;
private final static int GOOGLE_USER_DIALOG = 3;
private static final String ALERT_MSG = "alertmsg";
private static final String ALERT_SHOWING = "alertshowing";
private ProgressDialog mProgressDialog;
private AlertDialog mAlertDialog;
private String mAlertMsg;
private boolean mAlertShowing;
private GetProjectIDTask mUlTask;
private ListPreference mSelectedGoogleAccountPreference;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.gme_preferences);
// default initializers
mAlertMsg = getString(R.string.please_wait);
mAlertShowing = false;
boolean adminMode = getIntent().getBooleanExtra(PreferencesActivity.INTENT_KEY_ADMIN_MODE, false);
SharedPreferences adminPreferences = getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
// determine if the partners list should be showing or not
if (savedInstanceState != null
&& savedInstanceState.containsKey("partner_dialog")) {
partnerListDialogShowing = savedInstanceState
.getBoolean("partner_dialog");
} else {
partnerListDialogShowing = false;
if (savedInstanceState != null
&& savedInstanceState.containsKey(ALERT_MSG)) {
mAlertMsg = savedInstanceState.getString(ALERT_MSG);
}
if (savedInstanceState != null
&& savedInstanceState.containsKey(ALERT_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING,
false);
}
}
mGMEProjectIDPreference = (DynamicListPreference) findPreference(PreferencesActivity.KEY_GME_PROJECT_ID);
mGMEProjectIDPreference.setShowDialog(partnerListDialogShowing);
mGMEProjectIDPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
mGMEProjectIDPreference.setValue((String) newValue);
mGMEProjectIDPreference
.setSummary(mGMEProjectIDPreference.getEntry());
mGMEProjectIDPreference.setShowDialog(false);
return false;
}
});
mSelectedGoogleAccountPreference = (ListPreference) findPreference(PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT);
PreferenceCategory gmePreferences = (PreferenceCategory) findPreference(getString(R.string.gme_preferences));
mGMEProjectIDPreference
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// mUlTask.setUserName(googleUsername);
// ensure we have a google account selected
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(GMEPreferencesActivity.this);
String googleUsername = prefs
.getString(
PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT,
null);
if (googleUsername == null || googleUsername.equals("")) {
showDialog(GOOGLE_USER_DIALOG);
return true;
}
//TODO: CHECK FOR NETWORK CONNECTIVITY.
// setup dialog and upload task
showDialog(PROGRESS_DIALOG);
mUlTask = new GetProjectIDTask();
mUlTask.setUserName(googleUsername);
mUlTask.setUploaderListener(GMEPreferencesActivity.this);
mUlTask.execute();
return true;
}
});
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
// Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString(
PreferencesActivity.KEY_GME_ID_HASHMAP, "");
HashMap<String, String> idhashmap = gson.fromJson(json, HashMap.class);
if (idhashmap != null) {
String[] entries = new String[idhashmap.size()];
String[] values = new String[idhashmap.size()];
Iterator<String> iterator = idhashmap.keySet().iterator();
int it = 0;
while (iterator.hasNext()) {
String key = iterator.next();
entries[it] = key;
values[it] = idhashmap.get(key);
it++;
}
mGMEProjectIDPreference.setEntries(entries);
mGMEProjectIDPreference.setEntryValues(values);
mGMEProjectIDPreference.setSummary(mGMEProjectIDPreference
.getEntry());
}
// get list of google accounts
final Account[] accounts = AccountManager.get(getApplicationContext())
.getAccountsByType("com.google");
ArrayList<String> accountEntries = new ArrayList<String>();
ArrayList<String> accountValues = new ArrayList<String>();
for (int i = 0; i < accounts.length; i++) {
accountEntries.add(accounts[i].name);
accountValues.add(accounts[i].name);
}
accountEntries.add(getString(R.string.no_account));
accountValues.add("");
mSelectedGoogleAccountPreference.setEntries(accountEntries
.toArray(new String[accountEntries.size()]));
mSelectedGoogleAccountPreference.setEntryValues(accountValues
.toArray(new String[accountValues.size()]));
mSelectedGoogleAccountPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
int index = ((ListPreference) preference)
.findIndexOfValue(newValue.toString());
String value = (String) ((ListPreference) preference)
.getEntryValues()[index];
((ListPreference) preference).setSummary(value);
return true;
}
});
mSelectedGoogleAccountPreference
.setSummary(mSelectedGoogleAccountPreference.getValue());
boolean googleAccountAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_GOOGLE_ACCOUNT, true);
if (!(googleAccountAvailable || adminMode)) {
gmePreferences.removePreference(mSelectedGoogleAccountPreference);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("partner_dialog",
mGMEProjectIDPreference.shouldShow());
outState.putString(ALERT_MSG, mAlertMsg);
outState.putBoolean(ALERT_SHOWING, mAlertShowing);
}
@Override
protected void onResume() {
super.onResume();
if (mAlertShowing) {
createAlertDialog(mAlertMsg);
}
}
@Override
protected void onPause() {
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
private class GetProjectIDTask extends
GoogleMapsEngineTask<Void, Void, HashMap<String, String>> {
private InstanceUploaderListener mStateListener;
private String mGoogleUserName;
@Override
protected HashMap<String, String> doInBackground(Void... values) {
HashMap<String, String> projectList = new HashMap<String, String>();
String token = null;
try {
token = authenticate(GMEPreferencesActivity.this,
mGoogleUserName);
} catch (IOException e) {
// network or server error, the call is expected to succeed if
// you try again later. Don't attempt to call again immediately
// - the request is likely to fail, you'll hit quotas or
// back-off.
e.printStackTrace();
return null;
} catch (GooglePlayServicesAvailabilityException playEx) {
Dialog alert = GooglePlayServicesUtil.getErrorDialog(
playEx.getConnectionStatusCode(),
GMEPreferencesActivity.this, PLAYSTORE_REQUEST_CODE);
alert.show();
return null;
} catch (UserRecoverableAuthException e) {
GMEPreferencesActivity.this.startActivityForResult(
e.getIntent(), USER_RECOVERABLE_REQUEST_CODE);
e.printStackTrace();
return null;
} catch (GoogleAuthException e) {
// Failure. The call is not expected to ever succeed so it
// should not be retried.
e.printStackTrace();
return null;
}
if (token == null) {
// if token is null,
return null;
}
HttpURLConnection conn = null;
int status = -1;
try {
URL url = new URL(
"https://www.googleapis.com/mapsengine/v1/projects/");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.addRequestProperty("Authorization", "OAuth " + token);
conn.connect();
// try {
if (conn.getResponseCode() / 100 == 2) {
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
ProjectsListResponse projects = gson.fromJson(br,
ProjectsListResponse.class);
for (int i = 0; i < projects.projects.length; i++) {
Project p = projects.projects[i];
projectList.put(p.name, p.id);
}
} else {
String errorMessage = getErrorMesssage(conn
.getErrorStream());
if (status == 400) {
} else if (status == 403 || status == 401) {
GoogleAuthUtil.invalidateToken(
GMEPreferencesActivity.this, token);
}
projectList.put(GME_ERROR, errorMessage);
return projectList;
}
} catch (Exception e) {
e.printStackTrace();
GoogleAuthUtil.invalidateToken(GMEPreferencesActivity.this,
token);
String errorMessage = getErrorMesssage(conn.getErrorStream());
projectList.put(GME_ERROR, errorMessage);
return projectList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
return projectList;
}
public void setUserName(String username) {
mGoogleUserName = username;
}
@Override
protected void onPostExecute(HashMap<String, String> results) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.uploadingComplete(results);
}
}
}
public void setUploaderListener(InstanceUploaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
@Override
public void uploadingComplete(HashMap<String, String> result) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
// tried to close a dialog not open. don't care.
}
if (result == null) {
// If result is null, then we needed to authorize the user
return;
} else {
if (result.containsKey(GME_ERROR)) {
// something went wrong, show the user
String error = result.get(GME_ERROR);
createAlertDialog("GME Error:" + error);
return;
} else {
// everything is fine
String[] entries = new String[result.size()];
String[] values = new String[result.size()];
// creates an ordered map
Map<String, Object> copy = new TreeMap<String, Object>(result);
Iterator<String> iterator = copy.keySet().iterator();
int i = 0;
while (iterator.hasNext()) {
String key = iterator.next();
entries[i] = key;
values[i] = result.get(key);
i++;
}
mGMEProjectIDPreference.setEntries(entries);
mGMEProjectIDPreference.setEntryValues(values);
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this
.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(result);
prefsEditor.putString(PreferencesActivity.KEY_GME_ID_HASHMAP,
json);
prefsEditor.commit();
mGMEProjectIDPreference.setShowDialog(true);
mGMEProjectIDPreference.show();
}
}
}
@Override
public void progressUpdate(int progress, int total) {
}
@Override
public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
}
@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();
mUlTask.cancel(true);
mUlTask.setUploaderListener(null);
finish();
}
};
mProgressDialog.setTitle(R.string.get_project_IDs);
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel),
loadingButtonListener);
return mProgressDialog;
case GOOGLE_USER_DIALOG:
AlertDialog.Builder gudBuilder = new AlertDialog.Builder(this);
gudBuilder.setTitle(R.string.no_google_account);
gudBuilder.setMessage(R.string.select_maps_account);
gudBuilder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
gudBuilder.setCancelable(false);
return gudBuilder.create();
}
return null;
}
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();
}
// JSON
public static class Project {
public String id;
public String name;
}
public static class ProjectsListResponse {
public Project[] projects;
}
}
|
0nima0-f
|
src/org/odk/collect/android/preferences/GMEPreferencesActivity.java
|
Java
|
asf20
| 16,695
|
/*
* Copyright (C) 2014 Nafundi
*
* 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.preferences;
import org.odk.collect.android.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceCategory;
import android.text.InputFilter;
/**
* Handles 'other' specific preferences.
*
* @author Carl Hartung (chartung@nafundi.com)
*/
public class OtherPreferencesActivity extends AggregatePreferencesActivity
implements OnPreferenceChangeListener {
protected EditTextPreference mSubmissionUrlPreference;
protected EditTextPreference mFormListUrlPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.other_preferences);
SharedPreferences adminPreferences = getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
mFormListUrlPreference = (EditTextPreference) findPreference(PreferencesActivity.KEY_FORMLIST_URL);
mSubmissionUrlPreference = (EditTextPreference) findPreference(PreferencesActivity.KEY_SUBMISSION_URL);
PreferenceCategory otherPreferences = (PreferenceCategory) findPreference(getString(R.string.other_preferences));
mFormListUrlPreference.setOnPreferenceChangeListener(this);
mFormListUrlPreference.setSummary(mFormListUrlPreference.getText());
mServerUrlPreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter(), getWhitespaceFilter() });
mSubmissionUrlPreference.setOnPreferenceChangeListener(this);
mSubmissionUrlPreference.setSummary(mSubmissionUrlPreference.getText());
mServerUrlPreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter(), getWhitespaceFilter() });
}
/**
* Generic listener that sets the summary to the newly selected/entered
* value
*/
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary((CharSequence) newValue);
return true;
}
}
|
0nima0-f
|
src/org/odk/collect/android/preferences/OtherPreferencesActivity.java
|
Java
|
asf20
| 2,658
|
/*
* Copyright (C) 2014 Nafundi
*
* 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.preferences;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.UrlUtils;
import org.odk.collect.android.utilities.WebUtils;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.Toast;
/**
* Handles aggregate specific preferences.
*
* @author Carl Hartung (chartung@nafundi.com)
*/
public class AggregatePreferencesActivity extends PreferenceActivity {
protected EditTextPreference mServerUrlPreference;
protected EditTextPreference mUsernamePreference;
protected EditTextPreference mPasswordPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.aggregate_preferences);
mServerUrlPreference = (EditTextPreference) findPreference(PreferencesActivity.KEY_SERVER_URL);
mUsernamePreference = (EditTextPreference) findPreference(PreferencesActivity.KEY_USERNAME);
mPasswordPreference = (EditTextPreference) findPreference(PreferencesActivity.KEY_PASSWORD);
PreferenceCategory aggregatePreferences = (PreferenceCategory) findPreference(getString(R.string.aggregate_preferences));
mServerUrlPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
String url = newValue.toString();
// remove all trailing "/"s
while (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
if (UrlUtils.isValidUrl(url)) {
preference.setSummary(newValue.toString());
return true;
} else {
Toast.makeText(getApplicationContext(),
R.string.url_error, Toast.LENGTH_SHORT)
.show();
return false;
}
}
});
mServerUrlPreference.setSummary(mServerUrlPreference.getText());
mServerUrlPreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter() });
mUsernamePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary((CharSequence) newValue);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server = settings.getString(PreferencesActivity.KEY_SERVER_URL, getString(R.string.default_server_url));
Uri u = Uri.parse(server);
WebUtils.clearHostCredentials(u.getHost());
Collect.getInstance().getCookieStore().clear();
return true;
}
});
mUsernamePreference.setSummary(mUsernamePreference.getText());
mUsernamePreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter() });
mPasswordPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
String pw = newValue.toString();
if (pw.length() > 0) {
mPasswordPreference.setSummary("********");
} else {
mPasswordPreference.setSummary("");
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server = settings.getString(PreferencesActivity.KEY_SERVER_URL, getString(R.string.default_server_url));
Uri u = Uri.parse(server);
WebUtils.clearHostCredentials(u.getHost());
Collect.getInstance().getCookieStore().clear();
return true;
}
});
if (mPasswordPreference.getText() != null
&& mPasswordPreference.getText().length() > 0) {
mPasswordPreference.setSummary("********");
}
mPasswordPreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter() });
}
/**
* Disallows carriage returns from user entry
*
* @return
*/
protected InputFilter getReturnFilter() {
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;
}
};
return returnFilter;
}
protected InputFilter getWhitespaceFilter() {
InputFilter whitespaceFilter = 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.isWhitespace(source.charAt(i))) {
return "";
}
}
return null;
}
};
return whitespaceFilter;
}
}
|
0nima0-f
|
src/org/odk/collect/android/preferences/AggregatePreferencesActivity.java
|
Java
|
asf20
| 5,839
|
/*
* 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.preferences;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.utilities.MediaUtils;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.provider.MediaStore.Images;
import android.text.InputFilter;
import android.text.Spanned;
/**
* Handles general preferences.
*
* @author Thomas Smyth, Sassafras Tech Collective (tom@sassafrastech.com;
* constraint behavior option)
*/
public class PreferencesActivity extends PreferenceActivity implements OnPreferenceChangeListener {
public static final String INTENT_KEY_ADMIN_MODE = "adminMode";
protected static final int IMAGE_CHOOSER = 0;
// PUT ALL PREFERENCE KEYS HERE
public static final String KEY_INFO = "info";
public static final String KEY_LAST_VERSION = "lastVersion";
public static final String KEY_FIRST_RUN = "firstRun";
public static final String KEY_SHOW_SPLASH = "showSplash";
public static final String KEY_SPLASH_PATH = "splashPath";
public static final String KEY_FONT_SIZE = "font_size";
public static final String KEY_DELETE_AFTER_SEND = "delete_send";
public static final String KEY_PROTOCOL = "protocol";
public static final String KEY_PROTOCOL_SETTINGS = "protocol_settings";
// leaving these in the main screen because username can be used as a
// pre-fill
// value in a form
public static final String KEY_SELECTED_GOOGLE_ACCOUNT = "selected_google_account";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
// AGGREGATE SPECIFIC
public static final String KEY_SERVER_URL = "server_url";
// GME SPECIFIC
public static final String KEY_GME_PROJECT_ID = "gme_project_id";
public static final String KEY_GME_ID_HASHMAP = "gme_id_hashmap";
// OTHER SPECIFIC
public static final String KEY_FORMLIST_URL = "formlist_url";
public static final String KEY_SUBMISSION_URL = "submission_url";
public static final String NAVIGATION_SWIPE = "swipe";
public static final String NAVIGATION_BUTTONS = "buttons";
public static final String NAVIGATION_SWIPE_BUTTONS = "swipe_buttons";
public static final String CONSTRAINT_BEHAVIOR_ON_SWIPE = "on_swipe";
public static final String CONSTRAINT_BEHAVIOR_ON_FINALIZE = "on_finalize";
public static final String CONSTRAINT_BEHAVIOR_DEFAULT = "on_swipe";
public static final String KEY_COMPLETED_DEFAULT = "default_completed";
public static final String KEY_HIGH_RESOLUTION = "high_resolution";
public static final String KEY_AUTH = "auth";
public static final String KEY_AUTOSEND_WIFI = "autosend_wifi";
public static final String KEY_AUTOSEND_NETWORK = "autosend_network";
public static final String KEY_NAVIGATION = "navigation";
public static final String KEY_CONSTRAINT_BEHAVIOR = "constraint_behavior";
private PreferenceScreen mSplashPathPreference;
private ListPreference mSelectedGoogleAccountPreference;
private ListPreference mFontSizePreference;
private ListPreference mNavigationPreference;
private ListPreference mConstraintBehaviorPreference;
private CheckBoxPreference mAutosendWifiPreference;
private CheckBoxPreference mAutosendNetworkPreference;
private ListPreference mProtocolPreference;
private PreferenceScreen mProtocolSettings;
protected EditTextPreference mUsernamePreference;
protected EditTextPreference mPasswordPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.general_preferences));
// not super safe, but we're just putting in this mode to help
// administrate
// would require code to access it
final boolean adminMode = getIntent().getBooleanExtra(INTENT_KEY_ADMIN_MODE, false);
SharedPreferences adminPreferences = getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
// assign all the preferences in advance because changing one often
// affects another
// also avoids npe
PreferenceCategory autosendCategory = (PreferenceCategory) findPreference(getString(R.string.autosend));
mAutosendWifiPreference = (CheckBoxPreference) findPreference(KEY_AUTOSEND_WIFI);
mAutosendNetworkPreference = (CheckBoxPreference) findPreference(KEY_AUTOSEND_NETWORK);
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(getString(R.string.server_preferences));
mProtocolPreference = (ListPreference) findPreference(KEY_PROTOCOL);
mSelectedGoogleAccountPreference = (ListPreference) findPreference(KEY_SELECTED_GOOGLE_ACCOUNT);
PreferenceCategory clientCategory = (PreferenceCategory) findPreference(getString(R.string.client));
mNavigationPreference = (ListPreference) findPreference(KEY_NAVIGATION);
mFontSizePreference = (ListPreference) findPreference(KEY_FONT_SIZE);
Preference defaultFinalized = findPreference(KEY_COMPLETED_DEFAULT);
Preference deleteAfterSend = findPreference(KEY_DELETE_AFTER_SEND);
mSplashPathPreference = (PreferenceScreen) findPreference(KEY_SPLASH_PATH);
mConstraintBehaviorPreference = (ListPreference) findPreference(KEY_CONSTRAINT_BEHAVIOR);
mUsernamePreference = (EditTextPreference) findPreference(PreferencesActivity.KEY_USERNAME);
mPasswordPreference = (EditTextPreference) findPreference(PreferencesActivity.KEY_PASSWORD);
mProtocolSettings = (PreferenceScreen) findPreference(KEY_PROTOCOL_SETTINGS);
boolean autosendWifiAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_AUTOSEND_WIFI, true);
if (!(autosendWifiAvailable || adminMode)) {
autosendCategory.removePreference(mAutosendWifiPreference);
}
boolean autosendNetworkAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_AUTOSEND_NETWORK, true);
if (!(autosendNetworkAvailable || adminMode)) {
autosendCategory.removePreference(mAutosendNetworkPreference);
}
if (!(autosendNetworkAvailable || autosendWifiAvailable || adminMode)) {
getPreferenceScreen().removePreference(autosendCategory);
}
mProtocolPreference = (ListPreference) findPreference(KEY_PROTOCOL);
mProtocolPreference.setSummary(mProtocolPreference.getEntry());
Intent prefIntent = null;
if (mProtocolPreference.getValue().equals(getString(R.string.protocol_odk_default))) {
setDefaultAggregatePaths();
prefIntent = new Intent(this, AggregatePreferencesActivity.class);
} else if (mProtocolPreference.getValue().equals(
getString(R.string.protocol_google_maps_engine))) {
prefIntent = new Intent(this, GMEPreferencesActivity.class);
} else {
// other
prefIntent = new Intent(this, OtherPreferencesActivity.class);
}
prefIntent.putExtra(INTENT_KEY_ADMIN_MODE, adminMode);
mProtocolSettings.setIntent(prefIntent);
mProtocolPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String oldValue = ((ListPreference) preference).getValue();
int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference).getEntries()[index];
String value = (String) ((ListPreference) preference).getEntryValues()[index];
((ListPreference) preference).setSummary(entry);
Intent prefIntent = null;
if (value.equals(getString(R.string.protocol_odk_default))) {
setDefaultAggregatePaths();
prefIntent = new Intent(PreferencesActivity.this, AggregatePreferencesActivity.class);
} else if (value.equals(getString(R.string.protocol_google_maps_engine))) {
prefIntent = new Intent(PreferencesActivity.this, GMEPreferencesActivity.class);
} else {
// other
prefIntent = new Intent(PreferencesActivity.this, OtherPreferencesActivity.class);
}
prefIntent.putExtra(INTENT_KEY_ADMIN_MODE, adminMode);
mProtocolSettings.setIntent(prefIntent);
if (!((String) newValue).equals(oldValue)) {
startActivity(prefIntent);
}
return true;
}
});
boolean changeProtocol = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_SERVER, true);
if (!(changeProtocol || adminMode)) {
serverCategory.removePreference(mProtocolPreference);
}
boolean changeProtocolSettings = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_PROTOCOL_SETTINGS, true);
if (!(changeProtocolSettings || adminMode)) {
serverCategory.removePreference(mProtocolSettings);
}
// get list of google accounts
final Account[] accounts = AccountManager.get(getApplicationContext()).getAccountsByType(
"com.google");
ArrayList<String> accountEntries = new ArrayList<String>();
ArrayList<String> accountValues = new ArrayList<String>();
for (int i = 0; i < accounts.length; i++) {
accountEntries.add(accounts[i].name);
accountValues.add(accounts[i].name);
}
accountEntries.add(getString(R.string.no_account));
accountValues.add("");
mSelectedGoogleAccountPreference.setEntries(accountEntries.toArray(new String[accountEntries
.size()]));
mSelectedGoogleAccountPreference.setEntryValues(accountValues.toArray(new String[accountValues
.size()]));
mSelectedGoogleAccountPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
String value = (String) ((ListPreference) preference).getEntryValues()[index];
((ListPreference) preference).setSummary(value);
return true;
}
});
mSelectedGoogleAccountPreference.setSummary(mSelectedGoogleAccountPreference.getValue());
boolean googleAccountAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_GOOGLE_ACCOUNT, true);
if (!(googleAccountAvailable || adminMode)) {
serverCategory.removePreference(mSelectedGoogleAccountPreference);
}
mUsernamePreference.setOnPreferenceChangeListener(this);
mUsernamePreference.setSummary(mUsernamePreference.getText());
mUsernamePreference.getEditText().setFilters(new InputFilter[] { getReturnFilter() });
boolean usernameAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_USERNAME, true);
if (!(usernameAvailable || adminMode)) {
serverCategory.removePreference(mUsernamePreference);
}
mPasswordPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String pw = newValue.toString();
if (pw.length() > 0) {
mPasswordPreference.setSummary("********");
} else {
mPasswordPreference.setSummary("");
}
return true;
}
});
if (mPasswordPreference.getText() != null && mPasswordPreference.getText().length() > 0) {
mPasswordPreference.setSummary("********");
}
mPasswordPreference.getEditText().setFilters(new InputFilter[] { getReturnFilter() });
boolean passwordAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_PASSWORD, true);
if (!(passwordAvailable || adminMode)) {
serverCategory.removePreference(mPasswordPreference);
}
boolean navigationAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_NAVIGATION, true);
mNavigationPreference.setSummary(mNavigationPreference.getEntry());
mNavigationPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference).getEntries()[index];
((ListPreference) preference).setSummary(entry);
return true;
}
});
if (!(navigationAvailable || adminMode)) {
clientCategory.removePreference(mNavigationPreference);
}
boolean constraintBehaviorAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CONSTRAINT_BEHAVIOR, true);
mConstraintBehaviorPreference.setSummary(mConstraintBehaviorPreference.getEntry());
mConstraintBehaviorPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference).getEntries()[index];
((ListPreference) preference).setSummary(entry);
return true;
}
});
if (!(constraintBehaviorAvailable || adminMode)) {
clientCategory.removePreference(mConstraintBehaviorPreference);
}
boolean fontAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_FONT_SIZE, true);
mFontSizePreference.setSummary(mFontSizePreference.getEntry());
mFontSizePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference).getEntries()[index];
((ListPreference) preference).setSummary(entry);
return true;
}
});
if (!(fontAvailable || adminMode)) {
clientCategory.removePreference(mFontSizePreference);
}
boolean defaultAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_DEFAULT_TO_FINALIZED, true);
if (!(defaultAvailable || adminMode)) {
clientCategory.removePreference(defaultFinalized);
}
boolean deleteAfterAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_DELETE_AFTER_SEND, true);
if (!(deleteAfterAvailable || adminMode)) {
clientCategory.removePreference(deleteAfterSend);
}
boolean resolutionAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_HIGH_RESOLUTION, true);
Preference highResolution = findPreference(KEY_HIGH_RESOLUTION);
if (!(resolutionAvailable || adminMode)) {
clientCategory.removePreference(highResolution);
}
mSplashPathPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
private void launchImageChooser() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
startActivityForResult(i, PreferencesActivity.IMAGE_CHOOSER);
}
@Override
public boolean onPreferenceClick(Preference preference) {
// if you have a value, you can clear it or select new.
CharSequence cs = mSplashPathPreference.getSummary();
if (cs != null && cs.toString().contains("/")) {
final CharSequence[] items = { getString(R.string.select_another_image),
getString(R.string.use_odk_default) };
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setTitle(getString(R.string.change_splash_path));
builder.setNeutralButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(getString(R.string.select_another_image))) {
launchImageChooser();
} else {
setSplashPath(getString(R.string.default_splash_path));
}
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
launchImageChooser();
}
return true;
}
});
mSplashPathPreference.setSummary(mSplashPathPreference.getSharedPreferences().getString(
KEY_SPLASH_PATH, getString(R.string.default_splash_path)));
boolean showSplashAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_SHOW_SPLASH_SCREEN, true);
CheckBoxPreference showSplashPreference = (CheckBoxPreference) findPreference(KEY_SHOW_SPLASH);
if (!(showSplashAvailable || adminMode)) {
clientCategory.removePreference(showSplashPreference);
clientCategory.removePreference(mSplashPathPreference);
}
if (!(fontAvailable || defaultAvailable || showSplashAvailable || navigationAvailable
|| adminMode || resolutionAvailable)) {
getPreferenceScreen().removePreference(clientCategory);
}
}
@Override
protected void onPause() {
super.onPause();
// the property manager should be re-assigned, as properties
// may have changed.
PropertyManager mgr = new PropertyManager(this);
FormController.initializeJavaRosa(mgr);
}
@Override
protected void onResume() {
super.onResume();
// has to go in onResume because it may get updated by
// a sub-preference screen
// this just keeps the widgets in sync
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String account = sp.getString(KEY_SELECTED_GOOGLE_ACCOUNT, "");
mSelectedGoogleAccountPreference.setSummary(account);
mSelectedGoogleAccountPreference.setValue(account);
String user = sp.getString(KEY_USERNAME, "");
String pw = sp.getString(KEY_PASSWORD, "");
mUsernamePreference.setSummary(user);
mUsernamePreference.setText(user);
if (pw != null && pw.length() > 0) {
mPasswordPreference.setSummary("********");
mPasswordPreference.setText(pw);
}
}
private void setSplashPath(String path) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(KEY_SPLASH_PATH, path);
editor.commit();
mSplashPathPreference = (PreferenceScreen) findPreference(KEY_SPLASH_PATH);
mSplashPathPreference.setSummary(mSplashPathPreference.getSharedPreferences().getString(
KEY_SPLASH_PATH, getString(R.string.default_splash_path)));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
// request was canceled, so do nothing
return;
}
switch (requestCode) {
case IMAGE_CHOOSER:
// get gp of chosen file
Uri selectedMedia = intent.getData();
String sourceMediaPath = MediaUtils.getPathFromUri(this, selectedMedia, Images.Media.DATA);
// setting image path
setSplashPath(sourceMediaPath);
break;
}
}
private void setDefaultAggregatePaths() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sp.edit();
editor.putString(KEY_FORMLIST_URL, getString(R.string.default_odk_formlist));
editor.putString(KEY_SUBMISSION_URL, getString(R.string.default_odk_submission));
editor.commit();
}
/**
* Disallows carriage returns from user entry
*
* @return
*/
protected InputFilter getReturnFilter() {
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;
}
};
return returnFilter;
}
/**
* Generic listener that sets the summary to the newly selected/entered value
*/
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary((CharSequence) newValue);
return true;
}
}
|
0nima0-f
|
src/org/odk/collect/android/preferences/PreferencesActivity.java
|
Java
|
asf20
| 22,137
|
package org.odk.collect.android.preferences;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
public class PasswordDialogPreference extends DialogPreference implements
OnClickListener {
private EditText passwordEditText;
private EditText verifyEditText;
public PasswordDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.password_dialog_layout);
}
@Override
public void onBindDialogView(View view) {
passwordEditText = (EditText) view.findViewById(R.id.pwd_field);
verifyEditText = (EditText) view.findViewById(R.id.verify_field);
final String adminPW = getPersistedString("");
// populate the fields if a pw exists
if (!adminPW.equalsIgnoreCase("")) {
passwordEditText.setText(adminPW);
passwordEditText.setSelection(passwordEditText.getText().length());
verifyEditText.setText(adminPW);
}
Button positiveButton = (Button) view
.findViewById(R.id.positive_button);
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String pw = passwordEditText.getText().toString();
String ver = verifyEditText.getText().toString();
if (!pw.equalsIgnoreCase("") && !ver.equalsIgnoreCase("") && pw.equals(ver)) {
// passwords are the same
persistString(pw);
Toast.makeText(PasswordDialogPreference.this.getContext(),
R.string.admin_password_changed, Toast.LENGTH_SHORT).show();
PasswordDialogPreference.this.getDialog().dismiss();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "CHANGED");
} else if (pw.equalsIgnoreCase("") && ver.equalsIgnoreCase("")) {
persistString("");
Toast.makeText(PasswordDialogPreference.this.getContext(),
R.string.admin_password_disabled, Toast.LENGTH_SHORT).show();
PasswordDialogPreference.this.getDialog().dismiss();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "DISABLED");
} else {
Toast.makeText(PasswordDialogPreference.this.getContext(),
R.string.admin_password_mismatch, Toast.LENGTH_SHORT).show();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "MISMATCH");
}
}
});
Button negativeButton = (Button) view.findViewById(R.id.negative_button);
negativeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasswordDialogPreference.this.getDialog().dismiss();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "CANCELLED");
}
});
super.onBindDialogView(view);
}
@Override
protected void onClick() {
super.onClick();
// this seems to work to pop the keyboard when the dialog appears
// i hope this isn't a race condition
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
// we get rid of the default buttons (that close the dialog every time)
builder.setPositiveButton(null, null);
builder.setNegativeButton(null, null);
super.onPrepareDialogBuilder(builder);
}
}
|
0nima0-f
|
src/org/odk/collect/android/preferences/PasswordDialogPreference.java
|
Java
|
asf20
| 4,336
|
/*
* 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.preferences;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import android.preference.ListPreference;
import android.preference.Preference;
import org.javarosa.core.model.FormDef;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.CompatibilityUtils;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
/**
* Handles admin preferences, which are password-protectable and govern which app features and
* general preferences the end user of the app will be able to see.
*
* @author Thomas Smyth, Sassafras Tech Collective (tom@sassafrastech.com; constraint behavior option)
*/
public class AdminPreferencesActivity extends PreferenceActivity {
public static String ADMIN_PREFERENCES = "admin_prefs";
// key for this preference screen
public static String KEY_ADMIN_PW = "admin_pw";
// keys for each preference
// main menu
public static String KEY_EDIT_SAVED = "edit_saved";
public static String KEY_SEND_FINALIZED = "send_finalized";
public static String KEY_GET_BLANK = "get_blank";
public static String KEY_DELETE_SAVED = "delete_saved";
// server
public static String KEY_CHANGE_SERVER = "change_server";
public static String KEY_CHANGE_USERNAME = "change_username";
public static String KEY_CHANGE_PASSWORD = "change_password";
public static String KEY_CHANGE_GOOGLE_ACCOUNT = "change_google_account";
public static String KEY_CHANGE_PROTOCOL_SETTINGS = "change_protocol_settings";
// client
public static String KEY_CHANGE_FONT_SIZE = "change_font_size";
public static String KEY_DEFAULT_TO_FINALIZED = "default_to_finalized";
public static String KEY_HIGH_RESOLUTION = "high_resolution";
public static String KEY_SHOW_SPLASH_SCREEN = "show_splash_screen";
public static String KEY_SELECT_SPLASH_SCREEN = "select_splash_screen";
public static String KEY_DELETE_AFTER_SEND = "delete_after_send";
// form entry
public static String KEY_SAVE_MID = "save_mid";
public static String KEY_JUMP_TO = "jump_to";
public static String KEY_CHANGE_LANGUAGE = "change_language";
public static String KEY_ACCESS_SETTINGS = "access_settings";
public static String KEY_SAVE_AS = "save_as";
public static String KEY_MARK_AS_FINALIZED = "mark_as_finalized";
public static String KEY_AUTOSEND_WIFI = "autosend_wifi";
public static String KEY_AUTOSEND_NETWORK = "autosend_network";
public static String KEY_NAVIGATION = "navigation";
public static String KEY_CONSTRAINT_BEHAVIOR = "constraint_behavior";
public static String KEY_FORM_PROCESSING_LOGIC = "form_processing_logic";
private static final int SAVE_PREFS_MENU = Menu.FIRST;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.admin_preferences));
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName(ADMIN_PREFERENCES);
prefMgr.setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.admin_preferences);
ListPreference mFormProcessingLogicPreference = (ListPreference) findPreference(KEY_FORM_PROCESSING_LOGIC);
mFormProcessingLogicPreference.setSummary(mFormProcessingLogicPreference.getEntry());
mFormProcessingLogicPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference).getEntries()[index];
preference.setSummary(entry);
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
CompatibilityUtils.setShowAsAction(
menu.add(0, SAVE_PREFS_MENU, 0, R.string.save_preferences)
.setIcon(R.drawable.ic_menu_save),
MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case SAVE_PREFS_MENU:
File writeDir = new File(Collect.ODK_ROOT + "/settings");
if (!writeDir.exists()) {
if (!writeDir.mkdirs()) {
Toast.makeText(
this,
"Error creating directory "
+ writeDir.getAbsolutePath(),
Toast.LENGTH_SHORT).show();
return false;
}
}
File dst = new File(writeDir.getAbsolutePath()
+ "/collect.settings");
boolean success = AdminPreferencesActivity.saveSharedPreferencesToFile(dst, this);
if (success) {
Toast.makeText(
this,
"Settings successfully written to "
+ dst.getAbsolutePath(), Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this,
"Error writing settings to " + dst.getAbsolutePath(),
Toast.LENGTH_LONG).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public static boolean saveSharedPreferencesToFile(File dst, Context context) {
// this should be in a thread if it gets big, but for now it's tiny
boolean res = false;
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences adminPreferences = context.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
output.writeObject(pref.getAll());
output.writeObject(adminPreferences.getAll());
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
public static FormDef.EvalBehavior getConfiguredFormProcessingLogic(Context context) {
FormDef.EvalBehavior mode;
SharedPreferences adminPreferences = context.getSharedPreferences(ADMIN_PREFERENCES, 0);
String formProcessingLoginIndex = adminPreferences.getString(KEY_FORM_PROCESSING_LOGIC, context.getString(R.string.default_form_processing_logic));
try {
if ("-1".equals(formProcessingLoginIndex)) {
mode = FormDef.recommendedMode;
} else {
int preferredModeIndex = Integer.parseInt(formProcessingLoginIndex);
switch (preferredModeIndex) {
case 0: {
mode = FormDef.EvalBehavior.Fast_2014;
break;
}
case 1: {
mode = FormDef.EvalBehavior.Safe_2014;
break;
}
case 2: {
mode = FormDef.EvalBehavior.April_2014;
break;
}
case 3: {
mode = FormDef.EvalBehavior.Legacy;
break;
}
default: {
mode = FormDef.recommendedMode;
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
Log.w("AdminPreferencesActivity", "Unable to get EvalBehavior -- defaulting to recommended mode");
mode = FormDef.recommendedMode;
}
return mode;
}
}
|
0nima0-f
|
src/org/odk/collect/android/preferences/AdminPreferencesActivity.java
|
Java
|
asf20
| 8,489
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class MediaContent {
@Key("@type")
public String type;
@Key("@url")
public String url;
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/MediaContent.java
|
Java
|
asf20
| 808
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.util.List;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Feed {
@Key
public Author author;
@Key("openSearch:totalResults")
public int totalResults;
@Key("link")
public List<Link> links;
public String getPostLink() {
return Link.find(links, "http://schemas.google.com/g/2005#post");
}
public String getNextLink() {
return Link.find(links, "next");
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/Feed.java
|
Java
|
asf20
| 1,066
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.odk.collect.android.picasa;
import java.util.List;
import java.util.Map;
/**
* Represents the result of an HTTP request. Adapted from Ruby's "Rack" Web interface.
*/
public class Response {
/**
* The HTTP status code
*/
public int status;
/**
* The HTTP headers received in the response
*/
public Map<String, List<String>> headers;
/**
* The response body, if any
*/
public byte[] body;
public Response(int status, Map<String, List<String>> headers, byte[] body) {
this.status = status; this.headers = headers; this.body = body;
}
public Response(int status, Map<String, List<String>> headers, String body) {
this.status = status; this.headers = headers; this.body = body.getBytes();
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/Response.java
|
Java
|
asf20
| 1,406
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Category {
@Key("@scheme")
public String scheme;
@Key("@term")
public String term;
public static Category newKind(String kind) {
Category category = new Category();
category.scheme = "http://schemas.google.com/g/2005#kind";
category.term = "http://schemas.google.com/photos/2007#" + kind;
return category;
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/Category.java
|
Java
|
asf20
| 1,056
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class PicasaUrl extends GenericUrl {
/** Whether to pretty print HTTP requests and responses. */
private static final boolean PRETTY_PRINT = true;
public static final String ROOT_URL = "https://picasaweb.google.com/data/";
@Key("max-results")
public Integer maxResults;
@Key
public String kinds;
public PicasaUrl(String url) {
super(url);
this.set("prettyPrint", PRETTY_PRINT);
}
/**
* Constructs a new Picasa Web Albums URL based on the given relative path.
*
* @param relativePath encoded path relative to the {@link #ROOT_URL}
* @return new Picasa URL
*/
public static PicasaUrl relativeToRoot(String relativePath) {
return new PicasaUrl(ROOT_URL + relativePath);
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/PicasaUrl.java
|
Java
|
asf20
| 1,488
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.util.List;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class UserFeed extends Feed {
@Key("entry")
public List<AlbumEntry> albums;
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/UserFeed.java
|
Java
|
asf20
| 816
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.util.List;
import com.google.api.client.util.Data;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Entry implements Cloneable {
@Key("@gd:etag")
public String etag;
@Key("link")
public List<Link> links;
@Key
public String summary;
@Key
public String title;
@Key
public String updated;
@Key("content")
public Content content;
public String getFeedLink() {
return Link.find(links, "http://schemas.google.com/g/2005#feed");
}
public String getSelfLink() {
return Link.find(links, "self");
}
public String getImageLink() {
return content.src;
}
@Override
protected Entry clone() {
try {
@SuppressWarnings("unchecked")
Entry result = (Entry) super.clone();
Data.deepCopy(this, result);
return result;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
public String getEditLink() {
return Link.find(links, "edit");
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/Entry.java
|
Java
|
asf20
| 1,645
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class AlbumEntry extends Entry {
@Key("gphoto:access")
public String access;
@Key
public Category category = Category.newKind("album");
@Key("gphoto:numphotos")
public int numPhotos;
@Override
public AlbumEntry clone() {
return (AlbumEntry) super.clone();
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/AlbumEntry.java
|
Java
|
asf20
| 995
|
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.io.IOException;
import java.util.Arrays;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.MultipartContent;
import com.google.api.client.http.xml.atom.AtomContent;
import com.google.api.client.xml.XmlNamespaceDictionary;
import com.google.api.client.xml.atom.Atom;
/**
* Client for the Picasa Web Albums Data API.
*
* @author Yaniv Inbar
*/
public final class PicasaClient extends GDataXmlClient {
static final XmlNamespaceDictionary DICTIONARY =
new XmlNamespaceDictionary().set("", "http://www.w3.org/2005/Atom")
.set("exif", "http://schemas.google.com/photos/exif/2007")
.set("gd", "http://schemas.google.com/g/2005")
.set("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#")
.set("georss", "http://www.georss.org/georss")
.set("gml", "http://www.opengis.net/gml")
.set("gphoto", "http://schemas.google.com/photos/2007")
.set("media", "http://search.yahoo.com/mrss/")
.set("openSearch", "http://a9.com/-/spec/opensearch/1.1/")
.set("xml", "http://www.w3.org/XML/1998/namespace");
public PicasaClient(HttpRequestFactory requestFactory) {
super("2", requestFactory, DICTIONARY);
}
public void executeDelete(Entry entry) throws IOException {
PicasaUrl url = new PicasaUrl(entry.getEditLink());
super.executeDelete(url, entry.etag);
}
<T> T executeGet(PicasaUrl url, Class<T> parseAsType) throws IOException {
return super.executeGet(url, parseAsType);
}
public <T extends Entry> T executePatchRelativeToOriginal(T original, T updated)
throws IOException {
PicasaUrl url = new PicasaUrl(updated.getEditLink());
return super.executePatchRelativeToOriginal(url, original, updated, original.etag);
}
<T> T executePost(PicasaUrl url, T content) throws IOException {
return super.executePost(url, content instanceof Feed, content);
}
public AlbumEntry executeGetAlbum(String link) throws IOException {
PicasaUrl url = new PicasaUrl(link);
return executeGet(url, AlbumEntry.class);
}
public <T extends Entry> T executeInsert(PicasaUrl url, T entry) throws IOException {
return executePost(url, entry);
}
public <T extends Entry> T executeInsert(Feed feed, T entry) throws IOException {
return executeInsert(new PicasaUrl(feed.getPostLink()), entry);
}
public AlbumFeed executeGetAlbumFeed(PicasaUrl url) throws IOException {
url.kinds = "photo";
url.maxResults = 5;
return executeGet(url, AlbumFeed.class);
}
public UserFeed executeGetUserFeed(PicasaUrl url) throws IOException {
url.kinds = "album";
return executeGet(url, UserFeed.class);
}
public PhotoEntry executeInsertPhotoEntry(
PicasaUrl albumFeedUrl, InputStreamContent content, String fileName) throws IOException {
HttpRequest request = getRequestFactory().buildPostRequest(albumFeedUrl, content);
HttpHeaders headers = new HttpHeaders();
Atom.setSlugHeader(headers, fileName);
request.setHeaders(headers);
return execute(request).parseAs(PhotoEntry.class);
}
public PhotoEntry executeInsertPhotoEntryWithMetadata(
PhotoEntry photo, PicasaUrl albumFeedUrl, AbstractInputStreamContent content)
throws IOException {
HttpRequest request = getRequestFactory().buildPostRequest(albumFeedUrl, null);
AtomContent atomContent = AtomContent.forEntry(DICTIONARY, photo);
request.setContent(new MultipartContent().setContentParts(Arrays.asList(atomContent, content)));
request.getHeaders().setMimeVersion("1.0");
return execute(request).parseAs(PhotoEntry.class);
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/PicasaClient.java
|
Java
|
asf20
| 4,495
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Author {
@Key
public String name;
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/Author.java
|
Java
|
asf20
| 756
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.util.List;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class AlbumFeed extends Feed {
@Key("entry")
public List<PhotoEntry> photos;
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/AlbumFeed.java
|
Java
|
asf20
| 819
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.util.Key;
public class Content {
@Key("@type")
public String type;
@Key("@src")
public String src;
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/Content.java
|
Java
|
asf20
| 774
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class PhotoEntry extends Entry {
@Key
public Category category = Category.newKind("photo");
@Key("media:group")
public MediaGroup mediaGroup;
@Key("gphoto:id")
public String id;
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/PhotoEntry.java
|
Java
|
asf20
| 906
|
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.io.IOException;
import com.google.api.client.googleapis.xml.atom.AtomPatchRelativeToOriginalContent;
import com.google.api.client.googleapis.xml.atom.GoogleAtom;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.xml.atom.AtomContent;
import com.google.api.client.xml.XmlNamespaceDictionary;
import com.google.api.client.xml.XmlObjectParser;
/**
* GData XML client.
*
* @author Yaniv Inbar
*/
public abstract class GDataXmlClient extends GDataClient {
private final XmlNamespaceDictionary namespaceDictionary;
private boolean partialResponse = true;
protected GDataXmlClient(String gdataVersion, HttpRequestFactory requestFactory,
XmlNamespaceDictionary namespaceDictionary) {
super(gdataVersion, requestFactory);
this.namespaceDictionary = namespaceDictionary;
}
public XmlNamespaceDictionary getNamespaceDictionary() {
return namespaceDictionary;
}
@Override
protected void prepare(HttpRequest request) throws IOException {
super.prepare(request);
request.setParser(new XmlObjectParser(namespaceDictionary));
}
public final boolean getPartialResponse() {
return partialResponse;
}
public final void setPartialResponse(boolean partialResponse) {
this.partialResponse = partialResponse;
}
@Override
protected void prepareUrl(GenericUrl url, Class<?> parseAsType) {
super.prepareUrl(url, parseAsType);
if (partialResponse && parseAsType != null) {
url.put("fields", GoogleAtom.getFieldsFor(parseAsType));
}
}
protected final <T> T executePatchRelativeToOriginal(
GenericUrl url, T original, T updated, String etag) throws IOException {
AtomPatchRelativeToOriginalContent content =
new AtomPatchRelativeToOriginalContent(namespaceDictionary, original, updated);
@SuppressWarnings("unchecked")
Class<T> parseAsType = (Class<T>) updated.getClass();
return executePatchRelativeToOriginal(url, content, parseAsType, etag);
}
protected final <T> T executePost(GenericUrl url, boolean isFeed, T content) throws IOException {
AtomContent atomContent = isFeed ? AtomContent.forFeed(namespaceDictionary, content)
: AtomContent.forEntry(namespaceDictionary, content);
@SuppressWarnings("unchecked")
Class<T> parseAsType = (Class<T>) content.getClass();
return executePost(url, atomContent, parseAsType);
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/GDataXmlClient.java
|
Java
|
asf20
| 3,131
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class MediaGroup {
@Key("media:content")
public MediaContent content;
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/MediaGroup.java
|
Java
|
asf20
| 785
|
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.io.IOException;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.http.AbstractHttpContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
/**
* GData client.
*
* @author Yaniv Inbar
*/
public abstract class GDataClient {
private HttpRequestFactory requestFactory;
private final String gdataVersion;
private String applicationName;
private boolean prettyPrint;
/** Method override needed for PATCH. */
final MethodOverride override = new MethodOverride();
protected GDataClient(String gdataVersion, HttpRequestFactory requestFactory) {
this.gdataVersion = gdataVersion;
this.requestFactory = requestFactory;
}
protected final HttpRequestFactory getRequestFactory() {
return requestFactory;
}
public final String getApplicationName() {
return applicationName;
}
public final void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public final boolean getPrettyPrint() {
return prettyPrint;
}
public final void setPrettyPrint(boolean prettyPrint) {
this.prettyPrint = prettyPrint;
}
protected final HttpTransport getTransport() {
return getRequestFactory().getTransport();
}
protected void prepareUrl(GenericUrl url, Class<?> parseAsType){
url.set("prettyPrint", this.prettyPrint);
}
protected void prepare(HttpRequest request) throws IOException {
request.getHeaders().setUserAgent(applicationName);
request.getHeaders().put("GData-Version", gdataVersion);
override.intercept(request);
}
protected final HttpResponse execute(HttpRequest request) throws IOException {
prepare(request);
return request.execute();
}
protected final <T> T executeGet(GenericUrl url, Class<T> parseAsType) throws IOException {
prepareUrl(url, parseAsType);
HttpRequest request = getRequestFactory().buildGetRequest(url);
return execute(request).parseAs(parseAsType);
}
protected final void executeDelete(GenericUrl url, String etag) throws IOException {
prepareUrl(url, null);
HttpRequest request = getRequestFactory().buildDeleteRequest(url);
setIfMatch(request, etag);
execute(request).ignore();
}
protected final <T> T executePost(
GenericUrl url, AbstractHttpContent content, Class<T> parseAsType) throws IOException {
prepareUrl(url, parseAsType);
HttpRequest request = getRequestFactory().buildPostRequest(url, content);
return execute(request).parseAs(parseAsType);
}
protected final <T> T executePatchRelativeToOriginal(
GenericUrl url, AbstractHttpContent patchContent, Class<T> parseAsType, String etag)
throws IOException {
prepareUrl(url, parseAsType);
HttpRequest request = getRequestFactory().buildRequest("PATCH", url, patchContent);
setIfMatch(request, etag);
return execute(request).parseAs(parseAsType);
}
private void setIfMatch(HttpRequest request, String etag) {
if (etag != null && !etag.startsWith("W/")) {
request.getHeaders().setIfMatch(etag);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/GDataClient.java
|
Java
|
asf20
| 3,911
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.picasa;
import java.util.List;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Link {
@Key("@href")
public String href;
@Key("@rel")
public String rel;
public static String find(List<Link> links, String rel) {
if (links != null) {
for (Link link : links) {
if (rel.equals(link.rel)) {
return link.href;
}
}
}
return null;
}
}
|
0nima0-f
|
src/org/odk/collect/android/picasa/Link.java
|
Java
|
asf20
| 1,051
|
/*
* 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.logic;
import org.javarosa.core.model.FormIndex;
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
public class HierarchyElement {
private String mPrimaryText = "";
private String mSecondaryText = "";
private Drawable mIcon;
private int mColor;
int mType;
FormIndex mFormIndex;
ArrayList<HierarchyElement> mChildren;
public HierarchyElement(String text1, String text2, Drawable bullet, int color, int type,
FormIndex f) {
mIcon = bullet;
mPrimaryText = text1;
mSecondaryText = text2;
mColor = color;
mFormIndex = f;
mType = type;
mChildren = new ArrayList<HierarchyElement>();
}
public String getPrimaryText() {
return mPrimaryText;
}
public String getSecondaryText() {
return mSecondaryText;
}
public void setPrimaryText(String text) {
mPrimaryText = text;
}
public void setSecondaryText(String text) {
mSecondaryText = text;
}
public void setIcon(Drawable icon) {
mIcon = icon;
}
public Drawable getIcon() {
return mIcon;
}
public FormIndex getFormIndex() {
return mFormIndex;
}
public int getType() {
return mType;
}
public void setType(int newType) {
mType = newType;
}
public ArrayList<HierarchyElement> getChildren() {
return mChildren;
}
public void addChild(HierarchyElement h) {
mChildren.add(h);
}
public void setChildren(ArrayList<HierarchyElement> children) {
mChildren = children;
}
public void setColor(int color) {
mColor = color;
}
public int getColor() {
return mColor;
}
}
|
0nima0-f
|
src/org/odk/collect/android/logic/HierarchyElement.java
|
Java
|
asf20
| 2,413
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.odk.collect.android.logic;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.api.client.util.DateTime;
public class DriveListItem implements Comparable<DriveListItem>, Parcelable {
private String name;
private String data;
private String path;
private String image;
private String driveId;
private String parentId;
private DateTime date;
private int type;
public static final int FILE = 1;
public static final int DIR = 2;
public static final int UP = 3;
public static final int MY_DRIVE = 4;
public static final int SHARED_WITH_ME = 5;
public DriveListItem(String n, String d, DateTime dt, String p, String img, int type, String driveId, String parentId) {
name = n;
data = d;
date = dt;
path = p;
image = img;
this.type = type;
this.driveId = driveId;
this.parentId = parentId;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
public DateTime getDate() {
return date;
}
public String getPath() {
return path;
}
public String getImage() {
return image;
}
public int getType() {
return type;
}
public String getDriveId() {
return driveId;
}
public String getParentId() {
return parentId;
}
public int compareTo(DriveListItem o) {
if (this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.data);
dest.writeString(this.path);
dest.writeString(this.image);
dest.writeString(this.driveId);
dest.writeString(this.parentId);
dest.writeLong(date.getValue());
dest.writeInt(this.type);
}
public DriveListItem(Parcel pc) {
name = pc.readString();
data = pc.readString();
path = pc.readString();
image = pc.readString();
driveId = pc.readString();
parentId = pc.readString();
date = new DateTime(pc.readLong());
type = pc.readInt();
}
public static final Parcelable.Creator<DriveListItem> CREATOR = new Parcelable.Creator<DriveListItem>() {
public DriveListItem createFromParcel(Parcel pc) {
return new DriveListItem(pc);
}
public DriveListItem[] newArray(int size) {
return new DriveListItem[size];
}
};
}
|
0nima0-f
|
src/org/odk/collect/android/logic/DriveListItem.java
|
Java
|
asf20
| 3,233
|
/**
*
*/
package org.odk.collect.android.logic;
import org.javarosa.core.reference.PrefixedRootFactory;
import org.javarosa.core.reference.Reference;
/**
* @author ctsims
*/
public class FileReferenceFactory extends PrefixedRootFactory {
String localRoot;
public FileReferenceFactory(String localRoot) {
super(new String[] {
"file"
});
this.localRoot = localRoot;
}
@Override
protected Reference factory(String terminal, String URI) {
return new FileReference(localRoot, terminal);
}
}
|
0nima0-f
|
src/org/odk/collect/android/logic/FileReferenceFactory.java
|
Java
|
asf20
| 599
|
/*
* 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.logic;
import java.io.Serializable;
public class FormDetails implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public final String errorStr;
public final String formName;
public final String downloadUrl;
public final String manifestUrl;
public final String formID;
public final String formVersion;
public FormDetails(String error) {
manifestUrl = null;
downloadUrl = null;
formName = null;
formID = null;
formVersion = null;
errorStr = error;
}
public FormDetails(String name, String url, String manifest, String id, String version) {
manifestUrl = manifest;
downloadUrl = url;
formName = name;
formID = id;
formVersion = version;
errorStr = null;
}
}
|
0nima0-f
|
src/org/odk/collect/android/logic/FormDetails.java
|
Java
|
asf20
| 1,488
|
/**
*
*/
package org.odk.collect.android.logic;
import org.javarosa.core.reference.Reference;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author ctsims
*/
public class FileReference implements Reference {
String localPart;
String referencePart;
public FileReference(String localPart, String referencePart) {
this.localPart = localPart;
this.referencePart = referencePart;
}
private String getInternalURI() {
return "/" + localPart + referencePart;
}
@Override
public boolean doesBinaryExist() {
return new File(getInternalURI()).exists();
}
@Override
public InputStream getStream() throws IOException {
return new FileInputStream(getInternalURI());
}
@Override
public String getURI() {
return "jr://file" + referencePart;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public OutputStream getOutputStream() throws IOException {
return new FileOutputStream(getInternalURI());
}
@Override
public void remove() {
// TODO bad practice to ignore return values
new File(getInternalURI()).delete();
}
@Override
public String getLocalURI() {
return getInternalURI();
}
@Override
public Reference[] probeAlternativeReferences() {
//We can't poll the JAR for resources, unfortunately. It's possible
//we could try to figure out something about the file and poll alternatives
//based on type (PNG-> JPG, etc)
return new Reference [0];
}
}
|
0nima0-f
|
src/org/odk/collect/android/logic/FileReference.java
|
Java
|
asf20
| 1,806
|
/*
* 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.logic;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.javarosa.core.services.IPropertyManager;
import org.javarosa.core.services.properties.IPropertyRules;
import org.odk.collect.android.preferences.PreferencesActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* Used to return device properties to JavaRosa
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class PropertyManager implements IPropertyManager {
private String t = "PropertyManager";
private Context mContext;
private TelephonyManager mTelephonyManager;
private HashMap<String, String> mProperties;
public final static String DEVICE_ID_PROPERTY = "deviceid"; // imei
private final static String SUBSCRIBER_ID_PROPERTY = "subscriberid"; // imsi
private final static String SIM_SERIAL_PROPERTY = "simserial";
private final static String PHONE_NUMBER_PROPERTY = "phonenumber";
private final static String USERNAME = "username";
private final static String EMAIL = "email";
public final static String OR_DEVICE_ID_PROPERTY = "uri:deviceid"; // imei
public final static String OR_SUBSCRIBER_ID_PROPERTY = "uri:subscriberid"; // imsi
public final static String OR_SIM_SERIAL_PROPERTY = "uri:simserial";
public final static String OR_PHONE_NUMBER_PROPERTY = "uri:phonenumber";
public final static String OR_USERNAME = "uri:username";
public final static String OR_EMAIL = "uri:email";
public String getName() {
return "Property Manager";
}
public PropertyManager(Context context) {
Log.i(t, "calling constructor");
mContext = context;
mProperties = new HashMap<String, String>();
mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId = mTelephonyManager.getDeviceId();
String orDeviceId = null;
if (deviceId != null ) {
if ((deviceId.contains("*") || deviceId.contains("000000000000000"))) {
deviceId =
Settings.Secure
.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
orDeviceId = Settings.Secure.ANDROID_ID + ":" + deviceId;
} else {
orDeviceId = "imei:" + deviceId;
}
}
if ( deviceId == null ) {
// no SIM -- WiFi only
// Retrieve WiFiManager
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
if ( info != null ) {
deviceId = info.getMacAddress();
orDeviceId = "mac:" + deviceId;
}
}
// if it is still null, use ANDROID_ID
if ( deviceId == null ) {
deviceId =
Settings.Secure
.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
orDeviceId = Settings.Secure.ANDROID_ID + ":" + deviceId;
}
mProperties.put(DEVICE_ID_PROPERTY, deviceId);
mProperties.put(OR_DEVICE_ID_PROPERTY, orDeviceId);
String value;
value = mTelephonyManager.getSubscriberId();
if ( value != null ) {
mProperties.put(SUBSCRIBER_ID_PROPERTY, value);
mProperties.put(OR_SUBSCRIBER_ID_PROPERTY, "imsi:" + value);
}
value = mTelephonyManager.getSimSerialNumber();
if ( value != null ) {
mProperties.put(SIM_SERIAL_PROPERTY, value);
mProperties.put(OR_SIM_SERIAL_PROPERTY, "simserial:" + value);
}
value = mTelephonyManager.getLine1Number();
if ( value != null ) {
mProperties.put(PHONE_NUMBER_PROPERTY, value);
mProperties.put(OR_PHONE_NUMBER_PROPERTY, "tel:" + value);
}
// Get the username from the settings
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
value = settings.getString(PreferencesActivity.KEY_USERNAME, null);
if ( value != null ) {
mProperties.put(USERNAME, value);
mProperties.put(OR_USERNAME, "username:" + value);
}
value = settings.getString(PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null);
if ( value != null ) {
mProperties.put(EMAIL, value);
mProperties.put(OR_EMAIL, "mailto:" + value);
}
}
@Override
public List<String> getProperty(String propertyName) {
return null;
}
@Override
public String getSingularProperty(String propertyName) {
// for now, all property names are in english...
return mProperties.get(propertyName.toLowerCase(Locale.ENGLISH));
}
@Override
public void setProperty(String propertyName, String propertyValue) {
}
@Override
public void setProperty(String propertyName, List<String> propertyValue) {
}
@Override
public void addRules(IPropertyRules rules) {
}
@Override
public List<IPropertyRules> getRules() {
return null;
}
}
|
0nima0-f
|
src/org/odk/collect/android/logic/PropertyManager.java
|
Java
|
asf20
| 5,971
|
/*
* Copyright (C) 2009 JavaRosa
*
* 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.logic;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.GroupDef;
import org.javarosa.core.model.IDataReference;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.SubmissionProfile;
import org.javarosa.core.model.ValidateOutcome;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.services.IPropertyManager;
import org.javarosa.core.services.PrototypeManager;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormSerializingVisitor;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.model.xform.XPathReference;
import org.javarosa.xform.parse.XFormParser;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.XPathExpression;
import org.odk.collect.android.exception.JavaRosaException;
import org.odk.collect.android.views.ODKView;
import android.util.Log;
/**
* This class is a wrapper for Javarosa's FormEntryController. In theory, if you wanted to replace
* javarosa as the form engine, you should only need to replace the methods in this file. Also, we
* haven't wrapped every method provided by FormEntryController, only the ones we've needed so far.
* Feel free to add more as necessary.
*
* @author carlhartung
*/
public class FormController {
private static final String t = "FormController";
public static final boolean STEP_INTO_GROUP = true;
public static final boolean STEP_OVER_GROUP = false;
/**
* OpenRosa metadata tag names.
*/
private static final String INSTANCE_ID = "instanceID";
private static final String INSTANCE_NAME = "instanceName";
/**
* OpenRosa metadata of a form instance.
*
* Contains the values for the required metadata
* fields and nothing else.
*
* @author mitchellsundt@gmail.com
*
*/
public static final class InstanceMetadata {
public final String instanceId;
public final String instanceName;
InstanceMetadata( String instanceId, String instanceName ) {
this.instanceId = instanceId;
this.instanceName = instanceName;
}
};
/**
* Classes needed to serialize objects. Need to put anything from JR in here.
*/
private final static String[] SERIALIABLE_CLASSES = {
"org.javarosa.core.services.locale.ResourceFileDataSource", // JavaRosaCoreModule
"org.javarosa.core.services.locale.TableLocaleSource", // JavaRosaCoreModule
"org.javarosa.core.model.FormDef",
"org.javarosa.core.model.SubmissionProfile", // CoreModelModule
"org.javarosa.core.model.QuestionDef", // CoreModelModule
"org.javarosa.core.model.GroupDef", // CoreModelModule
"org.javarosa.core.model.instance.FormInstance", // CoreModelModule
"org.javarosa.core.model.data.BooleanData", // CoreModelModule
"org.javarosa.core.model.data.DateData", // CoreModelModule
"org.javarosa.core.model.data.DateTimeData", // CoreModelModule
"org.javarosa.core.model.data.DecimalData", // CoreModelModule
"org.javarosa.core.model.data.GeoPointData", // CoreModelModule
"org.javarosa.core.model.data.GeoShapeData", // CoreModelModule
"org.javarosa.core.model.data.GeoTraceData", // CoreModelModule
"org.javarosa.core.model.data.IntegerData", // CoreModelModule
"org.javarosa.core.model.data.LongData", // CoreModelModule
"org.javarosa.core.model.data.MultiPointerAnswerData", // CoreModelModule
"org.javarosa.core.model.data.PointerAnswerData", // CoreModelModule
"org.javarosa.core.model.data.SelectMultiData", // CoreModelModule
"org.javarosa.core.model.data.SelectOneData", // CoreModelModule
"org.javarosa.core.model.data.StringData", // CoreModelModule
"org.javarosa.core.model.data.TimeData", // CoreModelModule
"org.javarosa.core.model.data.UncastData", // CoreModelModule
"org.javarosa.core.model.data.helper.BasicDataPointer", // CoreModelModule
"org.javarosa.core.model.Action", // CoreModelModule
"org.javarosa.core.model.actions.SetValueAction" // CoreModelModule
};
private static boolean isJavaRosaInitialized = false;
/**
* Isolate the initialization of JavaRosa into one method, called first
* by the Collect Application. Called subsequently whenever the Preferences
* dialogs are exited (to potentially update username and email fields).
*
* @param mgr
*/
public static synchronized void initializeJavaRosa(IPropertyManager mgr) {
if ( !isJavaRosaInitialized ) {
// need a list of classes that formdef uses
// unfortunately, the JR registerModule() functions do more than this.
// register just the classes that would have been registered by:
// new JavaRosaCoreModule().registerModule();
// new CoreModelModule().registerModule();
// replace with direct call to PrototypeManager
PrototypeManager.registerPrototypes(SERIALIABLE_CLASSES);
new XFormsModule().registerModule();
isJavaRosaInitialized = true;
}
// needed to override rms property manager
org.javarosa.core.services.PropertyManager
.setPropertyManager(mgr);
}
private File mMediaFolder;
private File mInstancePath;
private FormEntryController mFormEntryController;
private FormIndex mIndexWaitingForData = null;
public FormController(File mediaFolder, FormEntryController fec, File instancePath) {
mMediaFolder = mediaFolder;
mFormEntryController = fec;
mInstancePath = instancePath;
}
public FormDef getFormDef() {
return mFormEntryController.getModel().getForm();
}
public File getMediaFolder() {
return mMediaFolder;
}
public File getInstancePath() {
return mInstancePath;
}
public void setInstancePath(File instancePath) {
mInstancePath = instancePath;
}
public void setIndexWaitingForData(FormIndex index) {
mIndexWaitingForData = index;
}
public FormIndex getIndexWaitingForData() {
return mIndexWaitingForData;
}
/**
* For logging purposes...
*
* @param index
* @return xpath value for this index
*/
public String getXPath(FormIndex index) {
String value;
switch ( getEvent() ) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
value = "beginningOfForm";
break;
case FormEntryController.EVENT_END_OF_FORM:
value = "endOfForm";
break;
case FormEntryController.EVENT_GROUP:
value = "group." + index.getReference().toString();
break;
case FormEntryController.EVENT_QUESTION:
value = "question." + index.getReference().toString();
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
value = "promptNewRepeat." + index.getReference().toString();
break;
case FormEntryController.EVENT_REPEAT:
value = "repeat." + index.getReference().toString();
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
value = "repeatJuncture." + index.getReference().toString();
break;
default:
value = "unexpected";
break;
}
return value;
}
public FormIndex getIndexFromXPath(String xPath) {
if ( xPath.equals("beginningOfForm") ) {
return FormIndex.createBeginningOfFormIndex();
} else if ( xPath.equals("endOfForm") ) {
return FormIndex.createEndOfFormIndex();
} else if ( xPath.equals("unexpected") ) {
Log.e(t, "Unexpected string from XPath");
throw new IllegalArgumentException("unexpected string from XPath");
} else {
FormIndex returned = null;
FormIndex saved = getFormIndex();
// the only way I know how to do this is to step through the entire form
// until the XPath of a form entry matches that of the supplied XPath
try {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
int event = stepToNextEvent(true);
while ( event != FormEntryController.EVENT_END_OF_FORM ) {
String candidateXPath = getXPath(getFormIndex());
// Log.i(t, "xpath: " + candidateXPath);
if ( candidateXPath.equals(xPath) ) {
returned = getFormIndex();
break;
}
event = stepToNextEvent(true);
}
} finally {
jumpToIndex(saved);
}
return returned;
}
}
/**
* returns the event for the current FormIndex.
*
* @return
*/
public int getEvent() {
return mFormEntryController.getModel().getEvent();
}
/**
* returns the event for the given FormIndex.
*
* @param index
* @return
*/
public int getEvent(FormIndex index) {
return mFormEntryController.getModel().getEvent(index);
}
/**
* @return current FormIndex.
*/
public FormIndex getFormIndex() {
return mFormEntryController.getModel().getFormIndex();
}
/**
* Return the langauges supported by the currently loaded form.
*
* @return Array of Strings containing the languages embedded in the XForm.
*/
public String[] getLanguages() {
return mFormEntryController.getModel().getLanguages();
}
/**
* @return A String containing the title of the current form.
*/
public String getFormTitle() {
return mFormEntryController.getModel().getFormTitle();
}
/**
* @return the currently selected language.
*/
public String getLanguage() {
return mFormEntryController.getModel().getLanguage();
}
public String getBindAttribute( String attributeNamespace, String attributeName) {
return getBindAttribute( getFormIndex(), attributeNamespace, attributeName );
}
public String getBindAttribute(FormIndex idx, String attributeNamespace, String attributeName) {
return mFormEntryController.getModel().getForm().getMainInstance().resolveReference(
idx.getReference()).getBindAttributeValue(attributeNamespace, attributeName);
}
/**
* @return an array of FormEntryCaptions for the current FormIndex. This is how we get group
* information Group 1 > Group 2> etc... The element at [size-1] is the current question
* text, with group names decreasing in hierarchy until array element at [0] is the root
*/
private FormEntryCaption[] getCaptionHierarchy() {
return mFormEntryController.getModel().getCaptionHierarchy();
}
/**
* @param index
* @return an array of FormEntryCaptions for the supplied FormIndex. This is how we get group
* information Group 1 > Group 2> etc... The element at [size-1] is the current question
* text, with group names decreasing in hierarchy until array element at [0] is the root
*/
private FormEntryCaption[] getCaptionHierarchy(FormIndex index) {
return mFormEntryController.getModel().getCaptionHierarchy(index);
}
/**
* Returns a caption prompt for the given index. This is used to create a multi-question per
* screen view.
*
* @param index
* @return
*/
public FormEntryCaption getCaptionPrompt(FormIndex index) {
return mFormEntryController.getModel().getCaptionPrompt(index);
}
/**
* Return the caption for the current FormIndex. This is usually used for a repeat prompt.
*
* @return
*/
public FormEntryCaption getCaptionPrompt() {
return mFormEntryController.getModel().getCaptionPrompt();
}
/**
* This fires off the jr:preload actions and events to save values like the
* end time of a form.
*
* @return
*/
public boolean postProcessInstance() {
return mFormEntryController.getModel().getForm().postProcessInstance();
}
/**
* TODO: We need a good description of what this does, exactly, and why.
*
* @return
*/
private FormInstance getInstance() {
return mFormEntryController.getModel().getForm().getInstance();
}
/**
* A convenience method for determining if the current FormIndex is in a group that is/should be
* displayed as a multi-question view. This is useful for returning from the formhierarchy view
* to a selected index.
*
* @param index
* @return
*/
private boolean groupIsFieldList(FormIndex index) {
// if this isn't a group, return right away
IFormElement element = mFormEntryController.getModel().getForm().getChild(index);
if (!(element instanceof GroupDef)) {
return false;
}
GroupDef gd = (GroupDef) element; // exceptions?
return (ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()));
}
private boolean repeatIsFieldList(FormIndex index) {
// if this isn't a group, return right away
IFormElement element = mFormEntryController.getModel().getForm().getChild(index);
if (!(element instanceof GroupDef)) {
return false;
}
GroupDef gd = (GroupDef) element; // exceptions?
return (ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()));
}
/**
* Tests if the FormIndex 'index' is located inside a group that is marked as a "field-list"
*
* @param index
* @return true if index is in a "field-list". False otherwise.
*/
private boolean indexIsInFieldList(FormIndex index) {
int event = getEvent(index);
if (event == FormEntryController.EVENT_QUESTION) {
// caption[0..len-1]
// caption[len-1] == the question itself
// caption[len-2] == the first group it is contained in.
FormEntryCaption[] captions = getCaptionHierarchy(index);
if (captions.length < 2) {
// no group
return false;
}
FormEntryCaption grp = captions[captions.length - 2];
return groupIsFieldList(grp.getIndex());
} else if (event == FormEntryController.EVENT_GROUP) {
return groupIsFieldList(index);
} else if (event == FormEntryController.EVENT_REPEAT) {
return repeatIsFieldList(index);
} else {
// right now we only test Questions and Groups. Should we also handle
// repeats?
return false;
}
}
public boolean currentPromptIsQuestion() {
return (getEvent() == FormEntryController.EVENT_QUESTION
|| ((getEvent() == FormEntryController.EVENT_GROUP ||
getEvent() == FormEntryController.EVENT_REPEAT)
&& indexIsInFieldList()));
}
/**
* Tests if the current FormIndex is located inside a group that is marked as a "field-list"
*
* @return true if index is in a "field-list". False otherwise.
*/
public boolean indexIsInFieldList() {
return indexIsInFieldList(getFormIndex());
}
/**
* Attempts to save answer into the given FormIndex into the data model.
*
* @param index
* @param data
* @return
*/
public int answerQuestion(FormIndex index, IAnswerData data) throws JavaRosaException {
try {
return mFormEntryController.answerQuestion(index, data, true);
} catch (Exception e) {
throw new JavaRosaException(e);
}
}
/**
* Goes through the entire form to make sure all entered answers comply with their constraints.
* Constraints are ignored on 'jump to', so answers can be outside of constraints. We don't
* allow saving to disk, though, until all answers conform to their constraints/requirements.
*
*
* @param markCompleted
* @return ANSWER_OK and leave index unchanged or change index to bad value and return error type.
* @throws JavaRosaException
*/
public int validateAnswers(Boolean markCompleted) throws JavaRosaException {
ValidateOutcome outcome = getFormDef().validate(markCompleted);
if ( outcome != null ) {
this.jumpToIndex(outcome.failedPrompt);
return outcome.outcome;
}
return FormEntryController.ANSWER_OK;
}
/**
* saveAnswer attempts to save the current answer into the data model without doing any
* constraint checking. Only use this if you know what you're doing. For normal form filling you
* should always use answerQuestion or answerCurrentQuestion.
*
* @param index
* @param data
* @return true if saved successfully, false otherwise.
*/
public boolean saveAnswer(FormIndex index, IAnswerData data) throws JavaRosaException {
try {
return mFormEntryController.saveAnswer(index, data, true);
} catch (Exception e) {
throw new JavaRosaException(e);
}
}
/**
* Navigates forward in the form.
*
* @return the next event that should be handled by a view.
*/
public int stepToNextEvent(boolean stepIntoGroup) {
if ((getEvent() == FormEntryController.EVENT_GROUP ||
getEvent() == FormEntryController.EVENT_REPEAT)
&& indexIsInFieldList() && !stepIntoGroup) {
return stepOverGroup();
} else {
return mFormEntryController.stepToNextEvent();
}
}
/**
* If using a view like HierarchyView that doesn't support multi-question per screen, step over
* the group represented by the FormIndex.
*
* @return
*/
private int stepOverGroup() {
ArrayList<FormIndex> indicies = new ArrayList<FormIndex>();
GroupDef gd =
(GroupDef) mFormEntryController.getModel().getForm()
.getChild(getFormIndex());
FormIndex idxChild =
mFormEntryController.getModel().incrementIndex(
getFormIndex(), true); // descend into group
for (int i = 0; i < gd.getChildren().size(); i++) {
indicies.add(idxChild);
// don't descend
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, false);
}
// jump to the end of the group
mFormEntryController.jumpToIndex(indicies.get(indicies.size() - 1));
return stepToNextEvent(STEP_OVER_GROUP);
}
/**
* used to go up one level in the formIndex. That is, if you're at 5_0, 1 (the second question
* in a repeating group), this method will return a FormInex of 5_0 (the start of the repeating
* group). If your at index 16 or 5_0, this will return null;
*
* @param index
* @return index
*/
public FormIndex stepIndexOut(FormIndex index) {
if (index.isTerminal()) {
return null;
} else {
return new FormIndex(stepIndexOut(index.getNextLevel()), index);
}
}
/**
* Move the current form index to the index of the previous question in the form.
* Step backward out of repeats and groups as needed. If the resulting question
* is itself within a field-list, move upward to the group or repeat defining that
* field-list.
*
* @return
*/
public int stepToPreviousScreenEvent() throws JavaRosaException {
try {
if (getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = stepToPreviousEvent();
while (event == FormEntryController.EVENT_REPEAT_JUNCTURE ||
event == FormEntryController.EVENT_PROMPT_NEW_REPEAT ||
(event == FormEntryController.EVENT_QUESTION && indexIsInFieldList()) ||
((event == FormEntryController.EVENT_GROUP
|| event == FormEntryController.EVENT_REPEAT) && !indexIsInFieldList())) {
event = stepToPreviousEvent();
}
// Work-around for broken field-list handling from 1.1.7 which breaks either
// build-generated forms or XLSForm-generated forms. If the current group
// is a GROUP with field-list and it is nested within a group or repeat with just
// this containing group, and that is also a field-list, then return the parent group.
if ( getEvent() == FormEntryController.EVENT_GROUP ) {
FormIndex currentIndex = getFormIndex();
IFormElement element = mFormEntryController.getModel().getForm().getChild(currentIndex);
if (element instanceof GroupDef) {
GroupDef gd = (GroupDef) element;
if ( ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()) ) {
// OK this group is a field-list... see what the parent is...
FormEntryCaption[] fclist = this.getCaptionHierarchy(currentIndex);
if ( fclist.length > 1) {
FormEntryCaption fc = fclist[fclist.length-2];
GroupDef pd = (GroupDef) fc.getFormElement();
if ( pd.getChildren().size() == 1 &&
ODKView.FIELD_LIST.equalsIgnoreCase(pd.getAppearanceAttr()) ) {
mFormEntryController.jumpToIndex(fc.getIndex());
}
}
}
}
}
}
return getEvent();
} catch (RuntimeException e) {
throw new JavaRosaException(e);
}
}
/**
* Move the current form index to the index of the next question in the form.
* Stop if we should ask to create a new repeat group or if we reach the end of the form.
* If we enter a group or repeat, return that if it is a field-list definition.
* Otherwise, descend into the group or repeat searching for the first question.
*
* @return
*/
public int stepToNextScreenEvent() throws JavaRosaException {
try {
if (getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
group_skip: do {
event = stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
break group_skip;
case FormEntryController.EVENT_GROUP:
case FormEntryController.EVENT_REPEAT:
if (indexIsInFieldList()
&& getQuestionPrompts().length != 0) {
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ 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;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
}
return getEvent();
} catch (RuntimeException e) {
throw new JavaRosaException(e);
}
}
/**
* Move the current form index to the index of the first enclosing repeat
* or to the start of the form.
*
* @return
*/
public int stepToOuterScreenEvent() {
FormIndex index = stepIndexOut(getFormIndex());
int currentEvent = getEvent();
// Step out of any group indexes that are present.
while (index != null
&& getEvent(index) == FormEntryController.EVENT_GROUP) {
index = stepIndexOut(index);
}
if (index == null) {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
} else {
if (currentEvent == FormEntryController.EVENT_REPEAT) {
// We were at a repeat, so stepping back brought us to then previous level
jumpToIndex(index);
} else {
// We were at a question, so stepping back brought us to either:
// The beginning. or The start of a repeat. So we need to step
// out again to go passed the repeat.
index = stepIndexOut(index);
if (index == null) {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
} else {
jumpToIndex(index);
}
}
}
return getEvent();
}
public static class FailedConstraint {
public final FormIndex index;
public final int status;
FailedConstraint(FormIndex index, int status) {
this.index = index;
this.status = status;
}
}
/**
*
* @param answers
* @param evaluateConstraints
* @return FailedConstraint of first failed constraint or null if all questions were saved.
*/
public FailedConstraint saveAllScreenAnswers(LinkedHashMap<FormIndex,IAnswerData> answers, boolean evaluateConstraints) throws JavaRosaException {
if (currentPromptIsQuestion()) {
Iterator<FormIndex> it = answers.keySet().iterator();
while (it.hasNext()) {
FormIndex index = it.next();
// Within a group, you can only save for question events
if (getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus;
IAnswerData answer = answers.get(index);
if (evaluateConstraints) {
saveStatus = answerQuestion(index, answer);
if (saveStatus != FormEntryController.ANSWER_OK) {
return new FailedConstraint(index, saveStatus);
}
} else {
saveAnswer(index, answer);
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
}
return null;
}
/**
* Navigates backward in the form.
*
* @return the event that should be handled by a view.
*/
public int stepToPreviousEvent() {
/*
* Right now this will always skip to the beginning of a group if that group is represented
* as a 'field-list'. Should a need ever arise to step backwards by only one step in a
* 'field-list', this method will have to be updated.
*/
mFormEntryController.stepToPreviousEvent();
// If after we've stepped, we're in a field-list, jump back to the beginning of the group
//
if (indexIsInFieldList()
&& getEvent() == FormEntryController.EVENT_QUESTION) {
// caption[0..len-1]
// caption[len-1] == the question itself
// caption[len-2] == the first group it is contained in.
FormEntryCaption[] captions = getCaptionHierarchy();
FormEntryCaption grp = captions[captions.length - 2];
int event = mFormEntryController.jumpToIndex(grp.getIndex());
// and test if this group or at least one of its children is relevant...
FormIndex idx = grp.getIndex();
if ( !mFormEntryController.getModel().isIndexRelevant(idx) ) {
return stepToPreviousEvent();
}
idx = mFormEntryController.getModel().incrementIndex(idx, true);
while ( FormIndex.isSubElement(grp.getIndex(), idx) ) {
if ( mFormEntryController.getModel().isIndexRelevant(idx) ) {
return event;
}
idx = mFormEntryController.getModel().incrementIndex(idx, true);
}
return stepToPreviousEvent();
} else if ( indexIsInFieldList() && getEvent() == FormEntryController.EVENT_GROUP) {
FormIndex grpidx = mFormEntryController.getModel().getFormIndex();
int event = mFormEntryController.getModel().getEvent();
// and test if this group or at least one of its children is relevant...
if ( !mFormEntryController.getModel().isIndexRelevant(grpidx) ) {
return stepToPreviousEvent(); // shouldn't happen?
}
FormIndex idx = mFormEntryController.getModel().incrementIndex(grpidx, true);
while ( FormIndex.isSubElement(grpidx, idx) ) {
if ( mFormEntryController.getModel().isIndexRelevant(idx) ) {
return event;
}
idx = mFormEntryController.getModel().incrementIndex(idx, true);
}
return stepToPreviousEvent();
}
return getEvent();
}
/**
* Jumps to a given FormIndex.
*
* @param index
* @return EVENT for the specified Index.
*/
public int jumpToIndex(FormIndex index) {
return mFormEntryController.jumpToIndex(index);
}
/**
* Creates a new repeated instance of the group referenced by the current FormIndex.
*
* @param questionIndex
*/
public void newRepeat() {
mFormEntryController.newRepeat();
}
/**
* If the current FormIndex is within a repeated group, will find the innermost repeat, delete
* it, and jump the FormEntryController to the previous valid index. That is, if you have group1
* (2) > group2 (3) and you call deleteRepeat, it will delete the 3rd instance of group2.
*/
public void deleteRepeat() {
FormIndex fi = mFormEntryController.deleteRepeat();
mFormEntryController.jumpToIndex(fi);
}
/**
* Sets the current language.
*
* @param language
*/
public void setLanguage(String language) {
mFormEntryController.setLanguage(language);
}
/**
* Returns an array of question promps.
*
* @return
*/
public FormEntryPrompt[] getQuestionPrompts() throws RuntimeException {
ArrayList<FormIndex> indicies = new ArrayList<FormIndex>();
FormIndex currentIndex = getFormIndex();
// For questions, there is only one.
// For groups, there could be many, but we set that below
FormEntryPrompt[] questions = new FormEntryPrompt[1];
IFormElement element = mFormEntryController.getModel().getForm().getChild(currentIndex);
if (element instanceof GroupDef) {
GroupDef gd = (GroupDef) element;
// descend into group
FormIndex idxChild = mFormEntryController.getModel().incrementIndex(currentIndex, true);
if ( gd.getChildren().size() == 1 && getEvent(idxChild) == FormEntryController.EVENT_GROUP ) {
// if we have a group definition within a field-list attribute group, and this is the
// only child in the group, check to see if it is also a field-list appearance.
// If it is, then silently recurse into it to pick up its elements.
// Work-around for the inconsistent treatment of field-list groups and repeats in 1.1.7 that
// either breaks forms generated by build or breaks forms generated by XLSForm.
IFormElement nestedElement = mFormEntryController.getModel().getForm().getChild(idxChild);
if (nestedElement instanceof GroupDef) {
GroupDef nestedGd = (GroupDef) nestedElement;
if ( ODKView.FIELD_LIST.equalsIgnoreCase(nestedGd.getAppearanceAttr()) ) {
gd = nestedGd;
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, true);
}
}
}
for (int i = 0; i < gd.getChildren().size(); i++) {
indicies.add(idxChild);
// don't descend
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, false);
}
// we only display relevant questions
ArrayList<FormEntryPrompt> questionList = new ArrayList<FormEntryPrompt>();
for (int i = 0; i < indicies.size(); i++) {
FormIndex index = indicies.get(i);
if (getEvent(index) != FormEntryController.EVENT_QUESTION) {
String errorMsg =
"Only questions are allowed in 'field-list'. Bad node is: "
+ index.getReference().toString(false);
RuntimeException e = new RuntimeException(errorMsg);
Log.e(t, errorMsg);
throw e;
}
// we only display relevant questions
if (mFormEntryController.getModel().isIndexRelevant(index)) {
questionList.add(getQuestionPrompt(index));
}
questions = new FormEntryPrompt[questionList.size()];
questionList.toArray(questions);
}
} else {
// We have a quesion, so just get the one prompt
questions[0] = getQuestionPrompt();
}
return questions;
}
public FormEntryPrompt getQuestionPrompt(FormIndex index) {
return mFormEntryController.getModel().getQuestionPrompt(index);
}
public FormEntryPrompt getQuestionPrompt() {
return mFormEntryController.getModel().getQuestionPrompt();
}
public String getQuestionPromptConstraintText(FormIndex index) {
return mFormEntryController.getModel().getQuestionPrompt(index).getConstraintText();
}
public String getQuestionPromptRequiredText(FormIndex index) {
// look for the text under the requiredMsg bind attribute
String constraintText = getBindAttribute(index, XFormParser.NAMESPACE_JAVAROSA, "requiredMsg");
if (constraintText != null) {
XPathExpression xPathRequiredMsg;
try {
xPathRequiredMsg = XPathParseTool.parseXPath("string(" + constraintText + ")");
} catch(Exception e) {
// Expected in probably most cases.
// This is a string literal, so no need to evaluate anything.
return constraintText;
}
if(xPathRequiredMsg != null) {
try{
FormDef form = mFormEntryController.getModel().getForm();
TreeElement mTreeElement = form.getMainInstance().resolveReference(index.getReference());
EvaluationContext ec = new EvaluationContext(form.getEvaluationContext(), mTreeElement.getRef());
Object value = xPathRequiredMsg.eval(form.getMainInstance(), ec);
if(value != "") {
return (String)value;
}
return null;
} catch(Exception e) {
Log.e(t,"Error evaluating a valid-looking required xpath ", e);
return constraintText;
}
} else {
return constraintText;
}
}
return null;
}
/**
* Returns an array of FormEntryCaptions for current FormIndex.
*
* @return
*/
public FormEntryCaption[] getGroupsForCurrentIndex() {
// return an empty array if you ask for something impossible
if (!(getEvent() == FormEntryController.EVENT_QUESTION
|| getEvent() == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| getEvent() == FormEntryController.EVENT_GROUP
|| getEvent() == FormEntryController.EVENT_REPEAT)) {
return new FormEntryCaption[0];
}
// the first caption is the question, so we skip it if it's an EVENT_QUESTION
// otherwise, the first caption is a group so we start at index 0
int lastquestion = 1;
if (getEvent() == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| getEvent() == FormEntryController.EVENT_GROUP
|| getEvent() == FormEntryController.EVENT_REPEAT) {
lastquestion = 0;
}
FormEntryCaption[] v = getCaptionHierarchy();
FormEntryCaption[] groups = new FormEntryCaption[v.length - lastquestion];
for (int i = 0; i < v.length - lastquestion; i++) {
groups[i] = v[i];
}
return groups;
}
/**
* This is used to enable/disable the "Delete Repeat" menu option.
*
* @return
*/
public boolean indexContainsRepeatableGroup() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups.length == 0) {
return false;
}
for (int i = 0; i < groups.length; i++) {
if (groups[i].repeats())
return true;
}
return false;
}
/**
* The count of the closest group that repeats or -1.
*/
public int getLastRepeatedGroupRepeatCount() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups.length > 0) {
for (int i = groups.length - 1; i > -1; i--) {
if (groups[i].repeats()) {
return groups[i].getMultiplicity();
}
}
}
return -1;
}
/**
* The name of the closest group that repeats or null.
*/
public String getLastRepeatedGroupName() {
FormEntryCaption[] groups = getCaptionHierarchy();
// no change
if (groups.length > 0) {
for (int i = groups.length - 1; i > -1; i--) {
if (groups[i].repeats()) {
return groups[i].getLongText();
}
}
}
return null;
}
/**
* The closest group the prompt belongs to.
*
* @return FormEntryCaption
*/
private FormEntryCaption getLastGroup() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups == null || groups.length == 0)
return null;
else
return groups[groups.length - 1];
}
/**
* The repeat count of closest group the prompt belongs to.
*/
public int getLastRepeatCount() {
if (getLastGroup() != null) {
return getLastGroup().getMultiplicity();
}
return -1;
}
/**
* The text of closest group the prompt belongs to.
*/
public String getLastGroupText() {
if (getLastGroup() != null) {
return getLastGroup().getLongText();
}
return null;
}
/**
* Find the portion of the form that is to be submitted
*
* @return
*/
private IDataReference getSubmissionDataReference() {
FormDef formDef = mFormEntryController.getModel().getForm();
// Determine the information about the submission...
SubmissionProfile p = formDef.getSubmissionProfile();
if (p == null || p.getRef() == null) {
return new XPathReference("/");
} else {
return p.getRef();
}
}
/**
* Once a submission is marked as complete, it is saved in the
* submission format, which might be a fragment of the original
* form or might be a SMS text string, etc.
*
* @return true if the submission is the entire form. If it is,
* then the submission can be re-opened for editing
* after it was marked-as-complete (provided it has
* not been encrypted).
*/
public boolean isSubmissionEntireForm() {
IDataReference sub = getSubmissionDataReference();
return ( getInstance().resolveReference(sub) == null );
}
/**
* Constructs the XML payload for a filled-in form instance. This payload
* enables a filled-in form to be re-opened and edited.
*
* @return
* @throws IOException
*/
public ByteArrayPayload getFilledInFormXml() throws IOException {
// assume no binary data inside the model.
FormInstance datamodel = getInstance();
XFormSerializingVisitor serializer = new XFormSerializingVisitor();
ByteArrayPayload payload =
(ByteArrayPayload) serializer.createSerializedPayload(datamodel);
return payload;
}
/**
* Extract the portion of the form that should be uploaded to the server.
*
* @return
* @throws IOException
*/
public ByteArrayPayload getSubmissionXml() throws IOException {
FormInstance instance = getInstance();
XFormSerializingVisitor serializer = new XFormSerializingVisitor();
ByteArrayPayload payload =
(ByteArrayPayload) serializer.createSerializedPayload(instance,
getSubmissionDataReference());
return payload;
}
/**
* Traverse the submission looking for the first matching tag in depth-first order.
*
* @param parent
* @param name
* @return
*/
private TreeElement findDepthFirst(TreeElement parent, String name) {
int len = parent.getNumChildren();
for ( int i = 0; i < len ; ++i ) {
TreeElement e = parent.getChildAt(i);
if ( name.equals(e.getName()) ) {
return e;
} else if ( e.getNumChildren() != 0 ) {
TreeElement v = findDepthFirst(e, name);
if ( v != null ) return v;
}
}
return null;
}
/**
* Get the OpenRosa required metadata of the portion of the form beng submitted
* @return
*/
public InstanceMetadata getSubmissionMetadata() {
FormDef formDef = mFormEntryController.getModel().getForm();
TreeElement rootElement = formDef.getInstance().getRoot();
TreeElement trueSubmissionElement;
// Determine the information about the submission...
SubmissionProfile p = formDef.getSubmissionProfile();
if ( p == null || p.getRef() == null ) {
trueSubmissionElement = rootElement;
} else {
IDataReference ref = p.getRef();
trueSubmissionElement = formDef.getInstance().resolveReference(ref);
// resolveReference returns null if the reference is to the root element...
if ( trueSubmissionElement == null ) {
trueSubmissionElement = rootElement;
}
}
// and find the depth-first meta block in this...
TreeElement e = findDepthFirst(trueSubmissionElement, "meta");
String instanceId = null;
String instanceName = null;
if ( e != null ) {
List<TreeElement> v;
// instance id...
v = e.getChildrenWithName(INSTANCE_ID);
if ( v.size() == 1 ) {
StringData sa = (StringData) v.get(0).getValue();
if ( sa != null ) {
instanceId = (String) sa.getValue();
}
}
// instance name...
v = e.getChildrenWithName(INSTANCE_NAME);
if ( v.size() == 1 ) {
StringData sa = (StringData) v.get(0).getValue();
if ( sa != null ) {
instanceName = (String) sa.getValue();
}
}
}
return new InstanceMetadata(instanceId,instanceName);
}
}
|
0nima0-f
|
src/org/odk/collect/android/logic/FormController.java
|
Java
|
asf20
| 45,048
|
/*
* 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.listeners;
import java.util.HashMap;
import android.net.Uri;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface InstanceUploaderListener {
void uploadingComplete(HashMap<String, String> result);
void progressUpdate(int progress, int total);
void authRequest(Uri url, HashMap<String, String> doneSoFar);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/InstanceUploaderListener.java
|
Java
|
asf20
| 977
|
/*
* 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.listeners;
import org.odk.collect.android.tasks.ProgressNotifier;
import org.odk.collect.android.tasks.SaveResult;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormSavedListener extends ProgressNotifier {
void savingComplete(SaveResult saveStatus);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/FormSavedListener.java
|
Java
|
asf20
| 923
|
/*
* 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.listeners;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface DiskSyncListener {
void SyncComplete(String result);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/DiskSyncListener.java
|
Java
|
asf20
| 783
|
/*
* 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.listeners;
/**
* Callback interface invoked upon completion of a DeleteFormsTask
*
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*/
public interface DeleteFormsListener {
void deleteComplete(int deletedForms);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/DeleteFormsListener.java
|
Java
|
asf20
| 900
|
/*
* 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.listeners;
/**
* Callback interface invoked upon the completion of a DeleteInstancesTask
*
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*/
public interface DeleteInstancesListener {
void deleteComplete(int deletedInstances);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/DeleteInstancesListener.java
|
Java
|
asf20
| 917
|
/*
* 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.listeners;
import java.util.HashMap;
import org.odk.collect.android.logic.FormDetails;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormDownloaderListener {
void formsDownloadingComplete(HashMap<FormDetails, String> result);
void progressUpdate(String currentFile, int progress, int total);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/FormDownloaderListener.java
|
Java
|
asf20
| 971
|
/*
* 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.listeners;
public interface AdvanceToNextListener {
void advance(); //Move on to the next question
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/AdvanceToNextListener.java
|
Java
|
asf20
| 748
|
/*
* 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.listeners;
import java.util.HashMap;
/**
*/
public interface TaskListener {
void taskComplete(HashMap<String, Object> results);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/TaskListener.java
|
Java
|
asf20
| 772
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* 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.listeners;
/**
*
* Author: Meletis Margaritis
* Date: 27/6/2013
* Time: 7:15 μμ
*/
public interface SavePointListener {
void onSavePointError(String errorMessage);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/SavePointListener.java
|
Java
|
asf20
| 918
|
/*
* 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.listeners;
import org.odk.collect.android.logic.FormDetails;
import java.util.HashMap;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormListDownloaderListener {
void formListDownloadingComplete(HashMap<String, FormDetails> value);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/FormListDownloaderListener.java
|
Java
|
asf20
| 906
|
/*
* 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.listeners;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.ProgressNotifier;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormLoaderListener extends ProgressNotifier {
void loadingComplete(FormLoaderTask task);
void loadingError(String errorMsg);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/FormLoaderListener.java
|
Java
|
asf20
| 967
|
/*
* 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.listeners;
import java.util.HashMap;
/**
*/
public interface GoogleDriveFormDownloadListener {
void formDownloadComplete(HashMap<String, Object> results);
}
|
0nima0-f
|
src/org/odk/collect/android/listeners/GoogleDriveFormDownloadListener.java
|
Java
|
asf20
| 799
|
#import "LibIDN.h"
#import "stringprep.h"
@implementation LibIDN
+ (NSString *)prepNode:(NSString *)node
{
if(node == nil) return nil;
// Each allowable portion of a JID MUST NOT be more than 1023 bytes in length.
// We make the buffer just big enough to hold a null-terminated string of this length.
char buf[1024];
strncpy(buf, [node UTF8String], sizeof(buf));
if(stringprep_xmpp_nodeprep(buf, sizeof(buf)) != 0) return nil;
return [NSString stringWithUTF8String:buf];
}
+ (NSString *)prepDomain:(NSString *)domain
{
if(domain == nil) return nil;
// Each allowable portion of a JID MUST NOT be more than 1023 bytes in length.
// We make the buffer just big enough to hold a null-terminated string of this length.
char buf[1024];
strncpy(buf, [domain UTF8String], sizeof(buf));
if(stringprep_nameprep(buf, sizeof(buf)) != 0) return nil;
return [NSString stringWithUTF8String:buf];
}
+ (NSString *)prepResource:(NSString *)resource
{
if(resource == nil) return nil;
// Each allowable portion of a JID MUST NOT be more than 1023 bytes in length.
// We make the buffer just big enough to hold a null-terminated string of this length.
char buf[1024];
strncpy(buf, [resource UTF8String], sizeof(buf));
if(stringprep_xmpp_resourceprep(buf, sizeof(buf)) != 0) return nil;
return [NSString stringWithUTF8String:buf];
}
@end
|
04081337-xmpp
|
Utilities/LibIDN.m
|
Objective-C
|
bsd
| 1,371
|
#import "XMPPIDTracker.h"
#define AssertProperQueue() NSAssert(dispatch_get_current_queue() == queue, @"Invoked on incorrect queue")
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation XMPPIDTracker
- (id)init
{
// You must use initWithDispatchQueue
[self release];
return nil;
}
- (id)initWithDispatchQueue:(dispatch_queue_t)aQueue
{
NSParameterAssert(aQueue != NULL);
if ((self = [super init]))
{
queue = aQueue;
dispatch_retain(queue);
dict = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)dealloc
{
// We don't call [self removeAllIDs] because dealloc might not be invoked on queue
for (id <XMPPTrackingInfo> info in [dict objectEnumerator])
{
[info cancelTimer];
}
[dict removeAllObjects];
[dict release];
dispatch_release(queue);
[super dealloc];
}
- (void)addID:(NSString *)elementID target:(id)target selector:(SEL)selector timeout:(NSTimeInterval)timeout
{
AssertProperQueue();
XMPPBasicTrackingInfo *trackingInfo;
trackingInfo = [[XMPPBasicTrackingInfo alloc] initWithTarget:target selector:selector timeout:timeout];
[self addID:elementID trackingInfo:trackingInfo];
[trackingInfo release];
}
- (void)addID:(NSString *)elementID
block:(void (^)(id obj, id <XMPPTrackingInfo> info))block
timeout:(NSTimeInterval)timeout
{
AssertProperQueue();
XMPPBasicTrackingInfo *trackingInfo;
trackingInfo = [[XMPPBasicTrackingInfo alloc] initWithBlock:block timeout:timeout];
[self addID:elementID trackingInfo:trackingInfo];
[trackingInfo release];
}
- (void)addID:(NSString *)elementID trackingInfo:(id <XMPPTrackingInfo>)trackingInfo
{
AssertProperQueue();
[dict setObject:trackingInfo forKey:elementID];
[trackingInfo setElementID:elementID];
[trackingInfo createTimerWithDispatchQueue:queue];
}
- (BOOL)invokeForID:(NSString *)elementID withObject:(id)obj
{
AssertProperQueue();
id <XMPPTrackingInfo> info = [dict objectForKey:elementID];
if (info)
{
[info invokeWithObject:obj];
[info cancelTimer];
[dict removeObjectForKey:elementID];
return YES;
}
return NO;
}
- (void)removeID:(NSString *)elementID
{
AssertProperQueue();
id <XMPPTrackingInfo> info = [dict objectForKey:elementID];
if (info)
{
[info cancelTimer];
[dict removeObjectForKey:elementID];
}
}
- (void)removeAllIDs
{
AssertProperQueue();
for (id <XMPPTrackingInfo> info in [dict objectEnumerator])
{
[info cancelTimer];
}
[dict removeAllObjects];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation XMPPBasicTrackingInfo
@synthesize timeout;
@synthesize elementID;
- (id)init
{
// Use initWithTarget:selector:timeout: or initWithBlock:timeout:
[self release];
return nil;
}
- (id)initWithTarget:(id)aTarget selector:(SEL)aSelector timeout:(NSTimeInterval)aTimeout
{
NSParameterAssert(aTarget);
NSParameterAssert(aSelector);
if ((self = [super init]))
{
target = aTarget;
selector = aSelector;
timeout = aTimeout;
}
return self;
}
- (id)initWithBlock:(void (^)(id obj, id <XMPPTrackingInfo> info))aBlock timeout:(NSTimeInterval)aTimeout
{
NSParameterAssert(aBlock);
if ((self = [super init]))
{
block = Block_copy(aBlock);
timeout = aTimeout;
}
return self;
}
- (void)dealloc
{
[self cancelTimer];
target = nil;
selector = NULL;
if (block) {
Block_release(block);
block = NULL;
}
[elementID release];
[super dealloc];
}
- (void)createTimerWithDispatchQueue:(dispatch_queue_t)queue
{
NSAssert(queue != NULL, @"Method invoked with NULL queue");
NSAssert(timer == NULL, @"Method invoked multiple times");
if (timeout > 0.0)
{
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_event_handler(timer, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self invokeWithObject:nil];
[pool drain];
});
dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC));
dispatch_source_set_timer(timer, tt, DISPATCH_TIME_FOREVER, 0);
dispatch_resume(timer);
}
}
- (void)cancelTimer
{
if (timer) {
dispatch_source_cancel(timer);
dispatch_release(timer);
timer = NULL;
}
}
- (void)invokeWithObject:(id)obj
{
if (block)
block(obj, self);
else
[target performSelector:selector withObject:obj withObject:self];
}
@end
|
04081337-xmpp
|
Utilities/XMPPIDTracker.m
|
Objective-C
|
bsd
| 4,751
|
#import "DDList.h"
@interface DDListEnumerator (PrivateAPI)
- (id)initWithList:(DDListNode *)list reverse:(BOOL)reverse;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation DDList
- (id)init
{
if ((self = [super init]))
{
list = NULL;
}
return self;
}
- (void)add:(void *)element
{
if(element == NULL) return;
DDListNode *node = malloc(sizeof(DDListNode));
node->element = element;
// Remember: The list is a linked list of DDListNode objects.
// Each node object is allocated and placed in the list.
// It is not deallocated until it is later removed from the linked list.
if (list == NULL)
{
node->prev = NULL;
node->next = NULL;
}
else
{
node->prev = NULL;
node->next = list;
node->next->prev = node;
}
list = node;
}
- (void)remove:(void *)element allInstances:(BOOL)allInstances
{
if(element == NULL) return;
DDListNode *node = list;
while (node != NULL)
{
if (element == node->element)
{
// Remove the node from the list.
// This is done by editing the pointers of the node's neighbors to skip it.
//
// In other words:
// node->prev->next = node->next
// node->next->prev = node->prev
//
// We also want to properly update our list pointer,
// which always points to the "first" element in the list. (Most recently added.)
if (node->prev != NULL)
node->prev->next = node->next;
else
list = node->next;
if (node->next != NULL)
node->next->prev = node->prev;
free(node);
if (!allInstances) break;
}
else
{
node = node->next;
}
}
}
- (void)remove:(void *)element
{
[self remove:element allInstances:NO];
}
- (void)removeAll:(void *)element
{
[self remove:element allInstances:YES];
}
- (void)removeAllElements
{
DDListNode *node = list;
while (node != NULL)
{
DDListNode *next = node->next;
free(node);
node = next;
}
list = NULL;
}
- (NSUInteger)count
{
NSUInteger count = 0;
DDListNode *node;
for (node = list; node != NULL; node = node->next)
{
count++;
}
return count;
}
- (DDListEnumerator *)listEnumerator
{
return [[[DDListEnumerator alloc] initWithList:list reverse:NO] autorelease];
}
- (DDListEnumerator *)reverseListEnumerator
{
return [[[DDListEnumerator alloc] initWithList:list reverse:YES] autorelease];
}
- (void)dealloc
{
[self removeAllElements];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation DDListEnumerator
- (id)initWithList:(DDListNode *)aList reverse:(BOOL)reverse
{
if ((self = [super init]))
{
numElements = 0;
currentElementIndex = 0;
// First get a count of the number of elements in the given list.
// Also, get a reference to the last node in the list.
DDListNode *node = aList;
if (node != NULL)
{
numElements++;
while (node->next != NULL)
{
numElements++;
node = node->next;
}
}
// At this point:
//
// aList -> points to the first element in the list
// node -> points to the last element in the list
// Recall that new elements are added to the beginning of the linked list.
// The last element in the list is the first element that was added.
if (numElements > 0)
{
elements = malloc(numElements * sizeof(void *));
if (reverse)
{
NSUInteger i = 0;
while (aList != NULL)
{
elements[i] = aList->element;
i++;
aList = aList->next;
}
}
else
{
NSUInteger i = 0;
while (node != NULL)
{
elements[i] = node->element;
i++;
node = node->prev;
}
}
}
}
return self;
}
- (NSUInteger)numTotal
{
return numElements;
}
- (NSUInteger)numLeft
{
if (currentElementIndex < numElements)
return numElements - currentElementIndex;
else
return 0;
}
- (void *)nextElement
{
if (currentElementIndex < numElements)
{
void *element = elements[currentElementIndex];
currentElementIndex++;
return element;
}
else
{
return NULL;
}
}
- (void)dealloc
{
if (elements)
{
free(elements);
}
[super dealloc];
}
@end
|
04081337-xmpp
|
Utilities/DDList.m
|
Objective-C
|
bsd
| 4,543
|
#import <Foundation/Foundation.h>
@class GCDMulticastDelegateEnumerator;
struct GCDMulticastDelegateListNode {
id delegate;
dispatch_queue_t delegateQueue;
struct GCDMulticastDelegateListNode * prev;
struct GCDMulticastDelegateListNode * next;
int32_t retainCount;
};
typedef struct GCDMulticastDelegateListNode GCDMulticastDelegateListNode;
/**
* This class provides multicast delegate functionality.
* That is, it provides a means for managing a list of delegates,
* and any method invocations to an instance of the class are automatically forwarded to all delegates.
*
* For example:
*
* // Make this method call on every added delegate (there may be several)
* [multicastDelegate cog:self didFindThing:thing];
*
* This allows multiple delegates to be added to an xmpp stream or any xmpp module,
* which in turn makes development easier as there can be proper separation of logically different code sections.
*
* In addition, this makes module development easier,
* as multiple delegates can be handled in the same manner as the traditional single delegate paradigm.
*
* This class also provides proper support for GCD queues.
* So each delegate specifies which queue they would like their delegate invocations to be dispatched onto.
*
* All delegate dispatching is done asynchronously (which is a critically important architectural design).
**/
@interface GCDMulticastDelegate : NSObject
{
GCDMulticastDelegateListNode *delegateList;
}
- (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
- (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
- (void)removeDelegate:(id)delegate;
- (void)removeAllDelegates;
- (NSUInteger)count;
- (NSUInteger)countOfClass:(Class)aClass;
- (NSUInteger)countForSelector:(SEL)aSelector;
- (GCDMulticastDelegateEnumerator *)delegateEnumerator;
@end
@interface GCDMulticastDelegateEnumerator : NSObject
{
NSUInteger numDelegates;
NSUInteger currentDelegateIndex;
GCDMulticastDelegateListNode **delegates;
}
- (NSUInteger)count;
- (NSUInteger)countOfClass:(Class)aClass;
- (NSUInteger)countForSelector:(SEL)aSelector;
- (BOOL)getNextDelegate:(id *)delPtr delegateQueue:(dispatch_queue_t *)dqPtr;
- (BOOL)getNextDelegate:(id *)delPtr delegateQueue:(dispatch_queue_t *)dqPtr ofClass:(Class)aClass;
- (BOOL)getNextDelegate:(id *)delPtr delegateQueue:(dispatch_queue_t *)dqPtr forSelector:(SEL)aSelector;
@end
|
04081337-xmpp
|
Utilities/GCDMulticastDelegate.h
|
Objective-C
|
bsd
| 2,447
|
#import <Foundation/Foundation.h>
@class DDListEnumerator;
struct DDListNode {
void * element;
struct DDListNode * prev;
struct DDListNode * next;
};
typedef struct DDListNode DDListNode;
/**
* The DDList class is designed as a simple list class.
* It can store objective-c objects as well as non-objective-c pointers.
* It does not retain objective-c objects as it treats all elements as simple pointers.
*
* Example usages:
* - Storing a list of delegates, where there is a desire to not retain the individual delegates.
* - Storing a list of dispatch timers, which are not NSObjects, and cannot be stored in NSCollection classes.
*
* This class is NOT thread-safe.
* It is designed to be used within a thread-safe context (e.g. within a single dispatch_queue).
**/
@interface DDList : NSObject
{
DDListNode *list;
}
- (void)add:(void *)element;
- (void)remove:(void *)element;
- (void)removeAll:(void *)element;
- (void)removeAllElements;
- (NSUInteger)count;
/**
* The enumerators return a snapshot of the list that can be enumerated.
* The list can later be altered (elements added/removed) without affecting enumerator snapshots.
**/
- (DDListEnumerator *)listEnumerator;
- (DDListEnumerator *)reverseListEnumerator;
@end
@interface DDListEnumerator : NSObject
{
NSUInteger numElements;
NSUInteger currentElementIndex;
void **elements;
}
- (NSUInteger)numTotal;
- (NSUInteger)numLeft;
- (void *)nextElement;
@end
|
04081337-xmpp
|
Utilities/DDList.h
|
Objective-C
|
bsd
| 1,452
|
#import <Foundation/Foundation.h>
@protocol XMPPTrackingInfo;
/**
* A common operation in XMPP is to send some kind of request with a unique id,
* and wait for the response to come back.
* The most common example is sending an IQ of type='get' with a unique id, and then awaiting the response.
*
* In order to properly handle the response, the id must be stored.
* If there are multiple queries going out and/or different kinds of queries,
* then information about the appropriate handling of the response must also be stored.
* This may be accomplished by storing the appropriate selector, or perhaps a block handler.
* Additionally one may need to setup timeouts and handle those properly as well.
*
* This class provides the scaffolding to simplify the tasks associated with this common operation.
* Essentially, it provides the following:
* - a dictionary where the unique id is the key, and the needed tracking info is the object
* - an optional timer to fire upon a timeout
*
* The class is designed to be flexible.
* You can provide a target/selector or a block handler to be invoked.
* Additionally, you can use the basic tracking info, or you can extend it to suit your needs.
*
* It is best illustrated with a few examples.
*
* ---- EXAMPLE 1 - SIMPLE TRACKING WITH TARGET / SELECTOR ----
*
* XMPPIQ *iq = ...
* [iqTracker addID:[iq elementID] target:self selector:@selector(processBookQuery:withInfo:) timeout:15.0];
*
* - (void)processBookQueury:(XMPPIQ *)iq withInfo:(id <XMPPTrackingInfo)info {
* ...
* }
*
* - (BOOL)xmppStream:(XMPPStream *)stream didReceiveIQ:(XMPPIQ *)iq
* {
* NSString *type = [iq type];
*
* if ([type isEqualToString:@"result"] || [type isEqualToString:@"error"])
* {
* return [iqTracker invokeForID:[iq elementID] withObject:iq];
* }
* else
* {
* ...
* }
* }
*
* ---- EXAMPLE 2 - SIMPLE TRACKING WITH BLOCK HANDLER ----
*
* XMPPIQ *iq = ...
*
* void (^blockHandler)(XMPPIQ *, id <XMPPTrackingInfo>) = ^(XMPPIQ *iq, id <XMPPTrackingInfo> info) {
* ...
* };
* [iqTracker addID:[iq elementID] block:blockHandler timeout:15.0];
*
* // Same xmppStream:didReceiveIQ: as example 1
*
* ---- EXAMPLE 2 - ADVANCED TRACKING ----
*
* @interface PingTrackingInfo : XMPPBasicTrackingInfo
* ...
* @end
*
* XMPPIQ *ping = ...
* PingTrackingInfo *pingInfo = ...
*
* [iqTracker addID:[ping elementID] trackingInfo:pingInfo];
*
* - (void)handlePong:(XMPPIQ *)iq withInfo:(PingTrackingInfo *)info {
* ...
* }
*
* // Same xmppStream:didReceiveIQ: as example 1
*
*
* This class is NOT thread-safe.
* It is designed to be used within a thread-safe context (e.g. within a single dispatch_queue).
**/
@interface XMPPIDTracker : NSObject
{
dispatch_queue_t queue;
NSMutableDictionary *dict;
}
- (id)initWithDispatchQueue:(dispatch_queue_t)queue;
- (void)addID:(NSString *)elementID target:(id)target selector:(SEL)selector timeout:(NSTimeInterval)timeout;
- (void)addID:(NSString *)elementID
block:(void (^)(id obj, id <XMPPTrackingInfo> info))block
timeout:(NSTimeInterval)timeout;
- (void)addID:(NSString *)elementID trackingInfo:(id <XMPPTrackingInfo>)trackingInfo;
- (BOOL)invokeForID:(NSString *)elementID withObject:(id)obj;
- (void)removeID:(NSString *)elementID;
- (void)removeAllIDs;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@protocol XMPPTrackingInfo <NSObject>
@property (nonatomic, readonly) NSTimeInterval timeout;
@property (nonatomic, readwrite, copy) NSString *elementID;
- (void)createTimerWithDispatchQueue:(dispatch_queue_t)queue;
- (void)cancelTimer;
- (void)invokeWithObject:(id)obj;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface XMPPBasicTrackingInfo : NSObject <XMPPTrackingInfo>
{
id target;
SEL selector;
void (^block)(id obj, id <XMPPTrackingInfo> info);
NSTimeInterval timeout;
NSString *elementID;
dispatch_source_t timer;
}
- (id)initWithTarget:(id)target selector:(SEL)selector timeout:(NSTimeInterval)timeout;
- (id)initWithBlock:(void (^)(id obj, id <XMPPTrackingInfo> info))block timeout:(NSTimeInterval)timeout;
@property (nonatomic, readonly) NSTimeInterval timeout;
@property (nonatomic, readwrite, copy) NSString *elementID;
- (void)createTimerWithDispatchQueue:(dispatch_queue_t)queue;
- (void)cancelTimer;
- (void)invokeWithObject:(id)obj;
@end
|
04081337-xmpp
|
Utilities/XMPPIDTracker.h
|
Objective-C
|
bsd
| 4,856
|
/*
File: RFImageToDataTransformer.h
Abstract: A value transformer, which transforms a UIImage or NSImage object into an NSData object.
Based on Apple's UIImageToDataTransformer
Copyright (C) 2010 Apple Inc. All Rights Reserved.
Copyright (C) 2011 RF.com All Rights Reserved.
*/
#import <Foundation/Foundation.h>
@interface RFImageToDataTransformer : NSValueTransformer {
}
@end
|
04081337-xmpp
|
Utilities/RFImageToDataTransformer.h
|
Objective-C
|
bsd
| 398
|
#import <Foundation/Foundation.h>
@interface LibIDN : NSObject
/**
* Preps a node identifier for use in a JID.
* If the given node is invalid, this method returns nil.
*
* See the XMPP RFC (3920) for details.
*
* Note: The prep properly converts the string to lowercase, as per the RFC.
**/
+ (NSString *)prepNode:(NSString *)node;
/**
* Preps a domain name for use in a JID.
* If the given domain is invalid, this method returns nil.
*
* See the XMPP RFC (3920) for details.
**/
+ (NSString *)prepDomain:(NSString *)domain;
/**
* Preps a resource identifier for use in a JID.
* If the given node is invalid, this method returns nil.
*
* See the XMPP RFC (3920) for details.
**/
+ (NSString *)prepResource:(NSString *)resource;
@end
|
04081337-xmpp
|
Utilities/LibIDN.h
|
Objective-C
|
bsd
| 756
|
//
// XMPPSRVResolver.m
//
// Originally created by Eric Chamberlain on 6/15/10.
// Based on SRVResolver by Apple, Inc.
//
#import "XMPPSRVResolver.h"
#import "XMPPLogging.h"
#include <dns_util.h>
#include <stdlib.h>
NSString *const XMPPSRVResolverErrorDomain = @"XMPPSRVResolverErrorDomain";
// Log levels: off, error, warn, info, verbose
#if DEBUG
static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE;
#else
static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN;
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface XMPPSRVRecord ()
@property(nonatomic, assign) NSUInteger srvResultsIndex;
@property(nonatomic, assign) NSUInteger sum;
- (NSComparisonResult)compareByPriority:(XMPPSRVRecord *)aRecord;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation XMPPSRVResolver
- (id)initWithdDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq resolverQueue:(dispatch_queue_t)rq
{
NSParameterAssert(aDelegate != nil);
NSParameterAssert(dq != NULL);
if ((self = [super init]))
{
XMPPLogTrace();
delegate = aDelegate;
delegateQueue = dq;
dispatch_retain(delegateQueue);
if (rq)
{
resolverQueue = rq;
dispatch_retain(resolverQueue);
}
else
{
resolverQueue = dispatch_queue_create("XMPPSRVResolver", NULL);
}
results = [[NSMutableArray alloc] initWithCapacity:2];
}
return self;
}
- (void)dealloc
{
XMPPLogTrace();
[self stop];
if (resolverQueue)
dispatch_release(resolverQueue);
[srvName release];
[results release];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Properties
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@dynamic srvName;
@dynamic timeout;
- (NSString *)srvName
{
__block NSString *result;
dispatch_block_t block = ^{
result = [srvName copy];
};
if (dispatch_get_current_queue() == resolverQueue)
block();
else
dispatch_sync(resolverQueue, block);
return [result autorelease];
}
- (NSTimeInterval)timeout
{
__block NSTimeInterval result;
dispatch_block_t block = ^{
result = timeout;
};
if (dispatch_get_current_queue() == resolverQueue)
block();
else
dispatch_sync(resolverQueue, block);
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)sortResults
{
NSAssert(dispatch_get_current_queue() == resolverQueue, @"Invoked on incorrect queue");
XMPPLogTrace();
// Sort results
NSMutableArray *sortedResults = [NSMutableArray arrayWithCapacity:[results count]];
// Sort the list by priority (lowest number first)
[results sortUsingSelector:@selector(compareByPriority:)];
/* From RFC 2782
*
* For each distinct priority level
* While there are still elements left at this priority level
*
* Select an element as specified above, in the
* description of Weight in "The format of the SRV
* RR" Section, and move it to the tail of the new
* list.
*
* The following algorithm SHOULD be used to order
* the SRV RRs of the same priority:
*/
NSUInteger srvResultsCount;
while ([results count] > 0)
{
srvResultsCount = [results count];
if (srvResultsCount == 1)
{
XMPPSRVRecord *srvRecord = [results objectAtIndex:0];
[sortedResults addObject:srvRecord];
[results removeObjectAtIndex:0];
}
else // (srvResultsCount > 1)
{
// more than two records so we need to sort
/* To select a target to be contacted next, arrange all SRV RRs
* (that have not been ordered yet) in any order, except that all
* those with weight 0 are placed at the beginning of the list.
*
* Compute the sum of the weights of those RRs, and with each RR
* associate the running sum in the selected order.
*/
NSUInteger runningSum = 0;
NSMutableArray *samePriorityRecords = [NSMutableArray arrayWithCapacity:srvResultsCount];
XMPPSRVRecord *srvRecord = [results objectAtIndex:0];
NSUInteger initialPriority = srvRecord.priority;
NSUInteger index = 0;
do
{
if (srvRecord.weight == 0)
{
// add to front of array
[samePriorityRecords insertObject:srvRecord atIndex:0];
srvRecord.srvResultsIndex = index;
srvRecord.sum = 0;
}
else
{
// add to end of array and update the running sum
[samePriorityRecords addObject:srvRecord];
runningSum += srvRecord.weight;
srvRecord.srvResultsIndex = index;
srvRecord.sum = runningSum;
}
if (++index < srvResultsCount)
{
srvRecord = [results objectAtIndex:index];
}
else
{
srvRecord = nil;
}
} while(srvRecord && (srvRecord.priority == initialPriority));
/* Then choose a uniform random number between 0 and the sum computed
* (inclusive), and select the RR whose running sum value is the
* first in the selected order which is greater than or equal to
* the random number selected.
*/
NSUInteger randomIndex = arc4random() % (runningSum + 1);
for (srvRecord in samePriorityRecords)
{
if (srvRecord.sum >= randomIndex)
{
/* The target host specified in the
* selected SRV RR is the next one to be contacted by the client.
* Remove this SRV RR from the set of the unordered SRV RRs and
* apply the described algorithm to the unordered SRV RRs to select
* the next target host. Continue the ordering process until there
* are no unordered SRV RRs. This process is repeated for each
* Priority.
*/
[sortedResults addObject:srvRecord];
[results removeObjectAtIndex:srvRecord.srvResultsIndex];
break;
}
}
}
}
[results release];
results = [sortedResults retain];
XMPPLogVerbose(@"%@: Sorted results:\n%@", THIS_FILE, results);
}
- (void)succeed
{
NSAssert(dispatch_get_current_queue() == resolverQueue, @"Invoked on incorrect queue");
XMPPLogTrace();
[self sortResults];
id theDelegate = delegate;
NSArray *records = [results copy];
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
SEL selector = @selector(srvResolver:didResolveRecords:);
if ([theDelegate respondsToSelector:selector])
{
[theDelegate srvResolver:self didResolveRecords:records];
}
else
{
XMPPLogWarn(@"%@: delegate doesn't implement %@", THIS_FILE, NSStringFromSelector(selector));
}
[pool drain];
});
[records release];
[self stop];
}
- (void)failWithError:(NSError *)error
{
NSAssert(dispatch_get_current_queue() == resolverQueue, @"Invoked on incorrect queue");
XMPPLogTrace2(@"%@: %@ %@", THIS_FILE, THIS_METHOD, error);
id theDelegate = delegate;
if (delegateQueue != NULL) {
dispatch_async(delegateQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
SEL selector = @selector(srvResolver:didNotResolveDueToError:);
if ([theDelegate respondsToSelector:selector])
{
[theDelegate srvResolver:self didNotResolveDueToError:error];
}
else
{
XMPPLogWarn(@"%@: delegate doesn't implement %@", THIS_FILE, NSStringFromSelector(selector));
}
[pool drain];
});
}
[self stop];
}
- (void)failWithDNSError:(DNSServiceErrorType)sdErr
{
XMPPLogTrace2(@"%@: %@ %i", THIS_FILE, THIS_METHOD, (int)sdErr);
[self failWithError:[NSError errorWithDomain:XMPPSRVResolverErrorDomain code:sdErr userInfo:nil]];
}
- (XMPPSRVRecord *)processRecord:(const void *)rdata length:(uint16_t)rdlen
{
XMPPLogTrace();
// Note: This method is almost entirely from Apple's sample code.
//
// Otherwise there would be a lot more comments and explanation...
if (rdata == NULL)
{
XMPPLogWarn(@"%@: %@ - rdata == NULL", THIS_FILE, THIS_METHOD);
return nil;
}
// Rather than write a whole bunch of icky parsing code, I just synthesise
// a resource record and use <dns_util.h>.
XMPPSRVRecord *result = nil;
NSMutableData * rrData;
dns_resource_record_t * rr;
uint8_t u8; // 1 byte
uint16_t u16; // 2 bytes
uint32_t u32; // 4 bytes
rrData = [NSMutableData dataWithCapacity:(1 + 2 + 2 + 4 + 2 + rdlen)];
u8 = 0;
[rrData appendBytes:&u8 length:sizeof(u8)];
u16 = htons(kDNSServiceType_SRV);
[rrData appendBytes:&u16 length:sizeof(u16)];
u16 = htons(kDNSServiceClass_IN);
[rrData appendBytes:&u16 length:sizeof(u16)];
u32 = htonl(666);
[rrData appendBytes:&u32 length:sizeof(u32)];
u16 = htons(rdlen);
[rrData appendBytes:&u16 length:sizeof(u16)];
[rrData appendBytes:rdata length:rdlen];
// Parse the record.
rr = dns_parse_resource_record([rrData bytes], (uint32_t) [rrData length]);
if (rr != NULL)
{
NSString *target;
target = [NSString stringWithCString:rr->data.SRV->target encoding:NSASCIIStringEncoding];
if (target != nil)
{
UInt16 priority = rr->data.SRV->priority;
UInt16 weight = rr->data.SRV->weight;
UInt16 port = rr->data.SRV->port;
result = [XMPPSRVRecord recordWithPriority:priority weight:weight port:port target:target];
}
dns_free_resource_record(rr);
}
return result;
}
static void QueryRecordCallback(DNSServiceRef sdRef,
DNSServiceFlags flags,
uint32_t interfaceIndex,
DNSServiceErrorType errorCode,
const char * fullname,
uint16_t rrtype,
uint16_t rrclass,
uint16_t rdlen,
const void * rdata,
uint32_t ttl,
void * context)
{
// Called when we get a response to our query.
// It does some preliminary work, but the bulk of the interesting stuff
// is done in the processRecord:length: method.
XMPPSRVResolver *resolver = (XMPPSRVResolver *)context;
NSCAssert(dispatch_get_current_queue() == resolver->resolverQueue, @"Invoked on incorrect queue");
XMPPLogCTrace();
if (!(flags & kDNSServiceFlagsAdd))
{
// If the kDNSServiceFlagsAdd flag is not set, the domain information is not valid.
return;
}
if (errorCode == kDNSServiceErr_NoError &&
rrtype == kDNSServiceType_SRV)
{
XMPPSRVRecord *record = [resolver processRecord:rdata length:rdlen];
if (record)
{
[resolver->results addObject:record];
}
if ( ! (flags & kDNSServiceFlagsMoreComing) )
{
[resolver succeed];
}
}
else
{
[resolver failWithDNSError:errorCode];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Public Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)startWithSRVName:(NSString *)aSRVName timeout:(NSTimeInterval)aTimeout
{
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (resolveInProgress)
{
[pool drain];
return;
}
XMPPLogTrace2(@"%@: startWithSRVName:%@ timeout:%f", THIS_FILE, aSRVName, aTimeout);
// Save parameters
[srvName release];
srvName = [aSRVName copy];
timeout = aTimeout;
// Check parameters
const char *srvNameCStr = [srvName cStringUsingEncoding:NSASCIIStringEncoding];
if (srvNameCStr == NULL)
{
[self failWithDNSError:kDNSServiceErr_BadParam];
[pool drain];
return;
}
// Create DNS Service
DNSServiceErrorType sdErr;
sdErr = DNSServiceQueryRecord(&sdRef, // Pointer to unitialized DNSServiceRef
kDNSServiceFlagsReturnIntermediates, // Flags
kDNSServiceInterfaceIndexAny, // Interface index
srvNameCStr, // Full domain name
kDNSServiceType_SRV, // rrtype
kDNSServiceClass_IN, // rrclass
QueryRecordCallback, // Callback method
self); // Context pointer
if (sdErr != kDNSServiceErr_NoError)
{
[self failWithDNSError:sdErr];
[pool drain];
return;
}
// Extract unix socket (so we can poll for events)
sdFd = DNSServiceRefSockFD(sdRef);
if (sdFd < 0)
{
// Todo...
}
// Create GCD read source for sd file descriptor
sdReadSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, sdFd, 0, resolverQueue);
dispatch_source_set_event_handler(sdReadSource, ^{
NSAutoreleasePool *handlerPool = [[NSAutoreleasePool alloc] init];
XMPPLogVerbose(@"%@: sdReadSource_eventHandler", THIS_FILE);
// There is data to be read on the socket (or an error occurred).
//
// Invoking DNSServiceProcessResult will invoke our QueryRecordCallback,
// the callback we set when we created the sdRef.
DNSServiceErrorType sdErr = DNSServiceProcessResult(sdRef);
if (sdErr != kDNSServiceErr_NoError)
{
[self failWithDNSError:sdErr];
}
[handlerPool drain];
});
dispatch_source_t theSdReadSource = sdReadSource;
DNSServiceRef theSdRef = sdRef;
dispatch_source_set_cancel_handler(sdReadSource, ^{
NSAutoreleasePool *handlerPool = [[NSAutoreleasePool alloc] init];
XMPPLogVerbose(@"%@: sdReadSource_cancelHandler", THIS_FILE);
dispatch_release(theSdReadSource);
DNSServiceRefDeallocate(theSdRef);
[handlerPool drain];
});
dispatch_resume(sdReadSource);
// Create timer (if requested timeout > 0)
if (timeout > 0.0)
{
timeoutTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, resolverQueue);
dispatch_source_set_event_handler(timeoutTimer, ^{
NSAutoreleasePool *handlerPool = [[NSAutoreleasePool alloc] init];
NSString *errMsg = @"Operation timed out";
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
NSError *err = [NSError errorWithDomain:XMPPSRVResolverErrorDomain code:0 userInfo:userInfo];
[self failWithError:err];
[handlerPool drain];
});
dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC));
dispatch_source_set_timer(timeoutTimer, tt, DISPATCH_TIME_FOREVER, 0);
dispatch_resume(timeoutTimer);
}
resolveInProgress = YES;
[pool drain];
};
if (dispatch_get_current_queue() == resolverQueue)
block();
else
dispatch_async(resolverQueue, block);
}
- (void)stop
{
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
XMPPLogTrace();
delegate = nil;
if (delegateQueue)
{
dispatch_release(delegateQueue);
delegateQueue = NULL;
}
[results removeAllObjects];
if (sdReadSource)
{
// Cancel the readSource.
// It will be released from within the cancel handler.
dispatch_source_cancel(sdReadSource);
sdReadSource = NULL;
sdFd = -1;
// The sdRef will be deallocated from within the cancel handler too.
sdRef = NULL;
}
if (timeoutTimer)
{
dispatch_source_cancel(timeoutTimer);
dispatch_release(timeoutTimer);
timeoutTimer = NULL;
}
resolveInProgress = NO;
[pool drain];
};
if (dispatch_get_current_queue() == resolverQueue)
block();
else
dispatch_sync(resolverQueue, block);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Utility Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ (NSString *)srvNameFromXMPPDomain:(NSString *)xmppDomain
{
if (xmppDomain == nil)
return nil;
else
return [NSString stringWithFormat:@"_xmpp-client._tcp.%@", xmppDomain];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation XMPPSRVRecord
@synthesize priority;
@synthesize weight;
@synthesize port;
@synthesize target;
@synthesize sum;
@synthesize srvResultsIndex;
+ (XMPPSRVRecord *)recordWithPriority:(UInt16)p1 weight:(UInt16)w port:(UInt16)p2 target:(NSString *)t
{
return [[[XMPPSRVRecord alloc] initWithPriority:p1 weight:w port:p2 target:t] autorelease];
}
- (id)initWithPriority:(UInt16)p1 weight:(UInt16)w port:(UInt16)p2 target:(NSString *)t
{
if ((self = [super init]))
{
priority = p1;
weight = w;
port = p2;
target = [t copy];
sum = 0;
srvResultsIndex = 0;
}
return self;
}
- (void)dealloc
{
[target release];
[super dealloc];
}
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@:%p target(%@) port(%hu) priority(%hu) weight(%hu)>",
NSStringFromClass([self class]), self, target, port, priority, weight];
}
- (NSComparisonResult)compareByPriority:(XMPPSRVRecord *)aRecord
{
UInt16 mPriority = self.priority;
UInt16 aPriority = aRecord.priority;
if (mPriority < aPriority)
return NSOrderedAscending;
if (mPriority > aPriority)
return NSOrderedDescending;
return NSOrderedSame;
}
@end
|
04081337-xmpp
|
Utilities/XMPPSRVResolver.m
|
Objective-C
|
bsd
| 18,529
|