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) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.audio
{
import flash.utils.Endian;
/**
* This class keeps track of all the information that defines the
* audio format independent of the actual audio container
* (e.g. .wav or .au)
*/
public class AudioFormat
{
// Allow 8 and 16 kHz as well.
public static var allrates:Boolean = false;
public var channels:uint;
public var rate:uint;
public var bits:uint;
public var endian:String;
public function AudioFormat(rate:uint, channels:uint, bits:uint, endian:String)
{
this.rate = rate;
this.channels = channels;
this.endian = endian;
this.bits = bits;
validate();
}
// flash.media.Microphone quasi-rounds sample rates in kHz
public static function toRoundedRate(rate:uint):uint
{
if (rate == 5512)
{
return 5;
}
else if (rate == 8000)
{
return 8;
}
else if (rate == 11025)
{
return 11;
}
else if (rate == 16000)
{
return 16;
}
else if (rate == 22050)
{
return 22;
}
else if (rate == 44100)
{
return 44;
}
throw new Error("Unsupported sample rate in Hz: " + rate);
}
public static function fromRoundedRate(rate:uint):uint
{
if (rate == 5)
{
return 5512;
}
else if (rate == 8)
{
return 8000;
}
else if (rate == 11)
{
return 11025;
}
else if (rate == 16)
{
return 16000;
}
else if (rate == 22)
{
return 22050;
}
else if (rate == 44)
{
return 44100;
}
throw new Error("Unsupported sample rate rounded in kHz: " + rate);
}
public function validate():void
{
if (bits != 8 && bits != 16 && bits != 32)
{
throw new Error("Unsupported number of bits per sample: " + bits);
}
if (channels != 1 && channels != 2)
{
throw new Error("Unsupported number of channels: " + channels);
}
if (endian != Endian.BIG_ENDIAN && endian != Endian.LITTLE_ENDIAN)
{
throw new Error("Unsupported endian type: " + endian);
}
var msg:String = "";
if (rate < 100)
{
throw new Error("Rate should be in Hz");
}
else if (rate != 5512 && rate != 8000 && rate != 11025 && rate != 16000 && rate != 22050 && rate != 44100)
{
msg = "Sample rate of " + rate + " is not supported.";
msg += " See flash.media.Microphone documentation."
throw new Error(msg);
}
else if (!allrates && (rate == 8000 || rate == 16000 || rate == 11025)) {
msg = "8kHz and 16kHz are supported for recording but not playback. 11kHz doesn't work in Ubuntu.";
msg += " Enable all rates via a parameter passed into the Flash."
throw new Error(msg);
}
}
public function toString():String
{
return "Rate: " + rate + " Channels " + channels + " Bits: " + bits + " Endian: " + endian;
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/audio/AudioFormat.as | ActionScript | mit | 4,046 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.audio
{
import edu.mit.csail.wami.audio.AudioFormat;
import edu.mit.csail.wami.audio.IAudioContainer;
import edu.mit.csail.wami.utils.External;
import edu.mit.csail.wami.utils.Pipe;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* Convert WAVE data coming in to the float-based format flash uses.
*/
public class DecodePipe extends Pipe
{
private var format:AudioFormat;
private var header:ByteArray = new ByteArray();
private var containers:Vector.<IAudioContainer>;
public function DecodePipe(containers:Vector.<IAudioContainer>) {
if (containers.length == 0) {
throw new Error("Must have at least one container.");
}
this.containers = containers;
}
override public function write(bytes:ByteArray):void
{
if (format == null)
{
// Try to get header by parsing from each container
bytes.readBytes(header, header.length, bytes.length);
for each (var container:IAudioContainer in containers) {
format = container.fromByteArray(header);
if (format != null) {
// Put the leftover bytes back
bytes = new ByteArray();
header.readBytes(bytes);
External.debug("Format: " + format);
break;
}
}
}
if (format != null && bytes.bytesAvailable)
{
bytes.endian = format.endian;
super.write(decode(bytes));
}
}
private function decode(bytes:ByteArray):ByteArray
{
var decoded:ByteArray = new ByteArray();
while (bytes.bytesAvailable)
{
var sample1:Number = getSample(bytes);
var sample2:Number = sample1;
if (format.channels == 2)
{
sample2 = getSample(bytes);
}
// cheap way to upsample
var repeat:uint = 44100 / format.rate;
while (repeat-- > 0) {
decoded.writeFloat(sample1);
decoded.writeFloat(sample2);
}
}
decoded.position = 0;
return decoded;
}
private function getSample(bytes:ByteArray):Number
{
var sample:Number;
if (format.bits == 8)
{
sample = bytes.readByte()/0x7f;
}
else if (format.bits == 16)
{
sample = bytes.readShort()/0x7fff;
}
else if (format.bits == 32)
{
sample = bytes.readInt()/0x7fffffff;
}
else
{
throw new Error("Unsupported bits per sample: " + format.bits);
}
return sample;
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/audio/DecodePipe.as | ActionScript | mit | 3,565 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.audio
{
import edu.mit.csail.wami.utils.External;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* This container is better for streaming, because it explicitly
* says what to do when the length of the audio is unknown. It's typically
* associated with mu-law compression (which wouldn't be too hard too implement)
* but here we're using linear PCM.
*/
public class AuContainer implements IAudioContainer
{
public function isLengthRequired():Boolean {
return false;
}
public function toByteArray(format:AudioFormat, length:int = -1):ByteArray
{
var dataLength:uint = 0xffffffff;
if (length > -1)
{
dataLength = length;
}
if (format.endian != Endian.BIG_ENDIAN)
{
throw new Error("AU is a container for big endian data");
}
// http://en.wikipedia.org/wiki/Au_file_format
var header:ByteArray = new ByteArray();
header.endian = format.endian;
header.writeUTFBytes(".snd");
header.writeInt(24); // Data offset
header.writeInt(dataLength);
var bits:uint = getEncodingFromBits(format);
header.writeInt(bits);
header.writeInt(format.rate);
header.writeInt(format.channels);
header.position = 0;
External.debugBytes(header);
return header;
}
private function getEncodingFromBits(format:AudioFormat):uint
{
if (format.bits == 16)
{
return 3;
}
else if (format.bits == 24)
{
return 4;
}
else if (format.bits == 32)
{
return 5;
}
throw new Error("Bits not supported");
}
private function getBitsFromEncoding(encoding:uint):uint
{
if (encoding == 3)
{
return 16;
}
else if (encoding == 4)
{
return 24;
}
else if (encoding == 5)
{
return 32;
}
throw new Error("Encoding not supported: " + encoding);
}
public function fromByteArray(header:ByteArray):AudioFormat
{
if (header.bytesAvailable < 24)
{
return notAu(header, "Header not yet long enough for Au");
}
var b:ByteArray = new ByteArray();
header.readBytes(b, 0, 24);
External.debugBytes(b);
header.position = 0;
header.endian = Endian.BIG_ENDIAN; // Header is big-endian
var magic:String = header.readUTFBytes(4);
if (magic != ".snd")
{
return notAu(header, "Not an AU header, first bytes should be .snd");
}
var dataOffset:uint = header.readInt();
var dataLength:uint = header.readInt();
if (header.bytesAvailable < dataOffset - 12)
{
return notAu(header, "Header of length " + header.bytesAvailable + " not long enough yet to include offset of length " + dataOffset);
}
var encoding:uint = header.readInt();
var bits:uint;
try {
bits = getBitsFromEncoding(encoding);
} catch (e:Error) {
return notAu(header, e.message);
}
var rate:uint = header.readInt();
var channels:uint = header.readInt();
header.position = dataOffset;
var format:AudioFormat;
try
{
format = new AudioFormat(rate, channels, bits, Endian.BIG_ENDIAN);
} catch (e:Error)
{
return notAu(header, e.message);
}
return format;
}
private function notAu(header:ByteArray, msg:String):AudioFormat
{
External.debug("Not Au: " + msg);
header.position = 0;
return null;
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/audio/AuContainer.as | ActionScript | mit | 4,588 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.audio
{
import edu.mit.csail.wami.audio.AudioFormat;
import edu.mit.csail.wami.audio.IAudioContainer;
import edu.mit.csail.wami.utils.Pipe;
import flash.utils.ByteArray;
/**
* Convert float format to raw audio accoring to the audio format passed in.
*/
public class EncodePipe extends Pipe
{
private var format:AudioFormat;
private var container:IAudioContainer;
// Buffer if container requires length. In this case,
// we cannot write the data to the sink until the very end.
private var buffer:ByteArray;
private var headerWritten:Boolean;
function EncodePipe(format:AudioFormat, container:IAudioContainer)
{
this.format = format;
this.container = container;
this.buffer = new ByteArray();
headerWritten = false;
}
override public function write(bytes:ByteArray):void
{
var transcoded:ByteArray = new ByteArray();
transcoded.endian = format.endian;
while (bytes.bytesAvailable >= 4)
{
var sample:int;
if (format.bits == 16)
{
sample = bytes.readFloat()*0x7fff;
transcoded.writeShort(sample);
if (format.channels == 2)
{
transcoded.writeShort(sample);
}
}
else if (format.bits == 32)
{
sample = bytes.readFloat()*0x7fffffff;
transcoded.writeInt(sample);
if (format.channels == 2)
{
transcoded.writeInt(sample);
}
}
else
{
throw new Error("Unsupported bits per sample: " + format.bits);
}
}
transcoded.position = 0;
handleEncoded(transcoded);
}
private function handleEncoded(bytes:ByteArray):void {
if (container == null) {
// No container, just stream it on
super.write(bytes);
return;
}
if (container.isLengthRequired())
{
buffer.writeBytes(bytes, bytes.position, bytes.bytesAvailable);
return;
}
if (!headerWritten)
{
var header:ByteArray = container.toByteArray(format);
super.write(header);
headerWritten = true;
}
super.write(bytes);
}
override public function close():void
{
if (container != null && container.isLengthRequired())
{
// Write the audio (including the header).
buffer.position = 0;
super.write(container.toByteArray(format, buffer.length));
super.write(buffer);
}
super.close();
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/audio/EncodePipe.as | ActionScript | mit | 3,572 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.audio
{
import edu.mit.csail.wami.utils.External;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* This class builds a WAVE header formt the audio format.
*/
public class WaveContainer implements IAudioContainer
{
public function isLengthRequired():Boolean {
return true;
}
public function toByteArray(audioFormat:AudioFormat, length:int = -1):ByteArray
{
// https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
var id:String = (audioFormat.endian == Endian.LITTLE_ENDIAN) ? "RIFF" : "RIFX";
var bytesPerSample:uint = audioFormat.channels*audioFormat.bits/8;
var header:ByteArray = new ByteArray();
// Little-endian is generally the way to go for WAVs
header.endian = Endian.LITTLE_ENDIAN;
header.writeUTFBytes(id);
header.writeInt(length > 0 ? 36 + length : 0);
header.writeUTFBytes("WAVE");
header.writeUTFBytes("fmt ");
header.writeInt(16);
header.writeShort(1);
header.writeShort(audioFormat.channels);
header.writeInt(audioFormat.rate);
header.writeInt(audioFormat.rate*bytesPerSample);
header.writeShort(bytesPerSample);
header.writeShort(audioFormat.bits);
header.writeUTFBytes('data');
header.writeInt(length);
header.position = 0;
return header;
}
public function fromByteArray(header:ByteArray):AudioFormat
{
if (header.bytesAvailable < 44) {
var msg:String = "This header is not yet long enough ";
msg += "(need 44 bytes only have " + header.bytesAvailable + ")."
return notWav(header, msg);
}
var endian:String = Endian.LITTLE_ENDIAN;
var chunkID:String = header.readUTFBytes(4);
if (chunkID == "RIFX")
{
endian = Endian.BIG_ENDIAN;
}
else if (chunkID != "RIFF")
{
return notWav(header, "Does not look like a WAVE header: " + chunkID);
}
header.endian = Endian.LITTLE_ENDIAN; // Header is little-endian
var totalLength:uint = header.readInt() + 8;
var waveFmtStr:String = header.readUTFBytes(8); // "WAVEfmt "
if (waveFmtStr != "WAVEfmt ")
{
return notWav(header, "RIFF header, but not a WAV.");
}
var subchunkSize:uint = header.readUnsignedInt(); // 16
var audioFormat:uint = header.readShort(); // 1
if (audioFormat != 1) {
return notWav(header, "Currently we only support linear PCM");
}
var channels:uint = header.readShort();
var rate:uint = header.readInt();
var bps:uint = header.readInt();
var bytesPerSample:uint = header.readShort();
var bits:uint = header.readShort();
var dataStr:String = header.readUTFBytes(4); // "data"
var length:uint = header.readInt();
var format:AudioFormat;
try
{
format = new AudioFormat(rate, channels, bits, endian);
} catch (e:Error)
{
return notWav(header, e.message);
}
return format;
}
/**
* Emit error message for debugging, reset the ByteArray and
* return null.
*/
private function notWav(header:ByteArray, msg:String):AudioFormat
{
External.debug("Not WAV: " + msg);
header.position = 0;
return null;
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/audio/WaveContainer.as | ActionScript | mit | 4,385 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.audio
{
import flash.utils.ByteArray;
/**
* There are a number of ways to store raw audio. WAV is a container from
* Microsoft. AU is a container from Sun Microsystems. This interface
* helps us separate the container format from the audio format itself.
*/
public interface IAudioContainer
{
function toByteArray(format:AudioFormat, length:int = -1):ByteArray;
/**
* If successful, the position is left at the first byte after
* the header. If the bytes do not represent the expected container
* header null is returned and the position is returned to 0.
*/
function fromByteArray(bytes:ByteArray):AudioFormat;
/**
* Some containers (e.g. WAV) require the length of the data to be specified,
* and thus are not amenable to streaming. Others (e.g. AU) have well
* defined ways of dealing with data of unknown length.
*/
function isLengthRequired():Boolean;
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/audio/IAudioContainer.as | ActionScript | mit | 2,168 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.record
{
import edu.mit.csail.wami.audio.AuContainer;
import edu.mit.csail.wami.audio.AudioFormat;
import edu.mit.csail.wami.audio.EncodePipe;
import edu.mit.csail.wami.audio.IAudioContainer;
import edu.mit.csail.wami.audio.WaveContainer;
import edu.mit.csail.wami.client.WamiParams;
import edu.mit.csail.wami.utils.BytePipe;
import edu.mit.csail.wami.utils.External;
import edu.mit.csail.wami.utils.Pipe;
import edu.mit.csail.wami.utils.StateListener;
import flash.events.SampleDataEvent;
import flash.events.StatusEvent;
import flash.media.Microphone;
import flash.media.SoundCodec;
import flash.utils.Endian;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class WamiRecorder implements IRecorder
{
private static var CHUNK_DURATION_MILLIS:Number = 200;
private var mic:Microphone = null;
private var params:WamiParams;
private var audioPipe:Pipe;
// For adding some audio padding to start and stop.
private var circularBuffer:BytePipe;
private var stopInterval:uint;
private var paddingMillis:uint = 0; // initially 0, but listen changes it.
private var listening:Boolean = false;
// To determine if the amount of audio recorded matches up with
// the length of time we've recorded (i.e. not dropping any frames)
private var handled:uint;
private var startTime:Date;
private var stopTime:Date;
private var listener:StateListener;
public function WamiRecorder(mic:Microphone, params:WamiParams)
{
this.params = params;
this.circularBuffer = new BytePipe(getPaddingBufferSize());
this.mic = mic;
mic.addEventListener(StatusEvent.STATUS, onMicStatus);
if (getChunkSize() <= 0)
{
throw new Error("Desired duration is too small, even for streaming chunks: " + getChunkSize());
}
}
/**
* The WAMI recorder can listen constantly, keeping a buffer of the last
* few milliseconds of audio. Often people start talking before they click the
* button, so we prepend paddingMillis milliseconds to the audio.
*/
public function listen(paddingMillis:uint):void {
if (!listening) {
this.paddingMillis = paddingMillis;
mic.rate = AudioFormat.toRoundedRate(params.format.rate);
mic.codec = SoundCodec.NELLYMOSER; // Just to clarify 5, 8, 11, 16, 22 and 44 kHz
mic.setSilenceLevel(0, 10000);
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, sampleHandler);
External.debug("Listening...");
listening = true;
}
}
public function unlisten():void {
if (listening) {
mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, sampleHandler);
listening = false;
if (paddingMillis > 0) {
circularBuffer = new BytePipe(getPaddingBufferSize());
}
External.debug("Unlistening.");
}
}
protected function onMicStatus(event:StatusEvent):void
{
External.debug("status: " + event.code);
if (event.code == "Microphone.Unmuted")
{
listen(this.paddingMillis);
} else if (event.code == "Microphone.Muted") {
unlisten();
}
}
public function start(url:String, listener:StateListener):void
{
// Forces security if mic is still muted in debugging mode.
listen(this.paddingMillis);
// Flash might be able to decide on a different sample rate
// than the one you suggest depending on your audio card...
params.format.rate = AudioFormat.fromRoundedRate(mic.rate);
External.debug("Recording at rate: " + params.format.rate);
stop(true);
audioPipe = createAudioPipe(url, listener);
if (paddingMillis > 0) {
// Prepend a small amount of audio we've already recorded.
circularBuffer.close();
audioPipe.write(circularBuffer.getByteArray());
circularBuffer = new BytePipe(getPaddingBufferSize());
}
listener.started();
handled = 0;
startTime = new Date();
}
public function createAudioPipe(url:String, listener:StateListener):Pipe
{
this.listener = listener;
var post:Pipe;
var container:IAudioContainer;
if (params.stream)
{
// The chunk parameter is something I made up. It would need
// to be handled on the server-side to piece all the chunks together.
post = new MultiPost(url, "audio/basic; chunk=%s", 3*1000, listener);
params.format.endian = Endian.BIG_ENDIAN;
container = new AuContainer();
}
else
{
post = new SinglePost(url, "audio/x-wav", 30*1000, listener);
container = new WaveContainer();
}
// Setup the audio pipes. A transcoding pipe converts floats
// to shorts and passes them on to a chunking pipe, which spits
// out chunks to a pipe that possibly adds a WAVE header
// before passing the chunks on to a pipe that does HTTP posts.
var pipe:Pipe = new EncodePipe(params.format, container);
pipe.setSink(new ChunkPipe(getChunkSize()))
.setSink(post);
return pipe;
}
internal function sampleHandler(evt:SampleDataEvent):void
{
evt.data.position = 0;
try
{
if (audioPipe)
{
audioPipe.write(evt.data);
handled += evt.data.length / 4;
}
else if (paddingMillis > 0)
{
circularBuffer.write(evt.data);
}
}
catch (error:Error)
{
audioPipe = null;
stop(true);
listener.failed(error);
}
}
public function stop(force:Boolean = false):void
{
clearInterval(stopInterval);
if (force)
{
reallyStop();
}
else
{
stopInterval = setInterval(function():void {
clearInterval(stopInterval);
reallyStop();
}, paddingMillis);
}
}
public function level():int
{
if (!audioPipe) return 0;
return mic.activityLevel;
}
private function reallyStop():void
{
if (!audioPipe) return;
try {
audioPipe.close();
} catch(error:Error) {
listener.failed(error);
}
audioPipe = null;
validateAudioLength();
if (this.paddingMillis == 0) {
// No need if we're not padding the audio
unlisten();
}
}
private function validateAudioLength():void
{
stopTime = new Date();
var seconds:Number = ((stopTime.time - startTime.time + paddingMillis) / 1000.0);
var expectedSamples:uint = uint(seconds*params.format.rate);
External.debug("Expected Samples: " + expectedSamples + " Actual Samples: " + handled);
startTime = null;
stopTime = null;
}
private function getBytesPerSecond():uint
{
return params.format.channels * (params.format.bits/8) * params.format.rate;
}
private function getChunkSize():uint
{
return params.stream ? getBytesPerSecond() * CHUNK_DURATION_MILLIS / 1000.0 : int.MAX_VALUE;
}
private function getPaddingBufferSize():uint
{
return uint(getBytesPerSecond()*params.paddingMillis/1000.0);
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/record/WamiRecorder.as | ActionScript | mit | 7,995 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.record
{
import edu.mit.csail.wami.utils.External;
import edu.mit.csail.wami.utils.Pipe;
import edu.mit.csail.wami.utils.StateListener;
import flash.utils.ByteArray;
public class MultiPost extends Pipe implements StateListener
{
private var url:String;
private var contentType:String = null;
private var partIndex:int = 0;
private var timeoutMillis:int;
private var totalBytes:int = 0;
private var totalPostsMade:int = 0;
private var totalPostsDone:int = 0;
private var error:Error = null;
private var listener:StateListener;
/**
* Does of POST of the data passed in to every call to "write"
*/
public function MultiPost(url:String, type:String, timeoutMillis:int, listener:StateListener)
{
this.url = url;
this.contentType = type;
this.timeoutMillis = timeoutMillis;
this.listener = listener;
}
override public function write(bytes:ByteArray):void
{
if (getError() != null) {
throw getError();
}
var type:String = contentType.replace("%s", partIndex++);
var post:Pipe = new SinglePost(url, type, timeoutMillis, this);
post.write(bytes);
post.close();
totalBytes += bytes.length;
totalPostsMade++;
}
// A final POST containing a -1 signifies the end of the MultiPost stream.
override public function close():void
{
External.debug("Total multi-posted bytes: " + totalBytes);
var arr:ByteArray = new ByteArray();
arr.writeInt(-1);
arr.position = 0;
write(arr);
super.close();
}
public function started():void
{
// nothing to do
}
public function finished():void
{
totalPostsDone++;
checkFinished();
}
public function failed(error:Error):void
{
this.error = error;
}
public function getError():Error
{
return error;
}
private function checkFinished():void
{
if (totalPostsDone == totalPostsMade && super.isClosed()) {
listener.finished();
}
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/record/MultiPost.as | ActionScript | mit | 3,196 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.record
{
import edu.mit.csail.wami.utils.StateListener;
public interface IRecorder
{
// Start and stop recording. Calling start while recording
// or calling stop when not recording should have no effect.
function start(url:String, listener:StateListener):void;
function stop(force:Boolean = false):void;
// It can be helpful to buffer a certain amount of audio to
// prepend (and append) to the audio collected between start
// and stop. This means, Flash needs to constantly listen.
// There are other times when it's obvious no recording will
// be done, and so listening is unnecesary.
function listen(paddingMillis:uint):void;
function unlisten():void;
// Audio level (between 0 and 100)
function level():int;
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/record/IRecorder.as | ActionScript | mit | 2,010 |
/*
* Copyright (c) 2011
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.wami.record
{
import edu.mit.csail.wami.utils.External;
import edu.mit.csail.wami.utils.Pipe;
import edu.mit.csail.wami.utils.StateListener;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
import flash.utils.setInterval;
/**
* Write data and POST on close.
*/
public class SinglePost extends Pipe
{
private var url:String;
private var contentType:String = null;
private var listener:StateListener;
private var finished:Boolean = false;
private var buffer:ByteArray = new ByteArray();
private var timeoutMillis:int;
public function SinglePost(url:String, type:String, timeoutMillis:int, listener:StateListener)
{
this.url = url;
this.contentType = type;
this.listener = listener;
this.timeoutMillis = timeoutMillis;
}
override public function write(bytes:ByteArray):void
{
bytes.readBytes(buffer, buffer.length, bytes.bytesAvailable);
}
override public function close():void
{
buffer.position = 0;
External.debug("POST " + buffer.length + " bytes of type " + contentType);
buffer.position = 0;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(Event.OPEN, openHandler);
loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST;
request.contentType = contentType;
request.data = buffer;
if (buffer.bytesAvailable == 0) {
External.debug("Note that flash does a GET request if bytes.length == 0");
}
try {
loader.load(request);
} catch (error:Error) {
if (listener)
{
listener.failed(error);
}
}
super.close();
}
private function completeHandler(event:Event):void {
External.debug("POST: completeHandler");
var loader:URLLoader = URLLoader(event.target);
loader.removeEventListener(Event.COMPLETE, completeHandler);
loader.removeEventListener(Event.OPEN, openHandler);
loader.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
listener.finished();
finished = true;
}
private function openHandler(event:Event):void {
External.debug("POST openHandler: " + event);
setInterval(checkFinished, timeoutMillis);
}
private function checkFinished():void {
if (!finished && listener) {
listener.failed(new Error("POST is taking too long."));
}
finished = true;
}
private function progressHandler(event:ProgressEvent):void {
External.debug("POST progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
if (!finished && listener)
{
listener.failed(new Error("Record security error: " + event.errorID));
}
finished = true;
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
// Apparently the event.status can be zero in some environments where nothing is wrong:
// http://johncblandii.com/2008/04/flex-3-firefox-beta-3-returns-0-for-http-status-codes.html
if (!finished && listener && event.status != 200 && event.status != 0)
{
listener.failed(new Error("HTTP status error: " + event.status));
}
finished = true;
}
private function ioErrorHandler(event:IOErrorEvent):void {
if (!finished && listener)
{
listener.failed(new Error("Record IO error: " + event.errorID));
}
finished = true;
}
}
} | 0930meixiaodong-wami-recorder | src/edu/mit/csail/wami/record/SinglePost.as | ActionScript | mit | 5,447 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<!-- swfobject is a commonly used library to embed Flash content -->
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<!-- Setup the recorder interface -->
<script type="text/javascript" src="recorder.js"></script>
<script>
function setup() {
Wami.setup("wami");
}
function record() {
status("Recording...");
Wami.startRecording("https://wami-recorder.appspot.com/audio");
}
function play() {
Wami.startPlaying("https://wami-recorder.appspot.com/audio");
}
function stop() {
status("");
Wami.stopRecording();
Wami.stopPlaying();
}
function status(msg) {
document.getElementById('status').innerHTML = msg;
}
</script>
</head>
<body onload="setup()">
<input type="button" value="Record" onclick="record()"></input>
<input type="button" value="Stop" onclick="stop()"></input>
<input type="button" value="Play" onclick="play()"></input>
<div id="status"></div>
<div id="wami"></div>
</body>
</html>
| 0930meixiaodong-wami-recorder | example/client/basic.html | HTML | mit | 1,110 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<!-- swfobject is a commonly used library to embed Flash content -->
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<!-- Setup the recorder interface -->
<script type="text/javascript" src="recorder.js"></script>
<!-- GUI code... take it or leave it -->
<script type="text/javascript" src="gui.js"></script>
<script>
function setupRecorder() {
Wami.setup({
id : "wami",
onReady : setupGUI
});
}
function setupGUI() {
var gui = new Wami.GUI({
id : "wami",
recordUrl : "https://wami-recorder.appspot.com/audio",
playUrl : "https://wami-recorder.appspot.com/audio"
});
gui.setPlayEnabled(false);
}
</script>
</head>
<body onload="setupRecorder()">
<div id="wami" style="margin-left: 100px;"></div>
<noscript>WAMI requires Javascript</noscript>
<div
style="position: absolute; left: 400px; top: 20px; font-family: arial, sans-serif; font-size: 82%">
Right-click to Download<br /> <br /> <a
href="https://wami-recorder.googlecode.com/hg/example/client/index.html">index.html</a><br />
<a
href="https://wami-recorder.googlecode.com/hg/example/client/Wami.swf">Wami.swf</a><br />
<a
href="https://wami-recorder.googlecode.com/hg/example/client/buttons.png">buttons.png</a><br />
<a
href="https://wami-recorder.googlecode.com/hg/example/client/recorder.js">recorder.js</a><br />
<a
href="https://wami-recorder.googlecode.com/hg/example/client/gui.js">gui.js</a><br />
</div>
</body>
</html>
| 0930meixiaodong-wami-recorder | example/client/index.html | HTML | mit | 1,628 |
var Wami = window.Wami || {};
// Upon a creation of a new Wami.GUI(options), we assume that a WAMI recorder
// has been initialized.
Wami.GUI = function(options) {
var RECORD_BUTTON = 1;
var PLAY_BUTTON = 2;
setOptions(options);
setupDOM();
var recordButton, playButton;
var recordInterval, playInterval;
function createDiv(id, style) {
var div = document.createElement("div");
if (id) {
div.setAttribute('id', id);
}
if (style) {
div.style.cssText = style;
}
return div;
}
function setOptions(options) {
if (!options.buttonUrl) {
options.buttonUrl = "buttons.png";
}
if (typeof options.listen == 'undefined' || options.listen) {
listen();
}
}
function setupDOM() {
var guidiv = createDiv(null,
"position: absolute; width: 214px; height: 137px;");
document.getElementById(options.id).appendChild(guidiv);
var rid = Wami.createID();
var recordDiv = createDiv(rid,
"position: absolute; left: 40px; top: 25px");
guidiv.appendChild(recordDiv);
recordButton = new Button(rid, RECORD_BUTTON, options.buttonUrl);
recordButton.onstart = startRecording;
recordButton.onstop = stopRecording;
recordButton.setEnabled(true);
if (!options.singleButton) {
var pid = Wami.createID();
var playDiv = createDiv(pid,
"position: absolute; right: 40px; top: 25px");
guidiv.appendChild(playDiv);
playButton = new Button(pid, PLAY_BUTTON, options.buttonUrl);
playButton.onstart = startPlaying;
playButton.onstop = stopPlaying;
}
}
/**
* These methods are called on clicks from the GUI.
*/
function startRecording() {
if (!options.recordUrl) {
alert("No record Url specified!");
}
recordButton.setActivity(0);
playButton.setEnabled(false);
Wami.startRecording(options.recordUrl,
Wami.nameCallback(onRecordStart), Wami
.nameCallback(onRecordFinish), Wami
.nameCallback(onError));
}
function stopRecording() {
Wami.stopRecording();
clearInterval(recordInterval);
recordButton.setEnabled(true);
}
function startPlaying() {
if (!options.playUrl) {
alert('No play URL specified!');
}
playButton.setActivity(0);
recordButton.setEnabled(false);
Wami.startPlaying(options.playUrl, Wami.nameCallback(onPlayStart), Wami
.nameCallback(onPlayFinish), Wami.nameCallback(onError));
}
function stopPlaying() {
Wami.stopPlaying();
}
this.setPlayUrl = function(url) {
options.playUrl = url;
}
this.setRecordUrl = function(url) {
options.recordUrl = url;
}
this.setPlayEnabled = function(val) {
playButton.setEnabled(val);
}
this.setRecordEnabled = function(val) {
recordButton.setEnabled(val);
}
/**
* Callbacks from the flash indicating certain events
*/
function onError(e) {
alert(e);
}
function onRecordStart() {
recordInterval = setInterval(function() {
if (recordButton.isActive()) {
var level = Wami.getRecordingLevel();
recordButton.setActivity(level);
}
}, 200);
if (options.onRecordStart) {
options.onRecordStart();
}
}
function onRecordFinish() {
playButton.setEnabled(true);
if (options.onRecordFinish) {
options.onRecordFinish();
}
}
function onPlayStart() {
playInterval = setInterval(function() {
if (playButton.isActive()) {
var level = Wami.getPlayingLevel();
playButton.setActivity(level);
}
}, 200);
if (options.onPlayStart) {
options.onPlayStart();
}
}
function onPlayFinish() {
clearInterval(playInterval);
recordButton.setEnabled(true);
playButton.setEnabled(true);
if (options.onPlayFinish) {
options.onPlayFinish();
}
}
function listen() {
Wami.startListening();
// Continually listening when the window is in focus allows us to
// buffer a little audio before the users clicks, since sometimes
// people talk too soon. Without "listening", the audio would record
// exactly when startRecording() is called.
window.onfocus = function() {
Wami.startListening();
};
// Note that the use of onfocus and onblur should probably be replaced
// with a more robust solution (e.g. jQuery's $(window).focus(...)
window.onblur = function() {
Wami.stopListening();
};
}
function Button(buttonid, type, url) {
var self = this;
self.active = false;
self.type = type;
init();
// Get the background button image position
// Index: 1) normal 2) pressed 3) mouse-over
function background(index) {
if (index == 1)
return "-56px 0px";
if (index == 2)
return "0px 0px";
if (index == 3)
return "-112px 0";
alert("Background not found: " + index);
}
// Get the type of meter and its state
// Index: 1) enabled 2) meter 3) disabled
function meter(index, offset) {
var top = 5;
if (offset)
top += offset;
if (self.type == RECORD_BUTTON) {
if (index == 1)
return "-169px " + top + "px";
if (index == 2)
return "-189px " + top + "px";
if (index == 3)
return "-249px " + top + "px";
} else {
if (index == 1)
return "-269px " + top + "px";
if (index == 2)
return "-298px " + top + "px";
if (index == 3)
return "-327px " + top + "px";
}
alert("Meter not found: " + self.type + " " + index);
}
function silhouetteWidth() {
if (self.type == RECORD_BUTTON) {
return "20px";
} else {
return "29px";
}
}
function mouseHandler(e) {
var rightclick;
if (!e)
var e = window.event;
if (e.which)
rightclick = (e.which == 3);
else if (e.button)
rightclick = (e.button == 2);
if (!rightclick) {
if (self.active && self.onstop) {
self.active = false;
self.onstop();
} else if (!self.active && self.onstart) {
self.active = true;
self.onstart();
}
}
}
function init() {
var div = document.createElement("div");
var elem = document.getElementById(buttonid);
if (elem) {
elem.appendChild(div);
} else {
alert('Could not find element on page named ' + buttonid);
}
self.guidiv = document.createElement("div");
self.guidiv.style.width = '56px';
self.guidiv.style.height = '63px';
self.guidiv.style.cursor = 'pointer';
self.guidiv.style.background = "url(" + url + ") no-repeat";
self.guidiv.style.backgroundPosition = background(1);
div.appendChild(self.guidiv);
// margin auto doesn't work in IE quirks mode
// http://stackoverflow.com/questions/816343/why-will-this-div-img-not-center-in-ie8
// text-align is a hack to force it to work even if you forget the
// doctype.
self.guidiv.style.textAlign = 'center';
self.meterDiv = document.createElement("div");
self.meterDiv.style.width = silhouetteWidth();
self.meterDiv.style.height = '63px';
self.meterDiv.style.margin = 'auto';
self.meterDiv.style.cursor = 'pointer';
self.meterDiv.style.position = 'relative';
self.meterDiv.style.background = "url(" + url + ") no-repeat";
self.meterDiv.style.backgroundPosition = meter(2);
self.guidiv.appendChild(self.meterDiv);
self.coverDiv = document.createElement("div");
self.coverDiv.style.width = silhouetteWidth();
self.coverDiv.style.height = '63px';
self.coverDiv.style.margin = 'auto';
self.coverDiv.style.cursor = 'pointer';
self.coverDiv.style.position = 'relative';
self.coverDiv.style.background = "url(" + url + ") no-repeat";
self.coverDiv.style.backgroundPosition = meter(1);
self.meterDiv.appendChild(self.coverDiv);
self.active = false;
self.guidiv.onmousedown = mouseHandler;
}
self.isActive = function() {
return self.active;
}
self.setActivity = function(level) {
self.guidiv.onmouseout = function() {
};
self.guidiv.onmouseover = function() {
};
self.guidiv.style.backgroundPosition = background(2);
self.coverDiv.style.backgroundPosition = meter(1, 5);
self.meterDiv.style.backgroundPosition = meter(2, 5);
var totalHeight = 31;
var maxHeight = 9;
// When volume goes up, the black image loses height,
// creating the perception of the colored one increasing.
var height = (maxHeight + totalHeight - Math.floor(level / 100
* totalHeight));
self.coverDiv.style.height = height + "px";
}
self.setEnabled = function(enable) {
var guidiv = self.guidiv;
self.active = false;
if (enable) {
self.coverDiv.style.backgroundPosition = meter(1);
self.meterDiv.style.backgroundPosition = meter(1);
guidiv.style.backgroundPosition = background(1);
guidiv.onmousedown = mouseHandler;
guidiv.onmouseover = function() {
guidiv.style.backgroundPosition = background(3);
};
guidiv.onmouseout = function() {
guidiv.style.backgroundPosition = background(1);
};
} else {
self.coverDiv.style.backgroundPosition = meter(3);
self.meterDiv.style.backgroundPosition = meter(3);
guidiv.style.backgroundPosition = background(1);
guidiv.onmousedown = null;
guidiv.onmouseout = function() {
};
guidiv.onmouseover = function() {
};
}
}
}
}
| 0930meixiaodong-wami-recorder | example/client/gui.js | JavaScript | mit | 8,988 |
var Wami = window.Wami || {};
// Returns a (very likely) unique string with of random letters and numbers
Wami.createID = function() {
return "wid" + ("" + 1e10).replace(/[018]/g, function(a) {
return (a ^ Math.random() * 16 >> a / 4).toString(16)
});
}
// Creates a named callback in WAMI and returns the name as a string.
Wami.nameCallback = function(cb, cleanup) {
Wami._callbacks = Wami._callbacks || {};
var id = Wami.createID();
Wami._callbacks[id] = function() {
if (cleanup) {
Wami._callbacks[id] = null;
}
cb.apply(null, arguments);
};
var named = "Wami._callbacks['" + id + "']";
return named;
}
// This method ensures that a WAMI recorder is operational, and that
// the following API is available in the Wami namespace. All functions
// must be named (i.e. cannot be anonymous).
//
// Wami.startPlaying(url, startfn = null, finishedfn = null, failedfn = null);
// Wami.stopPlaying()
//
// Wami.startRecording(url, startfn = null, finishedfn = null, failedfn = null);
// Wami.stopRecording()
//
// Wami.getRecordingLevel() // Returns a number between 0 and 100
// Wami.getPlayingLevel() // Returns a number between 0 and 100
//
// Wami.hide()
// Wami.show()
//
// Manipulate the WAMI recorder's settings. In Flash
// we need to check if the microphone permission has been granted.
// We might also set/return sample rate here, etc.
//
// Wami.getSettings();
// Wami.setSettings(options);
//
// Optional way to set up browser so that it's constantly listening
// This is to prepend audio in case the user starts talking before
// they click-to-talk.
//
// Wami.startListening()
//
Wami.setup = function(options) {
if (Wami.startRecording) {
// Wami's already defined.
if (options.onReady) {
options.onReady();
}
return;
}
// Assumes that swfobject.js is included if Wami.swfobject isn't
// already defined.
Wami.swfobject = Wami.swfobject || swfobject;
if (!Wami.swfobject) {
alert("Unable to find swfobject to help embed the SWF.");
}
var _options;
setOptions(options);
embedWamiSWF(_options.id, Wami.nameCallback(delegateWamiAPI));
function supportsTransparency() {
// Detecting the OS is a big no-no in Javascript programming, but
// I can't think of a better way to know if wmode is supported or
// not... since NOT supporting it (like Flash on Ubuntu) is a bug.
return (navigator.platform.indexOf("Linux") == -1);
}
function setOptions(options) {
// Start with default options
_options = {
swfUrl : "Wami.swf",
onReady : function() {
Wami.hide();
},
onSecurity : checkSecurity,
onError : function(error) {
alert(error);
}
};
if (typeof options == 'undefined') {
alert('Need at least an element ID to place the Flash object.');
}
if (typeof options == 'string') {
_options.id = options;
} else {
_options.id = options.id;
}
if (options.swfUrl) {
_options.swfUrl = options.swfUrl;
}
if (options.onReady) {
_options.onReady = options.onReady;
}
if (options.onLoaded) {
_options.onLoaded = options.onLoaded;
}
if (options.onSecurity) {
_options.onSecurity = options.onSecurity;
}
if (options.onError) {
_options.onError = options.onError;
}
// Create a DIV for the SWF under _options.id
var container = document.createElement('div');
container.style.position = 'absolute';
_options.cid = Wami.createID();
container.setAttribute('id', _options.cid);
var swfdiv = document.createElement('div');
var id = Wami.createID();
swfdiv.setAttribute('id', id);
container.appendChild(swfdiv);
document.getElementById(_options.id).appendChild(container);
_options.id = id;
}
function checkSecurity() {
var settings = Wami.getSettings();
if (settings.microphone.granted) {
_options.onReady();
} else {
// Show any Flash settings panel you want:
// http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/SecurityPanel.html
Wami.showSecurity("privacy", "Wami.show", Wami
.nameCallback(_options.onSecurity), Wami
.nameCallback(_options.onError));
}
}
// Embed the WAMI SWF and call the named callback function when loaded.
function embedWamiSWF(id, initfn) {
var flashVars = {
visible : false,
loadedCallback : initfn
}
var params = {
allowScriptAccess : "always"
}
if (supportsTransparency()) {
params.wmode = "transparent";
}
if (typeof console !== 'undefined') {
flashVars.console = true;
}
var version = '10.0.0';
document.getElementById(id).innerHTML = "WAMI requires Flash "
+ version
+ " or greater<br />https://get.adobe.com/flashplayer/";
// This is the minimum size due to the microphone security panel
Wami.swfobject.embedSWF(_options.swfUrl, id, 214, 137, version, null,
flashVars, params);
// Without this line, Firefox has a dotted outline of the flash
Wami.swfobject.createCSS("#" + id, "outline:none");
}
// To check if the microphone settings were 'remembered', we
// must actually embed an entirely new Wami client and check
// whether its microphone is granted. If it is, it was remembered.
function checkRemembered(finishedfn) {
var id = Wami.createID();
var div = document.createElement('div');
div.style.top = '-999px';
div.style.left = '-999px';
div.setAttribute('id', id);
var body = document.getElementsByTagName('body').item(0);
body.appendChild(div);
var fn = Wami.nameCallback(function() {
var swf = document.getElementById(id);
Wami._remembered = swf.getSettings().microphone.granted;
Wami.swfobject.removeSWF(id);
eval(finishedfn + "()");
});
embedWamiSWF(id, fn);
}
// Attach all the audio methods to the Wami namespace in the callback.
function delegateWamiAPI() {
var recorder = document.getElementById(_options.id);
function delegate(name) {
Wami[name] = function() {
return recorder[name].apply(recorder, arguments);
}
}
delegate('startPlaying');
delegate('stopPlaying');
delegate('startRecording');
delegate('stopRecording');
delegate('startListening');
delegate('stopListening');
delegate('getRecordingLevel');
delegate('getPlayingLevel');
delegate('setSettings');
// Append extra information about whether mic settings are sticky
Wami.getSettings = function() {
var settings = recorder.getSettings();
settings.microphone.remembered = Wami._remembered;
return settings;
}
Wami.showSecurity = function(panel, startfn, finishedfn, failfn) {
// Flash must be on top for this.
var container = document.getElementById(_options.cid);
var augmentedfn = Wami.nameCallback(function() {
checkRemembered(finishedfn);
container.style.cssText = "position: absolute;";
});
container.style.cssText = "position: absolute; z-index: 99999";
recorder.showSecurity(panel, startfn, augmentedfn, failfn);
}
Wami.show = function() {
if (!supportsTransparency()) {
recorder.style.visibility = "visible";
}
}
Wami.hide = function() {
// Hiding flash in all the browsers is tricky. Please read:
// https://code.google.com/p/wami-recorder/wiki/HidingFlash
if (!supportsTransparency()) {
recorder.style.visibility = "hidden";
}
}
// If we already have permissions, they were previously 'remembered'
Wami._remembered = recorder.getSettings().microphone.granted;
if (_options.onLoaded) {
_options.onLoaded();
}
if (!_options.noSecurityCheck) {
checkSecurity();
}
}
}
| 0930meixiaodong-wami-recorder | example/client/recorder.js | JavaScript | mit | 7,459 |
<?php
# Save the audio to a URL-accessible directory for playback.
parse_str($_SERVER['QUERY_STRING'], $params);
$name = isset($params['name']) ? $params['name'] : 'output.wav';
$content = file_get_contents('php://input');
$fh = fopen($name, 'w') or die("can't open file");
fwrite($fh, $content);
fclose($fh);
?> | 0930meixiaodong-wami-recorder | example/server/php/record.php | PHP | mit | 312 |
# Run from the commandline:
#
# python server.py
# POST audio to http://localhost:9000
# GET audio from http://localhost:9000
#
# A simple server to collect audio using python. To be more secure,
# you might want to check the file names and place size restrictions
# on the incoming data.
import cgi
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class WamiHandler(BaseHTTPRequestHandler):
dirname = "/tmp/"
def do_GET(self):
f = open(self.get_name())
self.send_response(200)
self.send_header('content-type','audio/x-wav')
self.end_headers()
self.wfile.write(f.read())
f.close()
def do_POST(self):
f = open(self.get_name(), "wb")
# Note that python's HTTPServer doesn't support chunked transfer.
# Thus, it requires a content-length.
length = int(self.headers.getheader('content-length'))
print "POST of length " + str(length)
f.write(self.rfile.read(length))
f.close();
def get_name(self):
filename = 'output.wav';
qs = self.path.split('?',1);
if len(qs) == 2:
params = cgi.parse_qs(qs[1])
if params['name']:
filename = params['name'][0];
return WamiHandler.dirname + filename
def main():
try:
server = HTTPServer(('', 9000), WamiHandler)
print 'Started server...'
server.serve_forever()
except KeyboardInterrupt:
print 'Stopping server'
server.socket.close()
if __name__ == '__main__':
main()
| 0930meixiaodong-wami-recorder | example/server/python/server.py | Python | mit | 1,569 |
using System;
using System.Collections.Generic;
using System.Text;
using QuanLyHocSinh.HeThongXuLy;
using System.Data;
namespace QuanLyHocSinh.HeThongLuuTru
{
class NguoiDungDAO
{
public static bool KiemTraNguoiDung(NguoiDungDTO user)
{
string sql = "select * from NGUOIDUNG where TenNguoiDung = '" + user.TenNguoiDung + "' and MatKhauNguoiDung = '" + user.MatKhau + "'";
DataTable dt = DataAccess.ExecQuery(sql);
if (dt.Rows.Count != 0)
{
return true;
}
else
{
return false;
}
}
public static DataTable LayDanhSachNguoiDung()
{
string sql = "Select * from NGUOIDUNG";
return DataAccess.ExecQuery(sql);
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongLuuTru/NguoiDungDAO.cs | C# | gpl3 | 872 |
using System;
using System.Collections.Generic;
using System.Text;
using QuanLyHocSinh.HeThongXuLy;
using System.Data;
namespace QuanLyHocSinh.HeThongLuuTru
{
class LopHocDAO
{
public static bool ThemLopHoc(LopHocDTO lh)
{
try
{
//tao cau truy van va thuc thi cau truy van
string sql = "insert into LOPHOC(TenLop, KhoiLop, LopChuyen, PhongHoc) values ('" +
lh.TenLop + "'," +
lh.KhoiLop + ",'" +
lh.LopChuyen + "','" +
lh.PhongHoc + "')";
DataAccess.ExecNonQuery(sql);
return true;
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
return false;
}
}
public static DataTable DanhSachLopHoc()
{
string sql = "SELECT * FROM LOPHOC";
return DataAccess.ExecQuery(sql);
}
public static bool SuaLopHoc(LopHocDTO lh)
{
try
{
string sql = " Update LOPHOC set TenLop = '" + lh.TenLop + "',KhoiLop = " + lh.KhoiLop + ",LopChuyen = '" + lh.LopChuyen + "',PhongHoc='" + lh.PhongHoc + "'where MaLop=" + lh.MaLop;
DataAccess.ExecNonQuery(sql);
return true;
}
catch(Exception ex) {
return false;
}
}
public static bool XoaLopHoc(LopHocDTO lh)
{
try {
string sql = "Delete from LOPHOC where MaLop=" + lh.MaLop;
DataAccess.ExecNonQuery(sql);
return true;
}
catch( Exception ex)
{
return false;
}
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongLuuTru/LopHocDAO.cs | C# | gpl3 | 1,873 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace QuanLyHocSinh.HeThongLuuTru
{
class DataAccess
{
//protected static String _connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=QuanLyHocSinh.mdb";
protected static String _connectionString = @"Provider=SQLOLEDB;Data Source=172.29.19.67\SQLEXPRESS2005;Initial Catalog=QuanLyHocSinh;User Id=sa;Password=123456;";
//protected static String _connectionString = @"Provider=SQLOLEDB;Data Source=(local);Initial Catalog=QuanLyHocSinh;User Id=sa;Password=123456;";
static OleDbConnection connection;
public static void OpenConnection()
{
try
{
connection = new OleDbConnection(_connectionString);
connection.Open();
}
catch (Exception ex)
{
}
}
public static void CloseConnection()
{
if (connection != null)
{
connection.Close();
}
}
public static DataTable ExecQuery(string sql)
{
OpenConnection();
DataTable dt = new DataTable();
OleDbCommand command = connection.CreateCommand();
command.CommandText = sql;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(dt);
CloseConnection();
return dt;
}
public static void ExecNonQuery(string sql)
{
OpenConnection();
OleDbCommand command = connection.CreateCommand();
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongLuuTru/DataAccess.cs | C# | gpl3 | 1,894 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QuanLyHocSinh.HeThongXuLy;
using QuanLyHocSinh.HeThongLuuTru;
using QuanLyThuVien;
namespace QuanLyHocSinh.HeThongGiaoDien
{
public partial class FormDangNhap : Form
{
public FormDangNhap()
{
InitializeComponent();
}
private void btnDangNhap_Click(object sender, EventArgs e)
{
NguoiDungDTO nd = new NguoiDungDTO();
nd.TenNguoiDung = txtNguoiDung.Text;
nd.MatKhau = txtMatKhau.Text;
nd.PhanQuyen = txtPhanQuyen.Text;
bool isLogin = NguoiDungDAO.KiemTraNguoiDung(nd);
if (isLogin == true)
{
this.Hide();
Form1 frm = new Form1();
frm.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Bạn nhập sai Tên người dùng và mật khẩu!", "Sai thông tin");
}
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongGiaoDien/FormDangNhap.cs | C# | gpl3 | 1,185 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace QuanLyThuVien
{
public partial class FormThongTin : Form
{
public FormThongTin()
{
InitializeComponent();
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongGiaoDien/FormThongTin.cs | C# | gpl3 | 357 |
using System;
using System.Data;
using System.Windows.Forms;
using QuanLyHocSinh.HeThongLuuTru;
using QuanLyHocSinh.HeThongXuLy;
namespace QuanLyThuVien
{
public partial class FormTiepNhanLopHoc : Form
{
LopHocDTO lhHienTai = new LopHocDTO();
public FormTiepNhanLopHoc()
{
InitializeComponent();
}
private void btnThem_Click(object sender, EventArgs e)
{
//Khoi tao doi tuong lop hoc
LopHocDTO lh = new LopHocDTO();
//doc thong tin cua lop hoc tu form
lh.TenLop = txtTenLop.Text;
lh.KhoiLop = int.Parse(txtKhoiLop.Text);
lh.LopChuyen = txtLopChuyen.Text;
lh.PhongHoc = txtPhongHoc.Text;
//goi ham de them du lieu vao csdl
if (LopHocDAO.ThemLopHoc(lh))
{
MessageBox.Show("Them lop hoc thanh cong", "Thong bao");
HienThiDanhSachLopHoc();
}
else
{
MessageBox.Show("Them lop hoc that bai", "Thong bao");
}
}
void HienThiDanhSachLopHoc()
{
DataTable ds = LopHocDAO.DanhSachLopHoc();
dgvDanhSachLop.DataSource = ds;
}
private void FormTiepNhanLopHoc_Load(object sender, EventArgs e)
{
HienThiDanhSachLopHoc();
}
private void btnThoat_Click(object sender, EventArgs e)
{
this.Close();
}
private void dgvDanhSachLop_SelectionChanged(object sender, EventArgs e)
{
if (dgvDanhSachLop.SelectedCells.Count > 0)
{
// lay chi so cua dong dang duoc chon
int row = dgvDanhSachLop.SelectedCells[0].RowIndex;
// lay lop hoc dc chon tu DGV ra
DongToiLopHocHienTai(dgvDanhSachLop.Rows[row]);
// hien thi lop hoc len form:
txtMaLop.Text = lhHienTai.MaLop.ToString();
txtTenLop.Text = lhHienTai.TenLop;
txtKhoiLop.Text = lhHienTai.KhoiLop.ToString();
txtLopChuyen.Text = lhHienTai.LopChuyen;
txtPhongHoc.Text = lhHienTai.PhongHoc;
}
}
private void DongToiLopHocHienTai(DataGridViewRow row)
{
// Cap nhat thong tin cho doi tuong lhHienTai (DTO)
lhHienTai.MaLop = (int)row.Cells[0].Value;
lhHienTai.TenLop = (String)row.Cells[1].Value;
lhHienTai.KhoiLop = (int)row.Cells[2].Value;
lhHienTai.LopChuyen = (String)row.Cells[3].Value;
lhHienTai.PhongHoc = (String)row.Cells[4].Value;
}
private void btnSua_Click(object sender, EventArgs e)
{
lhHienTai.TenLop = txtTenLop.Text;
lhHienTai.KhoiLop = int.Parse(txtKhoiLop.Text);
lhHienTai.LopChuyen = txtLopChuyen.Text;
lhHienTai.PhongHoc = txtPhongHoc.Text;
if (LopHocDAO.SuaLopHoc(lhHienTai))
{
MessageBox.Show("Sua Lop Hoc Thanh Cong ^_^", "Thong Bao");
HienThiDanhSachLopHoc();
}
else
{
MessageBox.Show("Sua Lop Hoc That Bai T_T","Thong Bao");
}
}
private void btnXoa_Click(object sender, EventArgs e)
{
if (LopHocDAO.XoaLopHoc(lhHienTai))
{
MessageBox.Show("Xoa Lop Hoc Thanh Cong ^_^", "Thong Bao");
HienThiDanhSachLopHoc();
}
else {
MessageBox.Show("Xoa Lop Hoc That Bai T_T", "Thong Bao");
}
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongGiaoDien/FormTiepNhanLopHoc.cs | C# | gpl3 | 3,928 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("QuanLyThuVien")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuanLyThuVien")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7a467f31-08a7-45ee-9ecc-c18ff2ed4781")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/Properties/AssemblyInfo.cs | C# | gpl3 | 1,438 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QuanLyHocSinh.HeThongGiaoDien;
namespace QuanLyThuVien
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Bạn có muốn thoát hay không?", "Thoát chương trình", MessageBoxButtons.OKCancel,
MessageBoxIcon.Question);
if (dr == DialogResult.Cancel)
{
e.Cancel = true;
}
}
private void thoátToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void tiếpNhậnLớpHọcToolStripMenuItem_Click(object sender, EventArgs e)
{
FormTiepNhanLopHoc frmTiepNhanLopHoc = new FormTiepNhanLopHoc { MdiParent = this };
frmTiepNhanLopHoc.Show();
}
private void thôngTinToolStripMenuItem_Click(object sender, EventArgs e)
{
FormThongTin frmThongTin = new FormThongTin { MdiParent = this };
frmThongTin.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
//FormDangNhap frmDanhNhap = new FormDangNhap();
//frmDanhNhap.MdiParent = this;
//frmDanhNhap.Show();
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/Form1.cs | C# | gpl3 | 1,625 |
using System;
using System.Collections.Generic;
using System.Text;
namespace QuanLyHocSinh.HeThongXuLy
{
//DATA TRANSFER OBJECT
class NguoiDungDTO
{
string m_strTenNguoiDung;
public string TenNguoiDung
{
get { return m_strTenNguoiDung; }
set { m_strTenNguoiDung = value; }
}
string m_strMatKhau;
public string MatKhau
{
get { return m_strMatKhau; }
set { m_strMatKhau = value; }
}
string m_strPhanQuyen;
public string PhanQuyen
{
get { return m_strPhanQuyen; }
set { m_strPhanQuyen = value; }
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongXuLy/NguoiDungDTO.cs | C# | gpl3 | 736 |
using System;
using System.Collections.Generic;
using System.Text;
namespace QuanLyHocSinh.HeThongXuLy
{
class LopHocDTO
{
int m_iMaLop;//chua ma lop
string m_strTenLop;//ten lop
int m_iKhoiLop;//khoi lop
string m_strLopChuyen;//lop chuyen
string m_strPhongHoc;// phong hoc
public int MaLop
{
get { return m_iMaLop; }
set { m_iMaLop = value; }
}
public string TenLop
{
get { return m_strTenLop; }
set { m_strTenLop = value; }
}
public int KhoiLop
{
get { return m_iKhoiLop; }
set { m_iKhoiLop = value; }
}
public string LopChuyen
{
get { return m_strLopChuyen; }
set { m_strLopChuyen = value; }
}
public string PhongHoc
{
get { return m_strPhongHoc; }
set { m_strPhongHoc = value; }
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/HeThongXuLy/LopHocDTO.cs | C# | gpl3 | 1,025 |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using QuanLyHocSinh.HeThongGiaoDien;
namespace QuanLyThuVien
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FormDangNhap frmDanhNhap = new FormDangNhap();
frmDanhNhap.StartPosition = FormStartPosition.CenterScreen;
Application.Run(frmDanhNhap);
}
}
}
| 0871073qlhs | trunk/QuanLyHocSinh/QuanLyHocSinh_v3/QuanLyHocSinh/QuanLyHocSinh/Program.cs | C# | gpl3 | 656 |
package Features.MainMenu
{
import com.greensock.TweenLite;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import org.SFramework.Architechture.SViewNode;
import org.SFramework.Core.SFramework;
import org.SuiComponents.SuiSimpleButton;
public class MainMenu extends SViewNode
{
private var btnPlayGame:SuiSimpleButton;
public function MainMenu()
{
super();
}
override public function onInit(initData:Object):Boolean
{
var bgMc:Sprite = SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "menuBg" );
addChild( bgMc );
btnPlayGame = new SuiSimpleButton("Play");
btnPlayGame.title.textAlign = "center";
btnPlayGame.title.textVerticalAlign = "center";
btnPlayGame.title.fontName = "WoodLook";
btnPlayGame.title.embedFont = true;
btnPlayGame.title.textSize = 15;
btnPlayGame.title.enabled = true;
btnPlayGame.title.textColor = 0xffffff;
btnPlayGame.x = 73;
btnPlayGame.y = 305;
btnPlayGame.setSize( 176, 30 );
btnPlayGame.setSWFSource( Assets.assetsSwfName, "btnPostScore" );
btnPlayGame.addEventListener( MouseEvent.CLICK, handleBtnPlayGame );
addChild( btnPlayGame );
//=================
var hog:MovieClip = bgMc.getChildByName( "Hog" ) as MovieClip;
var aniPopup:Boolean = true;
hog.gotoAndPlay( "popup" );
TweenLite.delayedCall( Math.random() * 2.0 + 2.0, changeAnim );
function changeAnim():void
{
hog.gotoAndPlay( "hide" );
TweenLite.delayedCall( 0.5, hog.gotoAndPlay, ["popup"] );
TweenLite.delayedCall( Math.random() * 2.0 + 2.0, changeAnim );
}
return true;
}
override public function onShow(initData:Object):void
{
}
override public function onHide(onHideComplete:Function):void
{
onHideComplete.call();
}
public function handleBtnPlayGame( e:Event ):void
{
Application.goRatField();
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Features/MainMenu/MainMenu.as | ActionScript | mit | 2,088 |
package Features
{
import com.greensock.TweenLite;
import flash.display.MovieClip;
import org.SuiComponents.ScreenLockers.FlatScreenLocker;
import org.SuiComponents.SuiImage;
public class EggPeiceScreenLocker extends FlatScreenLocker
{
private var mcLogo:SuiImage;
public function EggPeiceScreenLocker(_color:uint=0, _alpha:Number=1.0, _animDuration:Number=0.8)
{
super( 0, 1.0, 0.8 );
mcLogo = new SuiImage();
mcLogo.setSize( 144, 144 );
mcLogo.setSWFSource( Assets.assetsSwfName, "logo" );
}
override protected function onLock( onLockFinish:Function, params:Array ):Boolean
{
return super.onLock( function():void
{
(mcLogo.source as MovieClip).gotoAndPlay( 1 );
addChild( mcLogo );
if( onLockFinish != null )
TweenLite.delayedCall( 1.8, onLockFinish, params );
}, null );
}
override protected function onUnlock( onUnlockFinish:Function, params:Array ):Boolean
{
removeChild( mcLogo );
return super.onUnlock( function():void
{
if( onUnlockFinish != null )
onUnlockFinish.apply( null, params );
}, null);
}
override protected function onUpdateScreen(stageW:int, stageH:int):void
{
mcLogo.x = (stageW - mcLogo.width) / 2.0;
mcLogo.y = (stageH - mcLogo.height) / 2.0;
super.onUpdateScreen( stageW, stageH );
}
}
}
| 07092013-tltdq-ecipgge | trunk/RatHammer/src/Features/EggPeiceScreenLocker.as | ActionScript | mit | 1,419 |
package Features.RatFeild
{
import com.greensock.TimelineLite;
import com.greensock.TweenLite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextFormatAlign;
import org.SFramework.Architechture.SViewNode;
import org.SuiComponents.SuiImage;
import org.SuiComponents.SuiSimpleButton;
public class DlgSummary extends SViewNode
{
private var imgBg:SuiImage;
private var btnPostScore:SuiSimpleButton;
public function DlgSummary()
{
}
override public function onInit(initData:Object):Boolean
{
initData = [50, 64, 92, 20, 15, 13, 50];
imgBg = new SuiImage();
imgBg.setSWFSource( Assets.assetsSwfName, "dlgSummary" );
addChild( imgBg );
btnPostScore = new SuiSimpleButton( "" );
btnPostScore.setSize( 176, 30 );
btnPostScore.addEventListener( MouseEvent.CLICK, handleBtnPostScore );
btnPostScore.x = 130;
btnPostScore.y = 280;
btnPostScore.title.text = "Save My Score";
btnPostScore.title.fontName = "WoodLook";
btnPostScore.title.embedFont = true;
btnPostScore.title.textSize = 15;
btnPostScore.title.enabled = true;
btnPostScore.title.textColor = 0xffffff;
btnPostScore.title.textVerticalAlign = "center";
btnPostScore.title.textAlign = TextFormatAlign.CENTER;
btnPostScore.setSWFSource( Assets.assetsSwfName, "btnPostScore" );
addChild( btnPostScore );
return true;
}
override public function onShow(initData:Object):void
{
x = -300;
y = -300;
scaleX = 0.1;
scaleY = 0.1;
var tl:TimelineLite = new TimelineLite();
tl.append( TweenLite.to( this, 0.2, {scaleX:1.15, scaleY:1.2, x:75, y:75} ) );
tl.append( TweenLite.to( this, 0.1, {scaleX:0.85, scaleY:0.8, x:63, y:63} ) );
tl.append( TweenLite.to( this, 0.05, {scaleX:1.0, scaleY:1.0, x:68, y:68} ) );
tl.play();
}
override public function onHide(onHideComplete:Function):void
{
super.onHide( onHideComplete );
}
private function handleBtnPostScore( e:Event ):void
{
Global.viewsCabinet.hideLayer( ShareMacros.MV_DlgSummary );
Application.goMainMenu();
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Features/RatFeild/DlgSummary.as | ActionScript | mit | 2,252 |
package Features.RatFeild
{
import com.greensock.TweenLite;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import org.SFramework.Core.SFramework;
public class RatHog extends Sprite
{
private var mcCave:MovieClip;
public var showTime:Number;
public function RatHog()
{
super();
mcCave = SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "cave" );
addChild( mcCave );
mcCave.gotoAndStop( "stop" );
}
public function doPopup( sTime:Number, e:Boolean=true ):void
{
mcCave.gotoAndPlay( "popup" );
showTime = sTime;
enabled = e;
}
public function doWhack():int
{
mcCave.gotoAndPlay( "whack" );
enabled = false;
return 1;
}
public function doHide():void
{
mcCave.gotoAndPlay( "hide" );
}
public function set enabled( val:Boolean ):void
{
mouseEnabled = val;
mouseChildren = val;
}
public function applySmoke():void
{
var smoke:MovieClip = SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "smoke" );
addChild( smoke );
smoke.gotoAndPlay( 1 );
smoke.addEventListener( Event.ENTER_FRAME, handleEnterFrame );
function handleEnterFrame(e:Event):void
{
if( smoke.currentFrame >= 12 )
{
TweenLite.delayedCall( 1, removeSmoke, null, true );
smoke.removeEventListener( Event.ENTER_FRAME, handleEnterFrame );
}
}
function removeSmoke():void
{
removeChild( smoke );
}
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Features/RatFeild/RatHog.as | ActionScript | mit | 1,637 |
//==============================================
// Đập trúng bong bóng, tất cả các lổ điều có rat popup
// Đập trúng chồn hoi, trừ điểm
// Đập trúng chuột thỏ, điểm gấp đôi
// Đập chết boss cáo, điểm cực nhiều, đập nhiều lần
// => phát triển thành đi màn, có đấu boss
//==============================================
package Features.RatFeild
{
import com.greensock.TimelineLite;
import com.greensock.TweenLite;
import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextFieldAutoSize;
import org.SFramework.Architechture.SViewNode;
import org.SFramework.Core.SFramework;
import org.SUtility.SRandom;
import org.SUtility.SSequenceScheduler;
import org.SUtility.SStringFormatter;
import org.SuiComponents.SuiLabel;
import org.SuiComponents.SuiProgressBar;
public class RatField extends SViewNode
{
private static const MinumunNextRatTime:Number = 0.4;
private static const MinumunRatPopup:Number = 0.6;
private static const NumberHog:int = 12;
private static const RoundTime:int = 60 * 2; // 2 minutes
private var mcHand:MovieClip;
private var readytext:MovieClip;
private var hogListFree:Vector.<RatHog> = new Vector.<RatHog>();
private var hogListBusy:Vector.<RatHog> = new Vector.<RatHog>();
private var lblScore:SuiLabel;
private var lblTimer:SuiLabel;
private var pgbTimer:SuiProgressBar;
private var subUIContainer:Sprite;
private var lblInfo:SuiLabel;
//================================================
private var timeElapse:Number = 0.0;
private var nextRatTime:Number = 0.0;
private var scheduler:Scheduler = new Scheduler();
private var isAction:Boolean = false;
private var roundTimeElapse:Number = 0.0;
//================================================
private var scored:int = 0;
//================================================
public function RatField()
{
}
override public function onInit(initData:Object):Boolean
{
var bg:Sprite = SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "background" );
addChild( bg );
for( var i:int=0; i<NumberHog; i++ )
{
var hog:DisplayObject = bg.getChildByName( "Hog" + i );
var index:int = bg.getChildIndex( hog );
bg.removeChildAt( index );
var ratH:RatHog = new RatHog();
ratH.x = hog.x;
ratH.y = hog.y;
ratH.scaleX = hog.scaleX;
ratH.scaleY = hog.scaleY;
ratH.visible = false;
bg.addChildAt( ratH, index );
ratH.addEventListener( MouseEvent.CLICK, handleWhackRat );
hogListFree.push( ratH );
}
mcHand = SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "hand" ) as MovieClip;
mcHand.startDrag();
mcHand.mouseEnabled = false;
mcHand.mouseChildren = false;
mcHand.x = SFramework.singleton.getStage().mouseX;
mcHand.y = SFramework.singleton.getStage().mouseY;
addChild( mcHand );
//============
subUIContainer = new Sprite();
subUIContainer.visible = false;
addChild( subUIContainer );
var scoreBoard:Sprite = SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "scoreBoard" );
scoreBoard.x = 3;
scoreBoard.y = 3;
subUIContainer.addChild( scoreBoard );
lblScore = new SuiLabel();
lblScore.fontName = "WoodLook";
lblScore.text = "Score";
lblScore.embedFont = true;
lblScore.autoSize = TextFieldAutoSize.LEFT;
lblScore.textSize = 20;
lblScore.textColor = 0xffeeaa;
lblScore.enabled = true;
lblScore.x = 12;
lblScore.y = 7;
subUIContainer.addChild( lblScore );
pgbTimer = new SuiProgressBar();
pgbTimer.setSize( 365.4, 23.05 );
pgbTimer.x = 182.05;
pgbTimer.y = 7;
pgbTimer.labelType = "none";
pgbTimer.direction = "right";
pgbTimer.setDisplayObject( SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "pgbTime" ) );
subUIContainer.addChild( pgbTimer );
lblTimer = new SuiLabel();
lblTimer.fontName = "WoodLook";
lblTimer.text = "02:00";
lblTimer.embedFont = true;
lblTimer.autoSize = TextFieldAutoSize.LEFT;
lblTimer.textSize = 15;
lblTimer.textColor = 0xffeeaa;
lblTimer.enabled = true;
lblTimer.x = 337;
lblTimer.y = 7;
subUIContainer.addChild( lblTimer );
readytext = SFramework.singleton.resourceManager.getImmediateResourceInst( Assets.assetsSwfName, "readytext" );
readytext.visible = false;
addChild( readytext );
lblInfo = new SuiLabel();
lblInfo.autoSize = TextFieldAutoSize.CENTER;
lblInfo.textSize = 15;
lblInfo.y = 100;
lblInfo.x = 100;
lblInfo.enabled = true;
lblInfo.textColor = 0xffffff;
addChild( lblInfo );
SFramework.singleton.runtimeUpdater.addFunction( onFrameUpdate );
SFramework.singleton.runtimeUpdater.addFunction( onFrameUpdateSecond, null, 1.0 );
return true;
}
override public function onShow(initData:Object):void
{
var schl:SSequenceScheduler = new SSequenceScheduler();
schl.append( null, 1.3 );
for( var i:int=0; i<hogListFree.length; i++ )
schl.append( applyAnim, 0.15, hogListFree[i] );
schl.append( showTextReady, 0.5 );
schl.play();
function applyAnim( hog:RatHog ):Boolean
{
hog.applySmoke();
hog.visible = true;
return true;
}
function showTextReady():void
{
var tl:TimelineLite = new TimelineLite( {onComplete:startPlayGame} );
readytext.visible = true;
readytext.x = 200;
readytext.y = -100;
tl.append( TweenLite.to( readytext, 0.5, { y: (SFramework.singleton.getHeight() - readytext.height)/2} ) );
tl.append( TweenLite.to( readytext, 0.5, { delay:1.6, y: SFramework.singleton.getHeight() +100} ) );
tl.play();
}
}
override public function onHide(onHideComplete:Function):void
{
onHideComplete.call();
}
override public function onResize():void
{
}
private function stopPlayGame():void
{
isAction = false;
for( var i:String in hogListFree )
TweenLite.delayedCall( Math.random(), hogListFree[i].doPopup, [1, false] );
for( i in hogListBusy )
hogListBusy[i].enabled = false;
mcHand.stopDrag();
mcHand.x = -100;
mcHand.y = -100;
TweenLite.delayedCall( 2.0, Global.viewsCabinet.showLayer, [ShareMacros.MV_DlgSummary] );
}
private function startPlayGame():void
{
readytext.visible = false;
isAction = true;
nextRatTime = scheduler.getScheduleTime();
pgbTimer.minimum = 0;
pgbTimer.maximum = RoundTime;
pgbTimer.value = 40;
subUIContainer.visible = true;
subUIContainer.y = -100;
TweenLite.to( subUIContainer, 0.5, {y:0} );
}
private function onFrameUpdate( deltaTime:Number, totalTime:Number ):void
{
if( ! isAction )
return;
timeElapse += deltaTime;
if( timeElapse > nextRatTime )
{
showRandomRat( nextRatTime );
timeElapse = 0;
nextRatTime = scheduler.getScheduleTime();
// Delay between to rat popup
nextRatTime += SRandom.randomLeftGaussian( 0.0, 1.5 ) * nextRatTime;
if( nextRatTime < MinumunRatPopup )
nextRatTime = MinumunRatPopup;
lblInfo.text = String(nextRatTime);
}
//=====
scheduler.updateTime( deltaTime );
for( var i:int=0; i<hogListBusy.length; i++ )
{
hogListBusy[i].showTime -= deltaTime;
if( hogListBusy[i].showTime < 0 )
{
hogListBusy[i].doHide();
hogListFree.push( hogListBusy.splice( i, 1 )[0] );
}
}
//=====
roundTimeElapse += deltaTime;
if( roundTimeElapse >= RoundTime )
stopPlayGame();
}
private function onFrameUpdateSecond( deltaTime:Number, totalTime:Number ):void
{
lblScore.text = "Score: " + scored;
lblTimer.text = SStringFormatter.formatTime( RoundTime - uint(roundTimeElapse), true );
pgbTimer.value = (roundTimeElapse / Number(RoundTime)) * Number(RoundTime);
}
//==========================================
private function showRandomRat( showTime:Number ):void
{
if( hogListFree.length == 0 )
return;
var seek:int = int(Math.floor( Math.random() * hogListFree.length ) );
if( showTime < MinumunRatPopup )
showTime = MinumunRatPopup;
hogListFree[seek].doPopup( showTime );
hogListBusy.push( hogListFree.splice( seek, 1 )[0] );
}
private function handleWhackRat( e:Event ):void
{
if( ! isAction )
return;
mcHand.gotoAndPlay( 2 );
var ratH:RatHog = e.currentTarget as RatHog;
scored += ratH.doWhack();
var index:int = hogListBusy.indexOf( ratH );
if( index >= 0 )
hogListFree.push( hogListBusy.splice( index, 1 )[0] );
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Features/RatFeild/RatField.as | ActionScript | mit | 9,304 |
package Features.RatFeild
{
public class Scheduler
{
private var baseSpeed:Number = 0.15;
private var varX:Number = 1;
public function Scheduler()
{
}
public function updateTime( deltaTime:Number ):void
{
varX += deltaTime;
}
public function getScheduleTime():Number
{
var varY:Number = calcVarY();
return varY * baseSpeed;
}
private function calcVarY():Number
{
var logX:Number = Math.log( varX ) / Math.log( 10.0 );
var ePow:Number = Math.pow( Math.E, logX );
return 10.0 - ePow;
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Features/RatFeild/Scheduler.as | ActionScript | mit | 579 |
package
{
public class Global
{
public static var viewsCabinet:ViewsCabinet;
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Global.as | ActionScript | mit | 93 |
package
{
public class ShareConstants
{
public static const GData_exp:String = "exp";
public static const GData_level:String = "level";
public static const GData_gold:String = "gold";
public static const GData_coin:String = "coin";
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/ShareConstants.as | ActionScript | mit | 259 |
package
{
import Features.EggPeiceScreenLocker;
import org.SData.SGeneralData;
public class Application
{
public static function initApplication():void
{
SGeneralData.singleton.initIntegerValue( [ShareConstants.GData_exp, ShareConstants.GData_level, ShareConstants.GData_gold, ShareConstants.GData_coin] );
}
public static function goRatField():void
{
var lock:EggPeiceScreenLocker = new EggPeiceScreenLocker();
lock.lock( function():void
{
Global.viewsCabinet.setActiveScene( ShareMacros.MV_RatField );
lock.unlock( null);
});
}
public static function goMainMenu():void
{
var lock:EggPeiceScreenLocker = new EggPeiceScreenLocker();
lock.lock( function():void
{
Global.viewsCabinet.setActiveScene( ShareMacros.MV_MainMenu );
lock.unlock( null );
});
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Application.as | ActionScript | mit | 863 |
package
{
import com.demonsters.debugger.MonsterDebugger;
import flash.utils.ByteArray;
import org.SFramework.Core.SFramework;
import org.SFramework.Core.SViewCabinet;
[SWF( width="600", height="400", frameRate="60" )]
public class RatHammer extends SFramework
{
public function RatHammer()
{
super();
}
override protected function onAddToStage():void
{
super.onAddToStage();
MonsterDebugger.initialize( this );
MonsterDebugger.inspect(this);
try{ startInlineConfig( onFrameworkInitResult ) }catch(ex:*){}
}
private function onFrameworkInitResult( errCode : int, errMsg : String, ...params ) : void
{
// Handle Success code
if( errCode >= 0 )
{
switch( errCode )
{
case SFramework.SUCCESS:
Global.viewsCabinet = SFramework.singleton.viewsCabinet as ViewsCabinet;
Application.goMainMenu();
break;
case SFramework.RESOURCE_LOAD_COMPLETE:
SFramework.singleton.resourceManager.loadStreamSwf( Assets.assetsSwfName, new Assets.assetsSwf() as ByteArray );
SFramework.singleton.resourceManager.loadStreamFont( new Assets.fontSwf() as ByteArray );
break;
}
}
}
override protected function createViewCabinet():SViewCabinet
{
return new ViewsCabinet( this, resourceManager ) as SViewCabinet;
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/RatHammer.as | ActionScript | mit | 1,399 |
package
{
import Features.MainMenu.MainMenu;
import Features.RatFeild.DlgSummary;
import Features.RatFeild.RatField;
import flash.display.DisplayObjectContainer;
import flash.display.Stage;
import org.SFramework.Core.SViewCabinet;
import org.SFramework.Interface.IResourcesManager;
public class ViewsCabinet extends SViewCabinet
{
public function ViewsCabinet( host:DisplayObjectContainer, resMng:IResourcesManager )
{
super( host, resMng );
}
override public function onInit( stage:Stage ):void
{
super.onInit( stage );
registerScene( ShareMacros.MV_RatField, RatField, Assets.assetsSwfName );
registerScene( ShareMacros.MV_MainMenu, MainMenu, Assets.assetsSwfName );
registerLayer( ShareMacros.MV_DlgSummary, DlgSummary );
}
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/ViewsCabinet.as | ActionScript | mit | 810 |
package
{
public class ShareMacros
{
public static const MV_RatField:String = "MV_RatField";
public static const MV_MainMenu:String = "MV_MainMenu";
public static const MV_DlgSummary:String = "MV_DlgSummary";
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/ShareMacros.as | ActionScript | mit | 232 |
package
{
public class Assets
{
[Embed(source="assets/assets.swf", mimeType="application/octet-stream")]
public static var assetsSwf:Class;
public static var assetsSwfName:String = "assets.swf";
[Embed(source="assets/font.swf", mimeType="application/octet-stream")]
public static var fontSwf:Class;
}
} | 07092013-tltdq-ecipgge | trunk/RatHammer/src/Assets.as | ActionScript | mit | 330 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Media;
namespace TrainTicketsRobot
{
class TRSoundPlayer
{
///
/// 播放声音文件
///
/// 文件全名
public static void PlaySound(string FileName)
{//要加载COM组件:Microsoft speech object Library
if (!System.IO.File.Exists(FileName))
{
return;
}
SoundPlayer SPlayer = new SoundPlayer(FileName);
SPlayer.Play();
}
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/TRSoundPlayer.cs | C# | gpl3 | 624 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TrainTicketsRobot
{
class OrderWaiteTimeRet
{
public OrderWaiteTimeRet(int ret, string orderID)
{
this.RetValue = ret;
this.OrderID = orderID;
}
public int RetValue;
public string OrderID;
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/OrderWaiteTimeRet.cs | C# | gpl3 | 388 |
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
namespace TrainTicketsRobot
{
internal class WebBot
{
private static HttpWebRequest request;
public static string ReadStream(HttpWebResponse respRtn)
{
StreamReader reader;
Stream responseStream = respRtn.GetResponseStream();
if (respRtn.Headers["Content-Encoding"] == "gzip")
{
GZipStream stream = new GZipStream(responseStream, CompressionMode.Decompress);
reader = new StreamReader(stream, Encoding.UTF8);
}
else
{
reader = new StreamReader(responseStream, Encoding.UTF8);
}
string str = reader.ReadToEnd();
reader.Close();
responseStream.Close();
respRtn.Close();
request.KeepAlive = false;
return str;
}
private static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static HttpWebResponse SendData(Uri uri, ref CookieContainer cookconReq)
{
return SendData(uri, "", ref cookconReq, false);
}
public static HttpWebResponse SendData(Uri uri, ref CookieContainer cookconReq, bool IsAjax)
{
return SendData(uri, "", ref cookconReq, IsAjax);
}
public static HttpWebResponse SendData(Uri uri, string strPostData, ref CookieContainer cookconReq)
{
return SendData(uri, strPostData, ref cookconReq, false);
}
public static HttpWebResponse SendPostData(Uri uri, string strPostData, ref CookieContainer cookconReq)
{
return SendPostData(uri, strPostData, ref cookconReq, false);
}
public static HttpWebResponse SendData(Uri uri, string strPostData, ref CookieContainer cookconReq, bool IsAjax)
{
HttpWebResponse response2;
try
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(WebBot.RemoteCertificateValidationCallback);
request = (HttpWebRequest) WebRequest.Create(uri);
request.AllowAutoRedirect = true;
if (cookconReq.Count == 0)
{
request.CookieContainer = new CookieContainer();
cookconReq = request.CookieContainer;
}
else
{
request.CookieContainer = cookconReq;
}
if (IsAjax)
{
request.Headers["x-requested-with"] = "XMLHttpRequest";
}
request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
if (IsAjax)
{
request.Accept = "text/plain, */*";
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
}
request.Headers["Accept-Language"] = "zh-CN";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
request.Host = "dynamic.12306.cn";
if (IsAjax)
{
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; ";
}
request.Headers["Accept-Encoding"] = "gzip, deflate";
request.KeepAlive = true;
if (strPostData.Equals(""))
{
request.Method = "GET";
}
else
{
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
request.Headers["Cache-Control"] = "no-cache";
request.ServicePoint.Expect100Continue = false;
byte[] bytes = Encoding.ASCII.GetBytes(strPostData);
request.ContentLength = bytes.Length;
string Headers = request.Headers.ToString();
using (request.GetRequestStream())
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
}
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
Exception exception = new Exception();
exception.Data.Add("StatusCode", HttpStatusCode.OK);
throw exception;
}
response2 = response;
}
catch (WebException exception2)
{
Exception exception3 = new Exception(exception2.Message);
throw exception3;
}
catch (Exception exception4)
{
throw exception4;
}
return response2;
}
public static HttpWebResponse SendPostData(Uri uri, string strPostData, ref CookieContainer cookconReq, bool IsAjax)
{
HttpWebResponse response2;
try
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(WebBot.RemoteCertificateValidationCallback);
request = (HttpWebRequest)WebRequest.Create(uri);
if (cookconReq.Count == 0)
{
request.CookieContainer = new CookieContainer();
cookconReq = request.CookieContainer;
}
else
{
request.CookieContainer = cookconReq;
}
if (IsAjax)
{
request.Headers["x-requested-with"] = "XMLHttpRequest";
}
request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
if (IsAjax)
{
request.Accept = "text/plain, */*";
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
}
request.Headers["Accept-Language"] = "zh-CN";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)";
if (IsAjax)
{
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; ";
}
request.Headers["Accept-Encoding"] = "gzip, deflate";
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
request.Headers["Cache-Control"] = "no-cache";
request.ServicePoint.Expect100Continue = false;
byte[] bytes = Encoding.ASCII.GetBytes(strPostData);
request.ContentLength = bytes.Length;
using (request.GetRequestStream())
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
Exception exception = new Exception();
exception.Data.Add("StatusCode", HttpStatusCode.OK);
throw exception;
}
response2 = response;
}
catch (WebException exception2)
{
Exception exception3 = new Exception(exception2.Message);
throw exception3;
}
catch (Exception exception4)
{
throw exception4;
}
return response2;
}
public static string strProcessError(Exception ex)
{
if (ex.Data.Contains("StatusCode"))
{
return "网站忙,连接失败!";
}
return ex.Message;
}
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/WebBot.cs | C# | gpl3 | 9,900 |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Xml;
namespace TrainTicketsRobot
{
/*
* [{"end_station_name":"重庆",
* "end_time":"15:04",
* "id":"650000L94201",
* "start_station_name":"深圳",
* "start_time":"03:10",
* "value":"L942/L943"}]
*/
[Serializable]
class TrainInfo
{
public TrainInfo()
{
this.end_station_name = "";
this.end_time = "";
this.id = "";
this.start_station_name = "";
this.start_time = "";
this.value = "";
}
public string end_station_name;
public string end_time;
public string id;
public string start_station_name;
public string start_time;
public string value;
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/TrainInfo.cs | C# | gpl3 | 888 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Media;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Text;
using Microsoft;
namespace TrainTicketsRobot
{
public partial class FrmMain : Form
{
public CookieContainer cookconReq = new CookieContainer();
public Dictionary<string, string> dicStation;
private Hashtable htSeatType;
private const int i32InitInterval = 5000;
private bool IsPlayBeep = true;
private int PgmAccess;
public bool StopSearch;
public bool StopFinsh;
private string strOrderPage = "";
private string[] strsTrainInfo = new string[14];
private Uri uriBase = new Uri("https://dynamic.12306.cn");
private bool bIsLogin = false;
private string resDir = "./res";
private string soundFilePath = "./res/start.wav";
private Cracker loginCracker = new Cracker();
private Cracker orderCracker = new Cracker();
private static int nSearchTimes = 0;
private int nSearchIntev = 0;
private int nLoginIntev = 0;
private static int nOrderTimes = 0;
private TrainInfo[] TrainInfoArray = null;
private string strTrainNo = "";
public FrmMain()
{
InitializeComponent();
}
private int DoAutoLogin()
{
int ret = 0;
try
{
this.getLoginPassCode(new Random(DateTime.Now.Millisecond).NextDouble().ToString());
string strLoginPassCode = this.loginCracker.Read(new Bitmap(this.pbLoginPassCode.Image));
if (strLoginPassCode == "")
{
return -4;
}
this.txtLoginPassCode.Text = strLoginPassCode;
string strRtn = this.Login();
if (strRtn.Contains("myOrderAction"))
{
this.gbLogin.Text = "已登录";
this.gbLogin.Enabled = false;
this.gbSearch.Enabled = true;
this.bIsLogin = true;
this.txtLog.AppendText("登录成功,欢迎" + this.txtUserName.Text + "...\r\n");
return 0;
}
if (strRtn.Contains("请输入正确的验证码"))
{
this.txtLog.AppendText("验证码错误,请重试……\r\n");
ret = -2;
goto error1;
}
if (strRtn.Contains("密码输入错误"))
{
this.txtLog.AppendText("密码错误,请重试……\r\n");
ret = -3;
goto error1;
}
}
catch (Exception exception)
{
this.txtLog.AppendText("错误信息:" + exception.Message + "……");
ret = -1;
}
error1:
return ret;
}
private int DoHandLogin()
{
int ret = 0;
try
{
string strLoginPassCode = this.txtLoginPassCode.Text;
if (strLoginPassCode == "")
{
return -4;
}
this.txtLoginPassCode.Text = strLoginPassCode;
string strRtn = this.Login();
if (strRtn.Contains("myOrderAction"))
{
this.gbLogin.Text = "已登录";
this.gbLogin.Enabled = false;
this.gbSearch.Enabled = true;
this.bIsLogin = true;
this.txtLog.AppendText("登录成功,欢迎" + this.txtUserName.Text + "...\r\n");
return 0;
}
if (strRtn.Contains("请输入正确的验证码"))
{
this.txtLog.AppendText("验证码错误,请重试……\r\n");
ret = -2;
goto error1;
}
if (strRtn.Contains("密码输入错误"))
{
this.txtLog.AppendText("密码错误,请重试……\r\n");
ret = -3;
goto error1;
}
}
catch (Exception exception)
{
this.txtLog.AppendText("错误信息:" + exception.Message + "……");
ret = -1;
}
error1:
return ret;
}
private void RunLoginThead()
{
Thread.CurrentThread.IsBackground = true;
int loginIntev = Convert.ToInt32(this.txtLoginIntev.Text);
this.gbLogin.Enabled = false;
if (DoHandLogin() < 0)
{
this.gbLogin.Enabled = true;
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
Control.CheckForIllegalCrossThreadCalls = false;
new Thread(new ThreadStart(this.RunLoginThead)).Start();
}
catch (Exception exception)
{
MessageBox.Show(WebBot.strProcessError(exception), "出错了,请重试", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
private void btnManaul_Click(object sender, EventArgs e)
{
this.PopIE();
}
private void btnOrder_Click(object sender, EventArgs e)
{
}
private void btnReLogin_Click(object sender, EventArgs e)
{
}
private void btnReLoginAndSearch_Click(object sender, EventArgs e)
{
if (this.checkInput())
{
try
{
Control.CheckForIllegalCrossThreadCalls = false;
new Thread(new ThreadStart(this.DoLoginAndOrderTrainTicketsThread)).Start();
}
catch (Exception exception)
{
MessageBox.Show(WebBot.strProcessError(exception), "出错了,请重试", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
}
private void btnStopPlay_Click(object sender, EventArgs e)
{
this.IsPlayBeep = false;
this.btnStopPlay.Enabled = false;
}
private void btnStopSearch_Click(object sender, EventArgs e)
{
this.StopSearch = true;
nSearchTimes = 0;
nOrderTimes = 0;
this.txtLog.AppendText("正在停止……\r\n最近一步的操作必须全部执行完毕方能停止……\r\n");
}
private bool checkInput()
{
string text = "";
if (this.txtUserName.Text == "")
{
text = text + "用户名未输入\r\n";
}
if (this.txtPassword.Text == "")
{
text = text + "密码未输入\r\n";
}
if (this.txtLoginIntev.Text == "")
{
text = text + "登录间隔时间未输入\r\n";
}
Regex regex = new Regex("^[0-9]*$");
if (!regex.IsMatch(this.txtLoginIntev.Text))
{
text = text + "登录间隔时间应该为整数\r\n";
}
if (this.txtFromStation.Text == "")
{
text = text + "发站未输入\r\n";
}
if (this.txtToStation.Text == "")
{
text = text + "到站未输入\r\n";
}
if (this.txtTrainCode.Text == "")
{
text = text + "车次未输入,如想订多趟车,请多开\r\n";
}
Regex regex2 = new Regex("^[A-Za-z0-9]+$");
if (!regex2.IsMatch(this.txtTrainCode.Text))
{
text = text + "车次只能输入字母和数字,请以12306车票预订界面公布的车次为准\r\n";
}
if (this.txtSearchIntev.Text == "")
{
text = text + "检索间隔时间未输入\r\n";
}
if (!regex.IsMatch(this.txtSearchIntev.Text))
{
text = text + "检索间隔时间应该为整数\r\n";
}
if (this.cbSeatType.SelectedItem == null)
{
text = text + "席别未选择\r\n";
}
if (this.dgvInfo.Rows.Count <= 1)
{
text = text + "乘车人信息未输入\r\n";
}
if (text != "")
{
MessageBox.Show(text, "出错了,请重试", MessageBoxButtons.OK, MessageBoxIcon.Hand);
return false;
}
return true;
}
private int DoOrderTrainTickets()
{
if (!this.RepeatLogin())
{
return -1;
}
this.InitTrainInfo();
foreach (TrainInfo train in this.TrainInfoArray)
{
string[] valueArry = train.value.Split('/');
foreach(string v in valueArry)
{
if (this.txtTrainCode.Text == v)
{
this.strTrainNo = train.id;
}
}
}
return this.RepeatOrderTrain();
}
private void ResetResource()
{
this.gbLogin.Enabled = false;
this.gbSearch.Enabled = false;
this.gbOrder.Enabled = false;
this.btnReLoginAndSearch.Enabled = false;
this.nSearchIntev = Convert.ToInt32(this.txtSearchIntev.Text) * 1000;
this.nLoginIntev = Convert.ToInt32(this.txtLoginIntev.Text) * 1000;
this.loginCracker = new Cracker();
this.orderCracker = new Cracker();
this.strOrderPage = "";
this.strsTrainInfo = new string[14];
nOrderTimes = 0;
nSearchTimes = 0;
}
private void InitTrainInfo()
{
try
{
if (this.TrainInfoArray != null)
{
return;
}
Uri uri = new Uri(this.uriBase, "/otsweb/order/querySingleAction.do?method=queryststrainall");
string strPostData = "date=" + this.dtpGoDate.Value.ToString("yyyy-MM-dd")
+ "&fromstation=" + this.dicStation[this.txtFromStation.Text]
+ "&tostation=" + this.dicStation[this.txtToStation.Text]
+ "&starttime=" + HttpUtility.UrlEncode(this.cbGoTime.Text);
string strJson = WebBot.ReadStream(WebBot.SendData(uri, strPostData, ref this.cookconReq));
this.TrainInfoArray = TRConvert.ToTrainInfoArray(strJson);
}
catch
{
return;
}
}
private void DoLoginAndOrderTrainTicketsThread()
{
Thread.CurrentThread.IsBackground = true;
this.StopSearch = false;
this.StopFinsh = false;
while (!this.StopSearch)
{
this.ResetResource();
switch (this.DoOrderTrainTickets())
{
case 1:
case 0://订票成功
this.PgmAccess = 999;
goto success;
case -1:
this.PgmAccess = 10;
break;
case -2:
this.PgmAccess = 10;
this.txtLog.AppendText("程序发生异常。\r\n");
break;
case -3:
this.PgmAccess = 10;
this.txtLog.AppendText("找不到" + this.cbSeatType.SelectedItem.ToString() + ",请重新选择。\r\n");
break;
case -10:
this.PgmAccess = 10;
goto stop;
case -20:
this.PgmAccess = 0;
this.bIsLogin = false;
this.txtLog.AppendText("检索异常,应该是登录太久被系统踢掉了!请重新登录!\r\n");
break;
}
Thread.Sleep(1000);
}
stop:
this.resetForm();
this.StopFinsh = true;
this.txtLog.AppendText("手动停止成功。\r\n");
return;
success:
this.resetForm();
this.btnStopPlay.Enabled = true;
new Thread(new ThreadStart(this.playBeep)).Start();
return;
}
private void InitSystemRes()
{
if (!Directory.Exists(this.resDir))
{
Directory.CreateDirectory(this.resDir);
}
}
private void LoadFrmSeting()
{
RobotConfig cfg = new RobotConfig();
FrmMainConfig frmMainConfig = cfg.LoadConfig();
if (frmMainConfig == null)
{
return;
}
this.txtUserName.Text = frmMainConfig.frmMainSetting.UserName;
this.txtPassword.Text = frmMainConfig.frmMainSetting.UserPwd;
this.txtLoginIntev.Text = Convert.ToString(frmMainConfig.frmMainSetting.LoginInterval);
this.txtFromStation.Text = frmMainConfig.frmMainSetting.FromStation;
this.txtToStation.Text = frmMainConfig.frmMainSetting.ToStation;
this.dtpGoDate.Text = frmMainConfig.frmMainSetting.GoDate;
this.cbGoTime.Text = frmMainConfig.frmMainSetting.GoTime;
this.txtTrainCode.Text = frmMainConfig.frmMainSetting.TrainNo;
this.txtSearchIntev.Text = Convert.ToString(frmMainConfig.frmMainSetting.SearchInterval);
this.cbSeatType.Text = frmMainConfig.frmMainSetting.SetType;
checkPassengerInfo();
int pasgerCount = frmMainConfig.pasgerList.PassengerList.Length;
for (int i = 0; i < pasgerCount; i++)
{
string PasgerName = frmMainConfig.pasgerList.PassengerList[i].PasgerName;
string CardNumber = frmMainConfig.pasgerList.PassengerList[i].CardNumber;
string MobilePhone = frmMainConfig.pasgerList.PassengerList[i].MobilePhone;
DataGridViewRow dataGridViewRow = new DataGridViewRow();
this.dgvInfo.Rows.Add(PasgerName, CardNumber, MobilePhone);
}
}
private void FrmMain_Load(object sender, EventArgs e)
{
this.htSeatType = new Hashtable();
this.htSeatType.Add("硬座", "1");
this.htSeatType.Add("无座", "1");
this.htSeatType.Add("硬卧", "3");
this.htSeatType.Add("软卧", "4");
this.htSeatType.Add("一等软座", "7");
this.htSeatType.Add("二等软座", "8");
this.htSeatType.Add("高级软卧", "6");
this.htSeatType.Add("商务座", "9");
foreach (string str in this.htSeatType.Keys)
{
this.cbSeatType.Items.Add(str);
}
this.dtpGoDate.Value = DateTime.Now.AddDays(11.0);
ToolTip tip = new ToolTip
{
InitialDelay = 500,
ReshowDelay = 500
};
tip.SetToolTip(this.pbLoginPassCode, "点击后刷新验证码");
tip.SetToolTip(this.pbOrderPassCode, "点击后刷新验证码");
this.cbGoTime.SelectedIndex = 0;
this.InitSystemRes();
this.LoadFrmSeting();
}
private void FrmMain_Shown(object sender, EventArgs e)
{
try
{
Control.CheckForIllegalCrossThreadCalls = false;
new Thread(new ThreadStart(this.initLogin)).Start();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message + "\r\n请重新运行程序。", "出错了,请重新运行程序", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
public static List<Cookie> GetAllCookies(CookieContainer cc)
{
List<Cookie> list = new List<Cookie>();
Hashtable hashtable = (Hashtable)cc.GetType().InvokeMember("m_domainTable", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, cc, new object[0]);
foreach (object obj2 in hashtable.Values)
{
SortedList list2 = (SortedList)obj2.GetType().InvokeMember("m_list", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, obj2, new object[0]);
foreach (CookieCollection cookies in list2.Values)
{
foreach (Cookie cookie in cookies)
{
list.Add(cookie);
}
}
}
return list;
}
private void getLoginPassCode(string strRandom)
{
try
{
string relativeUri = "/otsweb/passCodeAction.do?rand=sjrand";
if (strRandom != "")
{
relativeUri = relativeUri + "&" + strRandom;
}
Uri uri = new Uri(this.uriBase, relativeUri);
HttpWebResponse response = WebBot.SendData(uri, ref this.cookconReq);
this.pbLoginPassCode.Image = new Bitmap(response.GetResponseStream());
}
catch (Exception exception)
{
throw exception;
}
}
private void getOrderPassCode(string strRandom)
{
try
{
string relativeUri = "/otsweb/passCodeAction.do?rand=randp";
if (strRandom != "")
{
relativeUri = relativeUri + "&" + strRandom;
}
Uri uri = new Uri(this.uriBase, relativeUri);
HttpWebResponse response = WebBot.SendData(uri, ref this.cookconReq);
Stream RepStream = response.GetResponseStream();
this.pbOrderPassCode.Image = new Bitmap(RepStream);
}
catch (Exception exception)
{
throw exception;
}
}
private string GetPageMessage(string strRtn)
{
Regex regex = new Regex("var message = \"(.+)?\";\r\n *?var messageShow");
return regex.Match(strRtn).Groups[1].Value;
}
private Dictionary<string, string> getStationDic()
{
Dictionary<string, string> dictionary2;
try
{
Uri uri = new Uri(this.uriBase, "/otsweb/js/common/station_name.js?version=1.9");
string[] strArray = WebBot.ReadStream(WebBot.SendData(uri, ref this.cookconReq)).Replace("';", "").Split(new char[] { '@' });
Dictionary<string, string> dictionary = new Dictionary<string, string>();
for (int i = 1; i < strArray.Length; i++)
{
string[] strArray2 = strArray[i].Split(new char[] { '|' });
dictionary.Add(strArray2[1], strArray2[2]);
}
dictionary2 = dictionary;
}
catch (Exception exception)
{
throw exception;
}
return dictionary2;
}
private void initLogin()
{
Thread.CurrentThread.IsBackground = true;
bool flag = false;
while (!flag)
{
try
{
this.txtLog.AppendText("正在初始化……");
Thread.Sleep(0x1388);
Uri uri = new Uri(this.uriBase, "/otsweb/");
WebBot.ReadStream(WebBot.SendData(uri, ref this.cookconReq));
this.dicStation = this.getStationDic();
flag = true;
this.txtLog.AppendText("初始化成功!\r\n");
this.gbLogin.Enabled = true;
this.gbSearch.Enabled = true;
this.gbOrder.Enabled = true;
this.gbButton.Enabled = true;
continue;
}
catch (Exception exception)
{
this.txtLog.AppendText(exception.Message + "\r\n");
continue;
}
}
}
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName,
string lbszCookieName, string lpszCookieData);
private string getLoginRandCode(string strJson)
{
LoginRand loginRand = new LoginRand(strJson);
return loginRand.loginRand;
}
private string Login()
{
string str2;
try
{
Uri loginAysnSuggestUri = new Uri(this.uriBase, "/otsweb/loginAction.do?method=loginAysnSuggest");
string loginRand = getLoginRandCode(
WebBot.ReadStream(
WebBot.SendPostData(loginAysnSuggestUri, "", ref this.cookconReq)
)
);
Uri uri = new Uri(this.uriBase, "/otsweb/loginAction.do?method=login");
string strPostData = "loginRand=" + loginRand;
strPostData += "&refundLogin=N&refundFlag=Y";
strPostData += "&loginUser.user_name=" + this.txtUserName.Text;
strPostData += "&nameErrorFocus=";
strPostData += "&user.password=" + this.txtPassword.Text;
strPostData += "&passwordErrorFocus=";
strPostData += "&randCode=" + this.txtLoginPassCode.Text;
strPostData += "&randErrorFocus=focus";
str2 = WebBot.ReadStream(
WebBot.SendData(uri, strPostData, ref this.cookconReq)
);
}
catch (Exception exception)
{
throw exception;
}
return str2;
}
private void checkPassengerInfo()
{
for (int i = 0; i < (this.dgvInfo.Rows.Count - 1); i++)
{
DataGridViewRow dataGridViewRow = this.dgvInfo.Rows[i];
for (int j = 0; j < this.dgvInfo.Columns.Count; j++)
{
if (dataGridViewRow.Cells[j].Value == null)
{
dataGridViewRow.Cells[j].Value = "";
}
}
if (((dataGridViewRow.Cells[0].Value.ToString() == "") && (dataGridViewRow.Cells[1].Value.ToString() == "")) && (dataGridViewRow.Cells[2].Value.ToString() == ""))
{
this.dgvInfo.Rows.Remove(dataGridViewRow);
}
}
}
private string getOrderTicketsPostData(string orderPassCode, string trainGoDate,
string setType, string leftTicketStr)
{
string strPostData = "";
Regex regex1 = new Regex("org.apache.struts.taglib.html.TOKEN\" value=\"(.+)?\">");
string org_apache_struts_taglib_html_TOKEN = regex1.Match(this.strOrderPage).Groups[1].Value;
Regex regex3 = new Regex("textfield\".*\\s+value=\"(.+)?\"\\s");
string textfield = regex3.Match(this.strOrderPage).Groups[1].Value;
Regex regex4 = new Regex("orderRequest.seat_type_code\" value=\"(.*)?\"\\s");
string seat_type_code = regex4.Match(this.strOrderPage).Groups[1].Value;
Regex regex6 = new Regex("orderRequest.ticket_type_order_num\" value=\"(.*)?\"\\s");
string ticket_type_order_num = regex6.Match(this.strOrderPage).Groups[1].Value;
strPostData = "org.apache.struts.taglib.html.TOKEN="
+ org_apache_struts_taglib_html_TOKEN
+ "&leftTicketStr=" + leftTicketStr
+ "&textfield=" + HttpUtility.UrlEncode(textfield)
+ "&orderRequest.train_date=" + trainGoDate
+ "&orderRequest.train_no=" + this.strsTrainInfo[3]
+ "&orderRequest.station_train_code=" + this.strsTrainInfo[0]
+ "&orderRequest.from_station_telecode=" + this.strsTrainInfo[4]
+ "&orderRequest.to_station_telecode=" + this.strsTrainInfo[5]
+ "&orderRequest.seat_type_code=" + seat_type_code
+ "&orderRequest.ticket_type_order_num=" + ticket_type_order_num
+ "&orderRequest.bed_level_order_num=000000000000000000000000000000"
+ "&orderRequest.start_time=" + HttpUtility.UrlEncode(this.strsTrainInfo[2])
+ "&orderRequest.end_time=" + HttpUtility.UrlEncode(this.strsTrainInfo[6])
+ "&orderRequest.from_station_name=" + HttpUtility.UrlEncode(this.strsTrainInfo[7])
+ "&orderRequest.to_station_name=" + HttpUtility.UrlEncode(this.strsTrainInfo[8])
+ "&orderRequest.cancel_flag=1" + "&orderRequest.id_mode=Y";
checkPassengerInfo();
string strPassenger = "";
for (int i = 0; i < (this.dgvInfo.Rows.Count - 1); i++)
{
DataGridViewRow dataGridViewRow = this.dgvInfo.Rows[i];
string passengerName = dataGridViewRow.Cells[0].Value.ToString();
string cardNo = dataGridViewRow.Cells[1].Value.ToString();
string mobileno = dataGridViewRow.Cells[2].Value.ToString();
strPassenger += "&passengerTickets="
+ HttpUtility.UrlEncode(
string.Concat(new object[] {
setType,
",0",
",1,",
passengerName,
",1,",
cardNo,
",",
mobileno,
",N"
}
)
);
strPassenger += "&passenger_" + Convert.ToString(i + 1) + "_seat=" + setType;
strPassenger += "&passenger_" + Convert.ToString(i + 1) + "_ticket=1";
strPassenger += "&passenger_" + Convert.ToString(i + 1) + "_name=" + HttpUtility.UrlEncode(passengerName);
strPassenger += "&passenger_" + Convert.ToString(i + 1) + "_cardtype=1";
strPassenger += "&passenger_" + Convert.ToString(i + 1) + "_cardno=" + cardNo;
strPassenger += "&passenger_" + Convert.ToString(i + 1) + "_mobileno=" + mobileno;
}
strPostData += strPassenger;
strPostData = (strPostData + "&randCode=" + orderPassCode) + "&orderRequest.reserve_flag=A&tFlag=dc";
return strPostData;
}
private OrderWaiteTimeRet OrderWaiteTimePage()
{
string strRtn = "";
int waiteTime = 0;
int tryIntev = 500; //0.5s
Uri uri = new Uri(this.uriBase, "/otsweb/order/myOrderAction.do?method=queryOrderWaitTime&tourFlag=dc");
do
{
strRtn = WebBot.ReadStream(WebBot.SendData(uri, ref this.cookconReq));
OrderWaitTime orderWaitTime = TRConvert.ToOrderWaiteTime(strRtn);
if (orderWaitTime == null)
{
this.txtLog.AppendText("订票发生异常,重试中......\r\n");
continue;
}
waiteTime = orderWaitTime.waitTime;
if (waiteTime == 0 || waiteTime == -1)
{
this.txtLog.AppendText("订票成功!请尽快付款!\r\n");
return new OrderWaiteTimeRet(0, orderWaitTime.orderId);
}
if (waiteTime == -2)
{
this.txtLog.AppendText("出票失败," + orderWaitTime.msg + ",请重新订票!\r\n");
return new OrderWaiteTimeRet(-1, "");
}
if (waiteTime == -3)
{
this.txtLog.AppendText("订单已经被取消!\r\n");
return new OrderWaiteTimeRet(-1, "");
}
if (waiteTime == -4)
{
this.txtLog.AppendText("正在处理中....\r\n");
}
if (waiteTime > 0)
{
this.txtLog.AppendText("排队中......排队数【" + orderWaitTime.waitCount + "】 预计时间【" + orderWaitTime.waitTime + "】 不过这时间不怎么靠谱 ╮(╯▽╰)╭\r\n");
}
else
{
this.txtLog.AppendText("奇怪的状态码 [" + orderWaitTime.waitTime + "]....\r\n");
}
Thread.Sleep(tryIntev);
} while (!this.StopSearch);
return new OrderWaiteTimeRet(-10, "");
}
private string PayOrderPage(string orderId, string strPostData)
{
Uri uri = new Uri(this.uriBase, "/otsweb/order/confirmPassengerAction.do?method=payOrder&orderSequence_no=" + orderId);
string strRtn = WebBot.ReadStream(WebBot.SendData(uri, strPostData,ref this.cookconReq));
return strRtn;
}
private int Order()
{
string pageMessage = "";
string strRtn = "";
do
{
try
{
this.getOrderPassCode(new Random(DateTime.Now.Millisecond).NextDouble().ToString());
string orderPassCode = this.orderCracker.Read(new Bitmap(this.pbOrderPassCode.Image));
this.txtOrderPassCode.Text = orderPassCode;
string trainGoDate = this.dtpGoDate.Value.ToString("yyyy-MM-dd");
string setType = this.htSeatType[this.cbSeatType.SelectedItem.ToString()].ToString();
Regex regex2 = new Regex("leftTicketStr\".*\\s+value=\"(.+)?\" />");
string leftTicketStr = regex2.Match(this.strOrderPage).Groups[1].Value;
string strPostData = getOrderTicketsPostData(orderPassCode,
trainGoDate, setType, leftTicketStr);
Uri uri1 = new Uri(this.uriBase, "/otsweb/order/confirmPassengerAction.do?method=checkOrderInfo&rand=" + orderPassCode);
strRtn = WebBot.ReadStream(WebBot.SendData(uri1, strPostData, ref this.cookconReq));
CheckOrderInfo checkOrderInfo = new CheckOrderInfo(strRtn);
if (checkOrderInfo.checkHuimd == "N" || checkOrderInfo.errMsg != "Y")
{
this.txtLog.AppendText("订票失败," + checkOrderInfo.msg + checkOrderInfo.errMsg + "\r\n");
continue;
}
Uri uri2 = new Uri(this.uriBase,
"/otsweb/order/confirmPassengerAction.do?method=getQueueCount"
+ "&train_date=" + trainGoDate
+ "&train_no=" + this.strsTrainInfo[3]
+ "&station=" + this.strsTrainInfo[0]
+ "&seat=" + setType
+ "&from=" + this.strsTrainInfo[4]
+ "&to=" + this.strsTrainInfo[5]
+ "&ticket=" + leftTicketStr
);
strRtn = WebBot.ReadStream(WebBot.SendData(uri2, ref this.cookconReq));
Uri uri3 = new Uri(this.uriBase, "/otsweb/order/confirmPassengerAction.do?method=confirmSingleForQueue");
strRtn = WebBot.ReadStream(WebBot.SendData(uri3, strPostData, ref this.cookconReq));
OrderWaiteTimeRet OrderRet = OrderWaiteTimePage();
string orderId = OrderRet.OrderID;
int ret = OrderRet.RetValue;
if (ret <= -1)
{
return -1;
}
strRtn = PayOrderPage(orderId, strPostData);
pageMessage = this.GetPageMessage(strRtn);
if ((pageMessage != "") || (!strRtn.Contains("successTicketNum") && !pageMessage.Contains("您还有未处理的订单")))
{
this.txtLog.AppendText("\r\n" + this.GetPageMessage(strRtn) + "\r\n");
this.txtLog.AppendText("订票失败,正在重试……第" + ++nOrderTimes + "次\r\n");
this.strOrderPage = strRtn;
}
else
{
this.txtLog.AppendText("★★★★订票至少已经部分成功,正在弹出IE并登录★★★★\r\n");
this.PopIE();
}
if ((pageMessage == "") && (strRtn.Contains("successTicketNum") || pageMessage.Contains("您还有未处理的订单")))
{
return 0;
}
}
catch
{
return -2;
}
} while (!this.StopSearch);
return -10;
}
private void pbLoginPassCode_Click(object sender, EventArgs e)
{
try
{
this.getLoginPassCode(new Random(DateTime.Now.Millisecond).NextDouble().ToString());
}
catch (Exception exception)
{
MessageBox.Show(WebBot.strProcessError(exception), "出错了,请重试", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
private void playBeep()
{
Thread.CurrentThread.IsBackground = true;
while (this.IsPlayBeep)
{
TRSoundPlayer.PlaySound(Application.StartupPath + this.soundFilePath);
Thread.Sleep(10000);
}
}
private void PopIE()
{
string lpszUrlName = "https://dynamic.12306.cn/otsweb/";
foreach (Cookie cookie in GetAllCookies(this.cookconReq))
{
string str2;
if (cookie.Name == "JSESSIONID")
{
str2 = cookie.Value + ";Path=/otsweb;expires=Sun,22-Feb-2099 00:00:00 GMT";
}
else
{
str2 = cookie.Value + ";path=/;expires=Sun,22-Feb-2099 00:00:00 GMT";
}
InternetSetCookie(lpszUrlName, cookie.Name, str2);
}
Process.Start("IEXPLORE.EXE", lpszUrlName);
}
private int PreOrderTrain()
{
this.strOrderPage = "";
try
{
string strFromStation = this.txtFromStation.Text;
string strToStation = this.txtToStation.Text;
Uri uri = new Uri(this.uriBase, "/otsweb/order/querySingleAction.do?method=submutOrderRequest");
string strPostData = "station_train_code=" + this.strsTrainInfo[0]
+ "&train_date=" + this.dtpGoDate.Value.ToString("yyyy-MM-dd")
+ "&seattype_num=&from_station_telecode=" + this.strsTrainInfo[4]
+ "&to_station_telecode=" + this.strsTrainInfo[5]
+ "&include_student=00&from_station_telecode_name=" + HttpUtility.UrlEncode(strFromStation)
+ "&to_station_telecode_name=" + HttpUtility.UrlEncode(strToStation)
+ "&round_train_date=" + this.dtpGoDate.Value.ToString("yyyy-MM-dd")
+ "&round_start_time_str=00%3A00--24%3A00&single_round_type=1"
+ "&train_pass_type=QB&train_class_arr=QB%23D%23Z%23T%23K%23QT%23"
+ "&start_time_str=" + HttpUtility.UrlEncode(this.cbGoTime.Text)
+ "&lishi=" + HttpUtility.UrlEncode(this.strsTrainInfo[1])
+ "&train_start_time=" + HttpUtility.UrlEncode(this.strsTrainInfo[2])
+ "&trainno4=" + this.strsTrainInfo[3]
+ "&arrive_time=" + HttpUtility.UrlEncode(this.strsTrainInfo[6])
+ "&from_station_name=" + HttpUtility.UrlEncode(this.strsTrainInfo[7])
+ "&to_station_name=" + HttpUtility.UrlEncode(this.strsTrainInfo[8])
+ "&from_station_no=" + this.strsTrainInfo[9]
+ "&to_station_no=" + this.strsTrainInfo[10]
+ "&ypInfoDetail=" + this.strsTrainInfo[11]
+ "&mmStr=" + this.strsTrainInfo[12]
+ "&locationCode=" + this.strsTrainInfo[13];
HttpWebResponse respRtn = WebBot.SendData(uri, strPostData, ref this.cookconReq);
this.strOrderPage = WebBot.ReadStream(respRtn);
string strcookie = this.cookconReq.ToString();
}
catch (Exception exception)
{
this.txtLog.AppendText(exception.Message + "\r\n");
return -1;
}
return ((this.strOrderPage == "") ? -1 : 0);
}
private bool RepeatLogin()
{
if (this.bIsLogin)
{
return true;
}
int ret = 0;
this.gbLogin.Enabled = false;
do
{
ret = DoAutoLogin();
if (ret <= -3)
{
break;
}
else if (ret < 0)
{
Thread.Sleep(this.nLoginIntev);
}
} while (!this.StopSearch && !this.bIsLogin);
bool bRet = true;
if (this.StopSearch || !this.bIsLogin)
{
bRet = false;
this.gbLogin.Enabled = true;
}
return bRet;
}
private int RepeatSearchTrain()
{
while (!this.StopSearch)
{
try
{
this.txtLog.AppendText("第" + ++nSearchTimes + "次检索车次……");
int ret = this.SearchTrainCode();
if (ret < -1)
{// 登录时间太久被系统提出
return ret;
}
else if (ret < 0)
{// 预订车次查找失败,继续查找
this.txtLog.AppendText("找不到" + this.txtTrainCode.Text.ToUpper() + "次列车,或该车次没有票。如果车次填写错误,请关闭程序重新输入。\r\n");
Thread.Sleep(this.nSearchIntev);
}
if ((this.strsTrainInfo[0] != null) && (this.strsTrainInfo[0] != ""))
{// 预订车次查找成功
return 0;
}
}
catch (Exception exception2)
{
//发生异常休眠后继续
this.txtLog.AppendText(exception2.Message + "\r\n");
Thread.Sleep(this.nSearchIntev);
}
}
// 手动停止
return -10;
}
private int RepeatOrderTrain()
{
try
{
this.IsPlayBeep = true;
this.StopSearch = false;
int ret = 0;
do {
ret = RepeatSearchTrain();
if (ret <= -10)
{// 被系统踢出或者手动停止,直接退出循环
return ret;
}
else if (ret < 0)
{// 查找预订车次失败
continue;
}
this.txtLog.AppendText("检索到" + this.strsTrainInfo[0] + "次列车\r\n");
this.txtLog.AppendText("尝试进入车辆预订页面……");
if ((this.PreOrderTrain() != 0)
|| (!this.strOrderPage.Contains("org.apache.struts.taglib.html.TOKEN")))
{
this.txtLog.AppendText("进入车辆预订页面失败!\r\n");
Thread.Sleep(this.nSearchIntev);
continue;
}
if (this.strOrderPage.Contains("您还有未处理的订单"))
{
this.txtLog.AppendText("您还有未处理的订单......\r\n");
return 1;
}
this.txtLog.AppendText("进入车辆预订页面成功。\r\n");
Regex regex = new Regex("<td>(" + this.cbSeatType.SelectedItem.ToString() + @"\(\d*\.\d*元\)(.*)?)</td>");
this.txtLog.AppendText("准备预订:" + this.cbSeatType.SelectedItem.ToString() );
Match ticketMatch = regex.Match(this.strOrderPage);
string strTicketInfo = ticketMatch.Groups[1].Value;
string strHaveTicket = ticketMatch.Groups[2].Value;
if (strTicketInfo == "" || strHaveTicket == "无票")
{
this.txtLog.AppendText("-->没有" + this.cbSeatType.SelectedItem.ToString() + ",正在重新查询……\r\n");
Thread.Sleep(this.nSearchIntev);
continue;
}
this.txtLog.AppendText("-->票务信息:" + strTicketInfo + "\r\n");
ret = this.Order();
if (ret <= -10 || ret >= 0)
{// 手动停止或者订票成功,退出循环
return ret;
}
} while (!this.StopSearch);
return -10;
}
catch (Exception exception4)
{
this.txtLog.AppendText("订票发生异常: " + exception4.Message + "\r\n");
return -2;
}
}
private void resetForm()
{
switch (this.PgmAccess)
{
case 0:
this.gbLogin.Enabled = true;
this.gbSearch.Enabled = true;
this.gbOrder.Enabled = true;
this.pbLoginPassCode.Image = null;
this.pbOrderPassCode.Image = null;
this.txtLoginPassCode.Text = "";
this.txtOrderPassCode.Text = "";
this.pbLoginPassCode_Click(null, null);
this.btnReLoginAndSearch.Enabled = true;
break;
case 10:
this.gbSearch.Enabled = true;
this.gbOrder.Enabled = true;
this.btnReLoginAndSearch.Enabled = true;
break;
}
}
private int SearchTrainCode()
{
try
{
Uri uri = new Uri(this.uriBase, "/otsweb/order/querySingleAction.do?method=queryLeftTicket&orderRequest.train_date=" + this.dtpGoDate.Value.ToString("yyyy-MM-dd")
+ "&orderRequest.from_station_telecode=" + this.dicStation[this.txtFromStation.Text]
+ "&orderRequest.to_station_telecode=" + this.dicStation[this.txtToStation.Text]
+ "&orderRequest.train_no=" + this.strTrainNo
+ "&trainPassType=QB&trainClass=QB%23D%23Z%23T%23K%23QT%23&includeStudent=00&seatTypeAndNum=&orderRequest.start_time_str="
+ HttpUtility.UrlEncode(this.cbGoTime.Text));
string input = WebBot.ReadStream(WebBot.SendData(uri, ref this.cookconReq, true));
this.strsTrainInfo = new string[14];
if (input == "-10")
{
return -20;
}
string searchTainCode = this.txtTrainCode.Text.ToUpper();
Regex regex = new Regex(@"onclick=javascript:getSelected\('(.*?)'\)");
foreach (Match match in regex.Matches(input))
{
string tmpTrainCode = match.Groups[1].Value.Split(new char[] { '#' })[0];
if (tmpTrainCode == searchTainCode)
{
this.strsTrainInfo = match.Groups[1].Value.Split(new char[] { '#' });
return 0;
}
}
return -1;
}
catch (Exception exception)
{
this.txtLog.AppendText("SearchTrainCode Exception: " + exception.Message + "\r\n");
return -1;
}
}
private void txtLog_TextChanged(object sender, EventArgs e)
{
this.txtLog.ScrollToCaret();
}
private delegate string MethodDelegate();
private void SaveCfgButton_Click(object sender, EventArgs e)
{
RobotConfig cfg = new RobotConfig();
FrmMainConfig frmMainConfig = new FrmMainConfig();
frmMainConfig.frmMainSetting.UserName = this.txtUserName.Text;
frmMainConfig.frmMainSetting.UserPwd = this.txtPassword.Text;
frmMainConfig.frmMainSetting.LoginInterval = Convert.ToInt32(this.txtLoginIntev.Text);
frmMainConfig.frmMainSetting.FromStation = this.txtFromStation.Text;
frmMainConfig.frmMainSetting.ToStation = this.txtToStation.Text;
frmMainConfig.frmMainSetting.GoDate = this.dtpGoDate.Text;
frmMainConfig.frmMainSetting.GoTime = this.cbGoTime.Text;
frmMainConfig.frmMainSetting.TrainNo = this.txtTrainCode.Text;
frmMainConfig.frmMainSetting.SearchInterval = Convert.ToInt32(this.txtSearchIntev.Text);
frmMainConfig.frmMainSetting.SetType = this.cbSeatType.Text;
checkPassengerInfo();
int pasgerCount = this.dgvInfo.Rows.Count - 1;
frmMainConfig.pasgerList.PassengerList = new Passenger[pasgerCount];
for (int i = 0; i < pasgerCount; i++)
{
DataGridViewRow dataGridViewRow = this.dgvInfo.Rows[i];
string passengerName = dataGridViewRow.Cells[0].Value.ToString();
string cardNo = dataGridViewRow.Cells[1].Value.ToString();
string mobileno = dataGridViewRow.Cells[2].Value.ToString();
Passenger pasger = new Passenger();
pasger.PasgerName = passengerName;
pasger.CardNumber = cardNo;
pasger.MobilePhone = mobileno;
frmMainConfig.pasgerList.PassengerList[i] = pasger;
}
cfg.SaveConfig(frmMainConfig);
this.txtLog.AppendText("保存配置文件成功...\r\n");
}
private void TestButton_Click(object sender, EventArgs e)
{
TRTester Tester = new TRTester();
Tester.Run();
}
private void TestButton_Click_1(object sender, EventArgs e)
{
TRTester Tester = new TRTester();
Tester.Run();
this.getLoginPassCode(new Random(DateTime.Now.Millisecond).NextDouble().ToString());
this.txtLoginPassCode.Text = AspriseOCR.OCRBitmap(new Bitmap(this.pbLoginPassCode.Image));
}
private void pbLoginPassCode_Click_1(object sender, EventArgs e)
{
this.getLoginPassCode(new Random(DateTime.Now.Millisecond).NextDouble().ToString());
}
private void pbOrderPassCode_Click(object sender, EventArgs e)
{
this.getOrderPassCode(new Random(DateTime.Now.Millisecond).NextDouble().ToString());
}
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/FrmMain.cs | C# | gpl3 | 50,650 |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace TrainTicketsRobot
{
[Serializable]
class Passenger
{
public Passenger()
{
this.PasgerName = "";
this.CardNumber = "";
this.MobilePhone = "";
}
public string PasgerName;
public string CardNumber;
public string MobilePhone;
}
[Serializable]
class PasgerList
{
public PasgerList()
{
PassengerList = null;
}
public Passenger[] PassengerList;
}
[Serializable]
class FrmMainSetting
{
public FrmMainSetting()
{
this.UserName = "";
this.UserPwd = "";
this.LoginInterval = 0;
this.FromStation = "";
this.ToStation = "";
this.GoDate = "";
this.GoTime = "";
this.TrainNo = "";
this.SearchInterval = 0;
this.SetType = "";
}
public string UserName;
public string UserPwd;
public int LoginInterval;
public string FromStation;
public string ToStation;
public string GoDate;
public string GoTime;
public string TrainNo;
public int SearchInterval;
public string SetType;
}
class FrmMainConfig
{
public FrmMainConfig()
{
this.frmMainSetting = new FrmMainSetting();
this.pasgerList = new PasgerList();
}
public FrmMainSetting frmMainSetting;
public PasgerList pasgerList;
}
class RobotConfig
{
public FrmMainConfig LoadConfig()
{
try
{
if (!File.Exists(this.configPath) || !File.Exists(this.configPasgerPath))
{
return null;
}
string strJson = File.ReadAllText(this.configPath);
string strPasgerJson = File.ReadAllText(this.configPasgerPath);
if (strJson == null || strJson == ""
|| strPasgerJson == null || strPasgerJson == "")
{
return null;
}
FrmMainConfig frmMainConfig = new FrmMainConfig();
FrmMainSetting frmMainSetting = new FrmMainSetting();
PasgerList pasgerList = new PasgerList();
DataContractJsonSerializer dataConSer = new DataContractJsonSerializer(typeof(FrmMainSetting));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
{
frmMainSetting = dataConSer.ReadObject(ms) as FrmMainSetting;
}
DataContractJsonSerializer dataConSer2 = new DataContractJsonSerializer(typeof(PasgerList));
using (MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(strPasgerJson)))
{
pasgerList = dataConSer2.ReadObject(ms2) as PasgerList;
}
frmMainConfig.frmMainSetting = frmMainSetting;
frmMainConfig.pasgerList = pasgerList;
return frmMainConfig;
}
catch
{
return null;
}
}
public int SaveConfig(FrmMainConfig frmMainConfig)
{
try
{
if (!Directory.Exists(this.configDir))
{
Directory.CreateDirectory(this.configDir);
}
DataContractJsonSerializer dataConSer = new DataContractJsonSerializer(frmMainConfig.frmMainSetting.GetType());
string szJson = "";
using (MemoryStream stream = new MemoryStream())
{
dataConSer.WriteObject(stream, frmMainConfig.frmMainSetting);
szJson = Encoding.UTF8.GetString(stream.ToArray());
}
DataContractJsonSerializer dataConSer2 = new DataContractJsonSerializer(frmMainConfig.pasgerList.GetType());
string szJson2 = "";
using (MemoryStream stream2 = new MemoryStream())
{
dataConSer2.WriteObject(stream2, frmMainConfig.pasgerList);
szJson2 = Encoding.UTF8.GetString(stream2.ToArray());
}
File.WriteAllText(this.configPath, szJson);
File.WriteAllText(this.configPasgerPath, szJson2);
return 0;
}
catch
{
return -1;
}
}
private string configDir = "./config";
private string configPath = "./config/winformSet.table";
private string configPasgerPath = "./config/list.table";
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/RobotConfig.cs | C# | gpl3 | 5,124 |
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace TrainTicketsRobot
{
[Serializable]
class OrderWaitTime
{
public OrderWaitTime()
{
this.tourFlag = "";
this.waitTime = -999;
this.waitCount = -999;
this.orderId = "";
this.requestId = "";
this.count = -999;
this.msg = "";
}
public string tourFlag;
public int waitTime;
public int waitCount;
public string orderId;
public string requestId;
public int count;
public string msg;
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/OrderWaitTime.cs | C# | gpl3 | 672 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("TrainTicketsRobot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TrainTicketsRobot")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2fa8434f-769f-4566-b521-2585abb10615")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/Properties/AssemblyInfo.cs | C# | gpl3 | 1,366 |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace TrainTicketsRobot
{
class TRConvert
{
public static OrderWaitTime ToOrderWaiteTime(string strJson)
{
try
{
if (strJson == null || strJson == "")
{
return null;
}
if (!strJson.Contains("\"tourFlag\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"tourFlag\":\"\"}";
}
if (!strJson.Contains("\"waitCount\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"waitCount\":-999}";
}
if (!strJson.Contains("\"orderId\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"orderId\":\"\"}";
}
if (!strJson.Contains("\"requestId\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"requestId\":\"\"}";
}
if (!strJson.Contains("\"count\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"count\":-999}";
}
if (!strJson.Contains("\"msg\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"msg\":\"\"}";
}
DataContractJsonSerializer dataConSer = new DataContractJsonSerializer(typeof(OrderWaitTime));
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJson)))
{
OrderWaitTime orderWaitTime = dataConSer.ReadObject(ms) as OrderWaitTime;
return orderWaitTime;
}
}
catch
{
return null;
}
}
public static TrainInfo[] ToTrainInfoArray(string strJson)
{
try
{
if (strJson == null || strJson == "")
{
return null;
}
DataContractJsonSerializer dataConSer = new DataContractJsonSerializer(typeof(TrainInfo[]));
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJson)))
{
TrainInfo[] trainInfoArray = dataConSer.ReadObject(ms) as TrainInfo[];
return trainInfoArray;
}
}
catch
{
return null;
}
}
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/TRConvert.cs | C# | gpl3 | 3,101 |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Runtime.InteropServices;
namespace TrainTicketsRobot
{
class AspriseOCR
{
[DllImport("AspriseOCR.dll", EntryPoint = "OCR", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr OCR(string file, int type);
[DllImport("AspriseOCR.dll", EntryPoint = "OCRpart", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr OCRpart(string file, int type, int startX, int startY, int width, int height);
[DllImport("AspriseOCR.dll", EntryPoint = "OCRBarCodes", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr OCRBarCodes(string file, int type);
[DllImport("AspriseOCR.dll", EntryPoint = "OCRpartBarCodes", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr OCRpartBarCodes(string file, int type, int startX, int startY, int width, int height);
public static string OCRBitmap(Bitmap img)
{
string filename = System.Windows.Forms.Application.StartupPath + VerificationCodeBaseDir + "4.bmp";
img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
int DgGrayValue = GetDgGrayValue(ref img);
ClearNoise(DgGrayValue, 1,ref img);
ClearNoise(DgGrayValue, ref img);
filename = System.Windows.Forms.Application.StartupPath + VerificationCodeBaseDir + "5.bmp";
img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
string VerifiCode = Marshal.PtrToStringAnsi(OCR(filename, -1));
return VerifiCode;
}
///
/// 得到灰度图像前景背景的临界值 最大类间方差法,yuanbao,2007.08
///
/// 前景背景的临界值
public static int GetDgGrayValue(ref Bitmap bmpobj)
{
int[] pixelNum = new int[256]; //图象直方图,共256个点
int n, n1, n2;
int total; //total为总和,累计值
double m1, m2, sum, csum, fmax, sb; //sb为类间方差,fmax存储最大方差值
int k, t, q;
int threshValue = 1; // 阈值
//生成直方图
for (int i = 0; i < bmpobj.Width; i++)
{
for (int j = 0; j < bmpobj.Height; j++)
{
//返回各个点的颜色,以RGB表示
pixelNum[bmpobj.GetPixel(i, j).R]++; //相应的直方图加1
}
}
//直方图平滑化
for (k = 0; k <= 255; k++)
{
total = 0;
for (t = -2; t <= 2; t++) //与附近2个灰度做平滑化,t值应取较小的值
{
q = k + t;
if (q < 0) //越界处理
q = 0;
if (q > 255)
q = 255;
total = total + pixelNum[q]; //total为总和,累计值
}
pixelNum[k] = (int)((float)total / 5.0 + 0.5); //平滑化,左边2个+中间1个+右边2个灰度,共5个,所以总和除以5,后面加0.5是用修正值
}
//求阈值
sum = csum = 0.0;
n = 0;
//计算总的图象的点数和质量矩,为后面的计算做准备
for (k = 0; k <= 255; k++)
{
sum += (double)k * (double)pixelNum[k]; //x*f(x)质量矩,也就是每个灰度的值乘以其点数(归一化后为概率),sum为其总和
n += pixelNum[k]; //n为图象总的点数,归一化后就是累积概率
}
fmax = -1.0; //类间方差sb不可能为负,所以fmax初始值为-1不影响计算的进行
n1 = 0;
for (k = 0; k < 256; k++) //对每个灰度(从0到255)计算一次分割后的类间方差sb
{
n1 += pixelNum[k]; //n1为在当前阈值遍前景图象的点数
if (n1 == 0) { continue; } //没有分出前景后景
n2 = n - n1; //n2为背景图象的点数
if (n2 == 0) { break; } //n2为0表示全部都是后景图象,与n1=0情况类似,之后的遍历不可能使前景点数增加,所以此时可以退出循环
csum += (double)k * pixelNum[k]; //前景的“灰度的值*其点数”的总和
m1 = csum / n1; //m1为前景的平均灰度
m2 = (sum - csum) / n2; //m2为背景的平均灰度
sb = (double)n1 * (double)n2 * (m1 - m2) * (m1 - m2); //sb为类间方差
if (sb > fmax) //如果算出的类间方差大于前一次算出的类间方差
{
fmax = sb; //fmax始终为最大类间方差(otsu)
threshValue = k; //取最大类间方差时对应的灰度的k就是最佳阈值
}
}
return threshValue;
}
///
/// 去掉杂点(适合杂点/杂线粗为1)
///
/// 背前景灰色界限
///
public static void ClearNoise(int dgGrayValue, int MaxNearPoints, ref Bitmap bmpobj)
{
Color piexl;
int nearDots = 0;
//逐点判断
for (int i = 0; i < bmpobj.Width; i++)
for (int j = 0; j < bmpobj.Height; j++)
{
piexl = bmpobj.GetPixel(i, j);
if (piexl.R < dgGrayValue)
{
nearDots = 0;
//判断周围8个点是否全为空
if (i == 0 || i == bmpobj.Width - 1 || j == 0 || j == bmpobj.Height - 1) //边框全去掉
{
bmpobj.SetPixel(i, j, Color.FromArgb(255, 255, 255));
}
else
{
if (bmpobj.GetPixel(i - 1, j - 1).R < dgGrayValue) nearDots++;
if (bmpobj.GetPixel(i, j - 1).R < dgGrayValue) nearDots++;
if (bmpobj.GetPixel(i + 1, j - 1).R < dgGrayValue) nearDots++;
if (bmpobj.GetPixel(i - 1, j).R < dgGrayValue) nearDots++;
if (bmpobj.GetPixel(i + 1, j).R < dgGrayValue) nearDots++;
if (bmpobj.GetPixel(i - 1, j + 1).R < dgGrayValue) nearDots++;
if (bmpobj.GetPixel(i, j + 1).R < dgGrayValue) nearDots++;
if (bmpobj.GetPixel(i + 1, j + 1).R < dgGrayValue) nearDots++;
}
if (nearDots < MaxNearPoints)
bmpobj.SetPixel(i, j, Color.FromArgb(255, 255, 255)); //去掉单点 && 粗细小3邻边点
}
else //背景
bmpobj.SetPixel(i, j, Color.FromArgb(255, 255, 255));
}
}
///
/// 3×3中值滤波除杂,yuanbao,2007.10
///
///
public static void ClearNoise(int dgGrayValue, ref Bitmap bmpobj)
{
int x, y;
byte[] p = new byte[9]; //最小处理窗口3*3
byte s;
int i, j;
//--!!!!!!!!!!!!!!下面开始窗口为3×3中值滤波!!!!!!!!!!!!!!!!
for (y = 1; y < bmpobj.Height - 1; y++) //--第一行和最后一行无法取窗口
{
for (x = 1; x < bmpobj.Width - 1; x++)
{
//取9个点的值
p[0] = bmpobj.GetPixel(x - 1, y - 1).R;
p[1] = bmpobj.GetPixel(x, y - 1).R;
p[2] = bmpobj.GetPixel(x + 1, y - 1).R;
p[3] = bmpobj.GetPixel(x - 1, y).R;
p[4] = bmpobj.GetPixel(x, y).R;
p[5] = bmpobj.GetPixel(x + 1, y).R;
p[6] = bmpobj.GetPixel(x - 1, y + 1).R;
p[7] = bmpobj.GetPixel(x, y + 1).R;
p[8] = bmpobj.GetPixel(x + 1, y + 1).R;
//计算中值
for (j = 0; j < 5; j++)
{
for (i = j + 1; i < 9; i++)
{
if (p[j] > p[i])
{
s = p[j];
p[j] = p[i];
p[i] = s;
}
}
}
// if (bmpobj.GetPixel(x, y).R < dgGrayValue)
bmpobj.SetPixel(x, y, Color.FromArgb(p[4], p[4], p[4])); //给有效值付中值
}
}
}
public static string VerificationCodeBaseDir = "/verificationcode/";
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/AspriseOCR.cs | C# | gpl3 | 9,207 |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace TrainTicketsRobot
{
[Serializable]
class CheckOrderInfo
{
public CheckOrderInfo(string strJson)
{
if (!strJson.Contains("\"checkHuimd\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"checkHuimd\":\"\"}";
}
if (!strJson.Contains("\"check608\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"check608\":\"\"}";
}
if (!strJson.Contains("\"msg\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"msg\":\"\"}";
}
if (!strJson.Contains("\"errMsg\":"))
{
strJson = strJson.Remove(strJson.Length - 1);
strJson = strJson + ",\"errMsg\":\"\"}";
}
DataContractJsonSerializer dataConSer = new DataContractJsonSerializer(typeof(CheckOrderInfo));
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJson)))
{
CheckOrderInfo checkOrderInfo = dataConSer.ReadObject(ms) as CheckOrderInfo;
this.checkHuimd = checkOrderInfo.checkHuimd;
this.check608 = checkOrderInfo.check608;
this.msg = checkOrderInfo.msg;
this.errMsg = checkOrderInfo.errMsg;
}
}
public string checkHuimd;
public string check608;
public string msg;
public string errMsg;
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/CheckOrderInfo.cs | C# | gpl3 | 1,845 |
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
namespace TrainTicketsRobot
{
public class Cracker
{
List<CharInfo> words_ = new List<CharInfo>();
public Cracker()
{
var bytes = new byte[] {
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xc5, 0x58, 0xd9, 0x92, 0x13, 0x31,
0x0c, 0x94, 0x9e, 0x93, 0x0c, 0x61, 0x97, 0x2f, 0xe1, 0x58, 0xe0, 0x91, 0x9b, 0x82, 0x62, 0x0b,
0x58, 0xee, 0xff, 0xff, 0x10, 0xd8, 0xcc, 0xc8, 0xea, 0x96, 0x6c, 0x8f, 0x13, 0x48, 0xe1, 0xaa,
0x4d, 0x46, 0x96, 0x6d, 0xb5, 0x8e, 0x96, 0x67, 0x73, 0x7f, 0x3b, 0x09, 0x0e, 0x25, 0x41, 0x49,
0xa3, 0xae, 0xd7, 0x5b, 0xa9, 0xa8, 0xd5, 0xb4, 0x76, 0x02, 0x6a, 0x5c, 0x52, 0x94, 0x54, 0xed,
0x18, 0x5a, 0x7f, 0x18, 0x00, 0x00, 0x84, 0x07, 0x1b, 0x80, 0x4a, 0x9a, 0x08, 0x35, 0xb8, 0x81,
0x50, 0xe7, 0xad, 0xbe, 0xc4, 0x8e, 0xb1, 0x4f, 0x2d, 0x5f, 0xba, 0x80, 0xbb, 0xfd, 0x9a, 0xad,
0x19, 0x36, 0xe5, 0xad, 0x87, 0xf1, 0x10, 0xc0, 0x8d, 0xc6, 0x50, 0x40, 0x52, 0xf8, 0xb3, 0x98,
0x2c, 0xd6, 0xec, 0x59, 0xe7, 0x0d, 0x3e, 0x0f, 0x93, 0x3e, 0x1d, 0x02, 0x7a, 0x18, 0x8f, 0xb6,
0xc7, 0x46, 0x4e, 0x01, 0xa3, 0x96, 0xdc, 0x3a, 0x20, 0x77, 0xbf, 0x2c, 0x24, 0xe4, 0x80, 0xa9,
0x20, 0x14, 0xe5, 0x2d, 0xb5, 0x68, 0xc9, 0x55, 0x89, 0x23, 0x96, 0x82, 0xaa, 0xba, 0x58, 0xa6,
0x03, 0x38, 0x71, 0x4b, 0x29, 0xd2, 0x47, 0x80, 0xe3, 0x84, 0x91, 0xf4, 0x78, 0x43, 0x64, 0x41,
0x7b, 0x73, 0x99, 0x80, 0x42, 0x48, 0x00, 0xde, 0x00, 0x12, 0x88, 0x80, 0xdb, 0x51, 0x4a, 0x49,
0x84, 0x43, 0xf6, 0x51, 0x90, 0x27, 0x21, 0xc9, 0xf8, 0xac, 0x00, 0x4d, 0xcd, 0x46, 0x09, 0x9d,
0x15, 0x78, 0xe0, 0x00, 0x1e, 0x44, 0x2a, 0x51, 0x8c, 0xbc, 0xd3, 0xa3, 0x68, 0x8a, 0xd5, 0x3a,
0x20, 0x79, 0xba, 0x4d, 0x71, 0x4c, 0x0b, 0x91, 0x98, 0x90, 0x7b, 0x2a, 0x42, 0xc5, 0x78, 0x7a,
0xfc, 0xd5, 0x1b, 0x4b, 0x09, 0xa7, 0x27, 0x99, 0x38, 0x05, 0x01, 0xc2, 0x80, 0x39, 0x9c, 0x67,
0xbb, 0x4e, 0x7f, 0x6c, 0x33, 0xdd, 0xed, 0x87, 0x55, 0xda, 0x5d, 0xb5, 0x56, 0x33, 0xc6, 0xf9,
0xea, 0x60, 0x64, 0xcf, 0xa7, 0x41, 0xe0, 0x5c, 0x1c, 0xc4, 0xb2, 0x25, 0xa3, 0x89, 0x88, 0x8d,
0x16, 0x00, 0xb5, 0xed, 0xa5, 0x22, 0x9d, 0x52, 0x41, 0x53, 0x8d, 0x92, 0x7f, 0x31, 0x51, 0x3f,
0xa8, 0x00, 0x85, 0x8a, 0x71, 0x10, 0x92, 0x78, 0xc4, 0x59, 0x08, 0x39, 0x69, 0xa9, 0x38, 0x41,
0x48, 0xf7, 0x40, 0x5a, 0x03, 0xd5, 0x3a, 0xf5, 0xe5, 0x9d, 0x33, 0x66, 0xc3, 0xd7, 0x1f, 0xef,
0x94, 0xa0, 0x53, 0xea, 0xf4, 0x15, 0xb2, 0x1c, 0x40, 0x2d, 0xcf, 0xaf, 0xce, 0xe9, 0xd4, 0x7a,
0x89, 0x09, 0xe6, 0xdd, 0xdb, 0x0e, 0xb8, 0x58, 0xa7, 0x60, 0x37, 0xfd, 0xf2, 0xfa, 0x2c, 0x4e,
0x51, 0x87, 0x0d, 0xfc, 0x16, 0x72, 0x2a, 0x5f, 0xc0, 0x80, 0xf0, 0x54, 0xa7, 0xde, 0xfc, 0x15,
0x8b, 0x9a, 0x36, 0x3a, 0x2c, 0x62, 0xfc, 0xd4, 0x8c, 0x31, 0xb7, 0xea, 0xd7, 0x26, 0xc4, 0xaf,
0x75, 0xea, 0xdb, 0x8b, 0xff, 0x9b, 0x9b, 0x50, 0x7e, 0xfe, 0x15, 0xab, 0x17, 0x2f, 0x96, 0x96,
0xbd, 0xaa, 0x87, 0xdd, 0x77, 0xa3, 0x77, 0xd3, 0x85, 0xf0, 0xe0, 0x58, 0xd5, 0xf6, 0x8c, 0xcd,
0xc4, 0x63, 0x52, 0x12, 0x48, 0x46, 0x0f, 0x93, 0x5a, 0xe3, 0xea, 0x24, 0x67, 0x73, 0x63, 0xa0,
0xdf, 0xdf, 0x3d, 0x67, 0xf6, 0xa9, 0xfc, 0xed, 0x08, 0xe3, 0x82, 0x57, 0x08, 0x35, 0x47, 0x68,
0x9c, 0x01, 0x40, 0x87, 0x8b, 0xbd, 0x0c, 0xb3, 0xf4, 0xe1, 0x72, 0xd7, 0x54, 0x62, 0xfd, 0x40,
0xed, 0x99, 0xa6, 0x7e, 0x2b, 0xe4, 0xb4, 0xc4, 0x62, 0x0d, 0x79, 0xae, 0x1b, 0xd7, 0xf4, 0x09,
0xb7, 0xe1, 0x7c, 0x44, 0x09, 0x9a, 0xda, 0xff, 0x52, 0x6a, 0x3c, 0xe1, 0xc8, 0xd7, 0xbd, 0xbb,
0xbe, 0x37, 0xfc, 0xd6, 0xd5, 0x4e, 0x3c, 0x40, 0x2a, 0x4b, 0x39, 0x1a, 0xbd, 0x2a, 0xcd, 0xc1,
0x18, 0x59, 0x40, 0x62, 0x78, 0xec, 0x63, 0x19, 0x72, 0xf0, 0xcf, 0xf8, 0x38, 0xfa, 0x42, 0x3a,
0xc8, 0x02, 0xec, 0x5b, 0xeb, 0x8d, 0xae, 0xf1, 0x45, 0xdd, 0x32, 0x98, 0x35, 0x3c, 0x9f, 0xa6,
0x3d, 0xce, 0x13, 0xce, 0x94, 0x38, 0x87, 0x00, 0x8d, 0x85, 0xc4, 0x70, 0x17, 0x26, 0x0e, 0xa6,
0x1e, 0x16, 0xcb, 0xbf, 0x52, 0xdf, 0x29, 0x63, 0xc4, 0xf6, 0x8c, 0x35, 0xba, 0xf2, 0xf9, 0x1f,
0xbf, 0x73, 0x1f, 0x91, 0x1b, 0x9e, 0x24, 0x5e, 0x63, 0x22, 0x82, 0x23, 0x05, 0x19, 0xb9, 0x71,
0x73, 0xdc, 0xcf, 0x05, 0x88, 0x94, 0x71, 0xdb, 0xdd, 0x48, 0x10, 0xd5, 0x55, 0xb3, 0x52, 0xc3,
0x1b, 0x01, 0x94, 0x13, 0x74, 0x94, 0x3a, 0x80, 0x2f, 0x39, 0xe2, 0x75, 0x0e, 0xf2, 0xc6, 0x18,
0xdc, 0x46, 0xfc, 0xf3, 0xea, 0x14, 0x80, 0xc1, 0xce, 0x24, 0xee, 0x72, 0xed, 0x94, 0xaf, 0xfb,
0xa9, 0xaa, 0x4a, 0xe0, 0xd4, 0x22, 0xc6, 0xf0, 0x57, 0x1d, 0x8e, 0xd2, 0x90, 0xc6, 0x0c, 0xd3,
0x9a, 0x53, 0xfb, 0xd6, 0xb7, 0xdd, 0x14, 0xd4, 0xbd, 0x41, 0xa7, 0x80, 0x7b, 0x23, 0xfe, 0x34,
0x56, 0x0d, 0x96, 0x46, 0x02, 0xfe, 0xfd, 0xb2, 0x00, 0x5f, 0x01, 0x9c, 0xa0, 0x32, 0x39, 0xd7,
0x90, 0xc2, 0x6c, 0xc7, 0x4e, 0x68, 0x88, 0x7d, 0x9f, 0x9b, 0xcf, 0xa7, 0xbe, 0xa0, 0xfc, 0x18,
0x7d, 0x07, 0x5b, 0xa9, 0xbe, 0x56, 0x1f, 0x67, 0x1a, 0x4a, 0x91, 0x9c, 0x04, 0x38, 0x53, 0x6b,
0x70, 0x68, 0x8f, 0xea, 0xf4, 0x34, 0x87, 0x7f, 0x6e, 0x82, 0xc3, 0xc1, 0xab, 0x40, 0xc4, 0x50,
0x13, 0x0e, 0x33, 0x5d, 0x67, 0x7d, 0x01, 0x1f, 0xdb, 0xc0, 0x7f, 0xed, 0x87, 0x7f, 0xbc, 0x0f,
0x75, 0xe0, 0xa5, 0xba, 0xc0, 0x84, 0x3d, 0x24, 0x04, 0xe0, 0xf1, 0x16, 0x41, 0x3b, 0x74, 0xd2,
0x52, 0xc5, 0xf8, 0x7c, 0x12, 0xfb, 0xe4, 0x37, 0x5b, 0xfb, 0x57, 0x11, 0xa1, 0x18, 0x00, 0x00,
};
using (var stream = new MemoryStream(bytes))
using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new BinaryReader(gzip))
{
while (true)
{
char ch = reader.ReadChar();
if (ch == '\0')
break;
int width = reader.ReadByte();
int height = reader.ReadByte();
bool[,] map = new bool[width, height];
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
map[i, j] = reader.ReadBoolean();
words_.Add(new CharInfo(ch, map));
}
}
}
public string Read(Bitmap bmp)
{
var result = string.Empty;
var width = bmp.Width;
var height = bmp.Height;
var table = ToTable(bmp);
var next = SearchNext(table, -1);
while (next < width - 7)
{
var matched = Match(table, next);
if (matched.Rate > 0.6)
{
result += matched.Char;
next = matched.X + 10;
}
else
{
next += 1;
}
}
return result;
}
private bool[,] ToTable(Bitmap bmp)
{
var table = new bool[bmp.Width, bmp.Height];
for (int i = 0; i < bmp.Width; i++)
for (int j = 0; j < bmp.Height; j++)
{
var color = bmp.GetPixel(i, j);
table[i, j] = (color.R + color.G + color.B < 500);
}
return table;
}
private int SearchNext(bool[,] table, int start)
{
var width = table.GetLength(0);
var height = table.GetLength(1);
for (start++; start < width; start++)
for (int j = 0; j < height; j++)
if (table[start, j])
return start;
return start;
}
private double FixedMatch(bool[,] source, bool[,] target, int x0, int y0)
{
double total = 0;
double count = 0;
int targetWidth = target.GetLength(0);
int targetHeight = target.GetLength(1);
int sourceWidth = source.GetLength(0);
int sourceHeight = source.GetLength(1);
int x, y;
for (int i = 0; i < targetWidth; i++)
{
x = i + x0;
if (x < 0 || x >= sourceWidth)
continue;
for (int j = 0; j < targetHeight; j++)
{
y = j + y0;
if (y < 0 || y >= sourceHeight)
continue;
if (target[i, j])
{
total++;
if (source[x, y])
count++;
else
count--;
}
else if (source[x, y])
count -= 0.55;
}
}
return count / total;
}
private MatchedChar ScopeMatch(bool[,] source, bool[,] target, int start)
{
int targetWidth = target.GetLength(0);
int targetHeight = target.GetLength(1);
int sourceWidth = source.GetLength(0);
int sourceHeight = source.GetLength(1);
double max = 0;
var matched = new MatchedChar();
for (int i = -2; i < 6; i++)
for (int j = -3; j < sourceHeight - targetHeight + 5; j++)
{
double rate = FixedMatch(source, target, i + start, j);
if (rate > max)
{
max = rate;
matched.X = i + start;
matched.Y = j;
matched.Rate = rate;
}
}
return matched;
}
private MatchedChar Match(bool[,] source, int start)
{
MatchedChar best = null;
foreach (var info in words_)
{
var matched = ScopeMatch(source, info.Table, start);
matched.Char = info.Char;
if (best == null || best.Rate < matched.Rate)
best = matched;
}
return best;
}
private class CharInfo
{
public char Char { get; private set; }
public bool[,] Table { get; private set; }
public CharInfo(char ch, bool[,] table)
{
Char = ch;
Table = table;
}
}
private class MatchedChar
{
public int X { get; set; }
public int Y { get; set; }
public char Char { get; set; }
public double Rate { get; set; }
}
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/Cracker.cs | C# | gpl3 | 11,537 |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace TrainTicketsRobot
{
[Serializable]
class LoginRand
{
public LoginRand(string strJson)
{
DataContractJsonSerializer dataConSer = new DataContractJsonSerializer(typeof(LoginRand));
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJson)))
{
LoginRand objloginRand = dataConSer.ReadObject(ms) as LoginRand;
this.loginRand = objloginRand.loginRand;
this.randError = objloginRand.randError;
}
}
public string loginRand;
public string randError;
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/LoginRand.cs | C# | gpl3 | 879 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TrainTicketsRobot
{
class TRTester
{
public void Run()
{
this.TestOrderWaitTime();
this.TestTrainInfo();
}
private void TestOrderWaitTime()
{
string strJson1 = "{\"tourFlag\":\"dc\",\"waitTime\":-2,\"waitCount\":0,\"requestId\":5692935325319965458,\"count\":0,\"orderId\":\"E3459\"}";
OrderWaitTime orderWaitTime1 =TRConvert.ToOrderWaiteTime(strJson1);
string strJson2 = "{\"tourFlag\":\"dc\",\"waitTime\":-2,\"waitCount\":0,\"requestId\":5692935325319965458,\"msg\":\"没有足够的票!\",\"count\":0}";
OrderWaitTime orderWaitTime2 = TRConvert.ToOrderWaiteTime(strJson2);
string strJson3 = "";
OrderWaitTime orderWaitTime3 = TRConvert.ToOrderWaiteTime(strJson3);
}
private void TestTrainInfo()
{
string strJson = "[{\"end_station_name\":\"重庆\",\"end_time\":\"15:04\",\"id\":\"650000L94201\",\"start_station_name\":\"深圳\",\"start_time\":\"03:10\",\"value\":\"L942/L943\"},{\"end_station_name\":\"广州\",\"end_time\":\"07:57\",\"id\":\"65000D701204\",\"start_station_name\":\"深圳\",\"start_time\":\"06:20\",\"value\":\"D7012\"},{\"end_station_name\":\"广州东\",\"end_time\":\"07:59\",\"id\":\"65000D705402\",\"start_station_name\":\"深圳\",\"start_time\":\"06:40\",\"value\":\"D7054\"},{\"end_station_name\":\"广州东\",\"end_time\":\"08:12\",\"id\":\"65000D713601\",\"start_station_name\":\"深圳\",\"start_time\":\"06:53\",\"value\":\"D7136\"},{\"end_station_name\":\"武汉\",\"end_time\":\"11:52\",\"id\":\"6i000G100201\",\"start_station_name\":\"深圳北\",\"start_time\":\"07:00\",\"value\":\"G1002\"},{\"end_station_name\":\"广州\",\"end_time\":\"08:50\",\"id\":\"65000D712630\",\"start_station_name\":\"深圳\",\"start_time\":\"07:10\",\"value\":\"D7126\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"10:39\",\"id\":\"6i000G601202\",\"start_station_name\":\"深圳北\",\"start_time\":\"07:12\",\"value\":\"G6012\"},{\"end_station_name\":\"广州东\",\"end_time\":\"08:39\",\"id\":\"65000D711402\",\"start_station_name\":\"深圳\",\"start_time\":\"07:20\",\"value\":\"D7114\"},{\"end_station_name\":\"广州东\",\"end_time\":\"08:49\",\"id\":\"65000D715802\",\"start_station_name\":\"深圳\",\"start_time\":\"07:30\",\"value\":\"D7158\"},{\"end_station_name\":\"广州南\",\"end_time\":\"08:10\",\"id\":\"6i000G620203\",\"start_station_name\":\"深圳北\",\"start_time\":\"07:34\",\"value\":\"G6202\"},{\"end_station_name\":\"广州\",\"end_time\":\"09:20\",\"id\":\"65000D700202\",\"start_station_name\":\"深圳\",\"start_time\":\"07:46\",\"value\":\"D7002\"},{\"end_station_name\":\"北京西\",\"end_time\":\"18:21\",\"id\":\"6i00000G7200\",\"start_station_name\":\"深圳北\",\"start_time\":\"07:56\",\"value\":\"G72\"},{\"end_station_name\":\"广州东\",\"end_time\":\"09:20\",\"id\":\"65000D702202\",\"start_station_name\":\"深圳\",\"start_time\":\"08:01\",\"value\":\"D7022\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"11:30\",\"id\":\"6i000G601405\",\"start_station_name\":\"深圳北\",\"start_time\":\"08:12\",\"value\":\"G6014\"},{\"end_station_name\":\"广州东\",\"end_time\":\"09:41\",\"id\":\"65000D704401\",\"start_station_name\":\"深圳\",\"start_time\":\"08:22\",\"value\":\"D7044\"},{\"end_station_name\":\"重庆北\",\"end_time\":\"19:10\",\"id\":\"690000K83600\",\"start_station_name\":\"深圳西\",\"start_time\":\"08:26\",\"value\":\"K836/K837\"},{\"end_station_name\":\"武汉\",\"end_time\":\"13:22\",\"id\":\"6i000G100401\",\"start_station_name\":\"深圳北\",\"start_time\":\"08:30\",\"value\":\"G1004\"},{\"end_station_name\":\"广州\",\"end_time\":\"10:03\",\"id\":\"65000D706602\",\"start_station_name\":\"深圳\",\"start_time\":\"08:31\",\"value\":\"D7066\"},{\"end_station_name\":\"广州东\",\"end_time\":\"09:58\",\"id\":\"65000D707603\",\"start_station_name\":\"深圳\",\"start_time\":\"08:39\",\"value\":\"D7076\"},{\"end_station_name\":\"广州东\",\"end_time\":\"10:06\",\"id\":\"65000D708602\",\"start_station_name\":\"深圳\",\"start_time\":\"08:47\",\"value\":\"D7086\"},{\"end_station_name\":\"郑州东\",\"end_time\":\"15:57\",\"id\":\"6i00000G7401\",\"start_station_name\":\"深圳北\",\"start_time\":\"08:50\",\"value\":\"G74\"},{\"end_station_name\":\"广州东\",\"end_time\":\"10:14\",\"id\":\"65000D709602\",\"start_station_name\":\"深圳\",\"start_time\":\"08:55\",\"value\":\"D7096\"},{\"end_station_name\":\"广州\",\"end_time\":\"10:36\",\"id\":\"65000D703403\",\"start_station_name\":\"深圳\",\"start_time\":\"09:04\",\"value\":\"D7034\"},{\"end_station_name\":\"广州东\",\"end_time\":\"10:40\",\"id\":\"65000D717040\",\"start_station_name\":\"深圳\",\"start_time\":\"09:21\",\"value\":\"D7170\"},{\"end_station_name\":\"武汉\",\"end_time\":\"14:22\",\"id\":\"6i000G100601\",\"start_station_name\":\"深圳北\",\"start_time\":\"09:22\",\"value\":\"G1006\"},{\"end_station_name\":\"韶关东\",\"end_time\":\"13:48\",\"id\":\"65000T837205\",\"start_station_name\":\"深圳\",\"start_time\":\"09:28\",\"value\":\"T8372\"},{\"end_station_name\":\"广州\",\"end_time\":\"11:10\",\"id\":\"65000D710600\",\"start_station_name\":\"深圳\",\"start_time\":\"09:31\",\"value\":\"D7106\"},{\"end_station_name\":\"广州南\",\"end_time\":\"10:21\",\"id\":\"6i000G620607\",\"start_station_name\":\"深圳北\",\"start_time\":\"09:38\",\"value\":\"G6206\"},{\"end_station_name\":\"广州东\",\"end_time\":\"10:58\",\"id\":\"65000D718005\",\"start_station_name\":\"深圳\",\"start_time\":\"09:39\",\"value\":\"D7180\"},{\"end_station_name\":\"广州东\",\"end_time\":\"11:06\",\"id\":\"65000D705604\",\"start_station_name\":\"深圳\",\"start_time\":\"09:47\",\"value\":\"D7056\"},{\"end_station_name\":\"广州东\",\"end_time\":\"11:14\",\"id\":\"65000D713804\",\"start_station_name\":\"深圳\",\"start_time\":\"09:55\",\"value\":\"D7138\"},{\"end_station_name\":\"西安北\",\"end_time\":\"19:42\",\"id\":\"6i0000G82201\",\"start_station_name\":\"深圳北\",\"start_time\":\"10:00\",\"value\":\"G822/G823\"},{\"end_station_name\":\"广州\",\"end_time\":\"11:53\",\"id\":\"65000D701404\",\"start_station_name\":\"深圳\",\"start_time\":\"10:12\",\"value\":\"D7014\"},{\"end_station_name\":\"成都\",\"end_time\":\"23:42\",\"id\":\"690000K58604\",\"start_station_name\":\"深圳西\",\"start_time\":\"10:17\",\"value\":\"K586/K587\"},{\"end_station_name\":\"广州东\",\"end_time\":\"11:41\",\"id\":\"65000D711603\",\"start_station_name\":\"深圳\",\"start_time\":\"10:22\",\"value\":\"D7116\"},{\"end_station_name\":\"武汉\",\"end_time\":\"15:26\",\"id\":\"6i000G100800\",\"start_station_name\":\"深圳北\",\"start_time\":\"10:25\",\"value\":\"G1008\"},{\"end_station_name\":\"广州东\",\"end_time\":\"11:53\",\"id\":\"65000D716004\",\"start_station_name\":\"深圳\",\"start_time\":\"10:35\",\"value\":\"D7160\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"14:00\",\"id\":\"6i000G601601\",\"start_station_name\":\"深圳北\",\"start_time\":\"10:40\",\"value\":\"G6016\"},{\"end_station_name\":\"广州东\",\"end_time\":\"12:07\",\"id\":\"65000D712804\",\"start_station_name\":\"深圳\",\"start_time\":\"10:48\",\"value\":\"D7128\"},{\"end_station_name\":\"广州东\",\"end_time\":\"12:22\",\"id\":\"65000D702400\",\"start_station_name\":\"深圳\",\"start_time\":\"11:03\",\"value\":\"D7024\"},{\"end_station_name\":\"广州东\",\"end_time\":\"12:39\",\"id\":\"65000D700405\",\"start_station_name\":\"深圳\",\"start_time\":\"11:20\",\"value\":\"D7004\"},{\"end_station_name\":\"铜仁\",\"end_time\":\"08:52\",\"id\":\"69000K906407\",\"start_station_name\":\"深圳西\",\"start_time\":\"11:20\",\"value\":\"K9064/K9065\"},{\"end_station_name\":\"武汉\",\"end_time\":\"16:21\",\"id\":\"6i000G101000\",\"start_station_name\":\"深圳北\",\"start_time\":\"11:20\",\"value\":\"G1010\"},{\"end_station_name\":\"广州南\",\"end_time\":\"12:12\",\"id\":\"6i000G621002\",\"start_station_name\":\"深圳北\",\"start_time\":\"11:29\",\"value\":\"G6210\"},{\"end_station_name\":\"广州\",\"end_time\":\"13:06\",\"id\":\"65000D704603\",\"start_station_name\":\"深圳\",\"start_time\":\"11:31\",\"value\":\"D7046\"},{\"end_station_name\":\"广州东\",\"end_time\":\"13:00\",\"id\":\"65000D707802\",\"start_station_name\":\"深圳\",\"start_time\":\"11:41\",\"value\":\"D7078\"},{\"end_station_name\":\"广州东\",\"end_time\":\"13:08\",\"id\":\"65000D708802\",\"start_station_name\":\"深圳\",\"start_time\":\"11:49\",\"value\":\"D7088\"},{\"end_station_name\":\"广州\",\"end_time\":\"13:35\",\"id\":\"65000D706801\",\"start_station_name\":\"深圳\",\"start_time\":\"12:00\",\"value\":\"D7068\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"15:44\",\"id\":\"6i000G601806\",\"start_station_name\":\"深圳北\",\"start_time\":\"12:00\",\"value\":\"G6018\"},{\"end_station_name\":\"广州东\",\"end_time\":\"13:27\",\"id\":\"65000D709802\",\"start_station_name\":\"深圳\",\"start_time\":\"12:08\",\"value\":\"D7098\"},{\"end_station_name\":\"广州南\",\"end_time\":\"12:58\",\"id\":\"6i000G621200\",\"start_station_name\":\"深圳北\",\"start_time\":\"12:15\",\"value\":\"G6212\"},{\"end_station_name\":\"广州东\",\"end_time\":\"13:43\",\"id\":\"65000D717201\",\"start_station_name\":\"深圳\",\"start_time\":\"12:24\",\"value\":\"D7172\"},{\"end_station_name\":\"广州东\",\"end_time\":\"13:53\",\"id\":\"65000D703660\",\"start_station_name\":\"深圳\",\"start_time\":\"12:34\",\"value\":\"D7036\"},{\"end_station_name\":\"武汉\",\"end_time\":\"17:35\",\"id\":\"6i000G101201\",\"start_station_name\":\"深圳北\",\"start_time\":\"12:38\",\"value\":\"G1012\"},{\"end_station_name\":\"广州\",\"end_time\":\"14:20\",\"id\":\"65000D718230\",\"start_station_name\":\"深圳\",\"start_time\":\"12:42\",\"value\":\"D7182\"},{\"end_station_name\":\"广州东\",\"end_time\":\"14:09\",\"id\":\"65000D705850\",\"start_station_name\":\"深圳\",\"start_time\":\"12:50\",\"value\":\"D7058\"},{\"end_station_name\":\"广州东\",\"end_time\":\"14:17\",\"id\":\"65000D714002\",\"start_station_name\":\"深圳\",\"start_time\":\"12:58\",\"value\":\"D7140\"},{\"end_station_name\":\"西安北\",\"end_time\":\"22:33\",\"id\":\"6i0000G82600\",\"start_station_name\":\"深圳北\",\"start_time\":\"13:00\",\"value\":\"G826/G827\"},{\"end_station_name\":\"广州东\",\"end_time\":\"14:33\",\"id\":\"65000D710802\",\"start_station_name\":\"深圳\",\"start_time\":\"13:14\",\"value\":\"D7108\"},{\"end_station_name\":\"广州\",\"end_time\":\"14:56\",\"id\":\"65000D711801\",\"start_station_name\":\"深圳\",\"start_time\":\"13:24\",\"value\":\"D7118\"},{\"end_station_name\":\"广州南\",\"end_time\":\"14:11\",\"id\":\"6i000G621600\",\"start_station_name\":\"深圳北\",\"start_time\":\"13:35\",\"value\":\"G6216\"},{\"end_station_name\":\"广州东\",\"end_time\":\"14:55\",\"id\":\"65000D716201\",\"start_station_name\":\"深圳\",\"start_time\":\"13:37\",\"value\":\"D7162\"},{\"end_station_name\":\"广州\",\"end_time\":\"15:28\",\"id\":\"65000D701604\",\"start_station_name\":\"深圳\",\"start_time\":\"13:50\",\"value\":\"D7016\"},{\"end_station_name\":\"广州东\",\"end_time\":\"15:17\",\"id\":\"65000D713004\",\"start_station_name\":\"深圳\",\"start_time\":\"13:58\",\"value\":\"D7130\"},{\"end_station_name\":\"武汉\",\"end_time\":\"18:13\",\"id\":\"6i00000G7800\",\"start_station_name\":\"深圳北\",\"start_time\":\"14:00\",\"value\":\"G78\"},{\"end_station_name\":\"广州东\",\"end_time\":\"15:27\",\"id\":\"65000D702604\",\"start_station_name\":\"深圳\",\"start_time\":\"14:08\",\"value\":\"D7026\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"17:31\",\"id\":\"6i000G602001\",\"start_station_name\":\"深圳北\",\"start_time\":\"14:12\",\"value\":\"G6020\"},{\"end_station_name\":\"广州东\",\"end_time\":\"15:44\",\"id\":\"65000D700604\",\"start_station_name\":\"深圳\",\"start_time\":\"14:25\",\"value\":\"D7006\"},{\"end_station_name\":\"邵阳\",\"end_time\":\"06:00\",\"id\":\"69000K908406\",\"start_station_name\":\"深圳西\",\"start_time\":\"14:30\",\"value\":\"K9084/K9085\"},{\"end_station_name\":\"广州南\",\"end_time\":\"15:13\",\"id\":\"6i000G621800\",\"start_station_name\":\"深圳北\",\"start_time\":\"14:30\",\"value\":\"G6218\"},{\"end_station_name\":\"广州\",\"end_time\":\"16:19\",\"id\":\"65000D708004\",\"start_station_name\":\"深圳\",\"start_time\":\"14:43\",\"value\":\"D7080\"},{\"end_station_name\":\"广州东\",\"end_time\":\"16:10\",\"id\":\"65000D709002\",\"start_station_name\":\"深圳\",\"start_time\":\"14:51\",\"value\":\"D7090\"},{\"end_station_name\":\"怀化\",\"end_time\":\"06:30\",\"id\":\"65000K905206\",\"start_station_name\":\"深圳东\",\"start_time\":\"14:52\",\"value\":\"K9052/K9053\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"17:52\",\"id\":\"6i000G600202\",\"start_station_name\":\"深圳北\",\"start_time\":\"15:00\",\"value\":\"G6002\"},{\"end_station_name\":\"广州东\",\"end_time\":\"16:20\",\"id\":\"65000D704804\",\"start_station_name\":\"深圳\",\"start_time\":\"15:01\",\"value\":\"D7048\"},{\"end_station_name\":\"广州东\",\"end_time\":\"16:29\",\"id\":\"65000D710004\",\"start_station_name\":\"深圳\",\"start_time\":\"15:10\",\"value\":\"D7100\"},{\"end_station_name\":\"武汉\",\"end_time\":\"20:21\",\"id\":\"6i000G101401\",\"start_station_name\":\"深圳北\",\"start_time\":\"15:20\",\"value\":\"G1014\"},{\"end_station_name\":\"广州东\",\"end_time\":\"16:45\",\"id\":\"65000D717404\",\"start_station_name\":\"深圳\",\"start_time\":\"15:26\",\"value\":\"D7174\"},{\"end_station_name\":\"广州\",\"end_time\":\"17:12\",\"id\":\"65000D707004\",\"start_station_name\":\"深圳\",\"start_time\":\"15:33\",\"value\":\"D7070\"},{\"end_station_name\":\"昆明\",\"end_time\":\"20:17\",\"id\":\"65000K120810\",\"start_station_name\":\"深圳东\",\"start_time\":\"15:34\",\"value\":\"K1208/K1205\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"18:56\",\"id\":\"6i000G602200\",\"start_station_name\":\"深圳北\",\"start_time\":\"15:35\",\"value\":\"G6022\"},{\"end_station_name\":\"广州东\",\"end_time\":\"17:00\",\"id\":\"65000D703804\",\"start_station_name\":\"深圳\",\"start_time\":\"15:41\",\"value\":\"D7038\"},{\"end_station_name\":\"郑州东\",\"end_time\":\"22:31\",\"id\":\"6i00000G7600\",\"start_station_name\":\"深圳北\",\"start_time\":\"15:50\",\"value\":\"G76\"},{\"end_station_name\":\"广州东\",\"end_time\":\"17:10\",\"id\":\"65000D706004\",\"start_station_name\":\"深圳\",\"start_time\":\"15:51\",\"value\":\"D7060\"},{\"end_station_name\":\"广州东\",\"end_time\":\"17:19\",\"id\":\"65000D714204\",\"start_station_name\":\"深圳\",\"start_time\":\"16:00\",\"value\":\"D7142\"},{\"end_station_name\":\"广州东\",\"end_time\":\"17:35\",\"id\":\"65000D711040\",\"start_station_name\":\"深圳\",\"start_time\":\"16:16\",\"value\":\"D7110\"},{\"end_station_name\":\"武汉\",\"end_time\":\"21:16\",\"id\":\"6i000G101601\",\"start_station_name\":\"深圳北\",\"start_time\":\"16:20\",\"value\":\"G1016\"},{\"end_station_name\":\"广州\",\"end_time\":\"18:04\",\"id\":\"65000D718430\",\"start_station_name\":\"深圳\",\"start_time\":\"16:28\",\"value\":\"D7184\"},{\"end_station_name\":\"广州南\",\"end_time\":\"17:18\",\"id\":\"6i000G622201\",\"start_station_name\":\"深圳北\",\"start_time\":\"16:35\",\"value\":\"G6222\"},{\"end_station_name\":\"广州东\",\"end_time\":\"17:58\",\"id\":\"65000D716430\",\"start_station_name\":\"深圳\",\"start_time\":\"16:40\",\"value\":\"D7164\"},{\"end_station_name\":\"广州东\",\"end_time\":\"18:13\",\"id\":\"65000D712004\",\"start_station_name\":\"深圳\",\"start_time\":\"16:54\",\"value\":\"D7120\"},{\"end_station_name\":\"南宁\",\"end_time\":\"08:00\",\"id\":\"65000K123200\",\"start_station_name\":\"深圳东\",\"start_time\":\"16:55\",\"value\":\"K1232/K1233\"},{\"end_station_name\":\"广州南\",\"end_time\":\"17:41\",\"id\":\"6i000G622406\",\"start_station_name\":\"深圳北\",\"start_time\":\"16:55\",\"value\":\"G6224\"},{\"end_station_name\":\"广州\",\"end_time\":\"18:35\",\"id\":\"65000D713230\",\"start_station_name\":\"深圳\",\"start_time\":\"17:02\",\"value\":\"D7132\"},{\"end_station_name\":\"广州东\",\"end_time\":\"18:29\",\"id\":\"65000D702804\",\"start_station_name\":\"深圳\",\"start_time\":\"17:10\",\"value\":\"D7028\"},{\"end_station_name\":\"广州东\",\"end_time\":\"18:46\",\"id\":\"65000D700803\",\"start_station_name\":\"深圳\",\"start_time\":\"17:27\",\"value\":\"D7008\"},{\"end_station_name\":\"广州东\",\"end_time\":\"18:57\",\"id\":\"65000D701804\",\"start_station_name\":\"深圳\",\"start_time\":\"17:38\",\"value\":\"D7018\"},{\"end_station_name\":\"汉口\",\"end_time\":\"06:47\",\"id\":\"6500000T9608\",\"start_station_name\":\"深圳\",\"start_time\":\"17:40\",\"value\":\"T96\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"20:54\",\"id\":\"6i000G602400\",\"start_station_name\":\"深圳北\",\"start_time\":\"17:40\",\"value\":\"G6024\"},{\"end_station_name\":\"桂林北\",\"end_time\":\"07:55\",\"id\":\"650000K95210\",\"start_station_name\":\"深圳\",\"start_time\":\"17:46\",\"value\":\"K952/K949\"},{\"end_station_name\":\"广州\",\"end_time\":\"19:32\",\"id\":\"65000D709230\",\"start_station_name\":\"深圳\",\"start_time\":\"17:53\",\"value\":\"D7092\"},{\"end_station_name\":\"武汉\",\"end_time\":\"22:49\",\"id\":\"6i000G101801\",\"start_station_name\":\"深圳北\",\"start_time\":\"18:00\",\"value\":\"G1018\"},{\"end_station_name\":\"广州东\",\"end_time\":\"19:22\",\"id\":\"65000D705005\",\"start_station_name\":\"深圳\",\"start_time\":\"18:03\",\"value\":\"D7050\"},{\"end_station_name\":\"广州东\",\"end_time\":\"19:31\",\"id\":\"65000D710204\",\"start_station_name\":\"深圳\",\"start_time\":\"18:12\",\"value\":\"D7102\"},{\"end_station_name\":\"怀化\",\"end_time\":\"09:45\",\"id\":\"69000K90560A\",\"start_station_name\":\"深圳西\",\"start_time\":\"18:15\",\"value\":\"K9056/K9057\"},{\"end_station_name\":\"广州东\",\"end_time\":\"19:39\",\"id\":\"65000D708204\",\"start_station_name\":\"深圳\",\"start_time\":\"18:20\",\"value\":\"D7082\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"21:40\",\"id\":\"6i000G602600\",\"start_station_name\":\"深圳北\",\"start_time\":\"18:20\",\"value\":\"G6026\"},{\"end_station_name\":\"广州\",\"end_time\":\"20:08\",\"id\":\"65000D717604\",\"start_station_name\":\"深圳\",\"start_time\":\"18:36\",\"value\":\"D7176\"},{\"end_station_name\":\"广州南\",\"end_time\":\"19:19\",\"id\":\"6i000G622802\",\"start_station_name\":\"深圳北\",\"start_time\":\"18:36\",\"value\":\"G6228\"},{\"end_station_name\":\"广州东\",\"end_time\":\"20:04\",\"id\":\"65000D704004\",\"start_station_name\":\"深圳\",\"start_time\":\"18:45\",\"value\":\"D7040\"},{\"end_station_name\":\"广州东\",\"end_time\":\"20:12\",\"id\":\"65000D706206\",\"start_station_name\":\"深圳\",\"start_time\":\"18:53\",\"value\":\"D7062\"},{\"end_station_name\":\"广州东\",\"end_time\":\"20:21\",\"id\":\"65000D714403\",\"start_station_name\":\"深圳\",\"start_time\":\"19:02\",\"value\":\"D7144\"},{\"end_station_name\":\"怀化\",\"end_time\":\"11:53\",\"id\":\"69000K906007\",\"start_station_name\":\"深圳西\",\"start_time\":\"19:08\",\"value\":\"K9060/K9061\"},{\"end_station_name\":\"岳阳\",\"end_time\":\"07:02\",\"id\":\"65000K900404\",\"start_station_name\":\"深圳\",\"start_time\":\"19:10\",\"value\":\"K9004\"},{\"end_station_name\":\"广州东\",\"end_time\":\"20:31\",\"id\":\"65000D707204\",\"start_station_name\":\"深圳\",\"start_time\":\"19:12\",\"value\":\"D7072\"},{\"end_station_name\":\"广州南\",\"end_time\":\"20:03\",\"id\":\"6i000G623200\",\"start_station_name\":\"深圳北\",\"start_time\":\"19:20\",\"value\":\"G6232\"},{\"end_station_name\":\"广州\",\"end_time\":\"21:01\",\"id\":\"65000D711204\",\"start_station_name\":\"深圳\",\"start_time\":\"19:29\",\"value\":\"D7112\"},{\"end_station_name\":\"广州东\",\"end_time\":\"20:58\",\"id\":\"65000D716605\",\"start_station_name\":\"深圳\",\"start_time\":\"19:40\",\"value\":\"D7166\"},{\"end_station_name\":\"常德\",\"end_time\":\"08:30\",\"id\":\"65000K907609\",\"start_station_name\":\"深圳东\",\"start_time\":\"19:43\",\"value\":\"K9076\"},{\"end_station_name\":\"长沙南\",\"end_time\":\"23:26\",\"id\":\"6i000G602800\",\"start_station_name\":\"深圳北\",\"start_time\":\"19:45\",\"value\":\"G6028\"},{\"end_station_name\":\"广州东\",\"end_time\":\"21:15\",\"id\":\"65000D712203\",\"start_station_name\":\"深圳\",\"start_time\":\"19:56\",\"value\":\"D7122\"},{\"end_station_name\":\"广州\",\"end_time\":\"21:43\",\"id\":\"65000D718605\",\"start_station_name\":\"深圳\",\"start_time\":\"20:04\",\"value\":\"D7186\"},{\"end_station_name\":\"广州\",\"end_time\":\"22:14\",\"id\":\"65000T837410\",\"start_station_name\":\"深圳东\",\"start_time\":\"20:08\",\"value\":\"T8374\"},{\"end_station_name\":\"广州南\",\"end_time\":\"20:46\",\"id\":\"6i000G623408\",\"start_station_name\":\"深圳北\",\"start_time\":\"20:10\",\"value\":\"G6234\"},{\"end_station_name\":\"广州东\",\"end_time\":\"21:31\",\"id\":\"65000D703004\",\"start_station_name\":\"深圳\",\"start_time\":\"20:12\",\"value\":\"D7030\"},{\"end_station_name\":\"广州东\",\"end_time\":\"21:48\",\"id\":\"65000D701004\",\"start_station_name\":\"深圳\",\"start_time\":\"20:29\",\"value\":\"D7010\"},{\"end_station_name\":\"广州南\",\"end_time\":\"21:13\",\"id\":\"6i000G623600\",\"start_station_name\":\"深圳北\",\"start_time\":\"20:30\",\"value\":\"G6236\"},{\"end_station_name\":\"广州\",\"end_time\":\"22:08\",\"id\":\"65000D713404\",\"start_station_name\":\"深圳\",\"start_time\":\"20:37\",\"value\":\"D7134\"},{\"end_station_name\":\"长沙\",\"end_time\":\"06:36\",\"id\":\"65000K901807\",\"start_station_name\":\"深圳\",\"start_time\":\"20:50\",\"value\":\"K9018\"},{\"end_station_name\":\"广州东\",\"end_time\":\"22:10\",\"id\":\"65000D702005\",\"start_station_name\":\"深圳\",\"start_time\":\"20:51\",\"value\":\"D7020\"},{\"end_station_name\":\"广州南\",\"end_time\":\"21:36\",\"id\":\"6i000G623800\",\"start_station_name\":\"深圳北\",\"start_time\":\"21:00\",\"value\":\"G6238\"},{\"end_station_name\":\"广州东\",\"end_time\":\"22:24\",\"id\":\"65000D705204\",\"start_station_name\":\"深圳\",\"start_time\":\"21:05\",\"value\":\"D7052\"},{\"end_station_name\":\"广州东\",\"end_time\":\"22:33\",\"id\":\"65000D710404\",\"start_station_name\":\"深圳\",\"start_time\":\"21:14\",\"value\":\"D7104\"},{\"end_station_name\":\"广州东\",\"end_time\":\"22:41\",\"id\":\"65000D708405\",\"start_station_name\":\"深圳\",\"start_time\":\"21:22\",\"value\":\"D7084\"},{\"end_station_name\":\"广州东\",\"end_time\":\"22:49\",\"id\":\"65000D709404\",\"start_station_name\":\"深圳\",\"start_time\":\"21:30\",\"value\":\"D7094\"},{\"end_station_name\":\"衡阳\",\"end_time\":\"05:48\",\"id\":\"65000K912208\",\"start_station_name\":\"深圳\",\"start_time\":\"21:40\",\"value\":\"K9122\"},{\"end_station_name\":\"广州东\",\"end_time\":\"23:06\",\"id\":\"65000D704203\",\"start_station_name\":\"深圳\",\"start_time\":\"21:47\",\"value\":\"D7042\"},{\"end_station_name\":\"广州东\",\"end_time\":\"23:14\",\"id\":\"65000D706404\",\"start_station_name\":\"深圳\",\"start_time\":\"21:55\",\"value\":\"D7064\"},{\"end_station_name\":\"广州南\",\"end_time\":\"22:36\",\"id\":\"6i000G624200\",\"start_station_name\":\"深圳北\",\"start_time\":\"22:00\",\"value\":\"G6242\"},{\"end_station_name\":\"广州东\",\"end_time\":\"23:23\",\"id\":\"65000D714604\",\"start_station_name\":\"深圳\",\"start_time\":\"22:04\",\"value\":\"D7146\"},{\"end_station_name\":\"广州东\",\"end_time\":\"23:31\",\"id\":\"65000D717806\",\"start_station_name\":\"深圳\",\"start_time\":\"22:12\",\"value\":\"D7178\"},{\"end_station_name\":\"广州东\",\"end_time\":\"23:39\",\"id\":\"65000D707404\",\"start_station_name\":\"深圳\",\"start_time\":\"22:20\",\"value\":\"D7074\"},{\"end_station_name\":\"广州南\",\"end_time\":\"23:06\",\"id\":\"6i000G624400\",\"start_station_name\":\"深圳北\",\"start_time\":\"22:30\",\"value\":\"G6244\"},{\"end_station_name\":\"广州东\",\"end_time\":\"23:59\",\"id\":\"65000D716806\",\"start_station_name\":\"深圳\",\"start_time\":\"22:40\",\"value\":\"D7168\"},{\"end_station_name\":\"广州南\",\"end_time\":\"23:36\",\"id\":\"6i000G624600\",\"start_station_name\":\"深圳北\",\"start_time\":\"23:00\",\"value\":\"G6246\"}]";
TrainInfo[] trainInfoArray = TRConvert.ToTrainInfoArray(strJson);
}
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/TRTester.cs | C# | gpl3 | 24,845 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TrainTicketsRobot
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
}
}
| 12306robot | trunk/12306RobotV1.0/TrainTicketsRobotV1.0/Program.cs | C# | gpl3 | 500 |
/*
* Copyright (C) 2009 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 com.ch_linghu.fanfoudroid;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.ui.module.MyTextView;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//禁止横屏
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// TODO: is this a hack?
setResult(RESULT_OK);
addPreferencesFromResource(R.xml.preferences);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) {
HttpClient httpClient = TwitterApplication.mApi.getHttpClient();
String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, "");
if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) {
Log.d("LDS", "Set proxy for cmwap mode.");
httpClient.setProxy("10.0.0.172", 80, "http");
} else {
Log.d("LDS", "No proxy.");
httpClient.removeProxy();
}
} else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) {
MyTextView.setFontSizeChanged(true);
}
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/PreferencesActivity.java | Java | asf20 | 3,039 |
package com.ch_linghu.fanfoudroid.app;
import java.util.HashMap;
import android.graphics.Bitmap;
public class MemoryImageCache implements ImageCache {
private HashMap<String, Bitmap> mCache;
public MemoryImageCache() {
mCache = new HashMap<String, Bitmap>();
}
@Override
public Bitmap get(String url) {
synchronized(this) {
Bitmap bitmap = mCache.get(url);
if (bitmap == null){
return mDefaultBitmap;
}else{
return bitmap;
}
}
}
@Override
public void put(String url, Bitmap bitmap) {
synchronized(this) {
mCache.put(url, bitmap);
}
}
public void putAll(MemoryImageCache imageCache) {
synchronized(this) {
// TODO: is this thread safe?
mCache.putAll(imageCache.mCache);
}
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/MemoryImageCache.java | Java | asf20 | 831 |
/*
* Copyright (C) 2009 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 com.ch_linghu.fanfoudroid.app;
public class Preferences {
public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
public static final String CHECK_UPDATES_KEY = "check_updates";
public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval";
public static final String VIBRATE_KEY = "vibrate";
public static final String TIMELINE_ONLY_KEY = "timeline_only";
public static final String REPLIES_ONLY_KEY = "replies_only";
public static final String DM_ONLY_KEY = "dm_only";
public static String RINGTONE_KEY = "ringtone";
public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound";
public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh";
public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh";
public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh";
public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state";
public static final String USE_PROFILE_IMAGE = "use_profile_image";
public static final String PHOTO_PREVIEW = "photo_preview";
public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image";
public static final String RT_PREFIX_KEY = "rt_prefix";
public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾
public static final String NETWORK_TYPE = "network_type";
// DEBUG标记
public static final String DEBUG = "debug";
// 当前用户相关信息
public static final String CURRENT_USER_ID = "current_user_id";
public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname";
public static final String UI_FONT_SIZE = "ui_font_size";
public static final String USE_ENTER_SEND = "use_enter_send";
public static final String USE_GESTRUE = "use_gestrue";
public static final String USE_SHAKE = "use_shake";
public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait";
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/Preferences.java | Java | asf20 | 2,782 |
package com.ch_linghu.fanfoudroid.app;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;
public class TestMovementMethod extends LinkMovementMethod {
private double mY;
private boolean mIsMoving = false;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
/*
int action = event.getAction();
if (action == MotionEvent.ACTION_MOVE) {
double deltaY = mY - event.getY();
mY = event.getY();
Log.d("foo", deltaY + "");
if (Math.abs(deltaY) > 1) {
mIsMoving = true;
}
} else if (action == MotionEvent.ACTION_DOWN) {
mIsMoving = false;
mY = event.getY();
} else if (action == MotionEvent.ACTION_UP) {
boolean wasMoving = mIsMoving;
mIsMoving = false;
if (wasMoving) {
return true;
}
}
*/
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new TestMovementMethod();
return sInstance;
}
private static TestMovementMethod sInstance;
} | 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/TestMovementMethod.java | Java | asf20 | 1,336 |
package com.ch_linghu.fanfoudroid.app;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.http.HttpServerException;
public class ExceptionHandler {
private Activity mActivity;
public ExceptionHandler(Activity activity) {
mActivity = activity;
}
public void handle(HttpException e) {
Throwable cause = e.getCause();
if (null == cause) return;
// Handle Different Exception
if (cause instanceof HttpAuthException) {
// 用户名/密码错误
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent); // redirect to the login activity
} else if (cause instanceof HttpServerException) {
// 服务器暂时无法响应
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
} else if (cause instanceof HttpAuthException) {
//FIXME: 集中处理用户名/密码验证错误,返回到登录界面
} else if (cause instanceof HttpRefusedException) {
// 服务器拒绝请求,如没有权限查看某用户信息
RefuseError error = ((HttpRefusedException) cause).getError();
switch (error.getErrorCode()) {
// TODO: finish it
case -1:
default:
Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show();
break;
}
}
}
private void handleCause() {
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/ExceptionHandler.java | Java | asf20 | 2,064 |
/*
* Copyright (C) 2009 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 com.ch_linghu.fanfoudroid.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Manages retrieval and storage of icon images. Use the put method to download
* and store images. Use the get method to retrieve images from the manager.
*/
public class ImageManager implements ImageCache {
private static final String TAG = "ImageManager";
// 饭否目前最大宽度支持596px, 超过则同比缩小
// 最大高度为1192px, 超过从中截取
public static final int DEFAULT_COMPRESS_QUALITY = 90;
public static final int IMAGE_MAX_WIDTH = 596;
public static final int IMAGE_MAX_HEIGHT = 1192;
private Context mContext;
// In memory cache.
private Map<String, SoftReference<Bitmap>> mCache;
// MD5 hasher.
private MessageDigest mDigest;
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public ImageManager(Context context) {
mContext = context;
mCache = new HashMap<String, SoftReference<Bitmap>>();
try {
mDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// This shouldn't happen.
throw new RuntimeException("No MD5 algorithm.");
}
}
public void setContext(Context context) {
mContext = context;
}
private String getHashString(MessageDigest digest) {
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest()) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
// MD5 hases are used to generate filenames based off a URL.
private String getMd5(String url) {
mDigest.update(url.getBytes());
return getHashString(mDigest);
}
// Looks to see if an image is in the file system.
private Bitmap lookupFile(String url) {
String hashedUrl = getMd5(url);
FileInputStream fis = null;
try {
fis = mContext.openFileInput(hashedUrl);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
// Not there.
return null;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore.
}
}
}
}
/**
* Downloads a file
* @param url
* @return
* @throws HttpException
*/
public Bitmap downloadImage(String url) throws HttpException {
Log.d(TAG, "Fetching image: " + url);
Response res = TwitterApplication.mApi.getHttpClient().get(url);
return BitmapFactory.decodeStream(new BufferedInputStream(res.asStream()));
}
public Bitmap downloadImage2(String url) throws HttpException {
Log.d(TAG, "[NEW]Fetching image: " + url);
final Response res = TwitterApplication.mApi.getHttpClient().get(url);
String file = writeToFile(res.asStream(), getMd5(url));
return BitmapFactory.decodeFile(file);
}
/**
* 下载远程图片 -> 转换为Bitmap -> 写入缓存器.
* @param url
* @param quality image quality 1~100
* @throws HttpException
*/
public void put(String url, int quality, boolean forceOverride) throws HttpException {
if (!forceOverride && contains(url)) {
// Image already exists.
return;
// TODO: write to file if not present.
}
Bitmap bitmap = downloadImage(url);
if (bitmap != null) {
put(url, bitmap, quality); // file cache
} else {
Log.w(TAG, "Retrieved bitmap is null.");
}
}
/**
* 重载 put(String url, int quality)
* @param url
* @throws HttpException
*/
public void put(String url) throws HttpException {
put(url, DEFAULT_COMPRESS_QUALITY, false);
}
/**
* 将本地File -> 转换为Bitmap -> 写入缓存器.
* 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放.
*
* @param file
* @param quality 图片质量(0~100)
* @param forceOverride
* @throws IOException
*/
public void put(File file, int quality, boolean forceOverride) throws IOException {
if (!file.exists()) {
Log.w(TAG, file.getName() + " is not exists.");
return;
}
if (!forceOverride && contains(file.getPath())) {
// Image already exists.
Log.d(TAG, file.getName() + " is exists");
return;
// TODO: write to file if not present.
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
//bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT);
if (bitmap == null) {
Log.w(TAG, "Retrieved bitmap is null.");
} else {
put(file.getPath(), bitmap, quality);
}
}
/**
* 将Bitmap写入缓存器.
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
public void put(String file, Bitmap bitmap, int quality) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
writeFile(file, bitmap, quality);
}
/**
* 重载 put(String file, Bitmap bitmap, int quality)
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
@Override
public void put(String file, Bitmap bitmap) {
put(file, bitmap, DEFAULT_COMPRESS_QUALITY);
}
/**
* 将Bitmap写入本地缓存文件.
* @param file URL/PATH
* @param bitmap
* @param quality
*/
private void writeFile(String file, Bitmap bitmap, int quality) {
if (bitmap == null) {
Log.w(TAG, "Can't write file. Bitmap is null.");
return;
}
BufferedOutputStream bos = null;
try {
String hashedUrl = getMd5(file);
bos = new BufferedOutputStream(
mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE));
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG
Log.d(TAG, "Writing file: " + file);
} catch (IOException ioe) {
Log.e(TAG, ioe.getMessage());
} finally {
try {
if (bos != null) {
bitmap.recycle();
bos.flush();
bos.close();
}
//bitmap.recycle();
} catch (IOException e) {
Log.e(TAG, "Could not close file.");
}
}
}
private String writeToFile(InputStream is, String filename) {
Log.d("LDS", "new write to file");
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(is);
out = new BufferedOutputStream(
mContext.openFileOutput(filename, Context.MODE_PRIVATE));
byte[] buffer = new byte[1024];
int l;
while ((l = in.read(buffer)) != -1) {
out.write(buffer, 0, l);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (in != null) in.close();
if (out != null) {
Log.d("LDS", "new write to file to -> " + filename);
out.flush();
out.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return mContext.getFilesDir() + "/" + filename;
}
public Bitmap get(File file) {
return get(file.getPath());
}
/**
* 判断缓存着中是否存在该文件对应的bitmap
*/
public boolean isContains(String file) {
return mCache.containsKey(file);
}
/**
* 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取
* @param file file URL/file PATH
* @param bitmap
* @param quality
* @throws HttpException
*/
public Bitmap safeGet(String file) throws HttpException {
Bitmap bitmap = lookupFile(file); // first try file.
if (bitmap != null) {
synchronized (this) { // memory cache
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
} else { //get from web
String url = file;
bitmap = downloadImage2(url);
// 注释掉以测试新的写入文件方法
//put(file, bitmap); // file Cache
return bitmap;
}
}
/**
* 从缓存器中读取文件
* @param file file URL/file PATH
* @param bitmap
* @param quality
*/
public Bitmap get(String file) {
SoftReference<Bitmap> ref;
Bitmap bitmap;
// Look in memory first.
synchronized (this) {
ref = mCache.get(file);
}
if (ref != null) {
bitmap = ref.get();
if (bitmap != null) {
return bitmap;
}
}
// Now try file.
bitmap = lookupFile(file);
if (bitmap != null) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
}
//TODO: why?
//upload: see profileImageCacheManager line 96
Log.w(TAG, "Image is missing: " + file);
// return the default photo
return mDefaultBitmap;
}
public boolean contains(String url) {
return get(url) != mDefaultBitmap;
}
public void clear() {
String[] files = mContext.fileList();
for (String file : files) {
mContext.deleteFile(file);
}
synchronized (this) {
mCache.clear();
}
}
public void cleanup(HashSet<String> keepers) {
String[] files = mContext.fileList();
HashSet<String> hashedUrls = new HashSet<String>();
for (String imageUrl : keepers) {
hashedUrls.add(getMd5(imageUrl));
}
for (String file : files) {
if (!hashedUrls.contains(file)) {
Log.d(TAG, "Deleting unused file: " + file);
mContext.deleteFile(file);
}
}
}
/**
* Compress and resize the Image
*
* <br />
* 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该
* 考虑图片将会被二次压缩所造成的图片质量损耗
*
* @param targetFile
* @param quality, 0~100, recommend 100
* @return
* @throws IOException
*/
public File compressImage(File targetFile, int quality) throws IOException {
String filepath = targetFile.getAbsolutePath();
// 1. Calculate scale
int scale = 1;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, o);
if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) {
scale = (int) Math.pow( 2.0,
(int) Math.round(Math.log(IMAGE_MAX_WIDTH
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
//scale = 2;
}
Log.d(TAG, scale + " scale");
// 2. File -> Bitmap (Returning a smaller image)
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, o);
// 2.1. Resize Bitmap
//bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
// 3. Bitmap -> File
writeFile(filepath, bitmap, quality);
// 4. Get resized Image File
String filePath = getMd5(targetFile.getPath());
File compressedImage = mContext.getFileStreamPath(filePath);
return compressedImage;
}
/**
* 保持长宽比缩小Bitmap
*
* @param bitmap
* @param maxWidth
* @param maxHeight
* @param quality 1~100
* @return
*/
public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
int originWidth = bitmap.getWidth();
int originHeight = bitmap.getHeight();
// no need to resize
if (originWidth < maxWidth && originHeight < maxHeight) {
return bitmap;
}
int newWidth = originWidth;
int newHeight = originHeight;
// 若图片过宽, 则保持长宽比缩放图片
if (originWidth > maxWidth) {
newWidth = maxWidth;
double i = originWidth * 1.0 / maxWidth;
newHeight = (int) Math.floor(originHeight / i);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
// 若图片过长, 则从中部截取
if (newHeight > maxHeight) {
newHeight = maxHeight;
int half_diff = (int)((originHeight - maxHeight) / 2.0);
bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight);
}
Log.d(TAG, newWidth + " width");
Log.d(TAG, newHeight + " height");
return bitmap;
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/ImageManager.java | Java | asf20 | 16,006 |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
public class SimpleImageLoader {
public static void display(final ImageView imageView, String url) {
imageView.setTag(url);
imageView.setImageBitmap(TwitterApplication.mImageLoader
.get(url, createImageViewCallback(imageView, url)));
}
public static ImageLoaderCallback createImageViewCallback(final ImageView imageView, String url)
{
return new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
if (url.equals(imageView.getTag())) {
imageView.setImageBitmap(bitmap);
}
}
};
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/SimpleImageLoader.java | Java | asf20 | 912 |
package com.ch_linghu.fanfoudroid.app;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
public class LazyImageLoader {
private static final String TAG = "ProfileImageCacheManager";
public static final int HANDLER_MESSAGE_ID = 1;
public static final String EXTRA_BITMAP = "extra_bitmap";
public static final String EXTRA_IMAGE_URL = "extra_image_url";
private ImageManager mImageManager = new ImageManager(
TwitterApplication.mContext);
private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50);
private CallbackManager mCallbackManager = new CallbackManager();
private GetImageTask mTask = new GetImageTask();
/**
* 取图片, 可能直接从cache中返回, 或下载图片后返回
*
* @param url
* @param callback
* @return
*/
public Bitmap get(String url, ImageLoaderCallback callback) {
Bitmap bitmap = ImageCache.mDefaultBitmap;
if (mImageManager.isContains(url)) {
bitmap = mImageManager.get(url);
} else {
// bitmap不存在,启动Task进行下载
mCallbackManager.put(url, callback);
startDownloadThread(url);
}
return bitmap;
}
private void startDownloadThread(String url) {
if (url != null) {
addUrlToDownloadQueue(url);
}
// Start Thread
State state = mTask.getState();
if (Thread.State.NEW == state) {
mTask.start(); // first start
} else if (Thread.State.TERMINATED == state) {
mTask = new GetImageTask(); // restart
mTask.start();
}
}
private void addUrlToDownloadQueue(String url) {
if (!mUrlList.contains(url)) {
try {
mUrlList.put(url);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Low-level interface to get ImageManager
public ImageManager getImageManager() {
return mImageManager;
}
private class GetImageTask extends Thread {
private volatile boolean mTaskTerminated = false;
private static final int TIMEOUT = 3 * 60;
private boolean isPermanent = true;
@Override
public void run() {
try {
while (!mTaskTerminated) {
String url;
if (isPermanent) {
url = mUrlList.take();
} else {
url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting
if (null == url) {
break;
} // no more, shutdown
}
// Bitmap bitmap = ImageCache.mDefaultBitmap;
final Bitmap bitmap = mImageManager.safeGet(url);
// use handler to process callback
final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID);
Bundle bundle = m.getData();
bundle.putString(EXTRA_IMAGE_URL, url);
bundle.putParcelable(EXTRA_BITMAP, bitmap);
handler.sendMessage(m);
}
} catch (HttpException ioe) {
Log.e(TAG, "Get Image failed, " + ioe.getMessage());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage());
} finally {
Log.v(TAG, "Get image task terminated.");
mTaskTerminated = true;
}
}
@SuppressWarnings("unused")
public boolean isPermanent() {
return isPermanent;
}
@SuppressWarnings("unused")
public void setPermanent(boolean isPermanent) {
this.isPermanent = isPermanent;
}
@SuppressWarnings("unused")
public void shutDown() throws InterruptedException {
mTaskTerminated = true;
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_MESSAGE_ID:
final Bundle bundle = msg.getData();
String url = bundle.getString(EXTRA_IMAGE_URL);
Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP));
// callback
mCallbackManager.call(url, bitmap);
break;
default:
// do nothing.
}
}
};
public interface ImageLoaderCallback {
void refresh(String url, Bitmap bitmap);
}
public static class CallbackManager {
private static final String TAG = "CallbackManager";
private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap;
public CallbackManager() {
mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>();
}
public void put(String url, ImageLoaderCallback callback) {
Log.v(TAG, "url=" + url);
if (!mCallbackMap.containsKey(url)) {
Log.v(TAG, "url does not exist, add list to map");
mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>());
//mCallbackMap.put(url, Collections.synchronizedList(new ArrayList<ImageLoaderCallback>()));
}
mCallbackMap.get(url).add(callback);
Log.v(TAG, "Add callback to list, count(url)=" + mCallbackMap.get(url).size());
}
public void call(String url, Bitmap bitmap) {
Log.v(TAG, "call url=" + url);
List<ImageLoaderCallback> callbackList = mCallbackMap.get(url);
if (callbackList == null) {
// FIXME: 有时会到达这里,原因我还没想明白
Log.e(TAG, "callbackList=null");
return;
}
for (ImageLoaderCallback callback : callbackList) {
if (callback != null) {
callback.refresh(url, bitmap);
}
}
callbackList.clear();
mCallbackMap.remove(url);
}
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/LazyImageLoader.java | Java | asf20 | 6,721 |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
public interface ImageCache {
public static Bitmap mDefaultBitmap = ImageManager.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo));
public Bitmap get(String url);
public void put(String url, Bitmap bitmap);
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/app/ImageCache.java | Java | asf20 | 443 |
/*
* Copyright (C) 2009 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 com.ch_linghu.fanfoudroid.data;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Tweet extends Message implements Parcelable {
private static final String TAG = "Tweet";
public com.ch_linghu.fanfoudroid.fanfou.User user;
public String source;
public String prevId;
private int statusType = -1; // @see StatusTable#TYPE_*
public void setStatusType(int type) {
statusType = type;
}
public int getStatusType() {
return statusType;
}
public Tweet(){}
public static Tweet create(Status status){
Tweet tweet = new Tweet();
tweet.id = status.getId();
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = status.getText();
tweet.createdAt = status.getCreatedAt();
tweet.favorited = status.isFavorited()?"true":"false";
tweet.truncated = status.isTruncated()?"true":"false";
tweet.inReplyToStatusId = status.getInReplyToStatusId();
tweet.inReplyToUserId = status.getInReplyToUserId();
tweet.inReplyToScreenName = status.getInReplyToScreenName();
tweet.screenName = TextHelper.getSimpleTweetText(status.getUser().getScreenName());
tweet.profileImageUrl = status.getUser().getProfileImageURL().toString();
tweet.userId = status.getUser().getId();
tweet.user = status.getUser();
tweet.thumbnail_pic = status.getThumbnail_pic();
tweet.bmiddle_pic = status.getBmiddle_pic();
tweet.original_pic = status.getOriginal_pic();
tweet.source = TextHelper.getSimpleTweetText(status.getSource());
return tweet;
}
public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException {
Tweet tweet = new Tweet();
tweet.id = jsonObject.getString("id") + "";
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = jsonObject.getString("text");
tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject.getString("created_at"));
tweet.favorited = jsonObject.getString("favorited");
tweet.truncated = jsonObject.getString("truncated");
tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id");
tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id");
tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name");
tweet.screenName = TextHelper.getSimpleTweetText(jsonObject.getString("from_user"));
tweet.profileImageUrl = jsonObject.getString("profile_image_url");
tweet.userId = jsonObject.getString("from_user_id");
tweet.source = TextHelper.getSimpleTweetText(jsonObject.getString("source"));
return tweet;
}
public static String buildMetaText(StringBuilder builder,
Date createdAt, String source, String replyTo) {
builder.setLength(0);
builder.append(DateTimeHelper.getRelativeDate(createdAt));
builder.append(" ");
builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix));
builder.append(source);
if (!TextUtils.isEmpty(replyTo)) {
builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix));
builder.append(replyTo);
builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix));
}
return builder.toString();
}
// For interface Parcelable
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(id);
out.writeString(text);
out.writeValue(createdAt); //Date
out.writeString(screenName);
out.writeString(favorited);
out.writeString(inReplyToStatusId);
out.writeString(inReplyToUserId);
out.writeString(inReplyToScreenName);
out.writeString(screenName);
out.writeString(profileImageUrl);
out.writeString(thumbnail_pic);
out.writeString(bmiddle_pic);
out.writeString(original_pic);
out.writeString(userId);
out.writeString(source);
}
public static final Parcelable.Creator<Tweet> CREATOR
= new Parcelable.Creator<Tweet>() {
public Tweet createFromParcel(Parcel in) {
return new Tweet(in);
}
public Tweet[] newArray(int size) {
// return new Tweet[size];
throw new UnsupportedOperationException();
}
};
public Tweet(Parcel in) {
id = in.readString();
text = in.readString();
createdAt = (Date) in.readValue(Date.class.getClassLoader());
screenName = in.readString();
favorited = in.readString();
inReplyToStatusId = in.readString();
inReplyToUserId = in.readString();
inReplyToScreenName = in.readString();
screenName = in.readString();
profileImageUrl = in.readString();
thumbnail_pic = in.readString();
bmiddle_pic = in.readString();
original_pic = in.readString();
userId = in.readString();
source = in.readString();
}
@Override
public String toString() {
return "Tweet [source=" + source + ", id=" + id + ", screenName="
+ screenName + ", text=" + text + ", profileImageUrl="
+ profileImageUrl + ", createdAt=" + createdAt + ", userId="
+ userId + ", favorited=" + favorited + ", inReplyToStatusId="
+ inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId
+ ", inReplyToScreenName=" + inReplyToScreenName + "]";
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/data/Tweet.java | Java | asf20 | 6,410 |
package com.ch_linghu.fanfoudroid.data;
import android.database.Cursor;
public interface BaseContent {
long insert();
int delete();
int update();
Cursor select();
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/data/BaseContent.java | Java | asf20 | 184 |
package com.ch_linghu.fanfoudroid.data;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Dm extends Message {
@SuppressWarnings("unused")
private static final String TAG = "Dm";
public boolean isSent;
public static Dm create(DirectMessage directMessage, boolean isSent){
Dm dm = new Dm();
dm.id = directMessage.getId();
dm.text = directMessage.getText();
dm.createdAt = directMessage.getCreatedAt();
dm.isSent = isSent;
User user = dm.isSent ? directMessage.getRecipient()
: directMessage.getSender();
dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName());
dm.userId = user.getId();
dm.profileImageUrl = user.getProfileImageURL().toString();
return dm;
}
} | 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/data/Dm.java | Java | asf20 | 884 |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
public String id;
public String name;
public String screenName;
public String location;
public String description;
public String profileImageUrl;
public String url;
public boolean isProtected;
public int followersCount;
public String lastStatus;
public int friendsCount;
public int favoritesCount;
public int statusesCount;
public Date createdAt;
public boolean isFollowing;
// public boolean notifications;
// public utc_offset
public User() {}
public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) {
User user = new User();
user.id = u.getId();
user.name = u.getName();
user.screenName = u.getScreenName();
user.location = u.getLocation();
user.description = u.getDescription();
user.profileImageUrl = u.getProfileImageURL().toString();
if (u.getURL() != null) {
user.url = u.getURL().toString();
}
user.isProtected = u.isProtected();
user.followersCount = u.getFollowersCount();
user.lastStatus = u.getStatusText();
user.friendsCount = u.getFriendsCount();
user.favoritesCount = u.getFavouritesCount();
user.statusesCount = u.getStatusesCount();
user.createdAt = u.getCreatedAt();
user.isFollowing = u.isFollowing();
return user;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
boolean[] boolArray = new boolean[] { isProtected, isFollowing };
out.writeString(id);
out.writeString(name);
out.writeString(screenName);
out.writeString(location);
out.writeString(description);
out.writeString(profileImageUrl);
out.writeString(url);
out.writeBooleanArray(boolArray);
out.writeInt(friendsCount);
out.writeInt(followersCount);
out.writeInt(statusesCount);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
public User createFromParcel(Parcel in) {
return new User(in);
}
public User[] newArray(int size) {
// return new User[size];
throw new UnsupportedOperationException();
}
};
public User(Parcel in){
boolean[] boolArray = new boolean[]{isProtected, isFollowing};
id = in.readString();
name = in.readString();
screenName = in.readString();
location = in.readString();
description = in.readString();
profileImageUrl = in.readString();
url = in.readString();
in.readBooleanArray(boolArray);
friendsCount = in.readInt();
followersCount = in.readInt();
statusesCount = in.readInt();
isProtected = boolArray[0];
isFollowing = boolArray[1];
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/data/User.java | Java | asf20 | 2,793 |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
public class Message {
public String id;
public String screenName;
public String text;
public String profileImageUrl;
public Date createdAt;
public String userId;
public String favorited;
public String truncated;
public String inReplyToStatusId;
public String inReplyToUserId;
public String inReplyToScreenName;
public String thumbnail_pic;
public String bmiddle_pic;
public String original_pic;
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/data/Message.java | Java | asf20 | 517 |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.service.TwitterService;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class FanfouWidget extends AppWidgetProvider {
public final String TAG = "FanfouWidget";
public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT";
public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV";
private static List<Tweet> tweets;
private SensorManager sensorManager;
private static int position = 0;
class CacheCallback implements ImageLoaderCallback {
private RemoteViews updateViews;
CacheCallback(RemoteViews updateViews) {
this.updateViews = updateViews;
}
@Override
public void refresh(String url, Bitmap bitmap) {
updateViews.setImageViewBitmap(R.id.status_image, bitmap);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appwidgetmanager,
int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
TwitterService.setWidgetStatus(true);
// if (!isRunning(context, WidgetService.class.getName())) {
// Intent i = new Intent(context, WidgetService.class);
// context.startService(i);
// }
update(context);
}
private void update(Context context) {
fetchMessages();
position = 0;
refreshView(context, NEXTACTION);
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId();
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
} else {
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
Log.d(TAG, "Tweets size " + tweets.size());
}
private void refreshView(Context context) {
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildLogin(context));
}
private RemoteViews buildLogin(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText("请登录"));
updateViews.setTextViewText(R.id.status_screen_name,"");
updateViews.setTextViewText(R.id.tweet_source,"");
updateViews.setTextViewText(R.id.tweet_created_at,
"");
return updateViews;
}
private void refreshView(Context context, String action) {
// 某些情况下,tweets会为null
if (tweets == null) {
fetchMessages();
}
// 防止引发IndexOutOfBoundsException
if (tweets.size() != 0) {
if (action.equals(NEXTACTION)) {
--position;
} else if (action.equals(PREACTION)) {
++position;
}
// Log.d(TAG, "Tweets size =" + tweets.size());
if (position >= tweets.size() || position < 0) {
position = 0;
}
// Log.d(TAG, "position=" + position);
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildUpdate(context));
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
Tweet t = tweets.get(position);
Log.d(TAG, "tweet=" + t);
updateViews.setTextViewText(R.id.status_screen_name, t.screenName);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText(t.text));
updateViews.setTextViewText(R.id.tweet_source,
context.getString(R.string.tweet_source_prefix) + t.source);
updateViews.setTextViewText(R.id.tweet_created_at,
DateTimeHelper.getRelativeDate(t.createdAt));
updateViews.setImageViewBitmap(R.id.status_image,
TwitterApplication.mImageLoader.get(
t.profileImageUrl, new CacheCallback(updateViews)));
Intent inext = new Intent(context, FanfouWidget.class);
inext.setAction(NEXTACTION);
PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_next, pinext);
Intent ipre = new Intent(context, FanfouWidget.class);
ipre.setAction(PREACTION);
PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre);
Intent write = WriteActivity.createNewTweetIntent("");
PendingIntent piwrite = PendingIntent.getActivity(context, 0, write,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.write_message, piwrite);
Intent home = TwitterActivity.createIntent(context);
PendingIntent pihome = PendingIntent.getActivity(context, 0, home,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.logo_image, pihome);
Intent status = StatusActivity.createIntent(t);
PendingIntent pistatus = PendingIntent.getActivity(context, 0, status,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.main_body, pistatus);
return updateViews;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive");
// FIXME: NullPointerException
Log.i(TAG, context.getApplicationContext().toString());
if (!TwitterApplication.mApi.isLoggedIn()) {
refreshView(context);
} else {
super.onReceive(context, intent);
String action = intent.getAction();
if (NEXTACTION.equals(action) || PREACTION.equals(action)) {
refreshView(context, intent.getAction());
} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
update(context);
}
}
}
/**
*
* @param c
* @param serviceName
* @return
*/
@Deprecated
public boolean isRunning(Context c, String serviceName) {
ActivityManager myAM = (ActivityManager) c
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM
.getRunningServices(40);
// 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办
int servicesSize = runningServices.size();
for (int i = 0; i < servicesSize; i++)// 循环枚举对比
{
if (runningServices.get(i).service.getClassName().toString()
.equals(serviceName)) {
return true;
}
}
return false;
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
Log.d(TAG, "onDeleted");
}
@Override
public void onEnabled(Context context) {
Log.d(TAG, "onEnabled");
TwitterService.setWidgetStatus(true);
}
@Override
public void onDisabled(Context context) {
Log.d(TAG, "onDisabled");
TwitterService.setWidgetStatus(false);
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/FanfouWidget.java | Java | asf20 | 8,105 |
package com.ch_linghu.fanfoudroid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class DmActivity extends BaseActivity implements Refreshable {
private static final String TAG = "DmActivity";
// Views.
private ListView mTweetList;
private Adapter mAdapter;
private Adapter mInboxAdapter;
private Adapter mSendboxAdapter;
Button inbox;
Button sendbox;
Button newMsg;
private int mDMType;
private static final int DM_TYPE_ALL = 0;
private static final int DM_TYPE_INBOX = 1;
private static final int DM_TYPE_SENDBOX = 2;
private TextView mProgressText;
private NavBar mNavbar;
private Feedback mFeedback;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_deleting));
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mAdapter.refresh();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmDeleteTask";
}
};
private TaskListener mRetrieveTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_refreshing));
}
@Override
public void onProgressUpdate(GenericTask task, Object params) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putLong(Preferences.LAST_DM_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
draw();
goTop();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmRetrieve";
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS";
public static Intent createIntent() {
return createIntent("");
}
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState))
{
setContentView(R.layout.dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavbar.setHeaderTitle("我的私信");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
bindFooterButtonEvent();
mTweetList = (ListView) findViewById(R.id.tweet_list);
mProgressText = (TextView) findViewById(R.id.progress_text);
TwitterDatabase db = getDb();
// Mark all as read.
db.markAllDmsRead();
setupAdapter(); // Make sure call bindFooterButtonEvent first
boolean shouldRetrieve = false;
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_DM_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
// Want to be able to focus on the items with the trackball.
// That way, we can navigate up and down by changing item focus.
mTweetList.setItemsCanFocus(true);
return true;
}else{
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
private static final String SIS_RUNNING_KEY = "running";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void bindFooterButtonEvent() {
inbox = (Button) findViewById(R.id.inbox);
sendbox = (Button) findViewById(R.id.sendbox);
newMsg = (Button) findViewById(R.id.new_message);
inbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_INBOX) {
mDMType = DM_TYPE_INBOX;
inbox.setEnabled(false);
sendbox.setEnabled(true);
mTweetList.setAdapter(mInboxAdapter);
mInboxAdapter.refresh();
}
}
});
sendbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_SENDBOX) {
mDMType = DM_TYPE_SENDBOX;
inbox.setEnabled(true);
sendbox.setEnabled(false);
mTweetList.setAdapter(mSendboxAdapter);
mSendboxAdapter.refresh();
}
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(DmActivity.this, WriteDmActivity.class);
intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id
startActivity(intent);
}
});
}
private void setupAdapter() {
Cursor cursor = getDb().fetchAllDms(-1);
startManagingCursor(cursor);
mAdapter = new Adapter(this, cursor);
Cursor inboxCursor = getDb().fetchInboxDms();
startManagingCursor(inboxCursor);
mInboxAdapter = new Adapter(this, inboxCursor);
Cursor sendboxCursor = getDb().fetchSendboxDms();
startManagingCursor(sendboxCursor);
mSendboxAdapter = new Adapter(this, sendboxCursor);
mTweetList.setAdapter(mInboxAdapter);
registerForContextMenu(mTweetList);
inbox.setEnabled(false);
}
private class DmRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
List<DirectMessage> dmList;
ArrayList<Dm> dms = new ArrayList<Dm>();
TwitterDatabase db = getDb();
//ImageManager imageManager = getImageManager();
String maxId = db.fetchMaxDmId(false);
HashSet<String> imageUrls = new HashSet<String>();
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getDirectMessages(paging);
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList));
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
maxId = db.fetchMaxDmId(true);
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getSentDirectMessages(paging);
} else {
dmList = getApi().getSentDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, true);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
db.addDms(dms, false);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress(null);
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// imageManager.put(imageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
return TaskResult.OK;
}
}
private static class Adapter extends CursorAdapter {
public Adapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
// TODO: 可使用:
//DM dm = MessageTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME);
mTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT);
mIsSentColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mIsSentColumn;
private int mCreatedAtColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.direct_message, parent,
false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
int isSent = cursor.getInt(mIsSentColumn);
String user = cursor.getString(mUserTextColumn);
if (0 == isSent) {
holder.userText.setText(context
.getString(R.string.direct_message_label_from_prefix)
+ user);
} else {
holder.userText.setText(context
.getString(R.string.direct_message_label_to_prefix)
+ user);
}
TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, new ImageLoaderCallback(){
@Override
public void refresh(String url,
Bitmap bitmap) {
Adapter.this.refresh();
}
}));
}
try {
holder.metaText.setText(DateTimeHelper
.getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER
.parse(cursor.getString(mCreatedAtColumn))));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
public void refresh() {
getCursor().requery();
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除
// case OPTIONS_MENU_ID_REFRESH:
// doRetrieve();
// return true;
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
}
return super.onOptionsItemSelected(item);
}
private static final int CONTEXT_REPLY_ID = 0;
private static final int CONTEXT_DELETE_ID = 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Cursor cursor = (Cursor) mAdapter.getItem(info.position);
if (cursor == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_REPLY_ID:
String user_id = cursor.getString(cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_ID));
Intent intent = WriteDmActivity.createIntent(user_id);
startActivity(intent);
return true;
case CONTEXT_DELETE_ID:
int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID);
String id = cursor.getString(idIndex);
doDestroy(id);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void doDestroy(String id) {
Log.d(TAG, "Attempting delete.");
if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mDeleteTask = new DmDeleteTask();
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
private class DmDeleteTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
DirectMessage directMessage = getApi().destroyDirectMessage(id);
Dm.create(directMessage, false);
getDb().deleteDm(id);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mRetrieveTask = new DmRetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
public void goTop() {
mTweetList.setSelection(0);
}
public void draw() {
mAdapter.refresh();
mInboxAdapter.refresh();
mSendboxAdapter.refresh();
}
private void updateProgress(String msg) {
mProgressText.setText(msg);
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/DmActivity.java | Java | asf20 | 17,720 |
/*
* Copyright (C) 2009 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 com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
//TODO: 数据来源换成 getFavorites()
public class FavoritesActivity extends TwitterCursorBaseActivity {
private static final String TAG = "FavoritesActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private static final int DIALOG_WRITE_ID = 0;
private String userId = null;
private String userName = null;
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle(getActivityTitle());
return true;
}else{
return false;
}
}
public static Intent createNewTaskIntent(String userId, String userName) {
Intent intent = createIntent(userId, userName);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
// TODO Auto-generated method stub
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
String template = getString(R.string.page_title_favorites);
String who;
if (getUserId().equals(TwitterApplication.getMyselfId())){
who = "我";
}else{
who = getUserName();
}
return MessageFormat.format(template, who);
}
@Override
protected void markAllRead() {
// TODO Auto-generated method stub
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getFavorites(getUserId(), new Paging(maxId));
}else{
return getApi().getFavorites(getUserId());
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFavorites(getUserId(), paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_FAVORITE;
}
@Override
public String getUserId() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userId = extras.getString(USER_ID);
} else {
userId = TwitterApplication.getMyselfId();
}
return userId;
}
public String getUserName(){
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userName = extras.getString(USER_NAME);
} else {
userName = TwitterApplication.getMyselfName();
}
return userName;
}
} | 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/FavoritesActivity.java | Java | asf20 | 4,543 |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowingActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
String myself="";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName = TwitterApplication.getMyselfName();
}
if(super._onCreate(savedInstanceState)){
myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), userName));
}
return true;
}else{
return false;
}
}
/*
* 添加取消关注按钮
* @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(getUserId()==myself){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix));
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFriendsStatuses(userId, page);
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/FollowingActivity.java | Java | asf20 | 3,315 |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
*
* @author Dino 2011-02-26
*/
// public class ProfileActivity extends WithHeaderActivity {
public class ProfileActivity extends BaseActivity {
private static final String TAG = "ProfileActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE";
private static final String STATUS_COUNT = "status_count";
private static final String EXTRA_USER = "user";
private static final String FANFOUROOT = "http://fanfou.com/";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private GenericTask profileInfoTask;// 获取用户信息
private GenericTask setFollowingTask;
private GenericTask cancelFollowingTask;
private String userId;
private String userName;
private String myself;
private User profileInfo;// 用户信息
private ImageView profileImageView;// 头像
private TextView profileName;// 名称
private TextView profileScreenName;// 昵称
private TextView userLocation;// 地址
private TextView userUrl;// url
private TextView userInfo;// 自述
private TextView friendsCount;// 好友
private TextView followersCount;// 收听
private TextView statusCount;// 消息
private TextView favouritesCount;// 收藏
private TextView isFollowingText;// 是否关注
private Button followingBtn;// 收听/取消关注按钮
private Button sendMentionBtn;// 发送留言按钮
private Button sendDmBtn;// 发送私信按钮
private ProgressDialog dialog; // 请稍候
private RelativeLayout friendsLayout;
private LinearLayout followersLayout;
private LinearLayout statusesLayout;
private LinearLayout favouritesLayout;
private NavBar mNavBar;
private Feedback mFeedback;
private TwitterDatabase db;
public static Intent createIntent(String userId) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(USER_ID, userId);
return intent;
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profileImageView.setImageBitmap(bitmap);
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "OnCreate start");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.profile);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
myself = TwitterApplication.getMyselfId();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
this.userId = myself;
this.userName = TwitterApplication.getMyselfName();
}
Uri data = intent.getData();
if (data != null) {
userId = data.getLastPathSegment();
}
// 初始化控件
initControls();
Log.d(TAG, "the userid is " + userId);
db = this.getDb();
draw();
return true;
} else {
return false;
}
}
private void initControls() {
mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavBar.setHeaderTitle("");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn);
sendDmBtn = (Button) findViewById(R.id.senddm_btn);
profileImageView = (ImageView) findViewById(R.id.profileimage);
profileName = (TextView) findViewById(R.id.profilename);
profileScreenName = (TextView) findViewById(R.id.profilescreenname);
userLocation = (TextView) findViewById(R.id.user_location);
userUrl = (TextView) findViewById(R.id.user_url);
userInfo = (TextView) findViewById(R.id.tweet_user_info);
friendsCount = (TextView) findViewById(R.id.friends_count);
followersCount = (TextView) findViewById(R.id.followers_count);
TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title);
TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title);
String who;
if (userId.equals(myself)) {
who = "我";
} else {
who = "ta";
}
friendsCountTitle.setText(MessageFormat.format(
getString(R.string.profile_friends_count_title), who));
followersCountTitle.setText(MessageFormat.format(
getString(R.string.profile_followers_count_title), who));
statusCount = (TextView) findViewById(R.id.statuses_count);
favouritesCount = (TextView) findViewById(R.id.favourites_count);
friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout);
followersLayout = (LinearLayout) findViewById(R.id.followersLayout);
statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout);
favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout);
isFollowingText = (TextView) findViewById(R.id.isfollowing_text);
followingBtn = (Button) findViewById(R.id.following_btn);
// 为按钮面板添加事件
friendsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowingActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowingActivity.class);
startActivity(intent);
}
});
followersLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowersActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowersActivity.class);
startActivity(intent);
}
});
statusesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = UserTimelineActivity.createIntent(
profileInfo.getId(), showName);
launchActivity(intent);
}
});
favouritesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
Intent intent = FavoritesActivity.createIntent(userId,
profileInfo.getName());
intent.setClass(ProfileActivity.this, FavoritesActivity.class);
startActivity(intent);
}
});
// 刷新
View.OnClickListener refreshListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetProfileInfo();
}
};
mNavBar.getRefreshButton().setOnClickListener(refreshListener);
}
private void draw() {
Log.d(TAG, "draw");
bindProfileInfo();
// doGetProfileInfo();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
/**
* 从数据库获取,如果数据库不存在则创建
*/
private void bindProfileInfo() {
dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息...");
if (null != db && db.existsUser(userId)) {
Cursor cursor = db.getUserInfoById(userId);
profileInfo = User.parseUser(cursor);
cursor.close();
if (profileInfo == null) {
Log.w(TAG, "cannot get userinfo from userinfotable the id is"
+ userId);
}
bindControl();
if (dialog != null) {
dialog.dismiss();
}
} else {
doGetProfileInfo();
}
}
private void doGetProfileInfo() {
mFeedback.start("");
if (profileInfoTask != null
&& profileInfoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
profileInfoTask = new GetProfileTask();
profileInfoTask.setListener(profileInfoTaskListener);
TaskParams params = new TaskParams();
profileInfoTask.execute(params);
}
}
private void bindControl() {
if (profileInfo.getId().equals(myself)) {
sendMentionBtn.setVisibility(View.GONE);
sendDmBtn.setVisibility(View.GONE);
} else {
// 发送留言
sendMentionBtn.setVisibility(View.VISIBLE);
sendMentionBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewTweetIntent(String
.format("@%s ", profileInfo.getScreenName()));
startActivity(intent);
}
});
// 发送私信
sendDmBtn.setVisibility(View.VISIBLE);
sendDmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteDmActivity.createIntent(profileInfo
.getId());
startActivity(intent);
}
});
}
if (userId.equals(myself)) {
mNavBar.setHeaderTitle("我"
+ getString(R.string.cmenu_user_profile_prefix));
} else {
mNavBar.setHeaderTitle(profileInfo.getScreenName()
+ getString(R.string.cmenu_user_profile_prefix));
}
profileImageView
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileInfo.getProfileImageURL().toString(),
callback));
profileName.setText(profileInfo.getId());
profileScreenName.setText(profileInfo.getScreenName());
if (profileInfo.getId().equals(myself)) {
isFollowingText.setText(R.string.profile_isyou);
followingBtn.setVisibility(View.GONE);
} else if (profileInfo.isFollowing()) {
isFollowingText.setText(R.string.profile_isfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_unfollow);
followingBtn.setOnClickListener(cancelFollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_unfollow), null, null, null);
} else {
isFollowingText.setText(R.string.profile_notfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_follow);
followingBtn.setOnClickListener(setfollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_follow), null, null, null);
}
String location = profileInfo.getLocation();
if (location == null || location.length() == 0) {
location = getResources().getString(R.string.profile_location_null);
}
userLocation.setText(location);
if (profileInfo.getURL() != null) {
userUrl.setText(profileInfo.getURL().toString());
} else {
userUrl.setText(FANFOUROOT + profileInfo.getId());
}
String description = profileInfo.getDescription();
if (description == null || description.length() == 0) {
description = getResources().getString(
R.string.profile_description_null);
}
userInfo.setText(description);
friendsCount.setText(String.valueOf(profileInfo.getFriendsCount()));
followersCount.setText(String.valueOf(profileInfo.getFollowersCount()));
statusCount.setText(String.valueOf(profileInfo.getStatusesCount()));
favouritesCount
.setText(String.valueOf(profileInfo.getFavouritesCount()));
}
private TaskListener profileInfoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
// 加载成功
if (result == TaskResult.OK) {
mFeedback.success("");
// 绑定控件
bindControl();
if (dialog != null) {
dialog.dismiss();
}
}
}
@Override
public String getName() {
return "GetProfileInfo";
}
};
/**
* 更新数据库中的用户
*
* @return
*/
private boolean updateUser() {
ContentValues v = new ContentValues();
v.put(BaseColumns._ID, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName());
v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo
.getProfileImageURL().toString());
v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation());
v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription());
v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected());
v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
profileInfo.getFollowersCount());
v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource());
v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount());
v.put(UserInfoTable.FIELD_FAVORITES_COUNT,
profileInfo.getFavouritesCount());
v.put(UserInfoTable.FIELD_STATUSES_COUNT,
profileInfo.getStatusesCount());
v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing());
if (profileInfo.getURL() != null) {
v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString());
}
return db.updateUser(profileInfo.getId(), v);
}
/**
* 获取用户信息task
*
* @author Dino
*
*/
private class GetProfileTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.v(TAG, "get profile task");
try {
profileInfo = getApi().showUser(userId);
mFeedback.update(80);
if (profileInfo != null) {
if (null != db && !db.existsUser(userId)) {
com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo
.parseUser();
db.createUserInfo(userinfodb);
} else {
// 更新用户
updateUser();
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage());
return TaskResult.FAILED;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
/**
* 设置关注监听
*/
private OnClickListener setfollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/*
* 取消关注监听
*/
private OnClickListener cancelFollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("取消关注");
isFollowingText.setText(getResources().getString(
R.string.profile_isfollowing));
followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("添加关注");
isFollowingText.setText(getResources().getString(
R.string.profile_notfollowing));
followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ProfileActivity.java | Java | asf20 | 24,896 |
package com.ch_linghu.fanfoudroid.dao;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper;
import com.ch_linghu.fanfoudroid.data2.Photo;
import com.ch_linghu.fanfoudroid.data2.Status;
import com.ch_linghu.fanfoudroid.data2.User;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db2.FanContent;
import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable;
import com.ch_linghu.fanfoudroid.db2.FanDatabase;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class StatusDAO {
private static final String TAG = "StatusDAO";
private SQLiteTemplate mSqlTemplate;
public StatusDAO(Context context) {
mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context)
.getSQLiteOpenHelper());
}
/**
* Insert a Status
*
* 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空
*
* @param status
* @param isUnread
* @return
*/
public long insertStatus(Status status) {
if (!isExists(status)) {
return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME, null,
statusToContentValues(status));
} else {
Log.e(TAG, status.getId() + " is exists.");
return -1;
}
}
// TODO:
public int insertStatuses(List<Status> statuses) {
int result = 0;
SQLiteDatabase db = mSqlTemplate.getDb(true);
try {
db.beginTransaction();
for (int i = statuses.size() - 1; i >= 0; i--) {
Status status = statuses.get(i);
long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME, null,
statusToContentValues(status),
SQLiteDatabase.CONFLICT_IGNORE);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + status.toString());
} else {
++result;
Log.v(TAG, String.format(
"Insert a status into database : %s",
status.toString()));
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
/**
* Delete a status
*
* @param statusId
* @param owner_id
* owner id
* @param type
* status type
* @return
* @see StatusDAO#deleteStatus(Status)
*/
public int deleteStatus(String statusId, String owner_id, int type) {
//FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过
String where = StatusesTable.Columns.ID + " =? ";
String[] binds;
if (!TextUtils.isEmpty(owner_id)) {
where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? ";
binds = new String[] { statusId, owner_id };
} else {
binds = new String[] { statusId };
}
if (-1 != type) {
where += " AND " + StatusesPropertyTable.Columns.TYPE + " = " + type;
}
return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME, where.toString(),
binds);
}
/**
* Delete a Status
*
* @param status
* @return
* @see StatusDAO#deleteStatus(String, String, int)
*/
public int deleteStatus(Status status) {
return deleteStatus(status.getId(), status.getOwnerId(),
status.getType());
}
/**
* Find a status by status ID
*
* @param statusId
* @return
*/
public Status fetchStatus(String statusId) {
return mSqlTemplate.queryForObject(mRowMapper, StatusesTable.TABLE_NAME, null,
StatusesTable.Columns.ID + " = ?", new String[] { statusId }, null,
null, "created_at DESC", "1");
}
/**
* Find user's statuses
*
* @param userId
* user id
* @param statusType
* status type, see {@link StatusTable#TYPE_USER}...
* @return list of statuses
*/
public List<Status> fetchStatuses(String userId, int statusType) {
return mSqlTemplate.queryForList(mRowMapper, FanContent.StatusesTable.TABLE_NAME, null,
StatusesPropertyTable.Columns.OWNER_ID + " = ? AND " + StatusesPropertyTable.Columns.TYPE
+ " = " + statusType, new String[] { userId }, null,
null, "created_at DESC", null);
}
/**
* @see StatusDAO#fetchStatuses(String, int)
*/
public List<Status> fetchStatuses(String userId, String statusType) {
return fetchStatuses(userId, Integer.parseInt(statusType));
}
/**
* Update by using {@link ContentValues}
*
* @param statusId
* @param newValues
* @return
*/
public int updateStatus(String statusId, ContentValues values) {
return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME, statusId, values);
}
/**
* Update by using {@link Status}
*
* @param status
* @return
*/
public int updateStatus(Status status) {
return updateStatus(status.getId(), statusToContentValues(status));
}
/**
* Check if status exists
*
* FIXME: 取消使用Query
*
* @param status
* @return
*/
public boolean isExists(Status status) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(FanContent.StatusesTable.TABLE_NAME)
.append(" WHERE ").append(StatusesTable.Columns.ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.OWNER_ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.TYPE).append(" = ")
.append(status.getType());
return mSqlTemplate.isExistsBySQL(sql.toString(),
new String[] { status.getId(), status.getUser().getId() });
}
/**
* Status -> ContentValues
*
* @param status
* @param isUnread
* @return
*/
private ContentValues statusToContentValues(Status status) {
final ContentValues v = new ContentValues();
v.put(StatusesTable.Columns.ID, status.getId());
v.put(StatusesPropertyTable.Columns.TYPE, status.getType());
v.put(StatusesTable.Columns.TEXT, status.getText());
v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId());
v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + "");
v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO:
v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId());
v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID, status.getInReplyToUserId());
// v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME,
// status.getInReplyToScreenName());
// v.put(IS_REPLY, status.isReply());
v.put(StatusesTable.Columns.CREATED_AT,
TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt()));
v.put(StatusesTable.Columns.SOURCE, status.getSource());
// v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead());
final User user = status.getUser();
if (user != null) {
v.put(UserTable.Columns.USER_ID, user.getId());
v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName());
v.put(UserTable.Columns.PROFILE_IMAGE_URL, user.getProfileImageUrl());
}
final Photo photo = status.getPhotoUrl();
/*if (photo != null) {
v.put(StatusTable.Columns.PIC_THUMB, photo.getThumburl());
v.put(StatusTable.Columns.PIC_MID, photo.getImageurl());
v.put(StatusTable.Columns.PIC_ORIG, photo.getLargeurl());
}*/
return v;
}
private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() {
@Override
public Status mapRow(Cursor cursor, int rowNum) {
Photo photo = new Photo();
/*photo.setImageurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_MID)));
photo.setLargeurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_ORIG)));
photo.setThumburl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_THUMB)));
*/
User user = new User();
user.setScreenName(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.SCREEN_NAME)));
user.setId(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.USER_ID)));
user.setProfileImageUrl(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL)));
Status status = new Status();
status.setPhotoUrl(photo);
status.setUser(user);
status.setOwnerId(cursor.getString(cursor
.getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID)));
// TODO: 将数据库中的statusType改成Int类型
status.setType(cursor.getInt(cursor
.getColumnIndex(StatusesPropertyTable.Columns.TYPE)));
status.setId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.ID)));
status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor
.getString(cursor.getColumnIndex(StatusesTable.Columns.CREATED_AT))));
// TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 "
status.setFavorited(cursor.getString(
cursor.getColumnIndex(StatusesTable.Columns.FAVORITED))
.equals("true"));
status.setText(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.TEXT)));
status.setSource(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.SOURCE)));
// status.setInReplyToScreenName(cursor.getString(cursor
// .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME)));
status.setInReplyToStatusId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID)));
status.setInReplyToUserId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID)));
status.setTruncated(cursor.getInt(cursor
.getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0);
// status.setUnRead(cursor.getInt(cursor
// .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0);
return status;
}
};
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/dao/StatusDAO.java | Java | asf20 | 11,168 |
package com.ch_linghu.fanfoudroid.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database Helper
*
* @see SQLiteDatabase
*/
public class SQLiteTemplate {
/**
* Default Primary key
*/
protected String mPrimaryKey = "_id";
/**
* SQLiteDatabase Open Helper
*/
protected SQLiteOpenHelper mDatabaseOpenHelper;
/**
* Construct
*
* @param databaseOpenHelper
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) {
mDatabaseOpenHelper = databaseOpenHelper;
}
/**
* Construct
*
* @param databaseOpenHelper
* @param primaryKey
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) {
this(databaseOpenHelper);
setPrimaryKey(primaryKey);
}
/**
* 根据某一个字段和值删除一行数据, 如 name="jack"
*
* @param table
* @param field
* @param value
* @return
*/
public int deleteByField(String table, String field, String value) {
return getDb(true).delete(table, field + "=?", new String[] { value });
}
/**
* 根据主键删除一行数据
*
* @param table
* @param id
* @return
*/
public int deleteById(String table, String id) {
return deleteByField(table, mPrimaryKey, id);
}
/**
* 根据主键更新一行数据
*
* @param table
* @param id
* @param values
* @return
*/
public int updateById(String table, String id, ContentValues values) {
return getDb(true).update(table, values, mPrimaryKey + "=?",
new String[] { id });
}
/**
* 根据主键查看某条数据是否存在
*
* @param table
* @param id
* @return
*/
public boolean isExistsById(String table, String id) {
return isExistsByField(table, mPrimaryKey, id);
}
/**
* 根据某字段/值查看某条数据是否存在
*
* @param status
* @return
*/
public boolean isExistsByField(String table, String field, String value) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ")
.append(field).append(" =?");
return isExistsBySQL(sql.toString(), new String[] { value });
}
/**
* 使用SQL语句查看某条数据是否存在
*
* @param sql
* @param selectionArgs
* @return
*/
public boolean isExistsBySQL(String sql, String[] selectionArgs) {
boolean result = false;
final Cursor c = getDb(false).rawQuery(sql, selectionArgs);
try {
if (c.moveToFirst()) {
result = (c.getInt(0) > 0);
}
} finally {
c.close();
}
return result;
}
/**
* Query for cursor
*
* @param <T>
* @param rowMapper
* @return a cursor
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> T queryForObject(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
T object = null;
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
if (c.moveToFirst()) {
object = rowMapper.mapRow(c, c.getCount());
}
} finally {
c.close();
}
return object;
}
/**
* Query for list
*
* @param <T>
* @param rowMapper
* @return list of object
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> List<T> queryForList(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
List<T> list = new ArrayList<T>();
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
while (c.moveToNext()) {
list.add(rowMapper.mapRow(c, 1));
}
} finally {
c.close();
}
return list;
}
/**
* Get Primary Key
*
* @return
*/
public String getPrimaryKey() {
return mPrimaryKey;
}
/**
* Set Primary Key
*
* @param primaryKey
*/
public void setPrimaryKey(String primaryKey) {
this.mPrimaryKey = primaryKey;
}
/**
* Get Database Connection
*
* @param writeable
* @return
* @see SQLiteOpenHelper#getWritableDatabase();
* @see SQLiteOpenHelper#getReadableDatabase();
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mDatabaseOpenHelper.getWritableDatabase();
} else {
return mDatabaseOpenHelper.getReadableDatabase();
}
}
/**
* Some as Spring JDBC RowMapper
*
* @see org.springframework.jdbc.core.RowMapper
* @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate
* @param <T>
*/
public interface RowMapper<T> {
public T mapRow(Cursor cursor, int rowNum);
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/dao/SQLiteTemplate.java | Java | asf20 | 5,766 |
package com.ch_linghu.fanfoudroid.db2;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class FanDatabase {
private static final String TAG = FanDatabase.class.getSimpleName();
/**
* SQLite Database file name
*/
private static final String DATABASE_NAME = "fanfoudroid.db";
/**
* Database Version
*/
public static final int DATABASE_VERSION = 2;
/**
* self instance
*/
private static FanDatabase sInstance = null;
/**
* SQLiteDatabase Open Helper
*/
private DatabaseHelper mOpenHelper = null;
/**
* SQLiteOpenHelper
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// TODO: create tables
createAllTables(db);
createAllIndexes(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
// TODO: DROP TABLE
onCreate(db);
}
}
/**
* Construct
*
* @param context
*/
private FanDatabase(Context context) {
mOpenHelper = new DatabaseHelper(context);
}
/**
* Get Database
*
* @param context
* @return
*/
public static synchronized FanDatabase getInstance(Context context) {
if (null == sInstance) {
sInstance = new FanDatabase(context);
}
return sInstance;
}
/**
* Get SQLiteDatabase Open Helper
*
* @return
*/
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
/**
* Get Database Connection
*
* @param writeable
* @return
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
/**
* Close Database
*/
public void close() {
if (null != sInstance) {
mOpenHelper.close();
sInstance = null;
}
}
// Create All tables
private static void createAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateSQL());
db.execSQL(StatusesPropertyTable.getCreateSQL());
db.execSQL(UserTable.getCreateSQL());
db.execSQL(DirectMessageTable.getCreateSQL());
db.execSQL(FollowRelationshipTable.getCreateSQL());
db.execSQL(TrendTable.getCreateSQL());
db.execSQL(SavedSearchTable.getCreateSQL());
}
private static void dropAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getDropSQL());
db.execSQL(StatusesPropertyTable.getDropSQL());
db.execSQL(UserTable.getDropSQL());
db.execSQL(DirectMessageTable.getDropSQL());
db.execSQL(FollowRelationshipTable.getDropSQL());
db.execSQL(TrendTable.getDropSQL());
db.execSQL(SavedSearchTable.getDropSQL());
}
private static void resetAllTables(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
dropAllTables(db);
} catch (SQLException e) {
Log.e(TAG, "resetAllTables ERROR!");
}
createAllTables(db);
}
//indexes
private static void createAllIndexes(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateIndexSQL());
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/db2/FanDatabase.java | Java | asf20 | 3,885 |
package com.ch_linghu.fanfoudroid.db2;
import java.util.zip.CheckedOutputStream;
import android.R.color;
public abstract class FanContent {
/**
* 消息表 消息表存放消息本身
*
* @author phoenix
*
*/
public static class StatusesTable {
public static final String TABLE_NAME = "t_statuses";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String AUTHOR_ID = "author_id";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String CREATED_AT = "created_at";
public static final String TRUNCATED = "truncated";
public static final String FAVORITED = "favorited";
public static final String PHOTO_URL = "photo_url";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.AUTHOR_ID + " TEXT, "
+ Columns.TEXT + " TEXT, " + Columns.SOURCE + " TEXT, "
+ Columns.CREATED_AT + " INT, " + Columns.TRUNCATED
+ " INT DEFAULT 0, " + Columns.FAVORITED
+ " INT DEFAULT 0, " + Columns.PHOTO_URL + " TEXT, "
+ Columns.IN_REPLY_TO_STATUS_ID + " TEXT, "
+ Columns.IN_REPLY_TO_USER_ID + " TEXT, "
+ Columns.IN_REPLY_TO_SCREEN_NAME + " TEXT " + ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.AUTHOR_ID, Columns.TEXT, Columns.SOURCE,
Columns.CREATED_AT, Columns.TRUNCATED, Columns.FAVORITED,
Columns.PHOTO_URL, Columns.IN_REPLY_TO_STATUS_ID,
Columns.IN_REPLY_TO_USER_ID,
Columns.IN_REPLY_TO_SCREEN_NAME };
}
public static String getCreateIndexSQL() {
String createIndexSQL = "CREATE INDEX " + TABLE_NAME + "_idx ON "
+ TABLE_NAME + " ( " + getIndexColumns()[1] + " );";
return createIndexSQL;
}
}
/**
* 消息属性表 每一条消息所属类别、所有者等信息 消息ID(外键) 所有者(随便看看的所有者为空)
* 消息类别(随便看看/首页(自己及自己好友)/个人(仅自己)/收藏/照片)
*
* @author phoenix
*
*/
public static class StatusesPropertyTable {
public static final String TABLE_NAME = "t_statuses_property";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String OWNER_ID = "owner_id";
public static final String TYPE = "type";
public static final String SEQUENCE_FLAG = "sequence_flag";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT NOT NULL, " + Columns.OWNER_ID + " TEXT, "
+ Columns.TYPE + " INT, " + Columns.SEQUENCE_FLAG
+ " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.OWNER_ID, Columns.TYPE, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* User表 包括User的基本信息和扩展信息(每次获得最新User信息都update进User表)
* 每次更新User表时希望能更新LOAD_TIME,记录最后更新时间
*
* @author phoenix
*
*/
public static class UserTable {
public static final String TABLE_NAME = "t_user";
public static class Columns {
public static final String ID = "_id";
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
public static final String SCREEN_NAME = "screen_name";
public static final String LOCATION = "location";
public static final String DESCRIPTION = "description";
public static final String URL = "url";
public static final String PROTECTED = "protected";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String FOLLOWERS_COUNT = "followers_count";
public static final String FRIENDS_COUNT = "friends_count";
public static final String FAVOURITES_COUNT = "favourites_count";
public static final String STATUSES_COUNT = "statuses_count";
public static final String CREATED_AT = "created_at";
public static final String FOLLOWING = "following";
public static final String NOTIFICATIONS = "notifications";
public static final String UTC_OFFSET = "utc_offset";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.USER_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.USER_NAME
+ " TEXT UNIQUE NOT NULL, " + Columns.SCREEN_NAME
+ " TEXT, " + Columns.LOCATION + " TEXT, "
+ Columns.DESCRIPTION + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.PROTECTED + " INT DEFAULT 0, "
+ Columns.PROFILE_IMAGE_URL + " TEXT "
+ Columns.FOLLOWERS_COUNT + " INT, "
+ Columns.FRIENDS_COUNT + " INT, "
+ Columns.FAVOURITES_COUNT + " INT, "
+ Columns.STATUSES_COUNT + " INT, " + Columns.CREATED_AT
+ " INT, " + Columns.FOLLOWING + " INT DEFAULT 0, "
+ Columns.NOTIFICATIONS + " INT DEFAULT 0, "
+ Columns.UTC_OFFSET + " TEXT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.USER_ID,
Columns.USER_NAME, Columns.SCREEN_NAME, Columns.LOCATION,
Columns.DESCRIPTION, Columns.URL, Columns.PROTECTED,
Columns.PROFILE_IMAGE_URL, Columns.FOLLOWERS_COUNT,
Columns.FRIENDS_COUNT, Columns.FAVOURITES_COUNT,
Columns.STATUSES_COUNT, Columns.CREATED_AT,
Columns.FOLLOWING, Columns.NOTIFICATIONS,
Columns.UTC_OFFSET, Columns.LOAD_TIME };
}
}
/**
* 私信表 私信的基本信息
*
* @author phoenix
*
*/
public static class DirectMessageTable {
public static final String TABLE_NAME = "t_direct_message";
public static class Columns {
public static final String ID = "_id";
public static final String MSG_ID = "msg_id";
public static final String TEXT = "text";
public static final String SENDER_ID = "sender_id";
public static final String RECIPINET_ID = "recipinet_id";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
public static final String SEQUENCE_FLAG = "sequence_flag";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.MSG_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.TEXT + " TEXT, "
+ Columns.SENDER_ID + " TEXT, " + Columns.RECIPINET_ID
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.MSG_ID, Columns.TEXT,
Columns.SENDER_ID, Columns.RECIPINET_ID,
Columns.CREATED_AT, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* Follow关系表 某个特定用户的Follow关系(User1 following User2,
* 查找关联某人好友只需限定User1或者User2)
*
* @author phoenix
*
*/
public static class FollowRelationshipTable {
public static final String TABLE_NAME = "t_follow_relationship";
public static class Columns {
public static final String USER1_ID = "user1_id";
public static final String USER2_ID = "user2_id";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.USER1_ID
+ " TEXT, " + Columns.USER2_ID + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.USER1_ID, Columns.USER2_ID,
Columns.LOAD_TIME };
}
}
/**
* 热门话题表 记录每次查询得到的热词
*
* @author phoenix
*
*/
public static class TrendTable {
public static final String TABLE_NAME = "t_trend";
public static class Columns {
public static final String NAME = "name";
public static final String QUERY = "query";
public static final String URL = "url";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.NAME + " TEXT, "
+ Columns.QUERY + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.NAME, Columns.QUERY, Columns.URL,
Columns.LOAD_TIME };
}
}
/**
* 保存搜索表 QUERY_ID(这个ID在API删除保存搜索词时使用)
*
* @author phoenix
*
*/
public static class SavedSearchTable {
public static final String TABLE_NAME = "t_saved_search";
public static class Columns {
public static final String QUERY_ID = "query_id";
public static final String QUERY = "query";
public static final String NAME = "name";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.QUERY_ID
+ " INT, " + Columns.QUERY + " TEXT, " + Columns.NAME
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.QUERY_ID, Columns.QUERY,
Columns.NAME, Columns.CREATED_AT, Columns.LOAD_TIME };
}
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/db2/FanContent.java | Java | asf20 | 13,587 |
package com.ch_linghu.fanfoudroid.db2;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Wrapper of SQliteDatabse#query, OOP style.
*
* Usage:
* ------------------------------------------------
* Query select = new Query(SQLiteDatabase);
*
* // SELECT
* query.from("tableName", new String[] { "colName" })
* .where("id = ?", 123456)
* .where("name = ?", "jack")
* .orderBy("created_at DESC")
* .limit(1);
* Cursor cursor = query.select();
*
* // DELETE
* query.from("tableName")
* .where("id = ?", 123455);
* .delete();
*
* // UPDATE
* query.setTable("tableName")
* .values(contentValues)
* .update();
*
* // INSERT
* query.into("tableName")
* .values(contentValues)
* .insert();
* ------------------------------------------------
*
* @see SQLiteDatabase#query(String, String[], String, String[], String, String, String, String)
*/
public class Query
{
private static final String TAG = "Query-Builder";
/** TEMP list for selctionArgs */
private ArrayList<String> binds = new ArrayList<String>();
private SQLiteDatabase mDb = null;
private String mTable;
private String[] mColumns;
private String mSelection = null;
private String[] mSelectionArgs = null;
private String mGroupBy = null;
private String mHaving = null;
private String mOrderBy = null;
private String mLimit = null;
private ContentValues mValues = null;
private String mNullColumnHack = null;
public Query() { }
/**
* Construct
*
* @param db
*/
public Query(SQLiteDatabase db) {
this.setDb(db);
}
/**
* Query the given table, returning a Cursor over the result set.
*
* @param db SQLitedatabase
* @return A Cursor object, which is positioned before the first entry, or NULL
*/
public Cursor select() {
if ( preCheck() ) {
buildQuery();
return mDb.query(mTable, mColumns, mSelection, mSelectionArgs,
mGroupBy, mHaving, mOrderBy, mLimit);
} else {
//throw new SelectException("Cann't build the query . " + toString());
Log.e(TAG, "Cann't build the query " + toString());
return null;
}
}
/**
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete() {
if ( preCheck() ) {
buildQuery();
return mDb.delete(mTable, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set FROM
*
* @param table
* The table name to compile the query against.
* @param columns
* A list of which columns to return. Passing null will return
* all columns, which is discouraged to prevent reading data from
* storage that isn't going to be used.
* @return self
*
*/
public Query from(String table, String[] columns) {
mTable = table;
mColumns = columns;
return this;
}
/**
* @see Query#from(String table, String[] columns)
* @param table
* @return self
*/
public Query from(String table) {
return from(table, null); // all columns
}
/**
* Add WHERE
*
* @param selection
* A filter declaring which rows to return, formatted as an SQL
* WHERE clause (excluding the WHERE itself). Passing null will
* return all rows for the given table.
* @param selectionArgs
* You may include ?s in selection, which will be replaced by the
* values from selectionArgs, in order that they appear in the
* selection. The values will be bound as Strings.
* @return self
*/
public Query where(String selection, String[] selectionArgs) {
addSelection(selection);
binds.addAll(Arrays.asList(selectionArgs));
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection, String selectionArg) {
addSelection(selection);
binds.add(selectionArg);
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection) {
addSelection(selection);
return this;
}
/**
* add selection part
*
* @param selection
*/
private void addSelection(String selection) {
if (null == mSelection) {
mSelection = selection;
} else {
mSelection += " AND " + selection;
}
}
/**
* set HAVING
*
* @param having
* A filter declare which row groups to include in the cursor, if
* row grouping is being used, formatted as an SQL HAVING clause
* (excluding the HAVING itself). Passing null will cause all row
* groups to be included, and is required when row grouping is
* not being used.
* @return self
*/
public Query having(String having) {
this.mHaving = having;
return this;
}
/**
* Set GROUP BY
*
* @param groupBy
* A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @return self
*/
public Query groupBy(String groupBy) {
this.mGroupBy = groupBy;
return this;
}
/**
* Set ORDER BY
*
* @param orderBy
* How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @return self
*/
public Query orderBy(String orderBy) {
this.mOrderBy = orderBy;
return this;
}
/**
* @param limit
* Limits the number of rows returned by the query, formatted as
* LIMIT clause. Passing null denotes no LIMIT clause.
* @return self
*/
public Query limit(String limit) {
this.mLimit = limit;
return this;
}
/**
* @see Query#limit(String limit)
*/
public Query limit(int limit) {
return limit(limit + "");
}
/**
* Merge selectionArgs
*/
private void buildQuery() {
mSelectionArgs = new String[binds.size()];
binds.toArray(mSelectionArgs);
Log.v(TAG, toString());
}
private boolean preCheck() {
return (mTable != null && mDb != null);
}
// For Insert
/**
* set insert table
*
* @param table table name
* @return self
*/
public Query into(String table) {
return setTable(table);
}
/**
* Set new values
*
* @param values new values
* @return self
*/
public Query values(ContentValues values) {
mValues = values;
return this;
}
/**
* Insert a row
*
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert() {
return mDb.insert(mTable, mNullColumnHack, mValues);
}
// For update
/**
* Set target table
*
* @param table table name
* @return self
*/
public Query setTable(String table) {
mTable = table;
return this;
}
/**
* Update a row
*
* @return the number of rows affected, or -1 if an error occurred
*/
public int update() {
if ( preCheck() ) {
buildQuery();
return mDb.update(mTable, mValues, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set back-end database
* @param db
*/
public void setDb(SQLiteDatabase db) {
if (null == this.mDb) {
this.mDb = db;
}
}
@Override
public String toString() {
return "Query [table=" + mTable + ", columns="
+ Arrays.toString(mColumns) + ", selection=" + mSelection
+ ", selectionArgs=" + Arrays.toString(mSelectionArgs)
+ ", groupBy=" + mGroupBy + ", having=" + mHaving + ", orderBy="
+ mOrderBy + "]";
}
/** for debug */
public ContentValues getContentValues() {
return mValues;
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/db2/Query.java | Java | asf20 | 9,118 |
package com.ch_linghu.fanfoudroid.http;
import java.util.HashMap;
import java.util.Map;
public class HTMLEntity {
public static String escape(String original) {
StringBuffer buf = new StringBuffer(original);
escape(buf);
return buf.toString();
}
public static void escape(StringBuffer original) {
int index = 0;
String escaped;
while (index < original.length()) {
escaped = entityEscapeMap.get(original.substring(index, index + 1));
if (null != escaped) {
original.replace(index, index + 1, escaped);
index += escaped.length();
} else {
index++;
}
}
}
public static String unescape(String original) {
StringBuffer buf = new StringBuffer(original);
unescape(buf);
return buf.toString();
}
public static void unescape(StringBuffer original) {
int index = 0;
int semicolonIndex = 0;
String escaped;
String entity;
while (index < original.length()) {
index = original.indexOf("&", index);
if (-1 == index) {
break;
}
semicolonIndex = original.indexOf(";", index);
if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) {
escaped = original.substring(index, semicolonIndex + 1);
entity = escapeEntityMap.get(escaped);
if (null != entity) {
original.replace(index, semicolonIndex + 1, entity);
}
index++;
} else {
break;
}
}
}
private static Map<String, String> entityEscapeMap = new HashMap<String, String>();
private static Map<String, String> escapeEntityMap = new HashMap<String, String>();
static {
String[][] entities =
{{" ", " "/* no-break space = non-breaking space */, "\u00A0"}
, {"¡", "¡"/* inverted exclamation mark */, "\u00A1"}
, {"¢", "¢"/* cent sign */, "\u00A2"}
, {"£", "£"/* pound sign */, "\u00A3"}
, {"¤", "¤"/* currency sign */, "\u00A4"}
, {"¥", "¥"/* yen sign = yuan sign */, "\u00A5"}
, {"¦", "¦"/* broken bar = broken vertical bar */, "\u00A6"}
, {"§", "§"/* section sign */, "\u00A7"}
, {"¨", "¨"/* diaeresis = spacing diaeresis */, "\u00A8"}
, {"©", "©"/* copyright sign */, "\u00A9"}
, {"ª", "ª"/* feminine ordinal indicator */, "\u00AA"}
, {"«", "«"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"}
, {"¬", "¬"/* not sign = discretionary hyphen */, "\u00AC"}
, {"­", "­"/* soft hyphen = discretionary hyphen */, "\u00AD"}
, {"®", "®"/* registered sign = registered trade mark sign */, "\u00AE"}
, {"¯", "¯"/* macron = spacing macron = overline = APL overbar */, "\u00AF"}
, {"°", "°"/* degree sign */, "\u00B0"}
, {"±", "±"/* plus-minus sign = plus-or-minus sign */, "\u00B1"}
, {"²", "²"/* superscript two = superscript digit two = squared */, "\u00B2"}
, {"³", "³"/* superscript three = superscript digit three = cubed */, "\u00B3"}
, {"´", "´"/* acute accent = spacing acute */, "\u00B4"}
, {"µ", "µ"/* micro sign */, "\u00B5"}
, {"¶", "¶"/* pilcrow sign = paragraph sign */, "\u00B6"}
, {"·", "·"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"}
, {"¸", "¸"/* cedilla = spacing cedilla */, "\u00B8"}
, {"¹", "¹"/* superscript one = superscript digit one */, "\u00B9"}
, {"º", "º"/* masculine ordinal indicator */, "\u00BA"}
, {"»", "»"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"}
, {"¼", "¼"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"}
, {"½", "½"/* vulgar fraction one half = fraction one half */, "\u00BD"}
, {"¾", "¾"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"}
, {"¿", "¿"/* inverted question mark = turned question mark */, "\u00BF"}
, {"À", "À"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"}
, {"Á", "Á"/* latin capital letter A with acute */, "\u00C1"}
, {"Â", "Â"/* latin capital letter A with circumflex */, "\u00C2"}
, {"Ã", "Ã"/* latin capital letter A with tilde */, "\u00C3"}
, {"Ä", "Ä"/* latin capital letter A with diaeresis */, "\u00C4"}
, {"Å", "Å"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"}
, {"Æ", "Æ"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"}
, {"Ç", "Ç"/* latin capital letter C with cedilla */, "\u00C7"}
, {"È", "È"/* latin capital letter E with grave */, "\u00C8"}
, {"É", "É"/* latin capital letter E with acute */, "\u00C9"}
, {"Ê", "Ê"/* latin capital letter E with circumflex */, "\u00CA"}
, {"Ë", "Ë"/* latin capital letter E with diaeresis */, "\u00CB"}
, {"Ì", "Ì"/* latin capital letter I with grave */, "\u00CC"}
, {"Í", "Í"/* latin capital letter I with acute */, "\u00CD"}
, {"Î", "Î"/* latin capital letter I with circumflex */, "\u00CE"}
, {"Ï", "Ï"/* latin capital letter I with diaeresis */, "\u00CF"}
, {"Ð", "Ð"/* latin capital letter ETH */, "\u00D0"}
, {"Ñ", "Ñ"/* latin capital letter N with tilde */, "\u00D1"}
, {"Ò", "Ò"/* latin capital letter O with grave */, "\u00D2"}
, {"Ó", "Ó"/* latin capital letter O with acute */, "\u00D3"}
, {"Ô", "Ô"/* latin capital letter O with circumflex */, "\u00D4"}
, {"Õ", "Õ"/* latin capital letter O with tilde */, "\u00D5"}
, {"Ö", "Ö"/* latin capital letter O with diaeresis */, "\u00D6"}
, {"×", "×"/* multiplication sign */, "\u00D7"}
, {"Ø", "Ø"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"}
, {"Ù", "Ù"/* latin capital letter U with grave */, "\u00D9"}
, {"Ú", "Ú"/* latin capital letter U with acute */, "\u00DA"}
, {"Û", "Û"/* latin capital letter U with circumflex */, "\u00DB"}
, {"Ü", "Ü"/* latin capital letter U with diaeresis */, "\u00DC"}
, {"Ý", "Ý"/* latin capital letter Y with acute */, "\u00DD"}
, {"Þ", "Þ"/* latin capital letter THORN */, "\u00DE"}
, {"ß", "ß"/* latin small letter sharp s = ess-zed */, "\u00DF"}
, {"à", "à"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"}
, {"á", "á"/* latin small letter a with acute */, "\u00E1"}
, {"â", "â"/* latin small letter a with circumflex */, "\u00E2"}
, {"ã", "ã"/* latin small letter a with tilde */, "\u00E3"}
, {"ä", "ä"/* latin small letter a with diaeresis */, "\u00E4"}
, {"å", "å"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"}
, {"æ", "æ"/* latin small letter ae = latin small ligature ae */, "\u00E6"}
, {"ç", "ç"/* latin small letter c with cedilla */, "\u00E7"}
, {"è", "è"/* latin small letter e with grave */, "\u00E8"}
, {"é", "é"/* latin small letter e with acute */, "\u00E9"}
, {"ê", "ê"/* latin small letter e with circumflex */, "\u00EA"}
, {"ë", "ë"/* latin small letter e with diaeresis */, "\u00EB"}
, {"ì", "ì"/* latin small letter i with grave */, "\u00EC"}
, {"í", "í"/* latin small letter i with acute */, "\u00ED"}
, {"î", "î"/* latin small letter i with circumflex */, "\u00EE"}
, {"ï", "ï"/* latin small letter i with diaeresis */, "\u00EF"}
, {"ð", "ð"/* latin small letter eth */, "\u00F0"}
, {"ñ", "ñ"/* latin small letter n with tilde */, "\u00F1"}
, {"ò", "ò"/* latin small letter o with grave */, "\u00F2"}
, {"ó", "ó"/* latin small letter o with acute */, "\u00F3"}
, {"ô", "ô"/* latin small letter o with circumflex */, "\u00F4"}
, {"õ", "õ"/* latin small letter o with tilde */, "\u00F5"}
, {"ö", "ö"/* latin small letter o with diaeresis */, "\u00F6"}
, {"÷", "÷"/* division sign */, "\u00F7"}
, {"ø", "ø"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"}
, {"ù", "ù"/* latin small letter u with grave */, "\u00F9"}
, {"ú", "ú"/* latin small letter u with acute */, "\u00FA"}
, {"û", "û"/* latin small letter u with circumflex */, "\u00FB"}
, {"ü", "ü"/* latin small letter u with diaeresis */, "\u00FC"}
, {"ý", "ý"/* latin small letter y with acute */, "\u00FD"}
, {"þ", "þ"/* latin small letter thorn with */, "\u00FE"}
, {"ÿ", "ÿ"/* latin small letter y with diaeresis */, "\u00FF"}
, {"ƒ", "ƒ"/* latin small f with hook = function = florin */, "\u0192"}
/* Greek */
, {"Α", "Α"/* greek capital letter alpha */, "\u0391"}
, {"Β", "Β"/* greek capital letter beta */, "\u0392"}
, {"Γ", "Γ"/* greek capital letter gamma */, "\u0393"}
, {"Δ", "Δ"/* greek capital letter delta */, "\u0394"}
, {"Ε", "Ε"/* greek capital letter epsilon */, "\u0395"}
, {"Ζ", "Ζ"/* greek capital letter zeta */, "\u0396"}
, {"Η", "Η"/* greek capital letter eta */, "\u0397"}
, {"Θ", "Θ"/* greek capital letter theta */, "\u0398"}
, {"Ι", "Ι"/* greek capital letter iota */, "\u0399"}
, {"Κ", "Κ"/* greek capital letter kappa */, "\u039A"}
, {"Λ", "Λ"/* greek capital letter lambda */, "\u039B"}
, {"Μ", "Μ"/* greek capital letter mu */, "\u039C"}
, {"Ν", "Ν"/* greek capital letter nu */, "\u039D"}
, {"Ξ", "Ξ"/* greek capital letter xi */, "\u039E"}
, {"Ο", "Ο"/* greek capital letter omicron */, "\u039F"}
, {"Π", "Π"/* greek capital letter pi */, "\u03A0"}
, {"Ρ", "Ρ"/* greek capital letter rho */, "\u03A1"}
/* there is no Sigmaf and no \u03A2 */
, {"Σ", "Σ"/* greek capital letter sigma */, "\u03A3"}
, {"Τ", "Τ"/* greek capital letter tau */, "\u03A4"}
, {"Υ", "Υ"/* greek capital letter upsilon */, "\u03A5"}
, {"Φ", "Φ"/* greek capital letter phi */, "\u03A6"}
, {"Χ", "Χ"/* greek capital letter chi */, "\u03A7"}
, {"Ψ", "Ψ"/* greek capital letter psi */, "\u03A8"}
, {"Ω", "Ω"/* greek capital letter omega */, "\u03A9"}
, {"α", "α"/* greek small letter alpha */, "\u03B1"}
, {"β", "β"/* greek small letter beta */, "\u03B2"}
, {"γ", "γ"/* greek small letter gamma */, "\u03B3"}
, {"δ", "δ"/* greek small letter delta */, "\u03B4"}
, {"ε", "ε"/* greek small letter epsilon */, "\u03B5"}
, {"ζ", "ζ"/* greek small letter zeta */, "\u03B6"}
, {"η", "η"/* greek small letter eta */, "\u03B7"}
, {"θ", "θ"/* greek small letter theta */, "\u03B8"}
, {"ι", "ι"/* greek small letter iota */, "\u03B9"}
, {"κ", "κ"/* greek small letter kappa */, "\u03BA"}
, {"λ", "λ"/* greek small letter lambda */, "\u03BB"}
, {"μ", "μ"/* greek small letter mu */, "\u03BC"}
, {"ν", "ν"/* greek small letter nu */, "\u03BD"}
, {"ξ", "ξ"/* greek small letter xi */, "\u03BE"}
, {"ο", "ο"/* greek small letter omicron */, "\u03BF"}
, {"π", "π"/* greek small letter pi */, "\u03C0"}
, {"ρ", "ρ"/* greek small letter rho */, "\u03C1"}
, {"ς", "ς"/* greek small letter final sigma */, "\u03C2"}
, {"σ", "σ"/* greek small letter sigma */, "\u03C3"}
, {"τ", "τ"/* greek small letter tau */, "\u03C4"}
, {"υ", "υ"/* greek small letter upsilon */, "\u03C5"}
, {"φ", "φ"/* greek small letter phi */, "\u03C6"}
, {"χ", "χ"/* greek small letter chi */, "\u03C7"}
, {"ψ", "ψ"/* greek small letter psi */, "\u03C8"}
, {"ω", "ω"/* greek small letter omega */, "\u03C9"}
, {"ϑ", "ϑ"/* greek small letter theta symbol */, "\u03D1"}
, {"ϒ", "ϒ"/* greek upsilon with hook symbol */, "\u03D2"}
, {"ϖ", "ϖ"/* greek pi symbol */, "\u03D6"}
/* General Punctuation */
, {"•", "•"/* bullet = black small circle */, "\u2022"}
/* bullet is NOT the same as bullet operator ,"\u2219*/
, {"…", "…"/* horizontal ellipsis = three dot leader */, "\u2026"}
, {"′", "′"/* prime = minutes = feet */, "\u2032"}
, {"″", "″"/* double prime = seconds = inches */, "\u2033"}
, {"‾", "‾"/* overline = spacing overscore */, "\u203E"}
, {"⁄", "⁄"/* fraction slash */, "\u2044"}
/* Letterlike Symbols */
, {"℘", "℘"/* script capital P = power set = Weierstrass p */, "\u2118"}
, {"ℑ", "ℑ"/* blackletter capital I = imaginary part */, "\u2111"}
, {"ℜ", "ℜ"/* blackletter capital R = real part symbol */, "\u211C"}
, {"™", "™"/* trade mark sign */, "\u2122"}
, {"ℵ", "ℵ"/* alef symbol = first transfinite cardinal */, "\u2135"}
/* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/
/* Arrows */
, {"←", "←"/* leftwards arrow */, "\u2190"}
, {"↑", "↑"/* upwards arrow */, "\u2191"}
, {"→", "→"/* rightwards arrow */, "\u2192"}
, {"↓", "↓"/* downwards arrow */, "\u2193"}
, {"↔", "↔"/* left right arrow */, "\u2194"}
, {"↵", "↵"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"}
, {"⇐", "⇐"/* leftwards double arrow */, "\u21D0"}
/* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */
, {"⇑", "⇑"/* upwards double arrow */, "\u21D1"}
, {"⇒", "⇒"/* rightwards double arrow */, "\u21D2"}
/* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */
, {"⇓", "⇓"/* downwards double arrow */, "\u21D3"}
, {"⇔", "⇔"/* left right double arrow */, "\u21D4"}
/* Mathematical Operators */
, {"∀", "∀"/* for all */, "\u2200"}
, {"∂", "∂"/* partial differential */, "\u2202"}
, {"∃", "∃"/* there exists */, "\u2203"}
, {"∅", "∅"/* empty set = null set = diameter */, "\u2205"}
, {"∇", "∇"/* nabla = backward difference */, "\u2207"}
, {"∈", "∈"/* element of */, "\u2208"}
, {"∉", "∉"/* not an element of */, "\u2209"}
, {"∋", "∋"/* contains as member */, "\u220B"}
/* should there be a more memorable name than 'ni'? */
, {"∏", "∏"/* n-ary product = product sign */, "\u220F"}
/* prod is NOT the same character as ,"\u03A0"}*/
, {"∑", "∑"/* n-ary sumation */, "\u2211"}
/* sum is NOT the same character as ,"\u03A3"}*/
, {"−", "−"/* minus sign */, "\u2212"}
, {"∗", "∗"/* asterisk operator */, "\u2217"}
, {"√", "√"/* square root = radical sign */, "\u221A"}
, {"∝", "∝"/* proportional to */, "\u221D"}
, {"∞", "∞"/* infinity */, "\u221E"}
, {"∠", "∠"/* angle */, "\u2220"}
, {"∧", "∧"/* logical and = wedge */, "\u2227"}
, {"∨", "∨"/* logical or = vee */, "\u2228"}
, {"∩", "∩"/* intersection = cap */, "\u2229"}
, {"∪", "∪"/* union = cup */, "\u222A"}
, {"∫", "∫"/* integral */, "\u222B"}
, {"∴", "∴"/* therefore */, "\u2234"}
, {"∼", "∼"/* tilde operator = varies with = similar to */, "\u223C"}
/* tilde operator is NOT the same character as the tilde ,"\u007E"}*/
, {"≅", "≅"/* approximately equal to */, "\u2245"}
, {"≈", "≈"/* almost equal to = asymptotic to */, "\u2248"}
, {"≠", "≠"/* not equal to */, "\u2260"}
, {"≡", "≡"/* identical to */, "\u2261"}
, {"≤", "≤"/* less-than or equal to */, "\u2264"}
, {"≥", "≥"/* greater-than or equal to */, "\u2265"}
, {"⊂", "⊂"/* subset of */, "\u2282"}
, {"⊃", "⊃"/* superset of */, "\u2283"}
/* note that nsup 'not a superset of ,"\u2283"}*/
, {"⊆", "⊆"/* subset of or equal to */, "\u2286"}
, {"⊇", "⊇"/* superset of or equal to */, "\u2287"}
, {"⊕", "⊕"/* circled plus = direct sum */, "\u2295"}
, {"⊗", "⊗"/* circled times = vector product */, "\u2297"}
, {"⊥", "⊥"/* up tack = orthogonal to = perpendicular */, "\u22A5"}
, {"⋅", "⋅"/* dot operator */, "\u22C5"}
/* dot operator is NOT the same character as ,"\u00B7"}
/* Miscellaneous Technical */
, {"⌈", "⌈"/* left ceiling = apl upstile */, "\u2308"}
, {"⌉", "⌉"/* right ceiling */, "\u2309"}
, {"⌊", "⌊"/* left floor = apl downstile */, "\u230A"}
, {"⌋", "⌋"/* right floor */, "\u230B"}
, {"⟨", "〈"/* left-pointing angle bracket = bra */, "\u2329"}
/* lang is NOT the same character as ,"\u003C"}*/
, {"⟩", "〉"/* right-pointing angle bracket = ket */, "\u232A"}
/* rang is NOT the same character as ,"\u003E"}*/
/* Geometric Shapes */
, {"◊", "◊"/* lozenge */, "\u25CA"}
/* Miscellaneous Symbols */
, {"♠", "♠"/* black spade suit */, "\u2660"}
/* black here seems to mean filled as opposed to hollow */
, {"♣", "♣"/* black club suit = shamrock */, "\u2663"}
, {"♥", "♥"/* black heart suit = valentine */, "\u2665"}
, {"♦", "♦"/* black diamond suit */, "\u2666"}
, {""", """ /* quotation mark = APL quote */, "\""}
, {"&", "&" /* ampersand */, "\u0026"}
, {"<", "<" /* less-than sign */, "\u003C"}
, {">", ">" /* greater-than sign */, "\u003E"}
/* Latin Extended-A */
, {"Œ", "Œ" /* latin capital ligature OE */, "\u0152"}
, {"œ", "œ" /* latin small ligature oe */, "\u0153"}
/* ligature is a misnomer this is a separate character in some languages */
, {"Š", "Š" /* latin capital letter S with caron */, "\u0160"}
, {"š", "š" /* latin small letter s with caron */, "\u0161"}
, {"Ÿ", "Ÿ" /* latin capital letter Y with diaeresis */, "\u0178"}
/* Spacing Modifier Letters */
, {"ˆ", "ˆ" /* modifier letter circumflex accent */, "\u02C6"}
, {"˜", "˜" /* small tilde */, "\u02DC"}
/* General Punctuation */
, {" ", " "/* en space */, "\u2002"}
, {" ", " "/* em space */, "\u2003"}
, {" ", " "/* thin space */, "\u2009"}
, {"‌", "‌"/* zero width non-joiner */, "\u200C"}
, {"‍", "‍"/* zero width joiner */, "\u200D"}
, {"‎", "‎"/* left-to-right mark */, "\u200E"}
, {"‏", "‏"/* right-to-left mark */, "\u200F"}
, {"–", "–"/* en dash */, "\u2013"}
, {"—", "—"/* em dash */, "\u2014"}
, {"‘", "‘"/* left single quotation mark */, "\u2018"}
, {"’", "’"/* right single quotation mark */, "\u2019"}
, {"‚", "‚"/* single low-9 quotation mark */, "\u201A"}
, {"“", "“"/* left double quotation mark */, "\u201C"}
, {"”", "”"/* right double quotation mark */, "\u201D"}
, {"„", "„"/* double low-9 quotation mark */, "\u201E"}
, {"†", "†"/* dagger */, "\u2020"}
, {"‡", "‡"/* double dagger */, "\u2021"}
, {"‰", "‰"/* per mille sign */, "\u2030"}
, {"‹", "‹"/* single left-pointing angle quotation mark */, "\u2039"}
/* lsaquo is proposed but not yet ISO standardized */
, {"›", "›"/* single right-pointing angle quotation mark */, "\u203A"}
/* rsaquo is proposed but not yet ISO standardized */
, {"€", "€" /* euro sign */, "\u20AC"}};
for (String[] entity : entities) {
entityEscapeMap.put(entity[2], entity[0]);
escapeEntityMap.put(entity[0], entity[2]);
escapeEntityMap.put(entity[1], entity[2]);
}
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/http/HTMLEntity.java | Java | asf20 | 26,524 |
package com.ch_linghu.fanfoudroid.http;
/**
* HTTP StatusCode is not 200
*/
public class HttpException extends Exception {
private int statusCode = -1;
public HttpException(String msg) {
super(msg);
}
public HttpException(Exception cause) {
super(cause);
}
public HttpException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public HttpException(String msg, Exception cause) {
super(msg, cause);
}
public HttpException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/http/HttpException.java | Java | asf20 | 741 |
package com.ch_linghu.fanfoudroid.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.CharArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import android.util.Log;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
public class Response {
private final HttpResponse mResponse;
private boolean mStreamConsumed = false;
public Response(HttpResponse res) {
mResponse = res;
}
/**
* Convert Response to inputStream
*
* @return InputStream or null
* @throws ResponseException
*/
public InputStream asStream() throws ResponseException {
try {
final HttpEntity entity = mResponse.getEntity();
if (entity != null) {
return entity.getContent();
}
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
return null;
}
/**
* @deprecated use entity.getContent();
* @param entity
* @return
* @throws ResponseException
*/
private InputStream asStream(HttpEntity entity) throws ResponseException {
if (null == entity) {
return null;
}
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
//mResponse = null;
return is;
}
/**
* Convert Response to Context String
*
* @return response context string or null
* @throws ResponseException
*/
public String asString() throws ResponseException {
try {
return entityToString(mResponse.getEntity());
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
}
/**
* EntityUtils.toString(entity, "UTF-8");
*
* @param entity
* @return
* @throws IOException
* @throws ResponseException
*/
private String entityToString(final HttpEntity entity) throws IOException, ResponseException {
DebugTimer.betweenStart("AS STRING");
if (null == entity) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
//InputStream instream = asStream(entity);
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int) entity.getContentLength();
if (i < 0) {
i = 4096;
}
Log.i("LDS", i + " content length");
Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
CharArrayBuffer buffer = new CharArrayBuffer(i);
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
DebugTimer.betweenEnd("AS STRING");
return buffer.toString();
}
/**
* @deprecated use entityToString()
* @param in
* @return
* @throws ResponseException
*/
private String inputStreamToString(final InputStream in) throws IOException {
if (null == in) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer buf = new StringBuffer();
try {
char[] buffer = new char[1024];
while ((reader.read(buffer)) != -1) {
buf.append(buffer);
}
return buf.toString();
} finally {
if (reader != null) {
reader.close();
setStreamConsumed(true);
}
}
}
public JSONObject asJSONObject() throws ResponseException {
try {
return new JSONObject(asString());
} catch (JSONException jsone) {
throw new ResponseException(jsone.getMessage() + ":"
+ asString(), jsone);
}
}
public JSONArray asJSONArray() throws ResponseException {
try {
return new JSONArray(asString());
} catch (Exception jsone) {
throw new ResponseException(jsone.getMessage(), jsone);
}
}
private void setStreamConsumed(boolean mStreamConsumed) {
this.mStreamConsumed = mStreamConsumed;
}
public boolean isStreamConsumed() {
return mStreamConsumed;
}
/**
* @deprecated
* @return
*/
public Document asDocument() {
// TODO Auto-generated method stub
return null;
}
private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});");
/**
* Unescape UTF-8 escaped characters to string.
* @author pengjianq...@gmail.com
*
* @param original The string to be unescaped.
* @return The unescaped string
*/
public static String unescape(String original) {
Matcher mm = escaped.matcher(original);
StringBuffer unescaped = new StringBuffer();
while (mm.find()) {
mm.appendReplacement(unescaped, Character.toString(
(char) Integer.parseInt(mm.group(1), 10)));
}
mm.appendTail(unescaped);
return unescaped.toString();
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/http/Response.java | Java | asf20 | 6,106 |
package com.ch_linghu.fanfoudroid.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* Wrap of org.apache.http.impl.client.DefaultHttpClient
*
* @author lds
*
*/
public class HttpClient {
private static final String TAG = "HttpClient";
private final static boolean DEBUG = Configuration.getDebug();
/** OK: Success! */
public static final int OK = 200;
/** Not Modified: There was no new data to return. */
public static final int NOT_MODIFIED = 304;
/** Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. */
public static final int BAD_REQUEST = 400;
/** Not Authorized: Authentication credentials were missing or incorrect. */
public static final int NOT_AUTHORIZED = 401;
/** Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. */
public static final int FORBIDDEN = 403;
/** Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. */
public static final int NOT_FOUND = 404;
/** Not Acceptable: Returned by the Search API when an invalid format is specified in the request. */
public static final int NOT_ACCEPTABLE = 406;
/** Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. */
public static final int INTERNAL_SERVER_ERROR = 500;
/** Bad Gateway: Weibo is down or being upgraded. */
public static final int BAD_GATEWAY = 502;
/** Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. */
public static final int SERVICE_UNAVAILABLE = 503;
private static final int CONNECTION_TIMEOUT_MS = 30 * 1000;
private static final int SOCKET_TIMEOUT_MS = 30 * 1000;
public static final int RETRIEVE_LIMIT = 20;
public static final int RETRIED_TIME = 3;
private static final String SERVER_HOST = "api.fanfou.com";
private DefaultHttpClient mClient;
private AuthScope mAuthScope;
private BasicHttpContext localcontext;
private String mUserId;
private String mPassword;
private static boolean isAuthenticationEnabled = false;
public HttpClient() {
prepareHttpClient();
}
/**
* @param user_id auth user
* @param password auth password
*/
public HttpClient(String user_id, String password) {
prepareHttpClient();
setCredentials(user_id, password);
}
/**
* Empty the credentials
*/
public void reset() {
setCredentials("", "");
}
/**
* @return authed user id
*/
public String getUserId() {
return mUserId;
}
/**
* @return authed user password
*/
public String getPassword() {
return mPassword;
}
/**
* @param hostname the hostname (IP or DNS name)
* @param port the port number. -1 indicates the scheme default port.
* @param scheme the name of the scheme. null indicates the default scheme
*/
public void setProxy(String host, int port, String scheme) {
HttpHost proxy = new HttpHost(host, port, scheme);
mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
public void removeProxy() {
mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
}
private void enableDebug() {
Log.d(TAG, "enable apache.http debug");
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINER);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
/*
System.setProperty("log.tag.org.apache.http", "VERBOSE");
System.setProperty("log.tag.org.apache.http.wire", "VERBOSE");
System.setProperty("log.tag.org.apache.http.headers", "VERBOSE");
在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息:
> adb shell setprop log.tag.org.apache.http VERBOSE
> adb shell setprop log.tag.org.apache.http.wire VERBOSE
> adb shell setprop log.tag.org.apache.http.headers VERBOSE
*/
}
/**
* Setup DefaultHttpClient
*
* Use ThreadSafeClientConnManager.
*
*/
private void prepareHttpClient() {
if (DEBUG) {
enableDebug();
}
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// Create an HttpClient with the ThreadSafeClientConnManager.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,
schemeRegistry);
mClient = new DefaultHttpClient(cm, params);
// Setup BasicAuth
BasicScheme basicScheme = new BasicScheme();
mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT);
// mClient.setAuthSchemes(authRegistry);
mClient.setCredentialsProvider(new BasicCredentialsProvider());
// Generate BASIC scheme object and stick it to the local
// execution context
localcontext = new BasicHttpContext();
localcontext.setAttribute("preemptive-auth", basicScheme);
// first request interceptor
mClient.addRequestInterceptor(preemptiveAuth, 0);
// Support GZIP
mClient.addResponseInterceptor(gzipResponseIntercepter);
// TODO: need to release this connection in httpRequest()
// cm.releaseConnection(conn, validDuration, timeUnit);
//httpclient.getConnectionManager().shutdown();
}
/**
* HttpRequestInterceptor for DefaultHttpClient
*/
private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(),
targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
private static HttpResponseInterceptor gzipResponseIntercepter =
new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context)
throws org.apache.http.HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
};
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
/**
* Setup Credentials for HTTP Basic Auth
*
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
mUserId = username;
mPassword = password;
mClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(username, password));
isAuthenticationEnabled = true;
}
public Response post(String url, ArrayList<BasicNameValuePair> postParams,
boolean authenticated) throws HttpException {
if (null == postParams) {
postParams = new ArrayList<BasicNameValuePair>();
}
return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpPost.METHOD_NAME);
}
public Response post(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url) throws HttpException {
return httpRequest(url, null, false, HttpPost.METHOD_NAME);
}
public Response post(String url, File file) throws HttpException {
return httpRequest(url, null, file, false, HttpPost.METHOD_NAME);
}
/**
* POST一个文件
*
* @param url
* @param file
* @param authenticate
* @return
* @throws HttpException
*/
public Response post(String url, File file, boolean authenticate)
throws HttpException {
return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params,
boolean authenticated) throws HttpException {
return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpGet.METHOD_NAME);
}
public Response get(String url) throws HttpException {
return httpRequest(url, null, false, HttpGet.METHOD_NAME);
}
public Response get(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME);
}
public Response httpRequest(String url,
ArrayList<BasicNameValuePair> postParams, boolean authenticated,
String httpMethod) throws HttpException {
return httpRequest(url, postParams, null, authenticated, httpMethod);
}
/**
* Execute the DefaultHttpClient
*
* @param url
* target
* @param postParams
* @param file
* can be NULL
* @param authenticated
* need or not
* @param httpMethod
* HttpPost.METHOD_NAME
* HttpGet.METHOD_NAME
* HttpDelete.METHOD_NAME
* @return Response from server
* @throws HttpException 此异常包装了一系列底层异常 <br /><br />
* 1. 底层异常, 可使用getCause()查看: <br />
* <li>URISyntaxException, 由`new URI` 引发的.</li>
* <li>IOException, 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li>
* <li>IOException和ClientProtocolException, 由`HttpClient.execute` 引发的.</li><br />
*
* 2. 当响应码不为200时报出的各种子类异常:
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams,
File file, boolean authenticated, String httpMethod) throws HttpException {
Log.d(TAG, "Sending " + httpMethod + " request to " + url);
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("HTTP");
}
URI uri = createURI(url);
HttpResponse response = null;
Response res = null;
HttpUriRequest method = null;
// Create POST, GET or DELETE METHOD
method = createMethod(httpMethod, uri, file, postParams);
// Setup ConnectionParams, Request Headers
SetupHTTPConnectionParams(method);
// Execute Request
try {
response = mClient.execute(method, localcontext);
res = new Response(response);
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException(e.getMessage(), e);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
// It will throw a weiboException while status code is not 200
HandleResponseStatusCode(statusCode, res);
} else {
Log.e(TAG, "response is null");
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("HTTP");
}
return res;
}
/**
* CreateURI from URL string
*
* @param url
* @return request URI
* @throws HttpException
* Cause by URISyntaxException
*/
private URI createURI(String url) throws HttpException {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException("Invalid URL.");
}
return uri;
}
/**
* 创建可带一个File的MultipartEntity
*
* @param filename
* 文件名
* @param file
* 文件
* @param postParams
* 其他POST参数
* @return 带文件和其他参数的Entity
* @throws UnsupportedEncodingException
*/
private MultipartEntity createMultipartEntity(String filename, File file,
ArrayList<BasicNameValuePair> postParams)
throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
// Don't try this. Server does not appear to support chunking.
// entity.addPart("media", new InputStreamBody(imageStream, "media"));
entity.addPart(filename, new FileBody(file));
for (BasicNameValuePair param : postParams) {
entity.addPart(param.getName(), new StringBody(param.getValue()));
}
return entity;
}
/**
* Setup HTTPConncetionParams
*
* @param method
*/
private void SetupHTTPConnectionParams(HttpUriRequest method) {
HttpConnectionParams.setConnectionTimeout(method.getParams(),
CONNECTION_TIMEOUT_MS);
HttpConnectionParams
.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
mClient.setHttpRequestRetryHandler(requestRetryHandler);
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
}
/**
* Create request method, such as POST, GET, DELETE
*
* @param httpMethod
* "GET","POST","DELETE"
* @param uri
* 请求的URI
* @param file
* 可为null
* @param postParams
* POST参数
* @return httpMethod Request implementations for the various HTTP methods
* like GET and POST.
* @throws HttpException
* createMultipartEntity 或 UrlEncodedFormEntity引发的IOException
*/
private HttpUriRequest createMethod(String httpMethod, URI uri, File file,
ArrayList<BasicNameValuePair> postParams) throws HttpException {
HttpUriRequest method;
if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
// POST METHOD
HttpPost post = new HttpPost(uri);
// See this: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b
post.getParams().setBooleanParameter("http.protocol.expect-continue", false);
try {
HttpEntity entity = null;
if (null != file) {
entity = createMultipartEntity("photo", file, postParams);
post.setEntity(entity);
} else if (null != postParams) {
entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
}
post.setEntity(entity);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
method = post;
} else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
method = new HttpDelete(uri);
} else {
method = new HttpGet(uri);
}
return method;
}
/**
* 解析HTTP错误码
*
* @param statusCode
* @return
*/
private static String getCause(int statusCode) {
String cause = null;
switch (statusCode) {
case NOT_MODIFIED:
break;
case BAD_REQUEST:
cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.";
break;
case NOT_AUTHORIZED:
cause = "Authentication credentials were missing or incorrect.";
break;
case FORBIDDEN:
cause = "The request is understood, but it has been refused. An accompanying error message will explain why.";
break;
case NOT_FOUND:
cause = "The URI requested is invalid or the resource requested, such as a user, does not exists.";
break;
case NOT_ACCEPTABLE:
cause = "Returned by the Search API when an invalid format is specified in the request.";
break;
case INTERNAL_SERVER_ERROR:
cause = "Something is broken. Please post to the group so the Weibo team can investigate.";
break;
case BAD_GATEWAY:
cause = "Weibo is down or being upgraded.";
break;
case SERVICE_UNAVAILABLE:
cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
}
public boolean isAuthenticationEnabled() {
return isAuthenticationEnabled;
}
public static void log(String msg) {
if (DEBUG) {
Log.d(TAG, msg);
}
}
/**
* Handle Status code
*
* @param statusCode
* 响应的状态码
* @param res
* 服务器响应
* @throws HttpException
* 当响应码不为200时都会报出此异常:<br />
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
private void HandleResponseStatusCode(int statusCode, Response res)
throws HttpException {
String msg = getCause(statusCode) + "\n";
RefuseError error = null;
switch (statusCode) {
// It's OK, do nothing
case OK:
break;
// Mine mistake, Check the Log
case NOT_MODIFIED:
case BAD_REQUEST:
case NOT_FOUND:
case NOT_ACCEPTABLE:
throw new HttpException(msg + res.asString(), statusCode);
// UserName/Password incorrect
case NOT_AUTHORIZED:
throw new HttpAuthException(msg + res.asString(), statusCode);
// Server will return a error message, use
// HttpRefusedException#getError() to see.
case FORBIDDEN:
throw new HttpRefusedException(msg, statusCode);
// Something wrong with server
case INTERNAL_SERVER_ERROR:
case BAD_GATEWAY:
case SERVICE_UNAVAILABLE:
throw new HttpServerException(msg, statusCode);
// Others
default:
throw new HttpException(msg + res.asString(), statusCode);
}
}
public static String encode(String value) throws HttpException {
try {
return URLEncoder.encode(value, HTTP.UTF_8);
} catch (UnsupportedEncodingException e_e) {
throw new HttpException(e_e.getMessage(), e_e);
}
}
public static String encodeParameters(ArrayList<BasicNameValuePair> params)
throws HttpException {
StringBuffer buf = new StringBuffer();
for (int j = 0; j < params.size(); j++) {
if (j != 0) {
buf.append("&");
}
try {
buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(params.get(j).getValue(),
"UTF-8"));
} catch (java.io.UnsupportedEncodingException neverHappen) {
throw new HttpException(neverHappen.getMessage(), neverHappen);
}
}
return buf.toString();
}
/**
* 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
*/
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
// 自定义的恢复策略
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试N次
if (executionCount >= RETRIED_TIME) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/http/HttpClient.java | Java | asf20 | 28,093 |
/*
* Copyright (C) 2009 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 com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.IDs;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener;
import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter;
import com.ch_linghu.fanfoudroid.ui.module.Widget;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
import com.hlidskialf.android.hardware.ShakeListener;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity {
static final String TAG = "TwitterCursorBaseActivity";
// Views.
protected ListView mTweetList;
protected TweetCursorAdapter mTweetAdapter;
protected View mListHeader;
protected View mListFooter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
protected ShakeListener mShaker = null;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;
private int mRetrieveCount = 0;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录信息出错");
logout();
} else if (result == TaskResult.OK) {
// TODO: XML处理, GC压力
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ;
if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) {
// 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性
getDb().gc(getUserId(), getDatabaseType()); // GC
}
draw();
if (task == mRetrieveTask) {
goTop();
}
} else if (result == TaskResult.IO_ERROR) {
// FIXME: bad smell
if (task == mRetrieveTask) {
mFeedback.failed(((RetrieveTask) task).getErrorMsg());
} else if (task == mGetMoreTask) {
mFeedback.failed(((GetMoreTask) task).getErrorMsg());
}
} else {
// do nothing
}
// 刷新按钮停止旋转
loadMoreGIFTop.setVisibility(View.GONE);
loadMoreGIF.setVisibility(View.GONE);
// DEBUG
if (TwitterApplication.DEBUG) {
DebugTimer.stop();
Log.v("DEBUG", DebugTimer.getProfileAsString());
}
}
@Override
public void onPreExecute(GenericTask task) {
mRetrieveCount = 0;
if (TwitterApplication.DEBUG) {
DebugTimer.start();
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected void markAllRead();
abstract protected Cursor fetchMessages();
public abstract int getDatabaseType();
public abstract String getUserId();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread);
public abstract List<Status> getMessageSinceId(String maxId)
throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchMessages(); // getDb().fetchMentions();
setTitle(getActivityTitle());
startManagingCursor(cursor);
mTweetList = (ListView) findViewById(R.id.tweet_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mTweetAdapter = new TweetCursorAdapter(this, cursor);
mTweetList.setAdapter(mTweetAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add Header to ListView
mListHeader = View.inflate(this, R.layout.listview_header, null);
mTweetList.addHeaderView(mListHeader, null, true);
// Add Footer to ListView
mListFooter = View.inflate(this, R.layout.listview_footer, null);
mTweetList.addFooterView(mListFooter, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header);
loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header);
}
@Override
protected void specialItemClicked(int position) {
// 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别
// 前者仅包含数据的数量(不包括foot和head),后者包含foot和head
// 因此在同时存在foot和head的情况下,list.count = adapter.count + 2
if (position == 0) {
// 第一个Item(header)
loadMoreGIFTop.setVisibility(View.VISIBLE);
doRetrieve();
} else if (position == mTweetList.getCount() - 1) {
// 最后一个Item(footer)
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.main;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected TweetAdapter getTweetAdapter() {
return mTweetAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected Tweet getContextItemTweet(int position) {
position = position - 1;
// 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个
if (position >= 0 && position < mTweetAdapter.getCount()) {
Cursor cursor = (Cursor) mTweetAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return StatusTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
// Mark all as read.
// getDb().markAllMentionsRead();
markAllRead();
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want
// dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
// FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。
// 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring
// 现在频繁会出现主键冲突的问题。
//
// Should Refresh Followers
// if (diff > FOLLOWERS_REFRESH_THRESHOLD
// && (mRetrieveTask == null || mRetrieveTask.getStatus() !=
// GenericTask.Status.RUNNING)) {
// Log.d(TAG, "Refresh followers.");
// doRetrieveFollowers();
// }
// 手势识别
registerGestureListener();
//晃动刷新
registerShakeListener();
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mTweetList.setSelection(lastPosition);
}
if (mShaker != null){
mShaker.resume();
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
if (mShaker != null){
mShaker.pause();
}
super.onPause();
lastPosition = mTweetList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
return null;
}
@Override
protected void adapterRefresh() {
mTweetAdapter.notifyDataSetChanged();
mTweetAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mTweetAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private class RetrieveTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
String maxId = fetchMaxId(); // getDb().fetchMaxMentionId();
statusList = getMessageSinceId(maxId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
mRetrieveCount = addMessages(tweets, false);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO: 目前仅做新API兼容性改动,待完善Follower处理
IDs followers = getApi().getFollowersIDs();
List<String> followerIds = Arrays.asList(followers.getIDs());
getDb().syncFollowers(followerIds);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// GET MORE TASK
private class GetMoreTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
String minId = fetchMinId(); // getDb().fetchMaxMentionId();
if (minId == null) {
return TaskResult.FAILED;
}
try {
statusList = getMoreMessageFromId(minId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
if (statusList == null) {
return TaskResult.FAILED;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addMessages(tweets, false); // getDb().addMentions(tweets, false);
return TaskResult.OK;
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(mRetrieveTaskListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useGestrue;
{
useGestrue = TwitterApplication.mPref.getBoolean(
Preferences.USE_GESTRUE, false);
if (useGestrue) {
Log.v(TAG, "Using Gestrue!");
} else {
Log.v(TAG, "Not Using Gestrue!");
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useShake;
{
useShake = TwitterApplication.mPref.getBoolean(
Preferences.USE_SHAKE, false);
if (useShake) {
Log.v(TAG, "Using Shake to refresh!");
} else {
Log.v(TAG, "Not Using Shake!");
}
}
protected FlingGestureListener myGestureListener = null;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (useGestrue && myGestureListener != null) {
return myGestureListener.getDetector().onTouchEvent(event);
}
return super.onTouchEvent(event);
}
// use it in _onCreate
private void registerGestureListener() {
if (useGestrue) {
myGestureListener = new FlingGestureListener(this,
MyActivityFlipper.create(this));
getTweetList().setOnTouchListener(myGestureListener);
}
}
// use it in _onCreate
private void registerShakeListener() {
if (useShake){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
@Override
public void onShake() {
doRetrieve();
}
});
}
}
} | 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/TwitterCursorBaseActivity.java | Java | asf20 | 22,549 |
/*
* Copyright (C) 2009 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 com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class UserCursorBaseActivity extends UserListBaseActivity {
/**
* 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。
*
* 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人
* 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。
* 当收听数>100时采取分页加载,先按照id
* 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载
* 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中
*
*/
static final String TAG = "UserCursorBaseActivity";
// Views.
protected ListView mUserList;
protected UserCursorAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次十个用户
protected abstract String getUserId();// 获得用户id
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC,
// 因为小于时可以保证数据的连续性
// FIXME: gc需要带owner
// getDb().gc(getDatabaseType()); // GC
draw();
goTop();
} else {
// Do nothing.
}
// loadMoreGIFTop.setVisibility(View.GONE);
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected Cursor fetchUsers();
public abstract int getDatabaseType();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers()
throws HttpException;
public abstract void addUsers(
ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers);
// public abstract List<Status> getMessageSinceId(String maxId)
// throws WeiboException;
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId(
String maxId) throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public abstract Paging getNextPage();// 下一页数
public abstract Paging getCurrentPage();// 当前页数
protected abstract String[] getIds();
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchUsers(); //
setTitle(getActivityTitle());
startManagingCursor(cursor);
mUserList = (ListView) findViewById(R.id.follower_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mUserListAdapter = new UserCursorAdapter(this, cursor);
mUserList.setAdapter(mUserListAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
// loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header);
// loadMoreGIFTop =
// (ProgressBar)findViewById(R.id.rectangleProgressBar_header);
// loadMoreAnimation = (AnimationDrawable)
// loadMoreGIF.getIndeterminateDrawable();
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
Cursor cursor = (Cursor) mUserListAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return UserInfoTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
/*
* if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if
* (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to
* see if it was running a send or retrieve task. // It makes no
* sense to resend the send request (don't want dupes) // so we
* instead retrieve (refresh) to see if the message has // posted.
* Log.d(TAG,
* "Was last running a retrieve or send task. Let's refresh.");
* shouldRetrieve = true; }
*/
shouldRetrieve = true;
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
/*
* if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null
* || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) {
* Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); }
*/
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mUserList.setSelection(lastPosition);
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
super.onPause();
lastPosition = mUserList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void adapterRefresh() {
mUserListAdapter.notifyDataSetChanged();
mUserListAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mUserListAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mUserList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
/**
* TODO:从API获取当前Followers,并同步到数据库
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
Log.d(TAG, "load FollowersErtrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers();
getDb().syncWeiboUsers(t_users);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getNextPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
loadMoreGIF.setVisibility(View.GONE);
}
};
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
} | 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/UserCursorBaseActivity.java | Java | asf20 | 19,270 |
/*
* Copyright (C) 2009 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.
*/
/**
* AbstractTwitterListBaseLine用于抽象tweets List的展现
* UI基本元素要求:一个ListView用于tweet列表
* 一个ProgressText用于提示信息
*/
package com.ch_linghu.fanfoudroid.ui.base;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.StatusActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class TwitterListBaseActivity extends BaseActivity
implements Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected Feedback mFeedback;
protected NavBar mNavbar;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter(){
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getTweetList();
abstract protected TweetAdapter getTweetAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected Tweet getContextItemTweet(int position);
abstract protected void updateTweet(Tweet tweet);
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法,
* 以保证其他人使用常量时不产生重复
* @return 最大的Context Menu常量
*/
protected int getLastContextMenuId(){
return CONTEXT_DEL_FAV_ID;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState){
if (super._onCreate(savedInstanceState)){
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL);
// 提示栏
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getTweetList());
registerOnClickListener(getTweetList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Log.d("FLING", "onContextItemSelected");
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix));
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet);
menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message);
if (tweet.favorited.equals("true")) {
menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav);
} else {
menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_MORE_ID:
launchActivity(ProfileActivity.createIntent(tweet.userId));
return true;
case CONTEXT_REPLY_ID: {
// TODO: this isn't quite perfect. It leaves extra empty spaces if
// you perform the reply action again.
Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
}
case CONTEXT_RETWEET_ID:
Intent intent = WriteActivity.createNewRepostIntent(this,
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
case CONTEXT_DM_ID:
launchActivity(WriteDmActivity.createIntent(tweet.userId));
return true;
case CONTEXT_ADD_FAV_ID:
doFavorite("add", tweet.id);
return true;
case CONTEXT_DEL_FAV_ID:
doFavorite("del", tweet.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
protected void draw() {
getTweetAdapter().refresh();
}
protected void goTop() {
getTweetList().setSelection(1);
}
protected void adapterRefresh(){
getTweetAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position){
}
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Tweet tweet = getContextItemTweet(position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
specialItemClicked(position);
}else{
launchActivity(StatusActivity.createIntent(tweet));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
} | 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/TwitterListBaseActivity.java | Java | asf20 | 9,533 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.ListActivity;
/**
* TODO: 准备重构现有的几个ListActivity
*
* 目前几个ListActivity存在的问题是 :
* 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法,
* 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity"
* 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可,
* 而无需强制要求子类去直接实现某些方法.
* 2. 父类过于专制, 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现,
* 诸如此类的, 应该下放给子类更自由的空间. 理想状态为不使用抽象类.
* 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, 已减少代码重复.
* 4. TwitterList和UserList代码存在重复现象, 可抽象.
* 5. TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类.
*
*/
public class BaseListActivity extends ListActivity {
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/BaseListActivity.java | Java | asf20 | 1,243 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.ch_linghu.fanfoudroid.AboutActivity;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.PreferencesActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.service.TwitterService;
/**
* A BaseActivity has common routines and variables for an Activity that
* contains a list of tweets and a text input field.
*
* Not the cleanest design, but works okay for several Activities in this app.
*/
public class BaseActivity extends Activity {
private static final String TAG = "BaseActivity";
protected SharedPreferences mPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_onCreate(savedInstanceState);
}
// 因为onCreate方法无法返回状态,因此无法进行状态判断,
// 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的
// onCreate进行工作。onCreate仅在顶层调用_onCreate。
protected boolean _onCreate(Bundle savedInstanceState) {
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (!checkIsLogedIn()) {
return false;
} else {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this);
return true;
}
}
protected void handleLoggedOut() {
if (isTaskRoot()) {
showLogin();
} else {
setResult(RESULT_LOGOUT);
}
finish();
}
public TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public Weibo getApi() {
return TwitterApplication.mApi;
}
public SharedPreferences getPreferences() {
return mPreferences;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
protected boolean isLoggedIn() {
return getApi().isLoggedIn();
}
private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1;
// Retrieve interface
// public ImageManager getImageManager() {
// return TwitterApplication.mImageManager;
// }
private void _logout() {
TwitterService.unschedule(BaseActivity.this);
getDb().clearData();
getApi().reset();
// Clear SharedPreferences
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
editor.commit();
// TODO: 提供用户手动情况所有缓存选项
TwitterApplication.mImageLoader.getImageManager().clear();
// TODO: cancel notifications.
TwitterService.unschedule(BaseActivity.this);
handleLoggedOut();
}
public void logout() {
Dialog dialog = new AlertDialog.Builder(BaseActivity.this)
.setTitle("提示").setMessage("确实要注销吗?")
.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
_logout();
}
}).setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
dialog.show();
}
protected void showLogin() {
Intent intent = new Intent(this, LoginActivity.class);
// TODO: might be a hack?
intent.putExtra(Intent.EXTRA_INTENT, getIntent());
startActivity(intent);
}
protected void manageUpdateChecks() {
//检查后台更新状态设置
boolean isUpdateEnabled = mPreferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
if (isUpdateEnabled) {
TwitterService.schedule(this);
} else if (!TwitterService.isWidgetEnabled()) {
TwitterService.unschedule(this);
}
//检查强制竖屏设置
boolean isOrientationPortrait = mPreferences.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false);
if (isOrientationPortrait) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
// Menus.
protected static final int OPTIONS_MENU_ID_LOGOUT = 1;
protected static final int OPTIONS_MENU_ID_PREFERENCES = 2;
protected static final int OPTIONS_MENU_ID_ABOUT = 3;
protected static final int OPTIONS_MENU_ID_SEARCH = 4;
protected static final int OPTIONS_MENU_ID_REPLIES = 5;
protected static final int OPTIONS_MENU_ID_DM = 6;
protected static final int OPTIONS_MENU_ID_TWEETS = 7;
protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8;
protected static final int OPTIONS_MENU_ID_FOLLOW = 9;
protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10;
protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11;
protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12;
protected static final int OPTIONS_MENU_ID_EXIT = 13;
/**
* 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Option Menu常量
*/
protected int getLastOptionMenuId() {
return OPTIONS_MENU_ID_EXIT;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// SubMenu submenu =
// menu.addSubMenu(R.string.write_label_insert_picture);
// submenu.setIcon(android.R.drawable.ic_menu_gallery);
//
// submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0,
// R.string.write_label_take_a_picture);
// submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0,
// R.string.write_label_choose_a_picture);
//
// MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0,
// R.string.omenu_search);
// item.setIcon(android.R.drawable.ic_search_category_default);
// item.setAlphabeticShortcut(SearchManager.MENU_KEY);
MenuItem item;
item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0,
R.string.omenu_settings);
item.setIcon(android.R.drawable.ic_menu_preferences);
item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout);
item.setIcon(android.R.drawable.ic_menu_revert);
item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about);
item.setIcon(android.R.drawable.ic_menu_info_details);
item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit);
item.setIcon(android.R.drawable.ic_menu_rotate);
return true;
}
protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0;
protected static final int REQUEST_CODE_PREFERENCES = 1;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_LOGOUT:
logout();
return true;
case OPTIONS_MENU_ID_SEARCH:
onSearchRequested();
return true;
case OPTIONS_MENU_ID_PREFERENCES:
Intent launchPreferencesIntent = new Intent().setClass(this,
PreferencesActivity.class);
startActivityForResult(launchPreferencesIntent,
REQUEST_CODE_PREFERENCES);
return true;
case OPTIONS_MENU_ID_ABOUT:
//AboutDialog.show(this);
Intent intent = new Intent().setClass(this, AboutActivity.class);
startActivity(intent);
return true;
case OPTIONS_MENU_ID_EXIT:
exit();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void exit() {
TwitterService.unschedule(this);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
protected void launchActivity(Intent intent) {
// TODO: probably don't need this result chaining to finish upon logout.
// since the subclasses have to check in onResume.
startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY);
}
protected void launchDefaultActivity() {
Intent intent = new Intent();
intent.setClass(this, TwitterActivity.class);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) {
manageUpdateChecks();
} else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY
&& resultCode == RESULT_LOGOUT) {
Log.d(TAG, "Result logout.");
handleLoggedOut();
}
}
protected boolean checkIsLogedIn() {
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
handleLoggedOut();
return false;
}
return true;
}
public static boolean isTrue(Bundle bundle, String key) {
return bundle != null && bundle.containsKey(key)
&& bundle.getBoolean(key);
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/BaseActivity.java | Java | asf20 | 10,752 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MenuDialog;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
* @deprecated 使用 {@link NavBar} 代替
*/
public class WithHeaderActivity extends BaseActivity {
private static final String TAG = "WithHeaderActivity";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
protected ImageView refreshButton;
protected ImageButton searchButton;
protected ImageButton writeButton;
protected TextView titleButton;
protected Button backButton;
protected ImageButton homeButton;
protected MenuDialog dialog;
protected EditText searchEdit;
protected Feedback mFeedback;
// FIXME: 刷新动画二选一, DELETE ME
protected AnimationDrawable mRefreshAnimation;
protected ProgressBar mProgress = null;
protected ProgressBar mLoadingProgress = null;
//搜索硬按键行为
@Override
public boolean onSearchRequested() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
// LOGO按钮
protected void addTitleButton() {
titleButton = (TextView) findViewById(R.id.title);
titleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = titleButton.getTop();
int height = titleButton.getHeight();
int x = top + height;
if (null == dialog) {
Log.d(TAG, "Create menu dialog.");
dialog = new MenuDialog(WithHeaderActivity.this);
dialog.bindEvent(WithHeaderActivity.this);
dialog.setPosition(-1, x);
}
// toggle dialog
if (dialog.isShowing()) {
dialog.dismiss(); //没机会触发
} else {
dialog.show();
}
}
});
}
protected void setHeaderTitle(String title) {
titleButton.setBackgroundDrawable( new BitmapDrawable());
titleButton.setText(title);
LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(3, 12, 0, 0);
titleButton.setLayoutParams(lp);
// 中文粗体
TextPaint tp = titleButton.getPaint();
tp.setFakeBoldText(true);
}
protected void setHeaderTitle(int resource) {
titleButton.setBackgroundResource(resource);
}
// 刷新
protected void addRefreshButton() {
final Activity that = this;
refreshButton = (ImageView) findViewById(R.id.top_refresh);
// FIXME: 暂时取消旋转效果, 测试ProgressBar
//refreshButton.setBackgroundResource(R.drawable.top_refresh);
//mRefreshAnimation = (AnimationDrawable) refreshButton.getBackground();
// FIXME: DELETE ME
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (that instanceof Refreshable) {
((Refreshable) that).doRetrieve();
} else {
Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved");
}
}
});
}
/**
* @param v
* @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)}
*/
protected void animRotate(View v) {
setRefreshAnimation(true);
}
/**
* @param progress 0~100
* @deprecated use feedback
*/
public void setGlobalProgress(int progress) {
if ( null != mProgress) {
mProgress.setProgress(progress);
}
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
// 搜索
protected void addSearchButton() {
searchButton = (ImageButton) findViewById(R.id.search);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// // 旋转动画
// Animation anim = AnimationUtils.loadAnimation(v.getContext(),
// R.anim.scale_lite);
// v.startAnimation(anim);
//go to SearchActivity
startSearch();
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
//搜索框
protected void addSearchBox() {
searchEdit = (EditText) findViewById(R.id.search_edit);
}
// 撰写
protected void addWriteButton() {
writeButton = (ImageButton) findViewById(R.id.writeMessage);
writeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 回首页
protected void addHomeButton() {
homeButton = (ImageButton) findViewById(R.id.home);
homeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 返回
protected void addBackButton() {
backButton = (Button) findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
finish();
}
});
}
protected void initHeader(int style) {
//FIXME: android 1.6似乎不支持addHeaderView中使用的方法
// 来增加header,造成header无法显示和使用。
// 改用在layout xml里include的方法来确保显示
switch (style) {
case HEADER_STYLE_HOME:
//addHeaderView(R.layout.header);
addTitleButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_BACK:
//addHeaderView(R.layout.header_back);
addBackButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_WRITE:
//addHeaderView(R.layout.header_write);
addBackButton();
//addHomeButton();
break;
case HEADER_STYLE_SEARCH:
//addHeaderView(R.layout.header_search);
addBackButton();
addSearchBox();
addSearchButton();
break;
}
}
private void addHeaderView(int resource) {
// find content root view
ViewGroup root = (ViewGroup) getWindow().getDecorView();
ViewGroup content = (ViewGroup) root.getChildAt(0);
View header = View.inflate(WithHeaderActivity.this, resource, null);
// LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
content.addView(header, 0);
}
@Override
protected void onDestroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (dialog != null){
dialog.dismiss();
}
super.onDestroy();
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/WithHeaderActivity.java | Java | asf20 | 8,811 |
package com.ch_linghu.fanfoudroid.ui.base;
public interface Refreshable {
void doRetrieve();
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/Refreshable.java | Java | asf20 | 97 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class UserListBaseActivity extends BaseActivity implements
Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected NavBar mNavbar;
protected Feedback mFeedback;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
private static final String USER_ID = "userId";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getUserList();
abstract protected TweetAdapter getUserAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected User getContextItemUser(int position);
abstract protected void updateTweet(Tweet tweet);
protected abstract String getUserId();// 获得用户id
public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1;
public static final int CONTENT_STATUS_ID = Menu.FIRST + 2;
public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3;
public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4;
public static final int CONTENT_SEND_DM = Menu.FIRST + 5;
public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Context Menu常量
*/
// protected int getLastContextMenuId(){
// return CONTEXT_DEL_FAV_ID;
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY,
STATE_ALL);
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getUserList());
registerOnClickListener(getUserList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()) {
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(0, CONTENT_PROFILE_ID, 0,
user.screenName + getResources().getString(
R.string.cmenu_user_profile_prefix));
menu.add(0, CONTENT_STATUS_ID, 0, user.screenName
+ getResources().getString(R.string.cmenu_user_status));
menu.add(0, CONTENT_SEND_MENTION, 0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_sendmention_suffix));
menu.add(0, CONTENT_SEND_DM, 0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_senddm_suffix));
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTENT_PROFILE_ID:
launchActivity(ProfileActivity.createIntent(user.id));
return true;
case CONTENT_STATUS_ID:
launchActivity(UserTimelineActivity
.createIntent(user.id, user.name));
return true;
case CONTENT_DEL_FRIEND:
delFriend(user.id);
return true;
case CONTENT_ADD_FRIEND:
addFriend(user.id);
return true;
case CONTENT_SEND_MENTION:
launchActivity(WriteActivity.createNewTweetIntent(String.format(
"@%s ", user.screenName)));
return true;
case CONTENT_SEND_DM:
launchActivity(WriteDmActivity.createIntent(user.id));
return true;
default:
return super.onContextItemSelected(item);
}
}
/**
* 取消关注
*
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO:userid
String userId = params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
*
* @param id
*/
private void addFriend(String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId = params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
private void draw() {
getUserAdapter().refresh();
}
private void goTop() {
getUserList().setSelection(0);
}
protected void adapterRefresh() {
getUserAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setFeedback(mFeedback);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position) {
}
/*
* TODO:单击列表项
*/
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getBaseContext(), "选择第"+position+"个列表",Toast.LENGTH_SHORT).show();
User user = getContextItemUser(position);
if (user == null) {
Log.w(TAG, "selected item not available");
specialItemClicked(position);
} else {
launchActivity(ProfileActivity.createIntent(user.id));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/UserListBaseActivity.java | Java | asf20 | 17,159 |
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public abstract class UserArrayBaseActivity extends UserListBaseActivity {
static final String TAG = "UserArrayBaseActivity";
// Views.
protected ListView mUserList;
protected UserArrayAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次100用户
public abstract Paging getCurrentPage();// 加载
public abstract Paging getNextPage();// 加载
// protected abstract String[] getIds();
protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException;
private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
doRetrieve();// 加载第一页
return true;
} else {
return false;
}
}
@Override
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
}
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
/**
* TODO:从API获取当前Followers
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
allUserList.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected void setupState() {
setTitle(getActivityTitle());
mUserList = (ListView) findViewById(R.id.follower_list);
setupListHeader(true);
mUserListAdapter = new UserArrayAdapter(this);
mUserList.setAdapter(mUserListAdapter);
allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>();
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
User item = (User) mUserListAdapter.getItem(position);
if (item == null) {
return null;
} else {
return item;
}
} else {
return null;
}
}
/**
* TODO:不知道啥用
*/
@Override
protected void updateTweet(Tweet tweet) {
// TODO Auto-generated method stub
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
mFeedback.start("");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
mFeedback.success("");
loadMoreGIF.setVisibility(View.GONE);
}
};
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getNextPage());
mFeedback.update(60);
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
// 将获取到的数据(保存/更新)到数据库
getDb().syncWeiboUsers(usersList);
mFeedback.update(100 - (int) Math.floor(usersList.size() * 2));
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
allUserList.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
mFeedback.update(99);
return TaskResult.OK;
}
}
public void draw() {
mUserListAdapter.refresh(allUserList);
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/base/UserArrayBaseActivity.java | Java | asf20 | 9,608 |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter {
private static final String TAG = "TweetArrayAdapter";
protected ArrayList<Tweet> mTweets;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetArrayAdapter.this.refresh();
}
};
public TweetArrayAdapter(Context context) {
mTweets = new ArrayList<Tweet>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
@Override
public int getCount() {
return mTweets.size();
}
@Override
public Object getItem(int position) {
return mTweets.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.tweet, parent, false);
ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
Tweet tweet = mTweets.get(position);
holder.tweetUserText.setText(tweet.screenName);
TextHelper.setSimpleTweetText(holder.tweetText, tweet.text);
// holder.tweetText.setText(tweet.text, BufferType.SPANNABLE);
String profileImageUrl = tweet.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
tweet.createdAt, tweet.source, tweet.inReplyToScreenName));
if (tweet.favorited.equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(tweet.thumbnail_pic)) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
return view;
}
public void refresh(ArrayList<Tweet> tweets) {
mTweets = tweets;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/TweetArrayAdapter.java | Java | asf20 | 4,073 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.widget.ListAdapter;
public interface TweetAdapter extends ListAdapter{
void refresh();
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/TweetAdapter.java | Java | asf20 | 152 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.view.MotionEvent;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
/**
* MyActivityFlipper 利用左右滑动手势切换Activity
*
* 1. 切换Activity, 继承与 {@link ActivityFlipper} 2. 手势识别, 实现接口
* {@link Widget.OnGestureListener}
*
*/
public class MyActivityFlipper extends ActivityFlipper implements
Widget.OnGestureListener {
public MyActivityFlipper() {
super();
}
public MyActivityFlipper(Activity activity) {
super(activity);
// TODO Auto-generated constructor stub
}
// factory
public static MyActivityFlipper create(Activity activity) {
MyActivityFlipper flipper = new MyActivityFlipper(activity);
flipper.addActivity(BrowseActivity.class);
flipper.addActivity(TwitterActivity.class);
flipper.addActivity(MentionActivity.class);
flipper.setToastResource(new int[] { R.drawable.point_left,
R.drawable.point_center, R.drawable.point_right });
flipper.setInAnimation(R.anim.push_left_in);
flipper.setOutAnimation(R.anim.push_left_out);
flipper.setPreviousInAnimation(R.anim.push_right_in);
flipper.setPreviousOutAnimation(R.anim.push_right_out);
return flipper;
}
@Override
public boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
autoShowNext();
return true;
}
@Override
public boolean onFlingRight(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
autoShowPrevious();
return true;
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/MyActivityFlipper.java | Java | asf20 | 2,183 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.ListView;
public class MyListView extends ListView implements ListView.OnScrollListener {
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnScrollListener(this);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = super.onInterceptTouchEvent(event);
if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) {
return true;
}
return result;
}
private OnNeedMoreListener mOnNeedMoreListener;
public static interface OnNeedMoreListener {
public void needMore();
}
public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) {
mOnNeedMoreListener = onNeedMoreListener;
}
private int mFirstVisibleItem;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnNeedMoreListener == null) {
return;
}
if (firstVisibleItem != mFirstVisibleItem) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
mOnNeedMoreListener.needMore();
}
} else {
mFirstVisibleItem = firstVisibleItem;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/MyListView.java | Java | asf20 | 1,620 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.Layout;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
public class MyTextView extends TextView {
private static float mFontSize = 15;
private static boolean mFontSizeChanged = true;
public MyTextView(Context context) {
super(context, null);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setLinksClickable(false);
Resources res = getResources();
int color = res.getColor(R.color.link_color);
setLinkTextColor(color);
initFontSize();
}
public void initFontSize() {
if ( mFontSizeChanged ) {
mFontSize = getFontSizeFromPreferences(mFontSize);
setFontSizeChanged(false); // reset
}
setTextSize(mFontSize);
}
private float getFontSizeFromPreferences(float defaultValue) {
SharedPreferences preferences = TwitterApplication.mPref;
if (preferences.contains(Preferences.UI_FONT_SIZE)) {
Log.v("DEBUG", preferences.getString(Preferences.UI_FONT_SIZE, "null") + " CHANGE FONT SIZE");
return Float.parseFloat(preferences.getString(
Preferences.UI_FONT_SIZE, "14"));
}
return defaultValue;
}
private URLSpan mCurrentLink;
private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan(
Color.RED);
@Override
public boolean onTouchEvent(MotionEvent event) {
CharSequence text = getText();
int action = event.getAction();
if (!(text instanceof Spannable)) {
return super.onTouchEvent(event);
}
Spannable buffer = (Spannable) text;
if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_MOVE) {
TextView widget = this;
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
if (mCurrentLink == link[0]) {
link[0].onClick(widget);
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
} else if (action == MotionEvent.ACTION_DOWN) {
mCurrentLink = link[0];
buffer.setSpan(mLinkFocusStyle,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return true;
}
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
return super.onTouchEvent(event);
}
public static void setFontSizeChanged(boolean isChanged) {
mFontSizeChanged = isChanged;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/MyTextView.java | Java | asf20 | 4,155 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.Log;
public class FeedbackFactory {
private static final String TAG = "FeedbackFactory";
public static enum FeedbackType {
DIALOG, PROGRESS, REFRESH
};
public static Feedback create(Context context, FeedbackType type) {
Feedback feedback = null;
switch (type) {
case PROGRESS:
feedback = new SimpleFeedback(context);
break;
}
if (null == feedback || !feedback.isAvailable()) {
feedback = new FeedbackAdapter(context);
Log.e(TAG, type + " feedback is not available.");
}
return feedback;
}
public static class FeedbackAdapter implements Feedback {
public FeedbackAdapter(Context context) {}
@Override
public void start(CharSequence text) {}
@Override
public void cancel(CharSequence text) {}
@Override
public void success(CharSequence text) {}
@Override
public void failed(CharSequence text) {}
@Override
public void update(Object arg0) {}
@Override
public boolean isAvailable() { return true; }
@Override
public void setIndeterminate(boolean indeterminate) {}
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/FeedbackFactory.java | Java | asf20 | 1,347 |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
public class SimpleFeedback implements Feedback, Widget {
private static final String TAG = "SimpleFeedback";
public static final int MAX = 100;
private ProgressBar mProgress = null;
private ProgressBar mLoadingProgress = null;
public SimpleFeedback(Context context) {
mProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.top_refresh_progressBar);
}
@Override
public void start(CharSequence text) {
mProgress.setProgress(20);
mLoadingProgress.setVisibility(View.VISIBLE);
}
@Override
public void success(CharSequence text) {
mProgress.setProgress(100);
mLoadingProgress.setVisibility(View.GONE);
resetProgressBar();
}
@Override
public void failed(CharSequence text) {
resetProgressBar();
showMessage(text);
}
@Override
public void cancel(CharSequence text) {
}
@Override
public void update(Object arg0) {
if (arg0 instanceof Integer) {
mProgress.setProgress((Integer) arg0);
} else if (arg0 instanceof CharSequence) {
showMessage((String) arg0);
}
}
@Override
public void setIndeterminate(boolean indeterminate) {
mProgress.setIndeterminate(indeterminate);
}
@Override
public Context getContext() {
if (mProgress != null) {
return mProgress.getContext();
}
if (mLoadingProgress != null) {
return mLoadingProgress.getContext();
}
return null;
}
@Override
public boolean isAvailable() {
if (null == mProgress) {
Log.e(TAG, "R.id.progress_bar is missing");
return false;
}
if (null == mLoadingProgress) {
Log.e(TAG, "R.id.top_refresh_progressBar is missing");
return false;
}
return true;
}
/**
* @param total 0~100
* @param maxSize max size of list
* @param list
* @return
*/
public static int calProgressBySize(int total, int maxSize, List<?> list) {
if (null != list) {
return (MAX - (int)Math.floor(list.size() * (total/maxSize)));
}
return MAX;
}
private void resetProgressBar() {
if (mProgress.isIndeterminate()) {
//TODO: 第二次不会出现
mProgress.setIndeterminate(false);
}
mProgress.setProgress(0);
}
private void showMessage(CharSequence text) {
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/SimpleFeedback.java | Java | asf20 | 3,029 |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//TODO:
/*
* 用于用户的Adapter
*/
public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{
private static final String TAG = "UserArrayAdapter";
private static final String USER_ID="userId";
protected ArrayList<User> mUsers;
private Context mContext;
protected LayoutInflater mInflater;
public UserArrayAdapter(Context context) {
mUsers = new ArrayList<User>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mUsers.size();
}
@Override
public Object getItem(int position) {
return mUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public ImageView profileImage;
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public TextView followBtn;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.follower_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.screenName = (TextView) view.findViewById(R.id.screen_name);
holder.userId = (TextView) view.findViewById(R.id.user_id);
//holder.lastStatus = (TextView) view.findViewById(R.id.last_status);
holder.followBtn = (TextView) view.findViewById(R.id.follow_btn);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
final User user = mUsers.get(position);
String profileImageUrl = user.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
//holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap);
holder.screenName.setText(user.screenName);
holder.userId.setText(user.id);
//holder.lastStatus.setText(user.lastStatus);
holder.followBtn.setText(user.isFollowing ? mContext
.getString(R.string.general_del_friend) : mContext
.getString(R.string.general_add_friend));
holder.followBtn.setOnClickListener(user.isFollowing?new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show();
delFriend(user.id);
}}:new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show();
addFriend(user.id);
}});
return view;
}
public void refresh(ArrayList<User> users) {
mUsers = users;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserArrayAdapter.this.refresh();
}
};
/**
* 取消关注
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
//TODO:userid
String userId=params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
* @param id
*/
private void addFriend(String id){
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId=params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
public Weibo getApi() {
return TwitterApplication.mApi;
}
}
| 061304011116lyj-2 | src/com/ch_linghu/fanfoudroid/ui/module/UserArrayAdapter.java | Java | asf20 | 9,395 |