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 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import com.google.zxing.Binarizer; import com.google.zxing.LuminanceSource; import com.google.zxing.NotFoundException; /** * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable * for low-end mobile devices which don't have enough CPU or memory to use a local thresholding * algorithm. However, because it picks a global black point, it cannot handle difficult shadows * and gradients. * * Faster mobile devices and all desktop applications should probably use HybridBinarizer instead. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ public class GlobalHistogramBinarizer extends Binarizer { private static final int LUMINANCE_BITS = 5; private static final int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; private static final int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; private static final byte[] EMPTY = new byte[0]; private byte[] luminances; private final int[] buckets; public GlobalHistogramBinarizer(LuminanceSource source) { super(source); luminances = EMPTY; buckets = new int[LUMINANCE_BUCKETS]; } // Applies simple sharpening to the row data to improve performance of the 1D Readers. @Override public BitArray getBlackRow(int y, BitArray row) throws NotFoundException { LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); if (row == null || row.getSize() < width) { row = new BitArray(width); } else { row.clear(); } initArrays(width); byte[] localLuminances = source.getRow(y, luminances); int[] localBuckets = buckets; for (int x = 0; x < width; x++) { int pixel = localLuminances[x] & 0xff; localBuckets[pixel >> LUMINANCE_SHIFT]++; } int blackPoint = estimateBlackPoint(localBuckets); int left = localLuminances[0] & 0xff; int center = localLuminances[1] & 0xff; for (int x = 1; x < width - 1; x++) { int right = localLuminances[x + 1] & 0xff; // A simple -1 4 -1 box filter with a weight of 2. int luminance = ((center << 2) - left - right) >> 1; if (luminance < blackPoint) { row.set(x); } left = center; center = right; } return row; } // Does not sharpen the data, as this call is intended to only be used by 2D Readers. @Override public BitMatrix getBlackMatrix() throws NotFoundException { LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); int height = source.getHeight(); BitMatrix matrix = new BitMatrix(width, height); // Quickly calculates the histogram by sampling four rows from the image. This proved to be // more robust on the blackbox tests than sampling a diagonal as we used to do. initArrays(width); int[] localBuckets = buckets; for (int y = 1; y < 5; y++) { int row = height * y / 5; byte[] localLuminances = source.getRow(row, luminances); int right = (width << 2) / 5; for (int x = width / 5; x < right; x++) { int pixel = localLuminances[x] & 0xff; localBuckets[pixel >> LUMINANCE_SHIFT]++; } } int blackPoint = estimateBlackPoint(localBuckets); // We delay reading the entire image luminance until the black point estimation succeeds. // Although we end up reading four rows twice, it is consistent with our motto of // "fail quickly" which is necessary for continuous scanning. byte[] localLuminances = source.getMatrix(); for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x< width; x++) { int pixel = localLuminances[offset + x] & 0xff; if (pixel < blackPoint) { matrix.set(x, y); } } } return matrix; } @Override public Binarizer createBinarizer(LuminanceSource source) { return new GlobalHistogramBinarizer(source); } private void initArrays(int luminanceSize) { if (luminances.length < luminanceSize) { luminances = new byte[luminanceSize]; } for (int x = 0; x < LUMINANCE_BUCKETS; x++) { buckets[x] = 0; } } private static int estimateBlackPoint(int[] buckets) throws NotFoundException { // Find the tallest peak in the histogram. int numBuckets = buckets.length; int maxBucketCount = 0; int firstPeak = 0; int firstPeakSize = 0; for (int x = 0; x < numBuckets; x++) { if (buckets[x] > firstPeakSize) { firstPeak = x; firstPeakSize = buckets[x]; } if (buckets[x] > maxBucketCount) { maxBucketCount = buckets[x]; } } // Find the second-tallest peak which is somewhat far from the tallest peak. int secondPeak = 0; int secondPeakScore = 0; for (int x = 0; x < numBuckets; x++) { int distanceToBiggest = x - firstPeak; // Encourage more distant second peaks by multiplying by square of distance. int score = buckets[x] * distanceToBiggest * distanceToBiggest; if (score > secondPeakScore) { secondPeak = x; secondPeakScore = score; } } // Make sure firstPeak corresponds to the black peak. if (firstPeak > secondPeak) { int temp = firstPeak; firstPeak = secondPeak; secondPeak = temp; } // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. if (secondPeak - firstPeak <= numBuckets >> 4) { throw NotFoundException.getNotFoundInstance(); } // Find a valley between them that is low and closer to the white peak. int bestValley = secondPeak - 1; int bestValleyScore = -1; for (int x = secondPeak - 1; x > firstPeak; x--) { int fromFirst = x - firstPeak; int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]); if (score > bestValleyScore) { bestValley = x; bestValleyScore = score; } } return bestValley << LUMINANCE_SHIFT; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/GlobalHistogramBinarizer.java
Java
epl
6,669
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; /** * <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the * number of bits read is not often a multiple of 8.</p> * * <p>This class is thread-safe but not reentrant -- unless the caller modifies the bytes array * it passed in, in which case all bets are off.</p> * * @author Sean Owen */ public final class BitSource { private final byte[] bytes; private int byteOffset; private int bitOffset; /** * @param bytes bytes from which this will read bits. Bits will be read from the first byte first. * Bits are read within a byte from most-significant to least-significant bit. */ public BitSource(byte[] bytes) { this.bytes = bytes; } /** * @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}. */ public int getBitOffset() { return bitOffset; } /** * @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}. */ public int getByteOffset() { return byteOffset; } /** * @param numBits number of bits to read * @return int representing the bits read. The bits will appear as the least-significant * bits of the int * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available */ public int readBits(int numBits) { if (numBits < 1 || numBits > 32 || numBits > available()) { throw new IllegalArgumentException(String.valueOf(numBits)); } int result = 0; // First, read remainder from current byte if (bitOffset > 0) { int bitsLeft = 8 - bitOffset; int toRead = numBits < bitsLeft ? numBits : bitsLeft; int bitsToNotRead = bitsLeft - toRead; int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; result = (bytes[byteOffset] & mask) >> bitsToNotRead; numBits -= toRead; bitOffset += toRead; if (bitOffset == 8) { bitOffset = 0; byteOffset++; } } // Next read whole bytes if (numBits > 0) { while (numBits >= 8) { result = (result << 8) | (bytes[byteOffset] & 0xFF); byteOffset++; numBits -= 8; } // Finally read a partial byte if (numBits > 0) { int bitsToNotRead = 8 - numBits; int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); bitOffset += numBits; } } return result; } /** * @return number of bits that can be read successfully */ public int available() { return 8 * (bytes.length - byteOffset) - bitOffset; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/BitSource.java
Java
epl
3,430
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import java.util.List; /** * <p>Encapsulates the result of decoding a matrix of bits. This typically * applies to 2D barcode formats. For now it contains the raw bytes obtained, * as well as a String interpretation of those bytes, if applicable.</p> * * @author Sean Owen */ public final class DecoderResult { private final byte[] rawBytes; private final String text; private final List<byte[]> byteSegments; private final String ecLevel; private Integer errorsCorrected; private Integer erasures; private Object other; public DecoderResult(byte[] rawBytes, String text, List<byte[]> byteSegments, String ecLevel) { this.rawBytes = rawBytes; this.text = text; this.byteSegments = byteSegments; this.ecLevel = ecLevel; } public byte[] getRawBytes() { return rawBytes; } public String getText() { return text; } public List<byte[]> getByteSegments() { return byteSegments; } public String getECLevel() { return ecLevel; } public Integer getErrorsCorrected() { return errorsCorrected; } public void setErrorsCorrected(Integer errorsCorrected) { this.errorsCorrected = errorsCorrected; } public Integer getErasures() { return erasures; } public void setErasures(Integer erasures) { this.erasures = erasures; } public Object getOther() { return other; } public void setOther(Object other) { this.other = other; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/DecoderResult.java
Java
epl
2,149
/* * Copyright 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; /** * Simply encapsulates a width and height. */ public final class Dimension { private final int width; private final int height; public Dimension(int width, int height) { if (width < 0 || height < 0) { throw new IllegalArgumentException(); } this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } @Override public boolean equals(Object other) { if (other instanceof Dimension) { Dimension d = (Dimension) other; return width == d.width && height == d.height; } return false; } @Override public int hashCode() { return width * 32713 + height; } @Override public String toString() { return width + "x" + height; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/Dimension.java
Java
epl
1,425
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; /** * Represents some type of metadata about the result of the decoding that the decoder * wishes to communicate back to the caller. * * @author Sean Owen */ public enum ResultMetadataType { /** * Unspecified, application-specific metadata. Maps to an unspecified {@link Object}. */ OTHER, /** * Denotes the likely approximate orientation of the barcode in the image. This value * is given as degrees rotated clockwise from the normal, upright orientation. * For example a 1D barcode which was found by reading top-to-bottom would be * said to have orientation "90". This key maps to an {@link Integer} whose * value is in the range [0,360). */ ORIENTATION, /** * <p>2D barcode formats typically encode text, but allow for a sort of 'byte mode' * which is sometimes used to encode binary data. While {@link Result} makes available * the complete raw bytes in the barcode for these formats, it does not offer the bytes * from the byte segments alone.</p> * * <p>This maps to a {@link java.util.List} of byte arrays corresponding to the * raw bytes in the byte segments in the barcode, in order.</p> */ BYTE_SEGMENTS, /** * Error correction level used, if applicable. The value type depends on the * format, but is typically a String. */ ERROR_CORRECTION_LEVEL, /** * For some periodicals, indicates the issue number as an {@link Integer}. */ ISSUE_NUMBER, /** * For some products, indicates the suggested retail price in the barcode as a * formatted {@link String}. */ SUGGESTED_PRICE , /** * For some products, the possible country of manufacture as a {@link String} denoting the * ISO country code. Some map to multiple possible countries, like "US/CA". */ POSSIBLE_COUNTRY, /** * For some products, the extension text */ UPC_EAN_EXTENSION, /** * PDF417-specific metadata */ PDF417_EXTRA_METADATA, }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/ResultMetadataType.java
Java
epl
2,571
/* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.maxicode; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DecoderResult; import com.google.zxing.maxicode.decoder.Decoder; import java.util.Map; /** * This implementation can detect and decode a MaxiCode in an image. */ public final class MaxiCodeReader implements Reader { private static final ResultPoint[] NO_POINTS = new ResultPoint[0]; private static final int MATRIX_WIDTH = 30; private static final int MATRIX_HEIGHT = 33; private final Decoder decoder = new Decoder(); Decoder getDecoder() { return decoder; } /** * Locates and decodes a MaxiCode in an image. * * @return a String representing the content encoded by the MaxiCode * @throws NotFoundException if a MaxiCode cannot be found * @throws FormatException if a MaxiCode cannot be decoded * @throws ChecksumException if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { DecoderResult decoderResult; if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.getBlackMatrix()); decoderResult = decoder.decode(bits, hints); } else { throw NotFoundException.getNotFoundInstance(); } ResultPoint[] points = NO_POINTS; Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.MAXICODE); String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } return result; } @Override public void reset() { // do nothing } /** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. * * @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix) * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int[] enclosingRectangle = image.getEnclosingRectangle(); if (enclosingRectangle == null) { throw NotFoundException.getNotFoundInstance(); } int left = enclosingRectangle[0]; int top = enclosingRectangle[1]; int width = enclosingRectangle[2]; int height = enclosingRectangle[3]; // Now just read off the bits BitMatrix bits = new BitMatrix(MATRIX_WIDTH, MATRIX_HEIGHT); for (int y = 0; y < MATRIX_HEIGHT; y++) { int iy = top + (y * height + height / 2) / MATRIX_HEIGHT; for (int x = 0; x < MATRIX_WIDTH; x++) { int ix = left + (x * width + width / 2 + (y & 0x01) * width / 2) / MATRIX_WIDTH; if (image.get(ix, iy)) { bits.set(x, y); } } } return bits; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/maxicode/MaxiCodeReader.java
Java
epl
4,213
/* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.maxicode.decoder; import com.google.zxing.common.BitMatrix; /** * @author mike32767 * @author Manuel Kasten */ final class BitMatrixParser { private static final int[][] BITNR = { {121,120,127,126,133,132,139,138,145,144,151,150,157,156,163,162,169,168,175,174,181,180,187,186,193,192,199,198, -2, -2}, {123,122,129,128,135,134,141,140,147,146,153,152,159,158,165,164,171,170,177,176,183,182,189,188,195,194,201,200,816, -3}, {125,124,131,130,137,136,143,142,149,148,155,154,161,160,167,166,173,172,179,178,185,184,191,190,197,196,203,202,818,817}, {283,282,277,276,271,270,265,264,259,258,253,252,247,246,241,240,235,234,229,228,223,222,217,216,211,210,205,204,819, -3}, {285,284,279,278,273,272,267,266,261,260,255,254,249,248,243,242,237,236,231,230,225,224,219,218,213,212,207,206,821,820}, {287,286,281,280,275,274,269,268,263,262,257,256,251,250,245,244,239,238,233,232,227,226,221,220,215,214,209,208,822, -3}, {289,288,295,294,301,300,307,306,313,312,319,318,325,324,331,330,337,336,343,342,349,348,355,354,361,360,367,366,824,823}, {291,290,297,296,303,302,309,308,315,314,321,320,327,326,333,332,339,338,345,344,351,350,357,356,363,362,369,368,825, -3}, {293,292,299,298,305,304,311,310,317,316,323,322,329,328,335,334,341,340,347,346,353,352,359,358,365,364,371,370,827,826}, {409,408,403,402,397,396,391,390, 79, 78, -2, -2, 13, 12, 37, 36, 2, -1, 44, 43,109,108,385,384,379,378,373,372,828, -3}, {411,410,405,404,399,398,393,392, 81, 80, 40, -2, 15, 14, 39, 38, 3, -1, -1, 45,111,110,387,386,381,380,375,374,830,829}, {413,412,407,406,401,400,395,394, 83, 82, 41, -3, -3, -3, -3, -3, 5, 4, 47, 46,113,112,389,388,383,382,377,376,831, -3}, {415,414,421,420,427,426,103,102, 55, 54, 16, -3, -3, -3, -3, -3, -3, -3, 20, 19, 85, 84,433,432,439,438,445,444,833,832}, {417,416,423,422,429,428,105,104, 57, 56, -3, -3, -3, -3, -3, -3, -3, -3, 22, 21, 87, 86,435,434,441,440,447,446,834, -3}, {419,418,425,424,431,430,107,106, 59, 58, -3, -3, -3, -3, -3, -3, -3, -3, -3, 23, 89, 88,437,436,443,442,449,448,836,835}, {481,480,475,474,469,468, 48, -2, 30, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 0, 53, 52,463,462,457,456,451,450,837, -3}, {483,482,477,476,471,470, 49, -1, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2, -1,465,464,459,458,453,452,839,838}, {485,484,479,478,473,472, 51, 50, 31, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 1, -2, 42,467,466,461,460,455,454,840, -3}, {487,486,493,492,499,498, 97, 96, 61, 60, -3, -3, -3, -3, -3, -3, -3, -3, -3, 26, 91, 90,505,504,511,510,517,516,842,841}, {489,488,495,494,501,500, 99, 98, 63, 62, -3, -3, -3, -3, -3, -3, -3, -3, 28, 27, 93, 92,507,506,513,512,519,518,843, -3}, {491,490,497,496,503,502,101,100, 65, 64, 17, -3, -3, -3, -3, -3, -3, -3, 18, 29, 95, 94,509,508,515,514,521,520,845,844}, {559,558,553,552,547,546,541,540, 73, 72, 32, -3, -3, -3, -3, -3, -3, 10, 67, 66,115,114,535,534,529,528,523,522,846, -3}, {561,560,555,554,549,548,543,542, 75, 74, -2, -1, 7, 6, 35, 34, 11, -2, 69, 68,117,116,537,536,531,530,525,524,848,847}, {563,562,557,556,551,550,545,544, 77, 76, -2, 33, 9, 8, 25, 24, -1, -2, 71, 70,119,118,539,538,533,532,527,526,849, -3}, {565,564,571,570,577,576,583,582,589,588,595,594,601,600,607,606,613,612,619,618,625,624,631,630,637,636,643,642,851,850}, {567,566,573,572,579,578,585,584,591,590,597,596,603,602,609,608,615,614,621,620,627,626,633,632,639,638,645,644,852, -3}, {569,568,575,574,581,580,587,586,593,592,599,598,605,604,611,610,617,616,623,622,629,628,635,634,641,640,647,646,854,853}, {727,726,721,720,715,714,709,708,703,702,697,696,691,690,685,684,679,678,673,672,667,666,661,660,655,654,649,648,855, -3}, {729,728,723,722,717,716,711,710,705,704,699,698,693,692,687,686,681,680,675,674,669,668,663,662,657,656,651,650,857,856}, {731,730,725,724,719,718,713,712,707,706,701,700,695,694,689,688,683,682,677,676,671,670,665,664,659,658,653,652,858, -3}, {733,732,739,738,745,744,751,750,757,756,763,762,769,768,775,774,781,780,787,786,793,792,799,798,805,804,811,810,860,859}, {735,734,741,740,747,746,753,752,759,758,765,764,771,770,777,776,783,782,789,788,795,794,801,800,807,806,813,812,861, -3}, {737,736,743,742,749,748,755,754,761,760,767,766,773,772,779,778,785,784,791,790,797,796,803,802,809,808,815,814,863,862} }; private final BitMatrix bitMatrix; /** * @param bitMatrix {@link BitMatrix} to parse */ BitMatrixParser(BitMatrix bitMatrix) { this.bitMatrix = bitMatrix; } byte[] readCodewords() { byte[] result = new byte[144]; int height = bitMatrix.getHeight(); int width = bitMatrix.getWidth(); for (int y = 0; y < height; y++) { int[] bitnrRow = BITNR[y]; for (int x = 0; x < width; x++) { int bit = bitnrRow[x]; if (bit >= 0 && bitMatrix.get(x, y)) { result[bit / 6] |= (byte) (1 << (5 - (bit % 6))); } } } return result; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/maxicode/decoder/BitMatrixParser.java
Java
epl
5,625
/* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.maxicode.decoder; import com.google.zxing.common.DecoderResult; import java.text.DecimalFormat; import java.text.NumberFormat; /** * <p>MaxiCodes can encode text or structured information as bits in one of several modes, * with multiple character sets in one code. This class decodes the bits back into text.</p> * * @author mike32767 * @author Manuel Kasten */ final class DecodedBitStreamParser { private static final char SHIFTA = '\uFFF0'; private static final char SHIFTB = '\uFFF1'; private static final char SHIFTC = '\uFFF2'; private static final char SHIFTD = '\uFFF3'; private static final char SHIFTE = '\uFFF4'; private static final char TWOSHIFTA = '\uFFF5'; private static final char THREESHIFTA = '\uFFF6'; private static final char LATCHA = '\uFFF7'; private static final char LATCHB = '\uFFF8'; private static final char LOCK = '\uFFF9'; private static final char ECI = '\uFFFA'; private static final char NS = '\uFFFB'; private static final char PAD = '\uFFFC'; private static final char FS = '\u001C'; private static final char GS = '\u001D'; private static final char RS = '\u001E'; private static final NumberFormat NINE_DIGITS = new DecimalFormat("000000000"); private static final NumberFormat THREE_DIGITS = new DecimalFormat("000"); private static final String[] SETS = { "\nABCDEFGHIJKLMNOPQRSTUVWXYZ"+ECI+FS+GS+RS+NS+' '+PAD+"\"#$%&'()*+,-./0123456789:"+SHIFTB+SHIFTC+SHIFTD+SHIFTE+LATCHB, "`abcdefghijklmnopqrstuvwxyz"+ECI+FS+GS+RS+NS+'{'+PAD+"}~\u007F;<=>?[\\]^_ ,./:@!|"+PAD+TWOSHIFTA+THREESHIFTA+PAD+SHIFTA+SHIFTC+SHIFTD+SHIFTE+LATCHA, "\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C6\u00C7\u00C8\u00C9\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D0\u00D1\u00D2\u00D3\u00D4\u00D5\u00D6\u00D7\u00D8\u00D9\u00DA"+ECI+FS+GS+RS+"\u00DB\u00DC\u00DD\u00DE\u00DF\u00AA\u00AC\u00B1\u00B2\u00B3\u00B5\u00B9\u00BA\u00BC\u00BD\u00BE\u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087\u0088\u0089"+LATCHA+' '+LOCK+SHIFTD+SHIFTE+LATCHB, "\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5\u00E6\u00E7\u00E8\u00E9\u00EA\u00EB\u00EC\u00ED\u00EE\u00EF\u00F0\u00F1\u00F2\u00F3\u00F4\u00F5\u00F6\u00F7\u00F8\u00F9\u00FA"+ECI+FS+GS+RS+NS+"\u00FB\u00FC\u00FD\u00FE\u00FF\u00A1\u00A8\u00AB\u00AF\u00B0\u00B4\u00B7\u00B8\u00BB\u00BF\u008A\u008B\u008C\u008D\u008E\u008F\u0090\u0091\u0092\u0093\u0094"+LATCHA+' '+SHIFTC+LOCK+SHIFTE+LATCHB, "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\n\u000B\u000C\r\u000E\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A"+ECI+PAD+PAD+'\u001B'+NS+FS+GS+RS+"\u001F\u009F\u00A0\u00A2\u00A3\u00A4\u00A5\u00A6\u00A7\u00A9\u00AD\u00AE\u00B6\u0095\u0096\u0097\u0098\u0099\u009A\u009B\u009C\u009D\u009E"+LATCHA+' '+SHIFTC+SHIFTD+LOCK+LATCHB, "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\n\u000B\u000C\r\u000E\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F\u0020\u0021\"\u0023\u0024\u0025\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u002D\u002E\u002F\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039\u003A\u003B\u003C\u003D\u003E\u003F" }; private DecodedBitStreamParser() { } static DecoderResult decode(byte[] bytes, int mode) { StringBuilder result = new StringBuilder(144); switch (mode) { case 2: case 3: String postcode; if (mode == 2) { int pc = getPostCode2(bytes); NumberFormat df = new DecimalFormat("0000000000".substring(0, getPostCode2Length(bytes))); postcode = df.format(pc); } else { postcode = getPostCode3(bytes); } String country = THREE_DIGITS.format(getCountry(bytes)); String service = THREE_DIGITS.format(getServiceClass(bytes)); result.append(getMessage(bytes, 10, 84)); if (result.toString().startsWith("[)>"+RS+"01"+GS)) { result.insert(9, postcode + GS + country + GS + service + GS); } else { result.insert(0, postcode + GS + country + GS + service + GS); } break; case 4: result.append(getMessage(bytes, 1, 93)); break; case 5: result.append(getMessage(bytes, 1, 77)); break; } return new DecoderResult(bytes, result.toString(), null, String.valueOf(mode)); } private static int getBit(int bit, byte[] bytes) { bit--; return (bytes[bit / 6] & (1 << (5 - (bit % 6)))) == 0 ? 0 : 1; } private static int getInt(byte[] bytes, byte[] x) { int val = 0; for (int i = 0; i < x.length; i++) { val += getBit(x[i], bytes) << (x.length - i - 1); } return val; } private static int getCountry(byte[] bytes) { return getInt(bytes, new byte[] {53, 54, 43, 44, 45, 46, 47, 48, 37, 38}); } private static int getServiceClass(byte[] bytes) { return getInt(bytes, new byte[] {55, 56, 57, 58, 59, 60, 49, 50, 51, 52}); } private static int getPostCode2Length(byte[] bytes) { return getInt(bytes, new byte[] {39, 40, 41, 42, 31, 32}); } private static int getPostCode2(byte[] bytes) { return getInt(bytes, new byte[] {33, 34, 35, 36, 25, 26, 27, 28, 29, 30, 19, 20, 21, 22, 23, 24, 13, 14, 15, 16, 17, 18, 7, 8, 9, 10, 11, 12, 1, 2}); } private static String getPostCode3(byte[] bytes) { return String.valueOf( new char[] { SETS[0].charAt(getInt(bytes, new byte[] {39, 40, 41, 42, 31, 32})), SETS[0].charAt(getInt(bytes, new byte[] {33, 34, 35, 36, 25, 26})), SETS[0].charAt(getInt(bytes, new byte[] {27, 28, 29, 30, 19, 20})), SETS[0].charAt(getInt(bytes, new byte[] {21, 22, 23, 24, 13, 14})), SETS[0].charAt(getInt(bytes, new byte[] {15, 16, 17, 18, 7, 8})), SETS[0].charAt(getInt(bytes, new byte[] { 9, 10, 11, 12, 1, 2})), } ); } private static String getMessage(byte[] bytes, int start, int len) { StringBuilder sb = new StringBuilder(); int shift = -1; int set = 0; int lastset = 0; for (int i = start; i < start + len; i++) { char c = SETS[set].charAt(bytes[i]); switch (c) { case LATCHA: set = 0; shift = -1; break; case LATCHB: set = 1; shift = -1; break; case SHIFTA: case SHIFTB: case SHIFTC: case SHIFTD: case SHIFTE: lastset = set; set = c - SHIFTA; shift = 1; break; case TWOSHIFTA: lastset = set; set = 0; shift = 2; break; case THREESHIFTA: lastset = set; set = 0; shift = 3; break; case NS: int nsval = (bytes[++i] << 24) + (bytes[++i] << 18) + (bytes[++i] << 12) + (bytes[++i] << 6) + bytes[++i]; sb.append(NINE_DIGITS.format(nsval)); break; case LOCK: shift = -1; break; default: sb.append(c); } if (shift-- == 0) { set = lastset; } } while (sb.length() > 0 && sb.charAt(sb.length() - 1) == PAD) { sb.setLength(sb.length() - 1); } return sb.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/maxicode/decoder/DecodedBitStreamParser.java
Java
epl
7,832
/* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.maxicode.decoder; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DecoderResult; import com.google.zxing.common.reedsolomon.GenericGF; import com.google.zxing.common.reedsolomon.ReedSolomonDecoder; import com.google.zxing.common.reedsolomon.ReedSolomonException; import java.util.Map; /** * <p>The main class which implements MaxiCode decoding -- as opposed to locating and extracting * the MaxiCode from an image.</p> * * @author Manuel Kasten */ public final class Decoder { private static final int ALL = 0; private static final int EVEN = 1; private static final int ODD = 2; private final ReedSolomonDecoder rsDecoder; public Decoder() { rsDecoder = new ReedSolomonDecoder(GenericGF.MAXICODE_FIELD_64); } public DecoderResult decode(BitMatrix bits) throws ChecksumException, FormatException { return decode(bits, null); } public DecoderResult decode(BitMatrix bits, Map<DecodeHintType,?> hints) throws FormatException, ChecksumException { BitMatrixParser parser = new BitMatrixParser(bits); byte[] codewords = parser.readCodewords(); correctErrors(codewords, 0, 10, 10, ALL); int mode = codewords[0] & 0x0F; byte[] datawords; switch (mode) { case 2: case 3: case 4: correctErrors(codewords, 20, 84, 40, EVEN); correctErrors(codewords, 20, 84, 40, ODD); datawords = new byte[94]; break; case 5: correctErrors(codewords, 20, 68, 56, EVEN); correctErrors(codewords, 20, 68, 56, ODD); datawords = new byte[78]; break; default: throw FormatException.getFormatInstance(); } System.arraycopy(codewords, 0, datawords, 0, 10); System.arraycopy(codewords, 20, datawords, 10, datawords.length - 10); return DecodedBitStreamParser.decode(datawords, mode); } private void correctErrors(byte[] codewordBytes, int start, int dataCodewords, int ecCodewords, int mode) throws ChecksumException { int codewords = dataCodewords + ecCodewords; // in EVEN or ODD mode only half the codewords int divisor = mode == ALL ? 1 : 2; // First read into an array of ints int[] codewordsInts = new int[codewords / divisor]; for (int i = 0; i < codewords; i++) { if ((mode == ALL) || (i % 2 == (mode - 1))) { codewordsInts[i / divisor] = codewordBytes[i + start] & 0xFF; } } try { rsDecoder.decode(codewordsInts, ecCodewords / divisor); } catch (ReedSolomonException ignored) { throw ChecksumException.getChecksumInstance(); } // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords for (int i = 0; i < dataCodewords; i++) { if ((mode == ALL) || (i % 2 == (mode - 1))) { codewordBytes[i + start] = (byte) codewordsInts[i / divisor]; } } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/maxicode/decoder/Decoder.java
Java
epl
3,830
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; /** * Thrown when a barcode was successfully detected and decoded, but * was not returned because its checksum feature failed. * * @author Sean Owen */ public final class ChecksumException extends ReaderException { private static final ChecksumException instance = new ChecksumException(); private ChecksumException() { // do nothing } public static ChecksumException getChecksumInstance() { return instance; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/ChecksumException.java
Java
epl
1,065
package com.zz.cc.common.data; import com.zz.common.utils.FileUtil; public abstract class IFileManager { private static final String FILE_NAME_NO_MEDIA = ".nomedia"; protected static final String PATH_ROOT = "CC/"; protected static final String PATH_BUSINES = "Business/"; protected static final String PATH_OWNER = "Owner"; protected static final String PATH_ICON_CACHE = "IconCache/"; protected static final String ICON_FILE_EXTENSION = ".jpg"; protected static final String PATH_LOG = "Log/"; public abstract String getWorkDir(); protected static void makeDirNoMedia(String path) { FileUtil.ensureDir(path); String filePath = path + FILE_NAME_NO_MEDIA; FileUtil.ensureFile(filePath); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/zz/cc/common/data/IFileManager.java
Java
epl
751
/** * */ package com.alipay.android.app.lib; import com.alipay.android.app.sdk.R; /** * @author 0ki * */ public class ResourceMap { public static int getString_confirm_title() { return R.string.confirm_title; } public static int getString_ensure() { return R.string.ensure; } public static int getString_cancel() { return R.string.cancel; } public static int getString_processing() { return R.string.processing; } public static int getString_download() { return R.string.download; } public static int getString_cancelInstallTips() { return R.string.cancel_install_msp; } public static int getString_cancelInstallAlipayTips() { return R.string.cancel_install_alipay; } public static int getString_download_fail() { return R.string.download_fail; } public static int getString_redo() { return R.string.redo; } public static int getString_install_msp() { return R.string.install_msp; } public static int getString_install_alipay() { return R.string.install_alipay; } public static int getLayout_pay_main() { return R.layout.alipay; } public static int getLayout_alert_dialog() { return R.layout.dialog_alert; } public static int getStyle_alert_dialog() { return R.style.AlertDialog; } public static int getImage_title() { return R.drawable.title; } public static int getImage_title_background() { return R.drawable.title_background; } public static int getId_mainView() { return R.id.mainView; } public static int getId_webView() { return R.id.webView; } public static int getId_btn_refresh() { return R.id.btn_refresh; } public static int getId_left_button() { return R.id.left_button; } public static int getId_right_button() { return R.id.right_button; } public static int getId_dialog_split_v() { return R.id.dialog_split_v; } public static int getId_dialog_title() { return R.id.dialog_title; } public static int getId_dialog_message() { return R.id.dialog_message; } public static int getId_dialog_divider() { return R.id.dialog_divider; } public static int getId_dialog_content_view() { return R.id.dialog_content_view; } public static int getId_dialog_button_group() { return R.id.dialog_button_group; } }
zzdache
trunk/android/cc/alipay_lib/src/com/alipay/android/app/lib/ResourceMap.java
Java
epl
2,256
package com.zz.cc.owner.data; public class CarSubModel { public String mModel; public String mModelId; public String mSubModel; public String mSubModelId; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/CarSubModel.java
Java
epl
164
package com.zz.cc.owner.data; import com.zz.common.tools.ImageLoader; public class OnrImageLoader extends ImageLoader { private static OnrImageLoader sLoader; public static OnrImageLoader getLoader() { if(null == sLoader) { FileManager fm = FileManager.getInstance(); sLoader = new OnrImageLoader(fm); } return sLoader; } protected OnrImageLoader(IUrlLocalFilePathCreator creator) { super(creator); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/OnrImageLoader.java
Java
epl
455
package com.zz.cc.owner.data; import android.content.Context; import com.zz.cc.common.data.IFileManager; import com.zz.cc.owner.OwnerApplication; import com.zz.common.tools.ImageLoader.IUrlLocalFilePathCreator; import com.zz.common.utils.AlgorithmUtil; import com.zz.common.utils.FileUtil; import com.zz.common.utils.StorageUtil; public class FileManager extends IFileManager implements IUrlLocalFilePathCreator { private static FileManager sInstance; private String mWorkPath; private String mIconCachePath; public static FileManager getInstance() { if(null == sInstance) { sInstance = new FileManager(OwnerApplication.getBaseApplication()); } return sInstance; } @Override public String getWorkDir() { return mWorkPath; } public String getIconPathForUrl(String url) { String md5 = AlgorithmUtil.md5(url); String path = mIconCachePath + md5 + ICON_FILE_EXTENSION; return path; } @Override //ImageLoader.IUrlLocalFilePathCreator public String createLocalFilePathForUrl(String url) { return getIconPathForUrl(url); } private FileManager(Context c) { String path = StorageUtil.getSDCardDir(); mWorkPath = path + PATH_ROOT + PATH_OWNER; mIconCachePath = mWorkPath + PATH_ICON_CACHE; FileUtil.ensureDir(mIconCachePath); makeDirNoMedia(mIconCachePath); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/FileManager.java
Java
epl
1,359
package com.zz.cc.owner.data; import android.os.Handler; import com.alipay.android.app.sdk.AliPay; import com.zz.common.app.BaseActivity; public class alipay { public static String syncAlipay(BaseActivity activity, float cost) { Handler handler = new Handler(); AliPay payer = new AliPay(activity, handler); String orderInfo = createOrderInfo(cost); String result = payer.pay(orderInfo); return result; } private static String createOrderInfo(float cost) { return "" + cost; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/alipay.java
Java
epl
502
package com.zz.cc.owner.data; public class Comment { public String mContent; public long mTime; public int mId; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/Comment.java
Java
epl
118
package com.zz.cc.owner.data; import com.alipay.android.app.sdk.AliPay; import com.zz.cc.owner.OwnerApplication; import com.zz.common.app.BaseActivity; import android.app.Application; import android.os.Handler; public class ModelCenter { private static final String TAG = "ModelCenter"; private static ModelCenter sCenter; private Application mContext; public static String syncAlipay(BaseActivity activity, float cost) { return alipay.syncAlipay(activity, cost); } public static ModelCenter getCenter() { synchronized (TAG) { if(null == sCenter) { sCenter = new ModelCenter(OwnerApplication.getBaseApplication()); } } return sCenter; } //limit Context as Application private ModelCenter(Application app) { mContext = app; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/ModelCenter.java
Java
epl
776
package com.zz.cc.owner.data; import java.io.Serializable; //车品牌 public class MyCarBrand implements Serializable { public Integer id; public String brandName; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/MyCarBrand.java
Java
epl
170
package com.zz.cc.owner.data; import java.io.Serializable; public class Store implements Serializable { public Integer id; //本地数据库中的ID public Integer serverId; //该店铺在我们系统server中的id public String name; public String address; public float originalPrice; public float preferencialPrice; public String introduce; public float score; public String phone; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/Store.java
Java
epl
400
package com.zz.cc.owner.data; import java.io.Serializable; //车型号 public class MyCarModel implements Serializable { public Integer id; public String modelName; public MyCarBrand brand; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/MyCarModel.java
Java
epl
196
package com.zz.cc.owner.data; public abstract class BoxAction { public static final int ACTION_ALIPAY = 0x10000; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/BoxAction.java
Java
epl
118
package com.zz.cc.owner.data; import java.util.ArrayList; public class CarModel { public String mModel; public String mModelId; public String mBrand; public String mBrandId; private ArrayList<CarSubModel> mSubModelList; public ArrayList<CarSubModel> getSubModelList() { return mSubModelList; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/CarModel.java
Java
epl
313
package com.zz.cc.owner.data; public class CarBrand { public String mBrandId; public int mIconId; public String mIconUrl; public String mBrand; public String mBrandPinyin; public String mFirstPinyinChar; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/CarBrand.java
Java
epl
219
package com.zz.cc.owner.data; import android.R.integer; public class Constants { public static final int OWNER_REG_SUCCESS = 0; public static final int OWNER_REG_FAILED = OWNER_REG_SUCCESS + 1; public static final int LOGIN_SUCCESS = OWNER_REG_FAILED + 1; public static final int LOGIN_FAILED = LOGIN_SUCCESS + 1; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/data/Constants.java
Java
epl
322
package com.zz.cc.owner; import com.baidu.location.LocationClient; import com.baidu.mapapi.BMapManager; import com.baidu.mapapi.MKGeneralListener; import com.zz.common.app.BaseApplication; public class OwnerApplication extends BaseApplication implements MKGeneralListener { private static final String MAK_KEY = "964206792a1c940290628a32947bd0f2"; public BMapManager mBMapManager = null; public LocationClient mLocationClient = null; @Override public void onCreate() { mLocationClient = new LocationClient( this ); mLocationClient.setAK("964206792a1c940290628a32947bd0f2"); createMapManager(); // sCrashPath = FileManager.getInstance().getWorkDir(); super.onCreate(); } private void createMapManager() { mBMapManager = new BMapManager(this); mBMapManager.init(MAK_KEY, this); mBMapManager.start(); } @Override public void onGetNetworkState(int state) { //TODO } @Override public void onGetPermissionState(int state) { //TODO } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/OwnerApplication.java
Java
epl
1,025
package com.zz.cc.owner.service; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import android.os.RemoteException; public interface ICcService extends IInterface { public static abstract class Stub extends Binder implements ICcService { private static final String DESCRIPTOR = ICcService.class.getName(); public Stub() { this.attachInterface(this, DESCRIPTOR); } public static ICcService asInterface(IBinder obj) { if(null == obj) { return null; } IInterface iin = (IInterface) obj.queryLocalInterface(DESCRIPTOR); if((null != null) && (iin instanceof ICcService)) { return (ICcService) iin; } else { return new Proxy(obj); } } @Override public IBinder asBinder() { return this; } @Override public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException{ switch(code) { case INTERFACE_TRANSACTION: { reply.writeString(DESCRIPTOR); return true; } case TRANSACTION_LOGIN: { data.enforceInterface(DESCRIPTOR); String userName = data.readString(); String pwd = data.readString(); int result = this.login(userName, pwd); reply.writeNoException(); reply.writeInt(result); return true; } case TRANSACTION_LOGOUT: { data.enforceInterface(DESCRIPTOR); int result = this.logout(); reply.writeNoException(); reply.writeInt(result); return true; } default: break; } return super.onTransact(code, data, reply, flags); } private static class Proxy implements ICcService { private IBinder mRemote; Proxy(IBinder remote) { mRemote = remote; } @Override public IBinder asBinder() { return mRemote; } public String getInterfaceDescriptor() { return DESCRIPTOR; } @Override public int login(String userName, String pwd) throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); int result; try { data.writeInterfaceToken(DESCRIPTOR); data.writeString(userName); data.writeString(pwd); mRemote.transact(Stub.TRANSACTION_LOGIN, data, reply, 0); reply.readException(); result = reply.readInt(); } finally { reply.recycle(); data.recycle(); } return result; } @Override public int logout() throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); int result; try { data.writeInterfaceToken(DESCRIPTOR); mRemote.transact(Stub.TRANSACTION_LOGOUT, data, reply, 0); reply.readException(); result = reply.readInt(); } finally { reply.recycle(); data.recycle(); } return result; } } } /*package*/ static final int TRANSACTION_LOGIN = IBinder.FIRST_CALL_TRANSACTION; /*package*/ static final int TRANSACTION_LOGOUT = TRANSACTION_LOGIN + 1; public int login(String userName, String pwd) throws RemoteException; public int logout() throws RemoteException; }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/service/ICcService.java
Java
epl
3,092
package com.zz.cc.owner; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import com.zz.common.app.BaseActivity; public class TitleBaseActivity extends BaseActivity { private TextView mTitle; private FrameLayout mContent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.layout_common_title_activity); initUI(); } @Override public void setContentView(int layoutId) { View v = LayoutInflater.from(this).inflate(layoutId, null); mContent.addView(v); } @Override public void setContentView(View layout) { mContent.addView(layout); } protected String getCurrentTitle() { return mTitle.getText().toString(); } protected void setCurrentTitle(int rId) { setCurrentTitle(getString(rId)); } protected void setCurrentTitle(String title) { mTitle.setText(title); } @Override protected String onGetTitleMirror() { return getCurrentTitle(); } @Override public void onBackPressed() { // super.onBackPressed(); finish(); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void initUI() { mTitle = (TextView) findViewById(R.id.common_title); mContent = (FrameLayout) findViewById(R.id.common_content); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/TitleBaseActivity.java
Java
epl
1,461
package com.zz.cc.owner.view; import com.zz.cc.owner.R; import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout; import android.widget.TextView; public class SummaryView extends RelativeLayout{ private TextView mBasicInfoTextView; private TextView mIntroduceTextView; public SummaryView(Context context) { super(context); } public SummaryView(Context context, AttributeSet attrs) { super(context, attrs); } public SummaryView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setBasicInfo(String baseInfo) { mBasicInfoTextView.setText(baseInfo); } public void setIntroduce(String introduce) { mIntroduceTextView.setText(introduce); } @Override public void onFinishInflate() { super.onFinishInflate(); mBasicInfoTextView = (TextView) findViewById(R.id.summary_basic_info); mIntroduceTextView = (TextView) findViewById(R.id.summary_introduce); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/view/SummaryView.java
Java
epl
989
package com.zz.cc.owner.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import android.widget.SectionIndexer; import android.widget.TextView; public class SideBar extends View { private char[] l; private SectionIndexer sectionIndexter = null; private ListView list; private TextView mDialogText; private int m_nItemHeight = 30; public SideBar(Context context) { super(context); init(); } public SideBar(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { l = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; } public SideBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void setListView(ListView _list) { list = _list; sectionIndexter = (SectionIndexer) _list.getAdapter(); } public void setTextView(TextView mDialogText) { this.mDialogText = mDialogText; } public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); int i = (int) event.getY(); int idx = i / m_nItemHeight; if (idx >= l.length) { idx = l.length - 1; } else if (idx < 0) { idx = 0; } if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) { mDialogText.setVisibility(View.VISIBLE); mDialogText.setText(""+l[idx]); if (sectionIndexter == null) { sectionIndexter = (SectionIndexer) list.getAdapter(); } int position = sectionIndexter.getPositionForSection(l[idx]); if (position == -1) { return true; } list.setSelection(position); }else{ mDialogText.setVisibility(View.INVISIBLE); } return true; } protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setTextSize(20); paint.setTextAlign(Paint.Align.CENTER); m_nItemHeight = (int)((float)getMeasuredHeight()/26); float widthCenter = getMeasuredWidth() / 2; for (int i = 0; i < l.length; i++) { canvas.drawText(String.valueOf(l[i]), widthCenter, m_nItemHeight + (i * m_nItemHeight), paint); } super.onDraw(canvas); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/view/SideBar.java
Java
epl
3,006
package com.zz.cc.owner.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Environment; import android.os.StatFs; import android.text.Editable; import android.text.InputFilter; import android.text.Spanned; import android.text.TextWatcher; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; public class Util { //private static final String TAG = "Util"; public static void log(String tag, String content) { log(tag, content, false); } public static void log(String tag, byte []content) { // if(Config.CONFIG_UTIL_PRINT_LOG) { // String temp = new String(content); // log(tag, temp); // } } public static void log(String tag, String content, boolean force) { if(force) { Log.d(tag, content); } else { // if(Config.CONFIG_UTIL_PRINT_LOG) { // Log.d(tag, content); // } } } public static void createDirectory(String strPath) { File file =new File(strPath); if(!file .exists()) { file .mkdirs(); } } public static boolean isFileExist(String filePath) { File file = new File(filePath); if(!file.exists() || file.isDirectory()) { return false; } return true; } public static boolean isDirExist(String path) { File file = new File(path); if(!file.exists() || file.isFile()) { return false; } return true; } public static String md5(String key) { try { char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] buf = key.getBytes(); md.update(buf, 0, buf.length); byte[] bytes = md.digest(); StringBuilder sb = new StringBuilder(32); for (byte b : bytes) { sb.append(hex[((b >> 4) & 0xF)]).append(hex[((b >> 0) & 0xF)]); } key = sb.toString(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return key; } public static int px2dip(Context context, float pxValue){ final float scale = context.getResources().getDisplayMetrics().density; return (int)(pxValue / scale + 0.5f); } public static int dip2px(Context context, float dipValue){ final float scale = context.getResources().getDisplayMetrics().density; return (int)(dipValue * scale + 0.5f); } public static String getSDCardDir() { return Environment.getExternalStorageDirectory().getPath(); } public static boolean isSDCardExist() { return Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState()); } public static long getFileSize(String path) { File file = new File(path); return getFileSize(file); } public static long getFileSize(File file) { if(!file.exists()) { return 0; } if(file.isFile()) { return file.length(); } long size = 0; File[] list = file.listFiles(); for(File tmp: list) { size += getFileSize(tmp); } return size; } public static boolean deleteDir(String path) { File f = new File(path); if(!f.exists() || !f.isDirectory()){ return false; } File[] fileList = f.listFiles(); for(File file: fileList) { if(file.isFile()) { file.delete(); } else if(file.isDirectory()) { deleteDir(file.getAbsolutePath()); } } f.delete(); return true; } public static long getAvailableExternalMemorySize() { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } public static long getTotalExternalMemorySize() { File path = Environment.getExternalStorageDirectory(); Environment.getExternalStorageState(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } public static String getDateString(long ms) { return getDateString(ms, "yyyy-MM-dd HH:mm:ss"); } public static String getDateString(long ms, String format) { Date curDate = new Date(ms); return getDateString(curDate, format); } public static String getNowDateString() { return getNowDateString("yyyy-MM-dd HH:mm:ss"); } public static String getNowDateString(String format) { Date curDate = new Date(System.currentTimeMillis()); return getDateString(curDate, format); } public static String getDateString(Date date) { return getDateString(date, "yyyy-MM-dd HH:mm:ss"); } public static void showToast(Context ctx,String content){ Toast.makeText(ctx, content, Toast.LENGTH_SHORT).show(); } public static String inputStream2String(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = -1; while ((i = is.read()) != -1) { baos.write(i); } return baos.toString(); } public static String getDateString(Date date, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(date); } public static String byteConvert(long byteNum) { double f = byteNum / (1024 * 1024 * 1024 * 1.0); String res; if(f > 1.0) { //大于1G res = new DecimalFormat("0.00").format(f); res += "GB"; } else { //小于1G f = byteNum / (1024 * 1024 * 1.0); if(f > 1.0) { //大于1M res = new DecimalFormat("0.00").format(f); res += "MB"; } else { //小于1M f = byteNum / (1024 * 1.0); if(f > 1.0) { //大于1K res = new DecimalFormat("0").format(f); res += "KB"; } else { //小于1K res = byteNum + "B"; } } } return res; } public static String byteConvertEx(long byteNum) { double f = byteNum / (1024 * 1024 * 1024 * 1.0); String res; if(f > 1.0) { //大于1G res = new DecimalFormat("0.0").format(f); res += "G"; } else { //小于1G f = byteNum / (1024 * 1024 * 1.0); if(f > 1.0) { //大于1M res = new DecimalFormat("0.0").format(f); res += "M"; } else { //小于1M f = byteNum / (1024 * 1.0); if(f > 1.0) { //大于1K res = new DecimalFormat("0").format(f); res += "K"; } else { //小于1K res = byteNum + "B"; } } } return res; } public static boolean checkEmail(String strAddress) { String reg = "[0-9a-zA-Z][0-9a-zA-Z_.]*[^_]@[0-9a-zA-Z]+(\\.[0-9a-zA-Z]+)*\\.[0-9a-zA-Z]+$"; if(!strAddress.matches(reg)) { return false; } return true; } public static void hiddenInput(Context ctx,View v){ InputMethodManager inputMethodManager = (InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } public static boolean copy(String from, String to) { try { String toPath = to.substring(0,to.lastIndexOf("/")); //提取文件路径 File f = new File(toPath); //建立文件目录路 if(!f.exists()) f.mkdirs(); BufferedInputStream bin = new BufferedInputStream(new FileInputStream(from)); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(to)); int c; while((c=bin.read()) != -1) //复制 bout.write(c); bin.close(); bout.close(); return true; } catch(Exception e) { e.printStackTrace(); return false; } } public static void showToast(Toast toast,String str){ try{ toast.setText(str); toast.show(); }catch(Exception e){ e.printStackTrace(); } } public static boolean isCharFiltered(char ch) { char table[] = {'/', '\\', '<', '>', ':', ':', '*', '?', '?', '"', '\n', '|'}; for(char c : table) { if(c == ch) return true; } return false; } public static final class FileNameInputFilter implements InputFilter{ private final String TAG = "FileNameInputFilter"; @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { Util.log(TAG, "source = " + source + " start = " + start + " end = " + end + " dstart =" + dstart + " dend = " + dend); String str = source.toString(); String dst = new String(); boolean show = false; for(int i =0 ; i < str.length(); i++){ char c = str.charAt(i); if(c !='/' && c !='\\' && c !='<' && c !='>' && c !=':' && c !='*' && c !='?' && c !='"' && c !='\n' && c !='|' ){ dst+=c; }else{ show = true; } } return dst; } } public static class TextLengthWatcher implements TextWatcher { private Context mCtx; private EditText mEditText; private int mMaxLength; private Toast mToast = null; public TextLengthWatcher(Context ctx, EditText editText, int maxLength) { mCtx = ctx; mEditText = editText; mMaxLength = maxLength; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { int nSelEnd = mEditText.getSelectionEnd(); if(nSelEnd == 0) { return; } boolean isOverMaxLength = s.length() > mMaxLength ? true : false; if(isOverMaxLength) { if(mToast == null) { mToast = Toast.makeText(mCtx, "超过最多字符限制!", Toast.LENGTH_SHORT); } mToast.show(); String tmp = mEditText.getText().toString().substring(0, mMaxLength); mEditText.setText(tmp); mEditText.setSelection(mEditText.getText().length()); } } } public static void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } public static String getTimePastDesc(String strtime){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return getTimePastDesc(formatter.parse(strtime).getTime()); } catch (ParseException e) { e.printStackTrace(); return strtime; } } public static String getTimePastDesc(long thetime){ String str = ""; long cur = System.currentTimeMillis(); cur -= thetime; if(cur<0) cur = 0; cur /= 1000; if(cur < 60){ str = cur+" 秒前"; return str; } cur /= 60; if(cur < 60){ str = cur+" 分钟前"; return str; } cur /= 60; if(cur < 24){ str = cur+" 小时前"; return str; } cur /= 24; str = getDateString(thetime, "yy-MM-dd"); /*if(cur < 365){ str = cur+" 天前"; return str; } cur /= 365; str = cur+" 年前"; */ return str; } public static DisplayMetrics getScreenDim(Activity ctx){ DisplayMetrics dm = new DisplayMetrics(); ctx.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm; } public static String getFirstClassDomainName(String url) { String ret = url; if(null != ret) { if(!ret.trim().equals("")) { String temp; ret = ret.replace("http://", ""); int index = ret.indexOf("/"); if(index != -1) { ret = ret.substring(0, index); } try { temp = ret.substring(ret.lastIndexOf(".")); ret = ret.substring(0, ret.lastIndexOf(".")); String temp1 = ret.substring(ret.lastIndexOf(".") + 1); ret = temp1 + temp; }catch(Exception e) { } } } return ret; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/util/Util.java
Java
epl
14,162
package com.zz.cc.owner.util; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class PinYin4j { public PinYin4j(){ } public String makeStringByStringSet(Set<String> stringSet) { StringBuilder str = new StringBuilder(); int i = 0; for (String s : stringSet) { if (i == stringSet.size() - 1) { str.append(s); } else { str.append(s + ","); } i++; } return str.toString().toLowerCase(); } public Set<String> getPinyin(String src) { char[] srcChar; srcChar = src.toCharArray(); //1:多少个汉字 //2:每个汉字多少种读音 String[][] temp = new String[src.length()][]; for (int i = 0; i < srcChar.length; i++) { char c = srcChar[i]; if (String.valueOf(c).matches("[\\u4E00-\\u9FA5]+")) { String[] t = PinyinHelper.getUnformattedHanyuPinyinStringArray(c); temp[i] = new String[t.length]; for(int j=0;j<t.length;j++){ temp[i][j]=t[j].substring(0,1); } } else if (((int) c >= 65 && (int) c <= 90) || ((int) c >= 97 && (int) c <= 122)||c>=48&&c<=57||c==42) {//a-zA-Z0-9* temp[i] = new String[] { String.valueOf(srcChar[i]) }; } else { temp[i] = new String[] {"null!"}; } } String[] pingyinArray = paiLie(temp); return array2Set(pingyinArray);//过滤重复的 } private String[] paiLie(String[][] str){ int max=1; for(int i=0;i<str.length;i++){ max*=str[i].length; } String[] result=new String[max]; for(int i = 0; i < max; i++){ String s = ""; int temp = 1; for(int j = 0; j < str.length; j++){ temp *= str[j].length; s += str[j][i / (max / temp) % str[j].length]; } result[i]=s; } return result; } public static <T extends Object> Set<T> array2Set(T[] tArray) { Set<T> tSet = new HashSet<T>(Arrays.asList(tArray)); return tSet; } public static void main(String[] args) { PinYin4j t=new PinYin4j(); String str = "农业银行1234567890abcdefghijklmnopqrstuvwxyz*"; System.out.println(t.makeStringByStringSet(t.getPinyin(str))); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/util/PinYin4j.java
Java
epl
2,270
package com.zz.cc.owner.util; import android.graphics.Bitmap; import android.view.View; public class BMapUtil { /** * 从view 得到图片 * @param view * @return */ public static Bitmap getBitmapFromView(View view) { view.destroyDrawingCache(); view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.setDrawingCacheEnabled(true); Bitmap bitmap = view.getDrawingCache(true); return bitmap; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/util/BMapUtil.java
Java
epl
667
package com.zz.cc.owner.util; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class PinyinHelper{ private static PinyinHelper instance; private Properties properties = null; public static String[] getUnformattedHanyuPinyinStringArray(char ch){ return getInstance().getHanyuPinyinStringArray(ch); } private PinyinHelper(){ initResource(); } public static PinyinHelper getInstance(){ if(instance==null){ instance = new PinyinHelper(); } return instance; } private void initResource(){ try{ final String resourceName = "/assets/unicode2pinyin.txt"; properties=new Properties(); properties.load(getResourceInputStream(resourceName)); } catch (FileNotFoundException ex){ ex.printStackTrace(); } catch (IOException ex){ ex.printStackTrace(); } } private BufferedInputStream getResourceInputStream(String resourceName){ return new BufferedInputStream(PinyinHelper.class.getResourceAsStream(resourceName)); } private String[] getHanyuPinyinStringArray(char ch){ String pinyinRecord = getHanyuPinyinRecordFromChar(ch); if (null != pinyinRecord){ int indexOfLeftBracket = pinyinRecord.indexOf(Field.LEFT_BRACKET); int indexOfRightBracket = pinyinRecord.lastIndexOf(Field.RIGHT_BRACKET); String stripedString = pinyinRecord.substring(indexOfLeftBracket + Field.LEFT_BRACKET.length(), indexOfRightBracket); return stripedString.split(Field.COMMA); } else return null; } private String getHanyuPinyinRecordFromChar(char ch){ int codePointOfChar = ch; String codepointHexStr = Integer.toHexString(codePointOfChar).toUpperCase(); String foundRecord = properties.getProperty(codepointHexStr); return foundRecord; } class Field{ static final String LEFT_BRACKET = "("; static final String RIGHT_BRACKET = ")"; static final String COMMA = ","; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/util/PinyinHelper.java
Java
epl
2,262
package com.zz.cc.owner.util; import java.util.Comparator; import com.zz.cc.owner.data.MyCarModel; public class PinyinComparator implements Comparator{ @Override public int compare(Object o1, Object o2) { String str1; String str2; str1 = PingYinUtil.getPingYin(((MyCarModel) o1).modelName .toLowerCase()); str2 = PingYinUtil.getPingYin(((MyCarModel) o2).modelName .toLowerCase()); return str1.compareTo(str2); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/util/PinyinComparator.java
Java
epl
464
package com.zz.cc.owner.util; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; public class PingYinUtil { /** * 将字符串中的中文转化为拼音,其他字符不变 * * @param inputString * @return */ public static String getPingYin(String inputString) { HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); char[] input = inputString.trim().toCharArray(); String output = ""; try { for (int i = 0; i < input.length; i++) { if (java.lang.Character.toString(input[i]). matches("[\\u4E00-\\u9FA5]+")) { String[] temp = PinyinHelper. toHanyuPinyinStringArray(input[i], format); output += temp[0]; } else output += java.lang.Character.toString( input[i]); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } return output; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/util/PingYinUtil.java
Java
epl
1,650
package com.zz.cc.owner.app; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; public class LoginActivity extends TitleBaseActivity implements OnClickListener, OnCheckedChangeListener { private EditText mUserNameInput; private EditText mPasswordInput; private Button mLoginBtn; private Button mRegisterBtn; private TextView mForgetPasswordInput; private CheckBox mManualCheckBox; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initUI(); fillView(); } private void initUI() { mUserNameInput = (EditText) findViewById(R.id.login_input_user_name); mPasswordInput = (EditText) findViewById(R.id.login_input_password); mLoginBtn = (Button) findViewById(R.id.login_login); mRegisterBtn = (Button) findViewById(R.id.login_register); mForgetPasswordInput = (TextView) findViewById(R.id.login_forget_password); mManualCheckBox = (CheckBox) findViewById(R.id.login_manual); } private void fillView() { super.setCurrentTitle(R.string.login_title); mLoginBtn.setOnClickListener(this); mRegisterBtn.setOnClickListener(this); mForgetPasswordInput.setOnClickListener(this); mManualCheckBox.setOnCheckedChangeListener(this); mManualCheckBox.setOnClickListener(this); } private void gotoForgetPasswordActivity() { Intent intent = new Intent(this, ForgetPasswordActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void gotoMainActivity() { Intent intent = new Intent(this, NewMainActivity.class); startActivity(intent); finish(); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void gotoRegisterActivity() { Intent intent = new Intent(this, RegisterPhoneNumActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } @Override public void onClick(View view) { int id = view.getId(); switch(id) { case R.id.login_login: //TODO gotoMainActivity(); break; case R.id.login_register: gotoRegisterActivity(); break; case R.id.login_forget_password: gotoForgetPasswordActivity(); break; default: break; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/LoginActivity.java
Java
epl
2,905
package com.zz.cc.owner.app; import android.content.Intent; import android.os.Bundle; import android.os.Handler.Callback; import android.os.Message; import com.zz.cc.owner.R; import com.zz.common.app.BaseActivity; import com.zz.common.tools.WeakReferenceHandler; public class StartUpActivity extends BaseActivity implements Callback { private static final int ACTION_START_UP_FINISH = 100; private static final int PERIOD_START_UP = 1000; private WeakReferenceHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new WeakReferenceHandler(this); setContentView(R.layout.activity_start_up); mHandler.sendEmptyMessageDelayed(ACTION_START_UP_FINISH, PERIOD_START_UP); } @Override public void onDestroy() { super.onDestroy(); mHandler.removeMessages(ACTION_START_UP_FINISH); } @Override public boolean handleMessage(Message msg) { if(msg.what == ACTION_START_UP_FINISH) { startNextActivity(); } return true; } private void startNextActivity() { Intent intent = new Intent(this, UserGuideActivity.class); startActivity(intent); finish(); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/StartUpActivity.java
Java
epl
1,305
package com.zz.cc.owner.app; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; public class ReserveActivity extends TitleBaseActivity implements OnClickListener, OnCheckedChangeListener { private RadioButton m50Radio; private RadioButton m100Radio; private RadioButton m1000Radio; private EditText mSearchInput; private Button mSearchSubmit; private EditText mRechargeInput; private Button mRechargeSubmit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reserve); initUI(); fillView(); } private void initUI() { m50Radio = (RadioButton) findViewById(R.id.reserve_destination_50_metre); m100Radio = (RadioButton) findViewById(R.id.reserve_destination_100_metre); m1000Radio = (RadioButton) findViewById(R.id.reserve_destination_1000_metre); mSearchInput = (EditText) findViewById(R.id.reserve_search_input); mSearchSubmit = (Button) findViewById(R.id.reserve_search_submit); mRechargeInput = (EditText) findViewById(R.id.reserve_pre_recharge_input); mRechargeSubmit = (Button) findViewById(R.id.reserve_recharge_submit); } private void fillView() { super.setCurrentTitle(R.string.reserve_title); mSearchSubmit.setOnClickListener(this); mRechargeSubmit.setOnClickListener(this); m50Radio.setOnCheckedChangeListener(this); m100Radio.setOnCheckedChangeListener(this); m1000Radio.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton btn, boolean check) { // TODO } @Override public void onClick(View view) { int id = view.getId(); if(id == R.id.reserve_recharge_submit) { onBackPressed(); } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/ReserveActivity.java
Java
epl
2,063
package com.zz.cc.owner.app; import com.zz.cc.owner.TitleBaseActivity; public class RegisterBasicInfoActivity extends TitleBaseActivity { }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/RegisterBasicInfoActivity.java
Java
epl
143
package com.zz.cc.owner.app; import java.util.List; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.map.ItemizedOverlay; import com.baidu.mapapi.map.LocationData; import com.baidu.mapapi.map.MKEvent; import com.baidu.mapapi.map.MapController; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationOverlay; import com.baidu.mapapi.map.OverlayItem; import com.baidu.mapapi.map.PopupClickListener; import com.baidu.mapapi.map.PopupOverlay; import com.baidu.mapapi.map.RouteOverlay; import com.baidu.mapapi.search.MKAddrInfo; import com.baidu.mapapi.search.MKBusLineResult; import com.baidu.mapapi.search.MKDrivingRouteResult; import com.baidu.mapapi.search.MKPlanNode; import com.baidu.mapapi.search.MKPoiInfo; import com.baidu.mapapi.search.MKPoiResult; import com.baidu.mapapi.search.MKSearch; import com.baidu.mapapi.search.MKSearchListener; import com.baidu.mapapi.search.MKShareUrlResult; import com.baidu.mapapi.search.MKSuggestionResult; import com.baidu.mapapi.search.MKTransitRouteResult; import com.baidu.mapapi.search.MKWalkingRouteResult; import com.baidu.platform.comapi.basestruct.GeoPoint; import com.zz.cc.owner.OwnerApplication; import com.zz.cc.owner.R; import com.zz.cc.owner.util.BMapUtil; import com.zz.cc.owner.util.Util; public class MapActivity extends OwnerBaseActivity { private MapView mMapView; private OwnerApplication mOwnerApplication; private LocationClient mLocClient; private MyLocationListener myLocationListener = new MyLocationListener(); private MapController mMapController; private MKSearch mMkSearch; private MyOverlay mOverlay; private double myLatitude,myLongitude; private View viewCache = null; private View popupInfo = null; private View popupLeft = null; private View popupRight = null; private TextView popupText; private Button mPopButton; private PopupOverlay pop = null; private OverlayItem mCurItem = null; private MapView.LayoutParams layoutParam = null; private RouteOverlay routeOverlay = null; private Button mGoBackBtn; private MKSearchListener mkSearchListener = new MKSearchListener() { @Override public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onGetShareUrlResult(MKShareUrlResult arg0, int arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onGetPoiResult(MKPoiResult result, int type, int iError) { if ( iError == MKEvent.ERROR_RESULT_NOT_FOUND){ mapMoveToPoint(myLatitude, myLongitude); Toast.makeText(MapActivity.this, "抱歉,未找到结果",Toast.LENGTH_LONG).show(); return ; } else if (iError != 0 || result == null) { mapMoveToPoint(myLatitude, myLongitude); Toast.makeText(MapActivity.this, "搜索出错啦..", Toast.LENGTH_LONG).show(); return; } Util.showToast(MapActivity.this, "onGetPoiResult"); initOverlay(result.getAllPoi()); mMapView.getController().animateTo(new GeoPoint((int)(myLatitude*1E6), (int)(myLongitude*1E6))); } @Override public void onGetPoiDetailSearchResult(int arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { // TODO Auto-generated method stub if (error == MKEvent.ERROR_ROUTE_ADDR){ Util.showToast(MapActivity.this, "抱歉,搜索出现错误,请稍候重试"); return; } if (error != 0 || res == null) { Toast.makeText(MapActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show(); return; } routeOverlay = new RouteOverlay(MapActivity.this, mMapView); // 此处仅展示一个方案作为示例 routeOverlay.setData(res.getPlan(0).getRoute(0)); //清除其他图层 mMapView.getOverlays().clear(); //添加路线图层 mMapView.getOverlays().add(routeOverlay); //执行刷新使生效 mMapView.refresh(); // 使用zoomToSpan()绽放地图,使路线能完全显示在地图上 mMapView.getController().zoomToSpan(routeOverlay.getLatSpanE6(), routeOverlay.getLonSpanE6()); //移动地图到起点 mMapView.getController().animateTo(res.getStart().pt); mGoBackBtn.setVisibility(View.VISIBLE); } @Override public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onGetAddrResult(MKAddrInfo arg0, int arg1) { // TODO Auto-generated method stub } }; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); mOwnerApplication = (OwnerApplication)this.getApplication(); mMkSearch = new MKSearch(); mMkSearch.setPoiPageCapacity(50); mMkSearch.init(mOwnerApplication.mBMapManager, mkSearchListener); mOwnerApplication.mLocationClient.registerLocationListener(myLocationListener); mLocClient = mOwnerApplication.mLocationClient; mLocClient.registerLocationListener(myLocationListener); mMkSearch.init(mOwnerApplication.mBMapManager,mkSearchListener ); initUI(); } private void mapMoveToPoint(double latitude,double longitude){ MyLocationOverlay myLocationOverlay = new MyLocationOverlay(mMapView); LocationData locData = new LocationData(); //手动将位置源置为天安门,在实际应用中,请使用百度定位SDK获取位置信息,要在SDK中显示一个位置,需要使用百度经纬度坐标(bd09ll) locData.latitude = latitude; locData.longitude = longitude; locData.direction = 2.0f; myLocationOverlay.setData(locData); mMapView.getOverlays().add(myLocationOverlay); mMapView.refresh(); mMapView.getController().animateTo(new GeoPoint((int)(locData.latitude*1e6), (int)(locData.longitude* 1e6))); } private void initOverlay(List<MKPoiInfo> poiInfos){ mOverlay.removeAll(); for (MKPoiInfo mkPoiInfo : poiInfos) { OverlayItem item = new OverlayItem(mkPoiInfo.pt, mkPoiInfo.name, mkPoiInfo.phoneNum); item.setMarker(getResources().getDrawable(R.drawable.nav_turn_via_1)); mOverlay.addItem(item); } OverlayItem myItem = new OverlayItem(new GeoPoint((int)(myLatitude*1E6), (int)(myLongitude*1E6)), "我的位置", ""); myItem.setMarker(getResources().getDrawable(R.drawable.icon_geo)); mOverlay.addItem(myItem); mMapView.getOverlays().add(mOverlay); mMapView.refresh(); mMapView.getController().animateTo(myItem.getPoint()); viewCache = getLayoutInflater().inflate(R.layout.custom_text_view, null); popupInfo = (View) viewCache.findViewById(R.id.popinfo); popupLeft = (View) viewCache.findViewById(R.id.popleft); popupRight = (View) viewCache.findViewById(R.id.popright); popupText =(TextView) viewCache.findViewById(R.id.textcache); mPopButton = new Button(this); mPopButton.setBackgroundResource(R.drawable.popup); PopupClickListener popListener = new PopupClickListener(){ @Override public void onClickedPopup(int index) { if ( index == 0){ searchDrivingDirection(mCurItem.getPoint()); mMapView.refresh(); } else if(index == 2){ //更新图标 mCurItem.setMarker(getResources().getDrawable(R.drawable.nav_turn_via_1)); mOverlay.updateItem(mCurItem); mMapView.refresh(); } } }; pop = new PopupOverlay(mMapView,popListener); } private void initUI(){ setContentView(R.layout.map); mGoBackBtn = (Button)findViewById(R.id.goback); mGoBackBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mMapView.getOverlays().clear(); mMapView.refresh(); requestLocation(); mGoBackBtn.setVisibility(viewCache.GONE); } }); ((TextView)findViewById(R.id.titleTextView)).setText("地图模式"); findViewById(R.id.backImg).setVisibility(View.GONE); ((Button)findViewById(R.id.rightBtn)).setText("列表模式"); ((Button)findViewById(R.id.rightBtn)).setVisibility(View.VISIBLE); ((Button)findViewById(R.id.rightBtn)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub startActivity(new Intent(MapActivity.this, StoreListActivity.class)); } }); mMapView = (MapView)findViewById(R.id.bmapsView); mMapView.setBuiltInZoomControls(true); //设置启用内置的缩放控件 mMapController=mMapView.getController(); mOverlay = new MyOverlay(getResources().getDrawable(R.drawable.nav_turn_via_1), mMapView); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放 GeoPoint point =new GeoPoint((int)(39.915* 1E6),(int)(116.404* 1E6)); //用给定的经纬度构造一个GeoPoint,单位是微度 (度 * 1E6) mMapController.setCenter(point);//设置地图中心点 mMapController.setZoom(16);//设置地图zoom级别 requestLocation(); } private void searchDrivingDirection(GeoPoint endPoint){ MKPlanNode startNode = new MKPlanNode(); startNode.pt = new GeoPoint((int)(myLatitude*1E6), (int)(myLongitude*1E6)); MKPlanNode endNode = new MKPlanNode(); endNode.pt = endPoint; mMkSearch.setDrivingPolicy(MKSearch.ECAR_TIME_FIRST); mMkSearch.drivingSearch(null, startNode, null, endNode); } private void requestLocation(){ LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); option.setAddrType("all");//返回的定位结果包含地址信息 option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02 option.setScanSpan(500);//设置发起定位请求的间隔时间为5000ms option.disableCache(true);//禁止启用缓存定位 option.setPoiNumber(5); //最多返回POI个数 option.setPoiDistance(1000); //poi查询距离 option.setPoiExtraInfo(true); //是否需要POI的电话和地址等详细信息 mLocClient.setLocOption(option); mLocClient.start(); mLocClient.requestLocation(); } @Override public void onDestroy() { mMapView.destroy(); super.onDestroy(); } @Override public void onPause() { mMapView.onPause(); super.onPause(); } @Override public void onResume() { mMapView.onResume(); super.onResume(); } class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null) return ; Util.showToast(MapActivity.this, "onReceiveLocation"); myLatitude = location.getLatitude(); myLongitude = location.getLongitude(); // mMkSearch.poiSearchNearBy("车", new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6)), 150000); mMkSearch.poiSearchInCity(location.getCity(), "车"); } public void onReceivePoi(BDLocation poiLocation) { } } class MyOverlay extends ItemizedOverlay{ public MyOverlay(Drawable defaultMarker, MapView mapView) { super(defaultMarker, mapView); } @Override protected boolean onTap(int index) { OverlayItem item = getItem(index); mCurItem = item ; if (index == getAllItem().size()-1){ mPopButton.setText("我的当前位置"); GeoPoint pt = new GeoPoint ((int)(myLatitude*1E6),(int)(myLongitude*1E6)); //创建布局参数 layoutParam = new MapView.LayoutParams( //控件宽,继承自ViewGroup.LayoutParams MapView.LayoutParams.WRAP_CONTENT, //控件高,继承自ViewGroup.LayoutParams MapView.LayoutParams.WRAP_CONTENT, //使控件固定在某个地理位置 pt, 0, -32, //控件对齐方式 MapView.LayoutParams.BOTTOM_CENTER); //添加View到MapView中 mMapView.addView(mPopButton,layoutParam); } else{ popupText.setText(getItem(index).getTitle()); Bitmap[] bitMaps={ BMapUtil.getBitmapFromView(popupLeft), BMapUtil.getBitmapFromView(popupInfo), BMapUtil.getBitmapFromView(popupRight) }; pop.showPopup(bitMaps,item.getPoint(),32); } return true; } @Override public boolean onTap(GeoPoint arg0, MapView arg1) { if (pop != null){ pop.hidePop(); mMapView.removeView(mPopButton); } return false; } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/MapActivity.java
Java
epl
13,271
package com.zz.cc.owner.app; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; public class QrCodeResultActivity extends TitleBaseActivity{ public static final String INDEX_QR_CODE = "index_qr_code"; private TextView mQrCodeTextView; private String mQrCode; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); getArgumentsFromIntent(intent); setContentView(R.layout.activity_qrcode_result); initUI(); fillView(); } private void initUI() { mQrCodeTextView = (TextView) findViewById(R.id.result_qr_code); } private void fillView() { setCurrentTitle("洗车信息"); mQrCodeTextView.setText(mQrCode); } private void getArgumentsFromIntent(Intent intent) { mQrCode = intent.getStringExtra(INDEX_QR_CODE); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/QrCodeResultActivity.java
Java
epl
940
package com.zz.cc.owner.app; import android.content.Intent; import android.os.Bundle; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; public class WebkitActivity extends TitleBaseActivity { private static final String INDEX_TITLE = "title"; private static final String INDEX_URL = "url"; private WebView mWebView; private String mInitTitle; private String mInitUrl; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initData(getIntent()); setContentView(R.layout.activity_webkit); initUI(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); releaseWebView(); } @Override public void onBackPressed() { if(mWebView.canGoBack()) { mWebView.goBack(); return; } super.onBackPressed(); } private void initData(Intent intent) { mInitTitle = intent.getStringExtra(INDEX_TITLE); mInitUrl = intent.getStringExtra(INDEX_URL); } private void initUI() { mWebView = (WebView) findViewById(R.id.webkit_webview); mWebView.getSettings().setCacheMode(WebSettings.LOAD_NORMAL); mWebView.getSettings().setBlockNetworkImage(true); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebChromeClient(new WebkitChromeClient()); mWebView.setWebViewClient(new WebkitWebViewClient()); setCurrentTitle(mInitTitle); loadUrl(mInitUrl); } private class WebkitChromeClient extends WebChromeClient { @Override public void onReceivedTitle(WebView webView, String title) { setCurrentTitle(title); } @Override public void onProgressChanged(WebView webView, int newProgress) { } } private class WebkitWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView webview, String url) { loadUrl(url); return true; } } private void loadUrl(String url) { mWebView.stopLoading(); mWebView.clearView(); mWebView.loadUrl(url); } private void releaseWebView() { mWebView.stopLoading(); mWebView.clearView(); mWebView.destroy(); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/WebkitActivity.java
Java
epl
2,226
package com.zz.cc.owner.app; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.SectionIndexer; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; import com.zz.cc.owner.data.CarBrand; import com.zz.common.widget.ZBladeView; import com.zz.common.widget.ZPinnedHeaderListView; import com.zz.common.widget.ZPinnedHeaderListView.PinnedHeaderAdapter; public class RegisterCarBrandActivity extends TitleBaseActivity implements OnItemClickListener { private ZPinnedHeaderListView mListView; private ZBladeView mBladeView; private final ArrayList<BrandItem> mBrandItems = new ArrayList<BrandItem>(); private final ArrayList<String> mSelections = new ArrayList<String>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_car_brand); initUI(); fillView(); } private void initUI() { mListView = (ZPinnedHeaderListView) findViewById(R.id.car_brank_list_view); mBladeView = (ZBladeView) findViewById(R.id.car_brank_blade_view); } private void fillView() { setCurrentTitle(R.string.card_brand_title); mListView.setOnItemClickListener(this); } private void loadData() { mBrandItems.clear(); mSelections.clear(); ArrayList<CarBrand> brands = null; //TODO load brands brands = new ArrayList<CarBrand>(); if(null != brands) { //sort the brand list Collections.sort(brands, mCarBrandComparator); //init the indexs String firstChar = null; BrandItem curItem = null; int index = -1; for(CarBrand brand: brands) { if(firstChar != brand.mFirstPinyinChar) { firstChar = brand.mFirstPinyinChar; index++; BrandItem item = new BrandItem(firstChar, index); mBrandItems.add(item); curItem = item; mSelections.add(firstChar); } else { BrandItem item = new BrandItem(brand, index); mBrandItems.add(item); curItem.mCount++; } } } } @Override public void onItemClick(AdapterView<?> parent, View convertView, int position, long itemId) { ViewHolder holder = (ViewHolder) convertView.getTag(); if(null != holder && holder.mBrandItem.mViewType == CarBrandAdapter.TYPE_ITEM) { Intent intent = new Intent(this, RegisterCarModelActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } } private Comparator<CarBrand> mCarBrandComparator = new Comparator<CarBrand>() { @Override public int compare(CarBrand lhs, CarBrand rhs) { int r = 0; do { r = lhs.mFirstPinyinChar.compareTo(rhs.mFirstPinyinChar); if(r != 0) { break; } r = lhs.mBrandPinyin.compareTo(rhs.mBrandPinyin); if(r != 0) { break; } r = lhs.mBrand.compareTo(rhs.mBrand); } while(false); return r; } }; private static class BrandItem { int mViewType; int mIndex; CarBrand mCarBrand; String mHeader; int mCount; public BrandItem(String header, int index) { mViewType = CarBrandAdapter.TYPE_HEADER; mHeader = header; mCount = 0; mIndex = index; } public BrandItem(CarBrand carBrand, int index) { mViewType = CarBrandAdapter.TYPE_ITEM; mCarBrand = carBrand; mCount = 0; mIndex = index; } } private static class ViewHolder { TextView mTvTitle; BrandItem mBrandItem; } private class CarBrandAdapter extends BaseAdapter implements SectionIndexer , PinnedHeaderAdapter, OnScrollListener { public static final int TYPE_ITEM = 0; public static final int TYPE_HEADER = TYPE_ITEM + 1; public static final int TYPE_COUNT = TYPE_HEADER; @Override //BaseAdapter public int getCount() { return mBrandItems.size(); } @Override //BaseAdapter public BrandItem getItem(int position) { return mBrandItems.get(position); } @Override //BaseAdapter public long getItemId(int position) { return 0; } @Override //BaseAdapter public View getView(int position, View convertView, ViewGroup parent) { BrandItem item = getItem(position); if(item.mViewType == TYPE_ITEM) { return getItemView(item, convertView); } else { return getHeaderView(item, convertView); } } private View getHeaderView(BrandItem item, View convertView) { ViewHolder holder = null; if(null == convertView) { convertView = LayoutInflater.from(RegisterCarBrandActivity.this).inflate(R.layout.layout_car_brank_header_item, null); holder = new ViewHolder(); holder.mTvTitle = (TextView) convertView.findViewById(R.id.car_brand_header); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.mBrandItem = item; holder.mTvTitle.setVisibility(View.VISIBLE); holder.mTvTitle.setText(item.mHeader); return convertView; } private View getItemView(BrandItem item, View convertView) { ViewHolder holder = null; if(null == convertView) { convertView = LayoutInflater.from(RegisterCarBrandActivity.this).inflate(R.layout.layout_car_brand_item, null); holder = new ViewHolder(); holder.mTvTitle = (TextView) convertView.findViewById(R.id.car_brand_name); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.mBrandItem = item; holder.mTvTitle.setVisibility(View.VISIBLE); holder.mTvTitle.setText(item.mCarBrand.mBrand); return convertView; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public int getItemViewType(int position) { BrandItem item = getItem(position); return item.mViewType; } @Override //OnScrollListener public void onScroll(AbsListView listView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { mListView.configureHeaderView(firstVisibleItem); } @Override //OnScrollListener public void onScrollStateChanged(AbsListView listView, int state) { } @Override public int getPinnedHeaderState(int position) { //TODO return PINNED_HEADER_GONE; } @Override public void configurePinnedHeader(View header, int position, int alpha) { //TODO } @Override //SelectionIndexer public int getPositionForSection(int selection) { int position = 0; BrandItem item = null; do { item = getItem(position); position = position + item.mCount + 1; } while(item.mIndex != selection); return position; } @Override //SelectionIndexer public int getSectionForPosition(int position) { BrandItem item = getItem(position); return item.mIndex; } @Override //SelectionIndexer public Object[] getSections() { return mSelections.toArray(); } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/RegisterCarBrandActivity.java
Java
epl
7,135
package com.zz.cc.owner.app; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; public class AddCommentActivity extends TitleBaseActivity implements OnClickListener { private EditText mCommentInput; private Button mSubmit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_comment); initUI(); fillView(); } private void initUI() { mCommentInput = (EditText) findViewById(R.id.add_comment_input); mSubmit = (Button) findViewById(R.id.add_comment_submit); } private void fillView() { setCurrentTitle(R.string.add_comment_title); mSubmit.setOnClickListener(this); } @Override public void onClick(View view) { int id = view.getId(); if(id == R.id.add_comment_submit) { //TODO submit a comment onBackPressed(); } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/AddCommentActivity.java
Java
epl
1,024
package com.zz.cc.owner.app; import java.io.IOException; import java.util.Collection; import java.util.EnumSet; import java.util.Map; import java.util.Set; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.google.zxing.BarcodeFormat; import com.google.zxing.DecodeHintType; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.client.android.Action; import com.google.zxing.client.android.AmbientLightManager; import com.google.zxing.client.android.BeepManager; import com.google.zxing.client.android.CaptureActivity; import com.google.zxing.client.android.DecodeActivityHandler; import com.google.zxing.client.android.DecodeFormatManager; import com.google.zxing.client.android.DecodeHintManager; import com.google.zxing.client.android.InactivityTimer; import com.google.zxing.client.android.IntentSource; import com.google.zxing.client.android.Intents; import com.google.zxing.client.android.ViewfinderView; import com.google.zxing.client.android.camera.CameraManager; import com.zz.cc.owner.R; import com.zz.common.app.BaseActivity; import com.zz.common.utils.ZLog; public class QrCodeScanActivity extends BaseActivity implements Callback, DecodeActivityHandler.IHandleActivity{ private static final String TAG = CaptureActivity.class.getSimpleName(); private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES = EnumSet.of(ResultMetadataType.ISSUE_NUMBER, ResultMetadataType.SUGGESTED_PRICE, ResultMetadataType.ERROR_CORRECTION_LEVEL, ResultMetadataType.POSSIBLE_COUNTRY); private CameraManager cameraManager; private DecodeActivityHandler handler; private Result savedResultToShow; private ViewfinderView viewfinderView; private Result lastResult; private boolean hasSurface; private Collection<BarcodeFormat> decodeFormats; private Map<DecodeHintType,?> decodeHints; private String characterSet; private InactivityTimer inactivityTimer; private BeepManager beepManager; private AmbientLightManager ambientLightManager; @Override public ViewfinderView getViewfinderView() { return viewfinderView; } @Override public Handler getHandler() { return handler; } @Override public CameraManager getCameraManager() { return cameraManager; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_qrcode_scan); hasSurface = false; inactivityTimer = new InactivityTimer(this); beepManager = new BeepManager(this, getBeepId()); ambientLightManager = new AmbientLightManager(this); } protected int getBeepId() { return R.raw.beep; } protected int getViewFinderViewId() { return R.id.qrcode_scan_viewfinder_view; } protected int getSurfaceViewId() { return R.id.qrcode_scan_preview_view; } @Override public void onResume() { super.onResume(); // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't // want to open the camera driver and measure the screen size if we're going to show the help on // first launch. That led to bugs where the scanning rectangle was the wrong size and partially // off screen. cameraManager = new CameraManager(getApplication()); viewfinderView = (ViewfinderView) findViewById(getViewFinderViewId()); viewfinderView.setCameraManager(cameraManager); handler = null; lastResult = null; SurfaceView surfaceView = (SurfaceView) findViewById(getSurfaceViewId()); SurfaceHolder surfaceHolder = surfaceView.getHolder(); if (hasSurface) { // The activity was paused but not stopped, so the surface still exists. Therefore // surfaceCreated() won't be called, so init the camera here. initCamera(surfaceHolder); } else { // Install the callback and wait for surfaceCreated() to init the camera. surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } beepManager.updateConfig(); ambientLightManager.start(cameraManager); inactivityTimer.onResume(); } @Override public void onPause() { if (handler != null) { handler.quitSynchronously(); handler = null; } inactivityTimer.onPause(); ambientLightManager.stop(); cameraManager.closeDriver(); if (!hasSurface) { SurfaceView surfaceView = (SurfaceView) findViewById(getSurfaceViewId()); SurfaceHolder surfaceHolder = surfaceView.getHolder(); surfaceHolder.removeCallback(this); } super.onPause(); } @Override public void onDestroy() { inactivityTimer.shutdown(); super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: break; case KeyEvent.KEYCODE_FOCUS: case KeyEvent.KEYCODE_CAMERA: // Handle these events so they don't launch the Camera app return true; // Use volume up/down to turn on light case KeyEvent.KEYCODE_VOLUME_DOWN: cameraManager.setTorch(false); return true; case KeyEvent.KEYCODE_VOLUME_UP: cameraManager.setTorch(true); return true; } return super.onKeyDown(keyCode, event); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); } private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) { // Bitmap isn't used yet -- will be used soon if (handler == null) { savedResultToShow = result; } else { if (result != null) { savedResultToShow = result; } if (savedResultToShow != null) { Message message = Message.obtain(handler, Action.ACTION_DECODE, savedResultToShow); handler.sendMessage(message); } savedResultToShow = null; } } @Override public void surfaceCreated(SurfaceHolder holder) { if (holder == null) { Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); } if (!hasSurface) { hasSurface = true; initCamera(holder); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { hasSurface = false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * A valid barcode has been found, so give an indication of success and show the results. * * @param rawResult The contents of the barcode. * @param scaleFactor amount by which thumbnail was scaled * @param barcode A greyscale bitmap of the camera data which was decoded. */ public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); lastResult = rawResult; // Then not from history, so beep/vibrate and we have an image to draw on beepManager.playBeepSoundAndVibrate(); drawResultPoints(barcode, scaleFactor, rawResult); handleDecodeExternally(rawResult, lastResult, barcode); } /** * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode. * * @param barcode A bitmap of the captured image. * @param scaleFactor amount by which thumbnail was scaled * @param rawResult The decoded results which contains the points to draw. */ private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) { ResultPoint[] points = rawResult.getResultPoints(); if (points != null && points.length > 0) { Canvas canvas = new Canvas(barcode); Paint paint = new Paint(); paint.setColor(Color.RED); if (points.length == 2) { paint.setStrokeWidth(4.0f); drawLine(canvas, paint, points[0], points[1], scaleFactor); } else if (points.length == 4 && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { // Hacky special case -- draw two lines, for the barcode and metadata drawLine(canvas, paint, points[0], points[1], scaleFactor); drawLine(canvas, paint, points[2], points[3], scaleFactor); } else { paint.setStrokeWidth(10.0f); for (ResultPoint point : points) { canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint); } } } } private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) { if (a != null && b != null) { canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(), scaleFactor * b.getX(), scaleFactor * b.getY(), paint); } } // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner. private void handleDecodeExternally(Result rawResult, Result result, Bitmap barcode) { String resultStr = rawResult.getText(); ZLog.d(TAG, "handleDecodeExternally: " + resultStr); Intent intent = new Intent(this, QrCodeResultActivity.class); intent.putExtra(QrCodeResultActivity.INDEX_QR_CODE, resultStr); startActivity(intent); finish(); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void initCamera(SurfaceHolder surfaceHolder) { if (surfaceHolder == null) { throw new IllegalStateException("No SurfaceHolder provided"); } if (cameraManager.isOpen()) { Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?"); return; } try { cameraManager.openDriver(surfaceHolder); // Creating the handler starts the preview, which can also throw a RuntimeException. if (handler == null) { handler = new DecodeActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager); } decodeOrStoreSavedBitmap(null, null); } catch (IOException ioe) { Log.w(TAG, ioe); finish(); } catch (RuntimeException e) { // Barcode Scanner has seen crashes in the wild of this variety: // java.?lang.?RuntimeException: Fail to connect to camera service Log.w(TAG, "Unexpected error initializing camera", e); finish(); } } public void restartPreviewAfterDelay(long delayMS) { if (handler != null) { handler.sendEmptyMessageDelayed(Action.ACTION_RESTART_PREVIEW, delayMS); } } public void drawViewfinder() { viewfinderView.drawViewfinder(); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/QrCodeScanActivity.java
Java
epl
11,545
package com.zz.cc.owner.app; import android.app.LocalActivityManager; import android.app.TabActivity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import android.widget.TabHost.TabSpec; import android.widget.TabWidget; import com.zz.cc.owner.R; public class NewMainActivity extends TabActivity { private static final String TAG = "MainActivity"; private TabHost mTabHost; private LocalActivityManager mActivityManager; private TabWidget mTabWidget; private long mExitTime = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); initUI(); initTabHost(); } public void backToDesk(){ Intent intent= new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); System.exit(0); } private void addTab(int iconResId,String tag,Intent intent){ RelativeLayout indicator = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.text_tab_indicator, null); ImageView icon = (ImageView)indicator.findViewById(R.id.tab_icon); icon.setImageResource(iconResId); TabSpec tSpec = mTabHost.newTabSpec(tag).setIndicator(indicator).setContent(intent); mTabHost.addTab(tSpec); } private void updateTagImg(){ for (int i = 0; i < mTabWidget.getTabCount(); i++) { View v = mTabWidget.getChildTabViewAt(i); ImageView selectBgImageView = (ImageView)v.findViewById(R.id.select_bg); selectBgImageView.setVisibility(View.GONE); ImageView icon = (ImageView)v.findViewById(R.id.tab_icon); if (i==0) { icon.setImageResource(R.drawable.tabbar_home); }else if (i==1) { icon.setImageResource(R.drawable.tabbar_profile); }else if (i==2) { icon.setImageResource(R.drawable.tabbar_more); } } int resId = R.drawable.tabbar_home_highlighted; int currentTab = mTabHost.getCurrentTab(); if (currentTab==0) { resId = R.drawable.tabbar_home_highlighted; }else if (currentTab==1) { resId = R.drawable.tabbar_profile_highlighted; }else if (currentTab==2) { resId = R.drawable.tabbar_more_highlighted; } mTabHost.getCurrentTabView().findViewById(R.id.select_bg).setVisibility(View.VISIBLE); ((ImageView)mTabHost.getCurrentTabView().findViewById(R.id.tab_icon)).setImageResource(resId); } private void initTabHost(){ mTabHost = this.getTabHost(); mActivityManager = new LocalActivityManager(this, false); mTabHost.setup(); mTabWidget = (TabWidget)findViewById(android.R.id.tabs); Intent intent1 = new Intent(); intent1.setClass(NewMainActivity.this, MapActivity.class); Intent intent2 = new Intent(NewMainActivity.this, RechargeActivity.class); Intent intent3 = new Intent(NewMainActivity.this, OtherActivity.class); addTab(R.drawable.tabbar_home, "microschool", intent1); addTab(R.drawable.tabbar_profile, "message", intent2); addTab(R.drawable.tabbar_more, "addressbook", intent3); mTabHost.setCurrentTab(0); updateTagImg(); mTabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { // TODO Auto-generated method stub updateTagImg(); } }); } private void initUI(){ setContentView(R.layout.main); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/NewMainActivity.java
Java
epl
3,528
package com.zz.cc.owner.app; import java.util.ArrayList; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ExpandableListView.OnGroupClickListener; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; import com.zz.cc.owner.data.CarModel; import com.zz.cc.owner.data.CarSubModel; import com.zz.common.utils.ZLog; import com.zz.common.widget.ZExpandableListView; public class RegisterCarModelActivity extends TitleBaseActivity implements OnGroupClickListener , OnChildClickListener{ private static final String TAG = "RegisterCarModelActivity"; private ZExpandableListView mListView; private CarModelExpandableAdapter mAdapter; private final ArrayList<CarModel> mModels = new ArrayList<CarModel>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_car_model); initUI(); fillView(); } private void initUI() { mListView = (ZExpandableListView) findViewById(R.id.car_model_list_view); } private void fillView() { setCurrentTitle(R.string.card_model_title); mListView.setOnChildClickListener(this); mListView.setOnGroupClickListener(this); mAdapter = new CarModelExpandableAdapter(); mListView.setAdapter(mAdapter); } @Override public boolean onChildClick(ExpandableListView listview, View view, int groupPosition, int childPosition, long id) { ViewHolder holder = (ViewHolder) view.getTag(); if(null != holder) { ZLog.d(TAG, "onClickClick: " + groupPosition + ", " + childPosition + ", " + holder.mSubModel.mSubModel + ", " + holder.mSubModel.mSubModelId); Intent intent = new Intent(this, RegisterPhoneNumActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } return true; } @Override public boolean onGroupClick(ExpandableListView listview, View view, int groupPosition, long id) { ViewHolder holder = (ViewHolder) view.getTag(); if(null != holder) { ZLog.d(TAG, "onGroupClick: " + groupPosition + ", " + holder.mModel.mModel + ", " + holder.mModel.mModelId); } return false; } private static class ViewHolder { TextView mTvName; CarModel mModel; CarSubModel mSubModel; } private class CarModelExpandableAdapter extends BaseExpandableListAdapter { @Override public CarSubModel getChild(int groupPosition, int childPosition) { CarModel model = getGroup(groupPosition); return model.getSubModelList().get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { CarSubModel subModel = getChild(groupPosition, childPosition); return 0; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ViewHolder holder = null; if(null == convertView) { convertView = LayoutInflater.from(RegisterCarModelActivity.this).inflate(R.layout.layout_car_model_item, null); holder = new ViewHolder(); holder.mTvName = (TextView) convertView.findViewById(R.id.car_model_name); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } CarSubModel subModel = getChild(groupPosition, childPosition); holder.mTvName.setText(subModel.mSubModel); holder.mSubModel = subModel; return convertView; } @Override public int getChildrenCount(int groupPosition) { CarModel model = getGroup(groupPosition); if(null == model.getSubModelList()) { return 0; } return model.getSubModelList().size(); } @Override public CarModel getGroup(int groupPosition) { return mModels.get(groupPosition); } @Override public int getGroupCount() { return mModels.size(); } @Override public long getGroupId(int groupPosition) { CarModel model = getGroup(groupPosition); return 0; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { ViewHolder holder = null; if(null == convertView) { convertView = LayoutInflater.from(RegisterCarModelActivity.this).inflate(R.layout.layout_car_brank_header_item, null); holder = new ViewHolder(); holder.mTvName = (TextView) convertView.findViewById(R.id.car_sub_model_name); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } CarModel model = getGroup(groupPosition); holder.mTvName.setText(model.mModel); holder.mModel = model; return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/RegisterCarModelActivity.java
Java
epl
5,043
package com.zz.cc.owner.app; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.data.Store; import com.zz.cc.owner.util.Util; //店铺列表界面 public class StoreListActivity extends OwnerBaseActivity { private ListView mListView; private MyAdapter mAdapter; private List<Store> mStores = new ArrayList<Store>(); private Button mRightBtnButton; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); emulateData(); initUI(); } private void emulateData(){ Store store1 = new Store(); store1.name = "天利洗车店"; store1.originalPrice = 20.0f; store1.preferencialPrice = 15.0f; store1.introduce="我们天利洗车店开了20年了,深受各位车友的喜爱"; store1.serverId = 1; store1.id = 1; store1.score = 4.5f; store1.address = "深圳市南山区南新路118号"; store1.phone = "13388948734"; mStores.add(store1); Store store2 = new Store(); store2.name = "小明洗车店"; store2.originalPrice = 20.0f; store2.preferencialPrice = 10.0f; store2.introduce="我们小明洗车店是最好的"; store2.serverId = 2; store2.id = 2; store2.score = 2.0f; store2.address = "深圳市罗湖区春风路10号"; store2.phone = "13788946512"; mStores.add(store2); } private void initUI(){ setContentView(R.layout.storelist); ((TextView)findViewById(R.id.titleTextView)).setText("我身边的洗车店"); findViewById(R.id.backImg).setVisibility(View.GONE); mRightBtnButton = (Button)findViewById(R.id.rightBtn); mRightBtnButton.setText("地图模式"); mRightBtnButton.setVisibility(View.VISIBLE); mRightBtnButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Util.showToast(StoreListActivity.this, "跳转到地图模式"); finish(); } }); mListView = (ListView)findViewById(R.id.storelist); mAdapter = new MyAdapter(this); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent intent = new Intent(StoreListActivity.this, DetailActivity.class); intent.putExtra(DetailActivity.STORE_DETAIL, (Store)mAdapter.getItem(arg2)); startActivity(intent); } }); } class MyAdapter extends BaseAdapter{ private Context ctx; public MyAdapter(Context context){ this.ctx = context; } @Override public int getCount() { // TODO Auto-generated method stub return mStores.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return mStores.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; Store store = (Store)getItem(position); if (convertView==null) { convertView = LayoutInflater.from(this.ctx).inflate(R.layout.storelist_item,null); viewHolder = new ViewHolder(); viewHolder.logoView = (ImageView)convertView.findViewById(R.id.logo_img); viewHolder.distance = (TextView)convertView.findViewById(R.id.distance); viewHolder.price = (TextView)convertView.findViewById(R.id.price); viewHolder.name = (TextView)convertView.findViewById(R.id.name); viewHolder.position = (TextView)convertView.findViewById(R.id.position); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder)convertView.getTag(); } viewHolder.name.setText(store.name); viewHolder.logoView.setImageResource(R.drawable.ic_launcher); viewHolder.distance.setText(((position+1)*100)+"米"); viewHolder.price.setText(store.preferencialPrice+"元"); viewHolder.position.setText(store.address); return convertView; } class ViewHolder{ ImageView logoView; TextView name; TextView distance; TextView price; TextView position; } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/StoreListActivity.java
Java
epl
4,607
package com.zz.cc.owner.app; public class SettingActivity extends OwnerBaseActivity { }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/SettingActivity.java
Java
epl
90
package com.zz.cc.owner.app; import java.util.Collections; import java.util.LinkedList; import java.util.List; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.LinearLayout.LayoutParams; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SectionIndexer; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.data.Constants; import com.zz.cc.owner.data.MyCarBrand; import com.zz.cc.owner.data.MyCarModel; import com.zz.cc.owner.util.PinyinComparator; import com.zz.cc.owner.util.Util; import com.zz.cc.owner.view.SideBar; import com.zz.common.app.BaseActivity; public class SelectCarToRegActivity extends OwnerBaseActivity implements OnClickListener{ private ListView mListView; private MyAdapter mAdapter; private SideBar mSideBar; private TextView mDialogText; private List<MyCarBrand> mCarBrands = new LinkedList<MyCarBrand>(); private List<MyCarModel> mCarModels = new LinkedList<MyCarModel>(); private WindowManager mWindowManager; private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case Constants.OWNER_REG_SUCCESS: dismissDialog(); showWaitDialog("注册成功,为你自动登录中...", false); sendEmptyMessageDelayed(Constants.LOGIN_SUCCESS, 1500); break; case Constants.LOGIN_SUCCESS: dismissDialog(); startActivity(new Intent(SelectCarToRegActivity.this, NewMainActivity.class)); finish(); break; case Constants.LOGIN_FAILED: Util.showToast(SelectCarToRegActivity.this, "自动登录失败,请手动登录"); dismissDialog(); startActivity(new Intent(SelectCarToRegActivity.this, LoginActivity.class)); finish(); break; case Constants.OWNER_REG_FAILED: dismissDialog(); Util.showToast(SelectCarToRegActivity.this, "注册失败,请重试"); break; default: break; } }; }; //模拟生成车品牌和车数据 private void emulateDatas(){ MyCarBrand honda_brand = new MyCarBrand(); honda_brand.id = 1; honda_brand.brandName = "本田"; mCarBrands.add(honda_brand); MyCarBrand bmw_brand = new MyCarBrand(); bmw_brand.id = 2; bmw_brand.brandName = "本田"; mCarBrands.add(bmw_brand); MyCarBrand benz_brand = new MyCarBrand(); benz_brand.id = 3; benz_brand.brandName = "奔驰"; mCarBrands.add(benz_brand); MyCarBrand audi_brand = new MyCarBrand(); audi_brand.id = 4; audi_brand.brandName = "奥迪"; mCarBrands.add(audi_brand); MyCarBrand aston_brand = new MyCarBrand(); aston_brand.id = 5; aston_brand.brandName = "丰田"; mCarBrands.add(aston_brand); //模拟车型 MyCarModel accord_model = new MyCarModel(); accord_model.id = 1; accord_model.modelName = "本田雅阁"; accord_model.brand = honda_brand; mCarModels.add(accord_model); MyCarModel fit_model = new MyCarModel(); fit_model.id = 2; fit_model.modelName = "本田飞度"; fit_model.brand = honda_brand; mCarModels.add(fit_model); MyCarModel bmw5_model = new MyCarModel(); bmw5_model.id = 3; bmw5_model.modelName = "宝马5系"; bmw5_model.brand = bmw_brand; mCarModels.add(bmw5_model); MyCarModel bmw7_model = new MyCarModel(); bmw7_model.id = 4; bmw7_model.modelName = "宝马7系"; bmw7_model.brand = bmw_brand; mCarModels.add(bmw7_model); MyCarModel benzs_model = new MyCarModel(); benzs_model.id = 5; benzs_model.modelName = "奔驰S系"; benzs_model.brand = benz_brand; mCarModels.add(benzs_model); MyCarModel benze_model = new MyCarModel(); benze_model.id = 6; benze_model.modelName = "奔驰E系"; benze_model.brand = benz_brand; mCarModels.add(benze_model); MyCarModel audia6_model = new MyCarModel(); audia6_model.id = 7; audia6_model.modelName = "奥迪A6"; audia6_model.brand = audi_brand; mCarModels.add(audia6_model); MyCarModel audia4_model = new MyCarModel(); audia4_model.id = 8; audia4_model.modelName = "奥迪A4"; audia4_model.brand = audi_brand; mCarModels.add(audia4_model); MyCarModel astongt_model = new MyCarModel(); astongt_model.id = 9; astongt_model.modelName = "丰田凯美瑞"; astongt_model.brand = aston_brand; mCarModels.add(astongt_model); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); emulateDatas(); initUI(); } private void initUI(){ setContentView(R.layout.selectcartoreg); ((TextView)findViewById(R.id.titleTextView)).setText("选择车型"); findViewById(R.id.backImg).setOnClickListener(this); mListView = (ListView)findViewById(R.id.lvContact); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub showWaitDialog("注册中,请稍候...", true); mHandler.sendEmptyMessageDelayed(Constants.OWNER_REG_SUCCESS, 2000); } }); mAdapter = new MyAdapter(this); mListView.setAdapter(mAdapter); mSideBar = (SideBar) findViewById(R.id.sideBar); mSideBar.setListView(mListView); mDialogText = (TextView) LayoutInflater.from(this).inflate( R.layout.sidebar_item, null); mDialogText.setVisibility(View.INVISIBLE); WindowManager.LayoutParams lp = new WindowManager.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); mWindowManager.addView(mDialogText, lp); mSideBar.setTextView(mDialogText); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.backImg: finish(); break; default: break; } } class MyAdapter extends BaseAdapter implements SectionIndexer { private Context mContext; private boolean mShowCheckbox; public MyAdapter(Context mContext) { this.mContext = mContext; doSort(); } public void doSort() { Collections.sort(mCarModels, new PinyinComparator()); } @Override public int getCount() { return mCarModels.size(); } public void showCheckbox(boolean show) { this.mShowCheckbox = show; } @Override public MyCarModel getItem(int position) { return mCarModels.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { MyCarModel model = mCarModels.get(position); final String nickName = model.modelName.trim(); ViewHolder viewHolder = null; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate( R.layout.selectcartoreg_item, null); viewHolder = new ViewHolder(); viewHolder.tvCatalog = (TextView) convertView .findViewById(R.id.contactitem_catalog); viewHolder.tvNick = (TextView) convertView .findViewById(R.id.contactitem_nick); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String catalog = converterToFirstSpell(nickName).substring(0,1); if (position == 0) { viewHolder.tvCatalog.setVisibility(View.VISIBLE); viewHolder.tvCatalog.setText(catalog); } else { String lastCatalog = converterToFirstSpell( mCarModels.get(position - 1).modelName).substring(0,1); if (!catalog.equalsIgnoreCase(lastCatalog)) { viewHolder.tvCatalog.setVisibility(View.VISIBLE); viewHolder.tvCatalog.setText(catalog); } else { viewHolder.tvCatalog.setVisibility(View.GONE); } } viewHolder.tvNick.setText(nickName); return convertView; } class ViewHolder { TextView tvCatalog;// 目录 TextView tvNick; } @Override public int getPositionForSection(int section) { for (int i = 0; i < mCarModels.size(); i++) { String l = converterToFirstSpell(mCarModels.get(i).brand.brandName) .trim(); char firstChar = l.toUpperCase().charAt(0); if (firstChar == section) { return i; } } return -1; } @Override public int getSectionForPosition(int position) { return 0; } @Override public Object[] getSections() { return null; } } public static String converterToFirstSpell(String chines) { String pinyinName = ""; char[] nameChar = chines.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < nameChar.length; i++) { if (nameChar[i] > 128) { try { pinyinName += PinyinHelper.toHanyuPinyinStringArray( nameChar[i], defaultFormat)[0].charAt(0); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pinyinName += nameChar[i]; } } return pinyinName; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/SelectCarToRegActivity.java
Java
epl
9,821
package com.zz.cc.owner.app; import android.os.Bundle; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; public class RechargeActivity extends TitleBaseActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recharge); fillView(); } private void fillView() { setCurrentTitle(R.string.recharge_title); } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/RechargeActivity.java
Java
epl
426
package com.zz.cc.owner.app; import android.app.ProgressDialog; import com.zz.cc.owner.R; import com.zz.common.app.BaseActivity; public class OwnerBaseActivity extends BaseActivity { private ProgressDialog mDialog; public void showWaitDialog(String content,boolean cancelable){ mDialog = new ProgressDialog(OwnerBaseActivity.this); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mDialog.setTitle("请稍候"); mDialog.setMessage(content); mDialog.setIcon(R.drawable.ic_launcher); mDialog.setCancelable(true); mDialog.show(); } public void dismissDialog(){ if (mDialog!=null&&mDialog.isShowing()) { mDialog.dismiss(); } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/OwnerBaseActivity.java
Java
epl
663
package com.zz.cc.owner.app; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; public class ForgetPasswordActivity extends TitleBaseActivity implements OnClickListener { private EditText mPhoneNumInput; private Button mSubmitBtn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forget_password); initUI(); fillView(); } private void initUI() { mPhoneNumInput = (EditText) findViewById(R.id.forget_password_input_phone_number); mSubmitBtn = (Button) findViewById(R.id.forget_password_submit); } private void fillView() { super.setCurrentTitle(R.string.forget_password_title); mSubmitBtn.setOnClickListener(this); } @Override public void onClick(View v) { int id = v.getId(); if(id == R.id.forget_password_submit) { onBackPressed(); } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/ForgetPasswordActivity.java
Java
epl
1,042
package com.zz.cc.owner.app; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.RatingBar; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; import com.zz.cc.owner.data.Comment; import com.zz.cc.owner.data.Store; import com.zz.common.utils.DateTimeUtil; import com.zz.common.widget.ZListView; public class DetailActivity extends TitleBaseActivity implements OnClickListener, OnItemClickListener { public static final String STORE_DETAIL = "store_detail"; private View mContentView; private TextView mBasicInfoTextView; private TextView mAddressTextView; private TextView mPhoneNumberTextView; private TextView mIntroduceTextView; private ZListView mListView; private CommentAdapter mAdapter; private View mBtnGroup; private Button mServiceBtn; private Button mGoThereBtn; private Button mCommentBtn; private Button mShareBtn; private Store mStore; private final List<Comment> mComments = new ArrayList<Comment>(); private RatingBar mRatingBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mStore = (Store)getIntent().getSerializableExtra(STORE_DETAIL); setContentView(R.layout.activity_detail); initUI(); fillView(); refresh(); } private void initUI() { mContentView = LayoutInflater.from(this).inflate(R.layout.layout_detail_content, null); initContentView(); mListView = (ZListView) findViewById(R.id.detail_list_view); mBtnGroup = findViewById(R.id.detail_btn_group); mRatingBar = (RatingBar)mContentView.findViewById(R.id.ratingbar_default); mRatingBar.setRating(mStore.score); initBtnGroup(); } private void initContentView() { mBasicInfoTextView = (TextView) mContentView.findViewById(R.id.detail_basic_info); mAddressTextView = (TextView) mContentView.findViewById(R.id.detail_address); mPhoneNumberTextView = (TextView) mContentView.findViewById(R.id.detail_phone_number); mIntroduceTextView = (TextView) mContentView.findViewById(R.id.detail_introduce); } private void initBtnGroup() { mServiceBtn = (Button) mBtnGroup.findViewById(R.id.detail_service); mGoThereBtn = (Button) mBtnGroup.findViewById(R.id.detail_go_there); mCommentBtn = (Button) mBtnGroup.findViewById(R.id.detail_comment); mShareBtn = (Button) mBtnGroup.findViewById(R.id.detail_share); } private void fillView() { setCurrentTitle(R.string.detail_title); fillContentView(); fillBtnGroup(); mListView.addHeaderView(mContentView); mAdapter = new CommentAdapter(); mListView.setAdapter(mAdapter); } private void fillContentView() { String basicInfo = mStore.name; mBasicInfoTextView.setText(basicInfo); String address = mStore.address; mAddressTextView.setText(address); String phoneNumber = mStore.phone; mPhoneNumberTextView.setText("电话: "+phoneNumber); String introduce = mStore.introduce; mIntroduceTextView.setText(introduce); } private void fillBtnGroup() { mServiceBtn.setOnClickListener(this); mGoThereBtn.setOnClickListener(this); mCommentBtn.setOnClickListener(this); mShareBtn.setOnClickListener(this); } private void refresh() { mComments.clear(); int i = 0; for(; i<10; i++) { Comment c = new Comment(); c.mContent = "那些花儿" + "\t" + i * 23423; c.mTime = System.currentTimeMillis() - i*10000; mComments.add(c); } mAdapter.notifyDataSetChanged(); } private void onCommentBtnClick() { Intent intent = new Intent(this, AddCommentActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void onServiceBtnClick() { Intent intent = new Intent(this, QrCodeScanActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } @Override public void onClick(View view) { int id = view.getId(); switch(id) { case R.id.detail_service: onServiceBtnClick(); break; case R.id.detail_go_there: onBackPressed(); break; case R.id.detail_comment: onCommentBtnClick(); break; case R.id.detail_share: //TODO break; default: break; } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO } private static class ViewHolder { public TextView mTvContent; public TextView mTvTime; public Comment mComment; } private class CommentAdapter extends BaseAdapter { @Override public int getCount() { return mComments.size(); } @Override public Comment getItem(int position) { return mComments.get(position); } @Override public long getItemId(int position) { Comment c = getItem(position); return c.mId; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(null == convertView) { convertView = LayoutInflater.from(DetailActivity.this).inflate(R.layout.layout_detail_comment_item, null); holder = new ViewHolder(); holder.mTvContent = (TextView) convertView.findViewById(R.id.comment_content); holder.mTvTime = (TextView) convertView.findViewById(R.id.comment_date_time); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.mComment = getItem(position); holder.mTvContent.setText(holder.mComment.mContent); holder.mTvTime.setText(DateTimeUtil.getDateString(holder.mComment.mTime)); return convertView; } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/DetailActivity.java
Java
epl
5,980
package com.zz.cc.owner.app; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.TitleBaseActivity; import com.zz.common.widget.ZListView; public class OtherActivity extends TitleBaseActivity implements OnItemClickListener { private ZListView mListView; private OtherAdapter mAdapter; private final List<Integer> mServices = new ArrayList<Integer>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); initUI(); fillView(); refresh(); } private void initUI() { mListView = (ZListView) findViewById(R.id.other_list_view); } private void fillView() { setCurrentTitle(R.string.other_title); mAdapter = new OtherAdapter(); mListView.setAdapter(mAdapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //TODO } private void refresh() { mServices.clear(); mServices.add(Integer.valueOf(R.string.other_modify_basic_info)); mServices.add(Integer.valueOf(R.string.other_account)); mServices.add(Integer.valueOf(R.string.other_upgrade)); mServices.add(Integer.valueOf(R.string.other_contact_us)); mServices.add(Integer.valueOf(R.string.other_help)); mServices.add(Integer.valueOf(R.string.other_about)); mAdapter.notifyDataSetChanged(); } private static class ViewHolder { public TextView mTvTitle; public int mTitleId; } private class OtherAdapter extends BaseAdapter { @Override public int getCount() { return mServices.size(); } @Override public Object getItem(int position) { return mServices.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(null == convertView) { convertView = LayoutInflater.from(OtherActivity.this).inflate(R.layout.list_item_other, null); holder = new ViewHolder(); holder.mTvTitle = (TextView) convertView.findViewById(R.id.other_list_item_title); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.mTitleId = mServices.get(position); holder.mTvTitle.setText(holder.mTitleId); return convertView; } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/OtherActivity.java
Java
epl
2,632
package com.zz.cc.owner.app; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.zz.cc.owner.R; import com.zz.cc.owner.util.Util; public class RegisterPhoneNumActivity extends Activity implements OnClickListener { private EditText mPhoneNumInput,mUsernameInput,mPwdInput,mConfirmPwdInput; private Button mNextBtn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_phone_num); initUI(); fillView(); } private void initUI() { ((TextView)findViewById(R.id.titleTextView)).setText("填写注册信息"); findViewById(R.id.backImg).setOnClickListener(this); mPhoneNumInput = (EditText) findViewById(R.id.phonenum_edittext); mUsernameInput = (EditText)findViewById(R.id.username_edittext); mPwdInput = (EditText)findViewById(R.id.pwd_edittext); mConfirmPwdInput = (EditText)findViewById(R.id.confirm_pwd_edittext); mNextBtn = (Button) findViewById(R.id.nextstep); } private void fillView() { mNextBtn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.nextstep: String account = mUsernameInput.getText().toString().trim(); String phonenum = mPhoneNumInput.getText().toString().trim(); String pwd = mPwdInput.getText().toString().trim(); String confirmpwd = mConfirmPwdInput.getText().toString().trim(); if (account.equals("") || phonenum.equals("") || pwd.equals("") || confirmpwd.equals("")) { Util.showToast(this, "还有必填内容没有填写"); return; } if (!pwd.equals(confirmpwd)) { Util.showToast(this, "两次密码必须相同"); return; } Intent intent = new Intent(this, SelectCarToRegActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); break; case R.id.backImg: finish(); break; } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/RegisterPhoneNumActivity.java
Java
epl
2,144
package com.zz.cc.owner.app; import java.io.InputStream; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.ViewFlipper; import com.zz.cc.owner.R; import com.zz.common.app.BaseActivity; import com.zz.common.utils.DeviceUtil; import com.zz.common.utils.ImageUtil; import com.zz.common.utils.ZLog; public class UserGuideActivity extends BaseActivity implements OnClickListener, OnTouchListener, GestureDetector.OnGestureListener { private static final String TAG = "UserGuideActivity"; private ViewFlipper mViewFlipper; private Button mDirectionView; private int mScreenWidth; private int mScreenHeight; private GestureDetector mDetetor; private int mCurrentIndex; private String []mGuides = new String[] { "guide/guide00.jpg", "guide/guide01.jpg", "guide/guide02.jpg" }; @Override public final void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mScreenHeight = DeviceUtil.getScreenHeight(this); mScreenWidth = DeviceUtil.getScreenWidth(this); setContentView(R.layout.activity_user_guide); initUI(); initGuides(); } private void initUI() { mViewFlipper = (ViewFlipper) findViewById(R.id.guide_image_container); mDirectionView = (Button) findViewById(R.id.guide_redirect); mDirectionView.setOnClickListener(this); mViewFlipper.setInAnimation(getInAnimation()); mViewFlipper.setOutAnimation(getOutAnimation()); mViewFlipper.setOnTouchListener(this); mDetetor = new GestureDetector(this, this); } private void initGuides() { AssetManager am = getAssets(); for(String path: mGuides) { InputStream is = null; try { is = am.open(path); Bitmap b = ImageUtil.decodeStream(is); mViewFlipper.addView(makeView(b)); } catch (Throwable t) { t = null; } finally { if(null != is) { try { is.close(); } catch(Exception e) { e = null; } } } } } private View makeView(Bitmap b) { ImageView imageView = new ImageView(this); imageView.setLayoutParams(new LayoutParams(mScreenWidth, mScreenHeight)); imageView.setImageBitmap(b); imageView.setScaleType(ScaleType.FIT_XY); imageView.setClickable(false); imageView.setEnabled(false); return imageView; } @Override //View.OnClickListener public void onClick(View view) { int id = view.getId(); if(id == R.id.guide_redirect) { if(mViewFlipper.isFlipping()) { return; } if(mCurrentIndex == mGuides.length - 1) { //the last guide image onEndOfGuide(); } else { showNextGuide(); } } } @Override //View.OnTouchListener public boolean onTouch(View v, MotionEvent event) { mDetetor.onTouchEvent(event); return true; } @Override //GestureDetector.OnGestureListener public boolean onDown(MotionEvent e) { return false; } @Override //GestureDetector.OnGestureListener public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if(mViewFlipper.isFlipping()){ return false; } if(Math.abs((e1.getY() - e2.getY())) < 30){ return false; } if((e1.getY() - e2.getY()) > 30){ if(mCurrentIndex == (mGuides.length - 1)){ onEndOfGuide(); } else { showNextGuide(); } }else if((e1.getY()-e2.getY())<-30){ if(mCurrentIndex == 0){ return false; } else { showPreGuide(); } } return true; } @Override //GestureDetector.OnGestureListener public void onLongPress(MotionEvent e) { } @Override //GestureDetector.OnGestureListener public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override //GestureDetector.OnGestureListener public void onShowPress(MotionEvent e) { } @Override //GestureDetector.OnGestureListener public boolean onSingleTapUp(MotionEvent e) { return false; } private void showNextGuide() { mViewFlipper.setInAnimation(getInAnimation()); mViewFlipper.setOutAnimation(getOutAnimation()); mViewFlipper.showNext(); mCurrentIndex ++; } private void showPreGuide() { mViewFlipper.setInAnimation(getPrivousInAnimation()); mViewFlipper.setOutAnimation(getPrivousOutAnimation()); mViewFlipper.showPrevious(); mCurrentIndex --; } private void onEndOfGuide() { ZLog.d(TAG, "onEndOfGuide"); Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private Animation getInAnimation() { Animation animation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0); animation.setDuration(250); return animation; } private Animation getOutAnimation() { Animation animation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0); animation.setDuration(250); return animation; } private Animation getPrivousInAnimation() { Animation animation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0); animation.setDuration(250); return animation; } private Animation getPrivousOutAnimation() { Animation animation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0); animation.setDuration(250); return animation; } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/UserGuideActivity.java
Java
epl
6,316
package com.zz.cc.owner.app; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.baidu.mapapi.map.MapView; import com.zz.cc.owner.R; import com.zz.cc.owner.view.SummaryView; import com.zz.common.app.BaseActivity; public class MainActivity extends BaseActivity implements OnClickListener { private EditText mSearchInput; private Button mSearchBtn; private Button mReserveBtn; private Button mRechargeBtn; private Button mOtherBtn; private MapView mMapView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUI(); fillView(); } @Override public void onResume() { super.onResume(); mMapView.onResume(); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mMapView.onRestoreInstanceState(savedInstanceState); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mMapView.onSaveInstanceState(outState); } @Override public void onDestroy() { super.onDestroy(); mMapView.destroy(); } private void initUI() { mSearchInput = (EditText) findViewById(R.id.main_search_input); mSearchBtn = (Button) findViewById(R.id.main_search_btn); mMapView = (MapView) findViewById(R.id.main_map_view); mReserveBtn = (Button) findViewById(R.id.main_reserve); mRechargeBtn = (Button) findViewById(R.id.main_recharge); mOtherBtn = (Button) findViewById(R.id.main_other); } private void fillView() { mSearchBtn.setOnClickListener(this); mReserveBtn.setOnClickListener(this); mRechargeBtn.setOnClickListener(this); mOtherBtn.setOnClickListener(this); showSummaryAtPosition(0, 0); } private void showSummaryAtPosition(long lat, long lon) { SummaryView sv = (SummaryView) LayoutInflater.from(this).inflate(R.layout.layout_summary_view, null); String basicInfo = "深圳在水一方BMW维护" + "\n五星" + "\n" + getString(R.string.detail_origin_cost) + "200" + "\n" + getString(R.string.detail_cc_cost) + "160"; sv.setBasicInfo(basicInfo); String introduce = getString(R.string.detail_introduce) + "\t" + "两只老虎两只老虎,跑得快跑得快,一只没有眼睛,一只尾巴,真奇怪,真奇怪!"; sv.setIntroduce(introduce); sv.setOnClickListener(this); mMapView.addView(sv); } private void onSummaryClick() { Intent intent = new Intent(this, DetailActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void onSearchBtnClick() { //TODO search } private void onReserveBtnClick() { Intent intent = new Intent(this, ReserveActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void onOtherBtnClick() { Intent intent = new Intent(this, OtherActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } private void onRechargeBtnClick() { Intent intent = new Intent(this, RechargeActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out); } @Override public void onClick(View view) { int id = view.getId(); switch(id) { case R.id.summary: onSummaryClick(); break; case R.id.main_search_btn: onSearchBtnClick(); break; case R.id.main_reserve: onReserveBtnClick(); break; case R.id.main_recharge: onRechargeBtnClick(); break; case R.id.main_other: onOtherBtnClick(); break; default: break; } } }
zzdache
trunk/android/cc/Owner/src/com/zz/cc/owner/app/MainActivity.java
Java
epl
4,041
/* CSS file */ @namespace s "library://ns.adobe.com/flex/spark"; @namespace mx "library://ns.adobe.com/flex/mx"; loginForm{ verticalAlign:middle; } .UpButton{ skin:Embed(source="assets/button/upButton.png"); upSkin:Embed(source="assets/button/upButton.png"); overSkin:Embed(source="assets/button/upButton_over.png"); downSkin:Embed(source="assets/button/upButton_over.png"); } .DownButton{ skin:Embed(source="assets/button/downButton.png"); upSkin:Embed(source="assets/button/downButton.png"); overSkin:Embed(source="assets/button/downButton_over.png"); downSkin:Embed(source="assets/button/downButton_over.png"); } .CloseButton { upSkin:Embed(source="assets/close.gif"); overSkin:Embed(source="assets/close.gif"); downSkin:Embed(source="assets/close.gif"); } .order { upSkin:Embed(source="assets/job.png"); overSkin:Embed(source="assets/job_over.png"); downSkin:Embed(source="assets/job_over.png"); }
zzti-cs-2008
trunk/flex/src/assets/css/cse2008.css
CSS
oos
949
package com.zzti { import com.zzti.model.User; import mx.collections.ArrayCollection; public class AppGlobal { [Bindable] public static var menuItems:ArrayCollection; [Bindable] public static var teachDirItems:ArrayCollection; [Bindable] public static var currentUser:User; public static var shareURL:String; public static var sharePic:String; public function AppGlobal() { } } }
zzti-cs-2008
trunk/flex/src/com/zzti/AppGlobal.as
ActionScript
oos
437
package com.zzti.model { [Bindable] [RemoteClass(alias="cn.edu.zzti.cs.bean.Order")] public class Order extends Entity { public function Order() { } } }
zzti-cs-2008
trunk/flex/src/com/zzti/model/Order.as
ActionScript
oos
173
package com.zzti.model { [Bindable] [RemoteClass(alias="cn.edu.zzti.cs.bean.Notice")] public class Notice { public function Notice() { } } }
zzti-cs-2008
trunk/flex/src/com/zzti/model/Notice.as
ActionScript
oos
161
package com.zzti.model { [Bindable] [RemoteClass(alias="cn.edu.zzti.cs.bean.Job")] public class Job extends Entity { public function Job() { } } }
zzti-cs-2008
trunk/flex/src/com/zzti/model/Job.as
ActionScript
oos
170
package com.zzti.model { [Bindable] [RemoteClass(alias="cn.edu.zzti.cs.bean.Swuserinfo")] public class User { private var _id:int; private var _username:String; private var _password:String; private var _email:String; private var _realname:String; private var _gender:String; private var _qq:String; private var _telNumber:String; private var _addressHome:String; private var _addressNow:String; private var _technoDir:String; private var _company:String; public function User() { } public function get id():int { return _id; } public function set id(value:int):void { _id = value; } public function get email():String { return _email; } public function set email(value:String):void { _email = value; } public function get gender():String { return _gender; } public function set gender(value:String):void { _gender = value; } public function get qq():String { return _qq; } public function set qq(value:String):void { _qq = value; } public function get addressNow():String { return _addressNow; } public function set addressNow(value:String):void { _addressNow = value; } public function get username():String { return _username; } public function set username(value:String):void { _username = value; } public function get password():String { return _password; } public function set password(value:String):void { _password = value; } public function get realname():String { return _realname; } public function set realname(value:String):void { _realname = value; } public function get telNumber():String { return _telNumber; } public function set telNumber(value:String):void { _telNumber = value; } public function get addressHome():String { return _addressHome; } public function set addressHome(value:String):void { _addressHome = value; } public function get technoDir():String { return _technoDir; } public function set technoDir(value:String):void { _technoDir = value; } public function get company():String { return _company; } public function set company(value:String):void { _company = value; } } }
zzti-cs-2008
trunk/flex/src/com/zzti/model/User.as
ActionScript
oos
2,473
package com.zzti.model { [RemoteClass(alias="cn.edu.zzti.cs.bean.AbsJobOrder")] public class Entity { private var _id:int; //id信息 private var _title:String; //信息标题 private var _authorID:int; private var _user:User; //信息的坐着 private var _content:String; //信息的详细内容 private var _url:String; //与信息相关的链接 private var _state:Boolean = true; //信息的状态,当前是否有效 private var _publishDate:String; private var _lastEditDate:String; public function Entity() { } public function get authorID():int { return _authorID; } public function set authorID(value:int):void { _authorID = value; } public function get id():int { return _id; } public function set id(value:int):void { _id = value; } public function get title():String { return _title; } public function set title(value:String):void { _title = value; } public function get user():User { return _user; } public function set user(value:User):void { _user = value; } public function get content():String { return _content; } public function set content(value:String):void { _content = value; } public function get url():String { return _url; } public function set url(value:String):void { _url = value; } public function get state():Boolean { return _state; } public function set state(value:Boolean):void { _state = value; } public function get publishDate():String { return _publishDate; } public function set publishDate(value:String):void { _publishDate = value; } public function get lastEditDate():String { return _lastEditDate; } public function set lastEditDate(value:String):void { _lastEditDate = value; } } }
zzti-cs-2008
trunk/flex/src/com/zzti/model/Entity.as
ActionScript
oos
1,969
package com.zzti.events { import flash.events.Event; public class SelectedChanged extends Event { public static const CHANGED:String = "SelectedChanged"; public var selectedID:int; public function SelectedChanged(type:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); } } }
zzti-cs-2008
trunk/flex/src/com/zzti/events/SelectedChanged.as
ActionScript
oos
348
package com.zzti.events { import flash.events.Event; public class AppEvent extends Event { public static const LOGINSUCCESS:String = "LoginSuccess"; public static const LOGINFAILD:String = "LoginFaild"; public static const REGIST:String = "Regist"; public static const LOGIN:String = "Login"; public static const LOGOUT:String = "Logout"; public var userName:String; public var passWord:String; public function AppEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); } } }
zzti-cs-2008
trunk/flex/src/com/zzti/events/AppEvent.as
ActionScript
oos
574
package com.zzti.data { import com.zzti.model.User; import mx.collections.ArrayCollection; import mx.messaging.AbstractConsumer; public class ExtraceData { private var obj:Object; public function ExtraceData() { } public function getAddress(users:Array):ArrayCollection { return new ArrayCollection(users); } } }
zzti-cs-2008
trunk/flex/src/com/zzti/data/ExtraceData.as
ActionScript
oos
360
package com.zzti.test { import com.zzti.AppGlobal; import com.zzti.model.Job; public class CreateJob { public function CreateJob() { } public static function getJob():Job { var job:Job = new Job(); job.author = AppGlobal.currentUser; job.title = "测试招聘信息"; job.content = "这是一条测试招聘信息,\n \t呵呵"; job.state = true; job.url = "http://www.vion-tech.com"; job.publishDate = new Date(); return job; } } }
zzti-cs-2008
trunk/flex/src/com/zzti/test/CreateJob.as
ActionScript
oos
502
package com.zzti.manager { import flash.events.EventDispatcher; import flash.events.IEventDispatcher; [Event(name="LoginSuccess", type="com.zzti.events.AppEvent")] [Event(name="LoginFaild", type="com.zzti.events.AppEvent")] [Event(name="Regist", type="com.zzti.events.AppEvent")] [Event(name="Login", type="com.zzti.events.AppEvent")] [Event(name="Logout", type="com.zzti.events.AppEvent")] public class AppManager extends EventDispatcher { public static var _instance:AppManager; public function AppManager(target:IEventDispatcher=null) { super(target); } public static function getInstance():AppManager { if(!_instance){ _instance = new AppManager(); } return _instance; } } }
zzti-cs-2008
trunk/flex/src/com/zzti/manager/AppManager.as
ActionScript
oos
752
package com.zzti.manager { import com.vion.loader.XMLLoader; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import mx.collections.ArrayCollection; import mx.rpc.events.ResultEvent; public class ConfigManager extends EventDispatcher { private var loader:XMLLoader; private var teach_loader:XMLLoader; private static var _instance:ConfigManager; private var xml:XML; private var _menuItems:ArrayCollection; private var _teachDirItems:ArrayCollection; private var flag:int = 0; public function ConfigManager(target:IEventDispatcher=null) { super(target); iniData(); } public function get menuItems():ArrayCollection { return _menuItems; } private function iniData():void { if(!loader){ loader = new XMLLoader(); teach_loader = new XMLLoader(); } loader.load("com/zzti/conf/conf.xml",resultHandler); teach_loader.load("com/zzti/conf/tech.xml",teach_result,ioerror); } private function ioerror(e:IOErrorEvent):void { trace(e); } protected function resultHandler(result:XML):void { _menuItems = xmlToArray(_menuItems,result); flag++; if(flag>1){ dispatchEvent(new Event("ConfigOK")); } } private function teach_result(result:XML):void { _teachDirItems = xmlToArray(_teachDirItems,result); flag++; if(flag>1){ dispatchEvent(new Event("ConfigOK")); flag = 0; } } private function xmlToArray(arr:ArrayCollection,xml:XML):ArrayCollection { if(!arr) { arr = new ArrayCollection(); } for each(var item:XML in xml.children()){ arr.addItem(String(item.attribute("label"))); } return arr; } public static function getInstance():ConfigManager { if(!_instance){ _instance = new ConfigManager(); } return _instance; } public function get teachDirItems():ArrayCollection { return _teachDirItems; } } }
zzti-cs-2008
trunk/flex/src/com/zzti/manager/ConfigManager.as
ActionScript
oos
2,086
package com.zzti.ui.component { import com.vion.loader.MediaLoader; import com.zzti.manager.AppManager; import flash.utils.ByteArray; import spark.components.BorderContainer; public class BaseComponent extends BorderContainer { private var mediaLoader:MediaLoader ; public function BaseComponent() { super(); } public function destroy():void { } public function get appManager():AppManager { return AppManager.getInstance(); } } }
zzti-cs-2008
trunk/flex/src/com/zzti/ui/component/BaseComponent.as
ActionScript
oos
507
import com.zzti.AppGlobal; import com.zzti.events.AppEvent; import com.zzti.manager.AppManager; import com.zzti.manager.ConfigManager; import com.zzti.model.User; import com.zzti.ui.component.AppPanel; import com.zzti.ui.control.copyright.CopyRight; import com.zzti.ui.control.login.LoginPanel; import com.zzti.ui.control.login.RegistPanel; import flash.events.Event; import mx.controls.Alert; import mx.core.FlexGlobals; import mx.events.FlexEvent; import mx.managers.BrowserManager; import mx.managers.IBrowserManager; import mx.managers.PopUpManager; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; private var loginPanel:LoginPanel; private var registPanel:RegistPanel; private var appPanel:AppPanel; private var copyright:CopyRight; protected function application1_initializeHandler(event:FlexEvent):void { // TODO Auto-generated method stub this.conifgManager.addEventListener("ConfigOK",configOKHandler); this.appManager.addEventListener(AppEvent.LOGINSUCCESS,loginSuccessHandler); this.appManager.addEventListener(AppEvent.REGIST,registHandler); this.appManager.addEventListener(AppEvent.LOGOUT,logoutHandler); var bm:IBrowserManager = BrowserManager.getInstance(); bm.init(); // AppGlobal.shareURL = bm.url; // AppGlobal.sharePic = createPicUrl(AppGlobal.shareURL); AppGlobal.shareURL = "http://www.google.com"; AppGlobal.sharePic = "http://file.service.qq.com/qqfans-files/uploadfile2012/10/23/112311.jpg"; iniLogin(); } protected function createPicUrl(shareUrl:String):String { var picUrl:String = ""; picUrl = shareUrl.substring(0,shareUrl.lastIndexOf("/")); picUrl += "images/ZZTI-CS2008.JPG"; return picUrl; } protected function iniLogin():void { if(!loginPanel) { loginPanel = new LoginPanel(); /*loginPanel.width = FlexGlobals.topLevelApplication.width; loginPanel.height = FlexGlobals.topLevelApplication.height; loginPanel.horizontalCenter = 0; loginPanel.verticalCenter = 0;*/ } // loginPanel.percentHeight = 100; // loginPanel.percentWidth = 100; loginPanel.horizontalCenter = 0; loginPanel.verticalCenter = 0; loginPanel.iniData(); app.addElement(loginPanel); } protected function loginSuccessHandler(event:AppEvent):void { iniUser.getUserByName(event.userName); app.removeElement(loginPanel); iniAppPanel(); } protected function registHandler(event:AppEvent):void { if(!registPanel) { registPanel = new RegistPanel(); } registPanel.horizontalCenter = 0; registPanel.verticalCenter = 0; /*app.removeElement(loginPanel); app.addElement(registPanel);*/ PopUpManager.addPopUp(registPanel,app,true); PopUpManager.centerPopUp(registPanel); } protected function logoutHandler(event:AppEvent):void { AppGlobal.currentUser = null; appPanel.destroy(); app.removeElement(appPanel); appPanel = null; app.removeElement(copyright); iniLogin(); } protected function iniAppPanel():void { if(!appPanel){ appPanel = new AppPanel(); copyright = new CopyRight(); } appPanel.percentHeight = 100; appPanel.percentWidth = 80; appPanel.horizontalCenter = 0; appPanel.top = 10; appPanel.bottom = 20; app.addElement(appPanel); copyright.bottom = 0; app.addElement(copyright); /*trace(app.height + "" + app.width); PopUpManager.addPopUp(appPanel,app);*/ } protected function configOKHandler(event:Event):void { AppGlobal.menuItems = this.conifgManager.menuItems; AppGlobal.teachDirItems = this.conifgManager.teachDirItems; for each(var name:String in AppGlobal.menuItems) { trace(name); } } public function get appManager():AppManager { return AppManager.getInstance(); } public function get conifgManager():ConfigManager { return ConfigManager.getInstance(); } protected function iniUser_resultHandler(event:ResultEvent):void { // TODO Auto-generated method stub AppGlobal.currentUser = event.result as User; } protected function iniUser_faultHandler(event:FaultEvent):void { // TODO Auto-generated method stub trace(event.toString()); Alert.show("获取当前用户信息失败","错误"); }
zzti-cs-2008
trunk/flex/src/mainLogic.as
ActionScript
oos
4,191
package cn.edu.zzti.cs.bean; public class Order extends AbsJobOrder{ public Order(){ } public Order(int authorID,String title,String content,int state,String publishDate,String lastEditDate,String url){ this.authorID = authorID; this.title = title; this.content = content; this.state= state; this.publishDate = publishDate; this.lastEditDate = lastEditDate; this.url = url; } public Order(int id,int authorID,String title,String content,int state,String publishDate,String lastEditDate,String url){ this.id = id; this.authorID = authorID; this.title = title; this.content = content; this.state= state; this.publishDate = publishDate; this.lastEditDate = lastEditDate; this.url = url; } private Swuserinfo user; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAuthorId() { return authorID; } public void setAuthorId(int authorId) { this.authorID = authorId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getPublishDate() { return publishDate; } public void setPublishDate(String publishDate) { this.publishDate = publishDate; } public String getLastEditDate() { return lastEditDate; } public void setLastEditDate(String lastEditDate) { this.lastEditDate = lastEditDate; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Swuserinfo getUser() { return user; } public void setUser(Swuserinfo user) { this.user = user; } }
zzti-cs-2008
trunk/java/src/cn/edu/zzti/cs/bean/Order.java
Java
oos
1,896
package cn.edu.zzti.cs.bean; public class Notice { public Notice(){ } public Notice(String inserttime,String content,int adminid,String title){ this.inserttime = inserttime; this.content = content; this.adminid = adminid; this.title = title; } public Notice(int id,String inserttime,String content,int adminid,String title){ this.id = id ; this.inserttime = inserttime; this.content = content; this.adminid = adminid; this.title = title; } private int id ; private String inserttime; private String content; private int adminid ; private String title; private Swuserinfo user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInserttime() { return inserttime; } public void setInserttime(String inserttime) { this.inserttime = inserttime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getAdminid() { return adminid; } public void setAdminid(int adminid) { this.adminid = adminid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Swuserinfo getUser() { return user; } public void setUser(Swuserinfo user) { this.user = user; } }
zzti-cs-2008
trunk/java/src/cn/edu/zzti/cs/bean/Notice.java
Java
oos
1,368
package cn.edu.zzti.cs.bean; public class Swuserinfo { private Integer id; private String username; private String password; private String realname; private String email; private String addressNow; private String qq; private String addressHome; private String company; private String technoDir; private String gender; private String telNumber; public Swuserinfo() { } public Swuserinfo(String username, String password, String realname, String email) { this.username = username; this.password = password; this.realname = realname; this.email = email; } public Swuserinfo(String username, String password, String realname, String email, String addressNow, String qq, String addressHome, String company, String technoDir, String gender, String telNumber) { this.username = username; this.password = password; this.realname = realname; this.email = email; this.addressNow = addressNow; this.qq = qq; this.addressHome = addressHome; this.company = company; this.technoDir = technoDir; this.gender = gender; this.telNumber = telNumber; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getRealname() { return this.realname; } public void setRealname(String realname) { this.realname = realname; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getAddressNow() { return this.addressNow; } public void setAddressNow(String addressNow) { this.addressNow = addressNow; } public String getQq() { return this.qq; } public void setQq(String qq) { this.qq = qq; } public String getAddressHome() { return this.addressHome; } public void setAddressHome(String addressHome) { this.addressHome = addressHome; } public String getCompany() { return this.company; } public void setCompany(String company) { this.company = company; } public String getTechnoDir() { return this.technoDir; } public void setTechnoDir(String technoDir) { this.technoDir = technoDir; } public String getGender() { return this.gender; } public void setGender(String gender) { this.gender = gender; } public String getTelNumber() { return this.telNumber; } public void setTelNumber(String telNumber) { this.telNumber = telNumber; } @Override public String toString() { return this.getRealname()+","+this.getUsername()+","+this.getEmail(); } }
zzti-cs-2008
trunk/java/src/cn/edu/zzti/cs/bean/Swuserinfo.java
Java
oos
3,059
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.multiple; import java.util.List; import java.util.regex.Pattern; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.crawler.WebCrawler; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.url.WebURL; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class BasicCrawler extends WebCrawler { private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4" + "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$"); private String[] myCrawlDomains; @Override public void onStart() { myCrawlDomains = (String[]) myController.getCustomData(); } @Override public boolean shouldVisit(WebURL url) { String href = url.getURL().toLowerCase(); if (FILTERS.matcher(href).matches()) { return false; } for (String crawlDomain : myCrawlDomains) { if (href.startsWith(crawlDomain)) { return true; } } return false; } @Override public void visit(Page page) { int docid = page.getWebURL().getDocid(); String url = page.getWebURL().getURL(); int parentDocid = page.getWebURL().getParentDocid(); System.out.println("Docid: " + docid); System.out.println("URL: " + url); System.out.println("Docid of parent page: " + parentDocid); if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); String text = htmlParseData.getText(); String html = htmlParseData.getHtml(); List<WebURL> links = htmlParseData.getOutgoingUrls(); System.out.println("Text length: " + text.length()); System.out.println("Html length: " + html.length()); System.out.println("Number of outgoing links: " + links.size()); } System.out.println("============="); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/multiple/BasicCrawler.java
Java
asf20
2,650
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.multiple; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.CrawlController; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class MultipleCrawlerController { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Needed parameter: "); System.out.println("\t rootFolder (it will contain intermediate crawl data)"); return; } /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = args[0]; CrawlConfig config1 = new CrawlConfig(); CrawlConfig config2 = new CrawlConfig(); /* * The two crawlers should have different storage folders for their * intermediate data */ config1.setCrawlStorageFolder(crawlStorageFolder + "/crawler1"); config2.setCrawlStorageFolder(crawlStorageFolder + "/crawler2"); config1.setPolitenessDelay(1000); config2.setPolitenessDelay(2000); config1.setMaxPagesToFetch(50); config2.setMaxPagesToFetch(100); /* * We will use different PageFetchers for the two crawlers. */ PageFetcher pageFetcher1 = new PageFetcher(config1); PageFetcher pageFetcher2 = new PageFetcher(config2); /* * We will use the same RobotstxtServer for both of the crawlers. */ RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher1); CrawlController controller1 = new CrawlController(config1, pageFetcher1, robotstxtServer); CrawlController controller2 = new CrawlController(config2, pageFetcher2, robotstxtServer); String[] crawler1Domains = new String[] { "http://www.ics.uci.edu/", "http://www.cnn.com/" }; String[] crawler2Domains = new String[] { "http://en.wikipedia.org/" }; controller1.setCustomData(crawler1Domains); controller2.setCustomData(crawler2Domains); controller1.addSeed("http://www.ics.uci.edu/"); controller1.addSeed("http://www.cnn.com/"); controller1.addSeed("http://www.ics.uci.edu/~lopes/"); controller1.addSeed("http://www.cnn.com/POLITICS/"); controller2.addSeed("http://en.wikipedia.org/wiki/Main_Page"); controller2.addSeed("http://en.wikipedia.org/wiki/Obama"); controller2.addSeed("http://en.wikipedia.org/wiki/Bing"); /* * The first crawler will have 5 cuncurrent threads and the second * crawler will have 7 threads. */ controller1.startNonBlocking(BasicCrawler.class, 5); controller2.startNonBlocking(BasicCrawler.class, 7); controller1.waitUntilFinish(); System.out.println("Crawler 1 is finished."); controller2.waitUntilFinish(); System.out.println("Crawler 2 is finished."); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/multiple/MultipleCrawlerController.java
Java
asf20
3,711
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.statushandler; import java.util.regex.Pattern; import org.apache.http.HttpStatus; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.crawler.WebCrawler; import edu.uci.ics.crawler4j.url.WebURL; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class StatusHandlerCrawler extends WebCrawler { private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4" + "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$"); /** * You should implement this function to specify whether * the given url should be crawled or not (based on your * crawling logic). */ @Override public boolean shouldVisit(WebURL url) { String href = url.getURL().toLowerCase(); return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/"); } /** * This function is called when a page is fetched and ready * to be processed by your program. */ @Override public void visit(Page page) { // Do nothing } @Override protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) { if (statusCode != HttpStatus.SC_OK) { if (statusCode == HttpStatus.SC_NOT_FOUND) { System.out.println("Broken link: " + webUrl.getURL() + ", this link was found in page: " + webUrl.getParentUrl()); } else { System.out.println("Non success status for link: " + webUrl.getURL() + ", status code: " + statusCode + ", description: " + statusDescription); } } } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/statushandler/StatusHandlerCrawler.java
Java
asf20
2,391
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.statushandler; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.CrawlController; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class StatusHandlerCrawlController { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Needed parameters: "); System.out.println("\t rootFolder (it will contain intermediate crawl data)"); System.out.println("\t numberOfCralwers (number of concurrent threads)"); return; } /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = args[0]; /* * numberOfCrawlers shows the number of concurrent threads that should * be initiated for crawling. */ int numberOfCrawlers = Integer.parseInt(args[1]); CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(crawlStorageFolder); /* * Be polite: Make sure that we don't send more than 1 request per * second (1000 milliseconds between requests). */ config.setPolitenessDelay(1000); /* * You can set the maximum crawl depth here. The default value is -1 for * unlimited depth */ config.setMaxDepthOfCrawling(2); /* * You can set the maximum number of pages to crawl. The default value * is -1 for unlimited number of pages */ config.setMaxPagesToFetch(1000); /* * Do you need to set a proxy? If so, you can use: * config.setProxyHost("proxyserver.example.com"); * config.setProxyPort(8080); * * If your proxy also needs authentication: * config.setProxyUsername(username); config.getProxyPassword(password); */ /* * This config parameter can be used to set your crawl to be resumable * (meaning that you can resume the crawl from a previously * interrupted/crashed crawl). Note: if you enable resuming feature and * want to start a fresh crawl, you need to delete the contents of * rootFolder manually. */ config.setResumableCrawling(false); /* * Instantiate the controller for this crawl. */ PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); /* * For each crawl, you need to add some seed urls. These are the first * URLs that are fetched and then the crawler starts following links * which are found in these pages */ controller.addSeed("http://www.ics.uci.edu/~welling/"); controller.addSeed("http://www.ics.uci.edu/~lopes/"); controller.addSeed("http://www.ics.uci.edu/"); /* * Start the crawl. This is a blocking operation, meaning that your code * will reach the line after this only when crawling is finished. */ controller.start(StatusHandlerCrawler.class, numberOfCrawlers); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/statushandler/StatusHandlerCrawlController.java
Java
asf20
3,971
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.shutdown; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.CrawlController; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class ControllerWithShutdown { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Needed parameters: "); System.out.println("\t rootFolder (it will contain intermediate crawl data)"); System.out.println("\t numberOfCralwers (number of concurrent threads)"); return; } /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = args[0]; /* * numberOfCrawlers shows the number of concurrent threads that should * be initiated for crawling. */ int numberOfCrawlers = Integer.parseInt(args[1]); CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(crawlStorageFolder); config.setPolitenessDelay(1000); // Unlimited number of pages can be crawled. config.setMaxPagesToFetch(-1); /* * Instantiate the controller for this crawl. */ PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); /* * For each crawl, you need to add some seed urls. These are the first * URLs that are fetched and then the crawler starts following links * which are found in these pages */ controller.addSeed("http://www.ics.uci.edu/~welling/"); controller.addSeed("http://www.ics.uci.edu/~lopes/"); controller.addSeed("http://www.ics.uci.edu/"); /* * Start the crawl. This is a blocking operation, meaning that your code * will reach the line after this only when crawling is finished. */ controller.startNonBlocking(BasicCrawler.class, numberOfCrawlers); // Wait for 30 seconds Thread.sleep(30 * 1000); // Send the shutdown request and then wait for finishing controller.Shutdown(); controller.waitUntilFinish(); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/shutdown/ControllerWithShutdown.java
Java
asf20
3,150
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.shutdown; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.crawler.WebCrawler; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.url.WebURL; import java.util.List; import java.util.regex.Pattern; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class BasicCrawler extends WebCrawler { private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4" + "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$"); private final static String DOMAIN = "http://www.ics.uci.edu/"; @Override public boolean shouldVisit(WebURL url) { String href = url.getURL().toLowerCase(); return !FILTERS.matcher(href).matches() && href.startsWith(DOMAIN); } @Override public void visit(Page page) { int docid = page.getWebURL().getDocid(); String url = page.getWebURL().getURL(); int parentDocid = page.getWebURL().getParentDocid(); System.out.println("Docid: " + docid); System.out.println("URL: " + url); System.out.println("Docid of parent page: " + parentDocid); if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); String text = htmlParseData.getText(); String html = htmlParseData.getHtml(); List<WebURL> links = htmlParseData.getOutgoingUrls(); System.out.println("Text length: " + text.length()); System.out.println("Html length: " + html.length()); System.out.println("Number of outgoing links: " + links.size()); } System.out.println("============="); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/shutdown/BasicCrawler.java
Java
asf20
2,463
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.imagecrawler; import java.security.MessageDigest; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Cryptography { private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static String MD5(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); return hexStringFromBytes(md.digest()); } catch (Exception e) { e.printStackTrace(); return ""; } } private static String hexStringFromBytes(byte[] b) { String hex = ""; int msb; int lsb; int i; // MSB maps to idx 0 for (i = 0; i < b.length; i++) { msb = ((int) b[i] & 0x000000FF) / 16; lsb = ((int) b[i] & 0x000000FF) % 16; hex = hex + hexChars[msb] + hexChars[lsb]; } return (hex); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/imagecrawler/Cryptography.java
Java
asf20
1,683
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.imagecrawler; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.CrawlController; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ /* * IMPORTANT: Make sure that you update crawler4j.properties file and set * crawler.include_images to true */ public class ImageCrawlController { public static void main(String[] args) throws Exception { if (args.length < 3) { System.out.println("Needed parameters: "); System.out.println("\t rootFolder (it will contain intermediate crawl data)"); System.out.println("\t numberOfCralwers (number of concurrent threads)"); System.out.println("\t storageFolder (a folder for storing downloaded images)"); return; } String rootFolder = args[0]; int numberOfCrawlers = Integer.parseInt(args[1]); String storageFolder = args[2]; CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(rootFolder); /* * Since images are binary content, we need to set this parameter to * true to make sure they are included in the crawl. */ config.setIncludeBinaryContentInCrawling(true); String[] crawlDomains = new String[] { "http://uci.edu/" }; PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); for (String domain : crawlDomains) { controller.addSeed(domain); } ImageCrawler.configure(crawlDomains, storageFolder); controller.start(ImageCrawler.class, numberOfCrawlers); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/imagecrawler/ImageCrawlController.java
Java
asf20
2,674
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.imagecrawler; import java.io.File; import java.util.regex.Pattern; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.crawler.WebCrawler; import edu.uci.ics.crawler4j.parser.BinaryParseData; import edu.uci.ics.crawler4j.url.WebURL; import edu.uci.ics.crawler4j.util.IO; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ /* * This class shows how you can crawl images on the web and store them in a * folder. This is just for demonstration purposes and doesn't scale for large * number of images. For crawling millions of images you would need to store * downloaded images in a hierarchy of folders */ public class ImageCrawler extends WebCrawler { private static final Pattern filters = Pattern.compile(".*(\\.(css|js|mid|mp2|mp3|mp4|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$"); private static final Pattern imgPatterns = Pattern.compile(".*(\\.(bmp|gif|jpe?g|png|tiff?))$"); private static File storageFolder; private static String[] crawlDomains; public static void configure(String[] crawlDomains, String storageFolderName) { ImageCrawler.crawlDomains = crawlDomains; storageFolder = new File(storageFolderName); if (!storageFolder.exists()) { storageFolder.mkdirs(); } } @Override public boolean shouldVisit(WebURL url) { String href = url.getURL().toLowerCase(); if (filters.matcher(href).matches()) { return false; } if (imgPatterns.matcher(href).matches()) { return true; } for (String domain : crawlDomains) { if (href.startsWith(domain)) { return true; } } return false; } @Override public void visit(Page page) { String url = page.getWebURL().getURL(); // We are only interested in processing images if (!(page.getParseData() instanceof BinaryParseData)) { return; } if (!imgPatterns.matcher(url).matches()) { return; } // Not interested in very small images if (page.getContentData().length < 10 * 1024) { return; } // get a unique name for storing this image String extension = url.substring(url.lastIndexOf(".")); String hashedName = Cryptography.MD5(url) + extension; // store image IO.writeBytesToFile(page.getContentData(), storageFolder.getAbsolutePath() + "/" + hashedName); System.out.println("Stored: " + url); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/imagecrawler/ImageCrawler.java
Java
asf20
3,162
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.basic; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.CrawlController; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class BasicCrawlController { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Needed parameters: "); System.out.println("\t rootFolder (it will contain intermediate crawl data)"); System.out.println("\t numberOfCralwers (number of concurrent threads)"); return; } /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = args[0]; /* * numberOfCrawlers shows the number of concurrent threads that should * be initiated for crawling. */ int numberOfCrawlers = Integer.parseInt(args[1]); CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(crawlStorageFolder); /* * Be polite: Make sure that we don't send more than 1 request per * second (1000 milliseconds between requests). */ config.setPolitenessDelay(1000); /* * You can set the maximum crawl depth here. The default value is -1 for * unlimited depth */ config.setMaxDepthOfCrawling(2); /* * You can set the maximum number of pages to crawl. The default value * is -1 for unlimited number of pages */ config.setMaxPagesToFetch(1000); /* * Do you need to set a proxy? If so, you can use: * config.setProxyHost("proxyserver.example.com"); * config.setProxyPort(8080); * * If your proxy also needs authentication: * config.setProxyUsername(username); config.getProxyPassword(password); */ /* * This config parameter can be used to set your crawl to be resumable * (meaning that you can resume the crawl from a previously * interrupted/crashed crawl). Note: if you enable resuming feature and * want to start a fresh crawl, you need to delete the contents of * rootFolder manually. */ config.setResumableCrawling(false); /* * Instantiate the controller for this crawl. */ PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); /* * For each crawl, you need to add some seed urls. These are the first * URLs that are fetched and then the crawler starts following links * which are found in these pages */ controller.addSeed("http://www.ics.uci.edu/"); controller.addSeed("http://www.ics.uci.edu/~lopes/"); controller.addSeed("http://www.ics.uci.edu/~welling/"); /* * Start the crawl. This is a blocking operation, meaning that your code * will reach the line after this only when crawling is finished. */ controller.start(BasicCrawler.class, numberOfCrawlers); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/basic/BasicCrawlController.java
Java
asf20
3,948
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.basic; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.crawler.WebCrawler; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.url.WebURL; import java.util.List; import java.util.regex.Pattern; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class BasicCrawler extends WebCrawler { private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4" + "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$"); /** * You should implement this function to specify whether the given url * should be crawled or not (based on your crawling logic). */ @Override public boolean shouldVisit(WebURL url) { String href = url.getURL().toLowerCase(); return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/"); } /** * This function is called when a page is fetched and ready to be processed * by your program. */ @Override public void visit(Page page) { int docid = page.getWebURL().getDocid(); String url = page.getWebURL().getURL(); String domain = page.getWebURL().getDomain(); String path = page.getWebURL().getPath(); String subDomain = page.getWebURL().getSubDomain(); String parentUrl = page.getWebURL().getParentUrl(); System.out.println("Docid: " + docid); System.out.println("URL: " + url); System.out.println("Domain: '" + domain + "'"); System.out.println("Sub-domain: '" + subDomain + "'"); System.out.println("Path: '" + path + "'"); System.out.println("Parent page: " + parentUrl); if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); String text = htmlParseData.getText(); String html = htmlParseData.getHtml(); List<WebURL> links = htmlParseData.getOutgoingUrls(); System.out.println("Text length: " + text.length()); System.out.println("Html length: " + html.length()); System.out.println("Number of outgoing links: " + links.size()); } System.out.println("============="); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/basic/BasicCrawler.java
Java
asf20
2,950
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.localdata; import org.apache.http.HttpStatus; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.fetcher.PageFetchResult; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.parser.ParseData; import edu.uci.ics.crawler4j.parser.Parser; import edu.uci.ics.crawler4j.url.WebURL; /** * This class is a demonstration of how crawler4j can be used to download a * single page and extract its title and text. */ public class Downloader { private Parser parser; private PageFetcher pageFetcher; public Downloader() { CrawlConfig config = new CrawlConfig(); parser = new Parser(config); pageFetcher = new PageFetcher(config); } private Page download(String url) { WebURL curURL = new WebURL(); curURL.setURL(url); PageFetchResult fetchResult = null; try { fetchResult = pageFetcher.fetchHeader(curURL); if (fetchResult.getStatusCode() == HttpStatus.SC_OK) { try { Page page = new Page(curURL); fetchResult.fetchContent(page); if (parser.parse(page, curURL.getURL())) { return page; } } catch (Exception e) { e.printStackTrace(); } } } finally { fetchResult.discardContentIfNotConsumed(); } return null; } public void processUrl(String url) { System.out.println("Processing: " + url); Page page = download(url); if (page != null) { ParseData parseData = page.getParseData(); if (parseData != null) { if (parseData instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) parseData; System.out.println("Title: " + htmlParseData.getTitle()); System.out.println("Text length: " + htmlParseData.getText().length()); System.out.println("Html length: " + htmlParseData.getHtml().length()); } } else { System.out.println("Couldn't parse the content of the page."); } } else { System.out.println("Couldn't fetch the content of the page."); } System.out.println("=============="); } public static void main(String[] args) { Downloader downloader = new Downloader(); downloader.processUrl("http://en.wikipedia.org/wiki/Main_Page/"); downloader.processUrl("http://www.yahoo.com/"); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/localdata/Downloader.java
Java
asf20
3,135
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.localdata; import java.util.List; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.CrawlController; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; public class LocalDataCollectorController { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Needed parameters: "); System.out.println("\t rootFolder (it will contain intermediate crawl data)"); System.out.println("\t numberOfCralwers (number of concurrent threads)"); return; } String rootFolder = args[0]; int numberOfCrawlers = Integer.parseInt(args[1]); CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(rootFolder); config.setMaxPagesToFetch(10); config.setPolitenessDelay(1000); PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); controller.addSeed("http://www.ics.uci.edu/"); controller.start(LocalDataCollectorCrawler.class, numberOfCrawlers); List<Object> crawlersLocalData = controller.getCrawlersLocalData(); long totalLinks = 0; long totalTextSize = 0; int totalProcessedPages = 0; for (Object localData : crawlersLocalData) { CrawlStat stat = (CrawlStat) localData; totalLinks += stat.getTotalLinks(); totalTextSize += stat.getTotalTextSize(); totalProcessedPages += stat.getTotalProcessedPages(); } System.out.println("Aggregated Statistics:"); System.out.println(" Processed Pages: " + totalProcessedPages); System.out.println(" Total Links found: " + totalLinks); System.out.println(" Total Text Size: " + totalTextSize); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/localdata/LocalDataCollectorController.java
Java
asf20
2,776
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.localdata; public class CrawlStat { private int totalProcessedPages; private long totalLinks; private long totalTextSize; public int getTotalProcessedPages() { return totalProcessedPages; } public void setTotalProcessedPages(int totalProcessedPages) { this.totalProcessedPages = totalProcessedPages; } public void incProcessedPages() { this.totalProcessedPages++; } public long getTotalLinks() { return totalLinks; } public void setTotalLinks(long totalLinks) { this.totalLinks = totalLinks; } public long getTotalTextSize() { return totalTextSize; } public void setTotalTextSize(long totalTextSize) { this.totalTextSize = totalTextSize; } public void incTotalLinks(int count) { this.totalLinks += count; } public void incTotalTextSize(int count) { this.totalTextSize += count; } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/localdata/CrawlStat.java
Java
asf20
1,675
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.examples.localdata; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.crawler.WebCrawler; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.url.WebURL; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.regex.Pattern; public class LocalDataCollectorCrawler extends WebCrawler { Pattern filters = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4" + "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$"); CrawlStat myCrawlStat; public LocalDataCollectorCrawler() { myCrawlStat = new CrawlStat(); } @Override public boolean shouldVisit(WebURL url) { String href = url.getURL().toLowerCase(); return !filters.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/"); } @Override public void visit(Page page) { System.out.println("Visited: " + page.getWebURL().getURL()); myCrawlStat.incProcessedPages(); if (page.getParseData() instanceof HtmlParseData) { HtmlParseData parseData = (HtmlParseData) page.getParseData(); List<WebURL> links = parseData.getOutgoingUrls(); myCrawlStat.incTotalLinks(links.size()); try { myCrawlStat.incTotalTextSize(parseData.getText().getBytes("UTF-8").length); } catch (UnsupportedEncodingException ignored) { } } // We dump this crawler statistics after processing every 50 pages if (myCrawlStat.getTotalProcessedPages() % 50 == 0) { dumpMyData(); } } // This function is called by controller to get the local data of this // crawler when job is finished @Override public Object getMyLocalData() { return myCrawlStat; } // This function is called by controller before finishing the job. // You can put whatever stuff you need here. @Override public void onBeforeExit() { dumpMyData(); } public void dumpMyData() { int myId = getMyId(); // This is just an example. Therefore I print on screen. You may // probably want to write in a text file. System.out.println("Crawler " + myId + "> Processed Pages: " + myCrawlStat.getTotalProcessedPages()); System.out.println("Crawler " + myId + "> Total Links Found: " + myCrawlStat.getTotalLinks()); System.out.println("Crawler " + myId + "> Total Text Size: " + myCrawlStat.getTotalTextSize()); } }
zzysiat-mycrawler
src/test/java/edu/uci/ics/crawler4j/examples/localdata/LocalDataCollectorCrawler.java
Java
asf20
3,144
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.util.EntityUtils; import edu.uci.ics.crawler4j.parser.ParseData; import edu.uci.ics.crawler4j.url.WebURL; /** * This class contains the data for a fetched and parsed page. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Page { /** * The URL of this page. */ protected WebURL url; /** * The content of this page in binary format. */ protected byte[] contentData; /** * The ContentType of this page. * For example: "text/html; charset=UTF-8" */ protected String contentType; /** * The encoding of the content. * For example: "gzip" */ protected String contentEncoding; /** * The charset of the content. * For example: "UTF-8" */ protected String contentCharset; /** * The parsed data populated by parsers */ protected ParseData parseData; public Page(WebURL url) { this.url = url; } public WebURL getWebURL() { return url; } public void setWebURL(WebURL url) { this.url = url; } /** * Loads the content of this page from a fetched * HttpEntity. */ public void load(HttpEntity entity) throws Exception { contentType = null; Header type = entity.getContentType(); if (type != null) { contentType = type.getValue(); } contentEncoding = null; Header encoding = entity.getContentEncoding(); if (encoding != null) { contentEncoding = encoding.getValue(); } contentCharset = EntityUtils.getContentCharSet(entity); contentData = EntityUtils.toByteArray(entity); } /** * Returns the parsed data generated for this page by parsers */ public ParseData getParseData() { return parseData; } public void setParseData(ParseData parseData) { this.parseData = parseData; } /** * Returns the content of this page in binary format. */ public byte[] getContentData() { return contentData; } public void setContentData(byte[] contentData) { this.contentData = contentData; } /** * Returns the ContentType of this page. * For example: "text/html; charset=UTF-8" */ public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } /** * Returns the encoding of the content. * For example: "gzip" */ public String getContentEncoding() { return contentEncoding; } public void setContentEncoding(String contentEncoding) { this.contentEncoding = contentEncoding; } /** * Returns the charset of the content. * For example: "UTF-8" */ public String getContentCharset() { return contentCharset; } public void setContentCharset(String contentCharset) { this.contentCharset = contentCharset; } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/crawler/Page.java
Java
asf20
3,758
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; import com.sleepycat.je.Environment; import com.sleepycat.je.EnvironmentConfig; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.frontier.DocIDServer; import edu.uci.ics.crawler4j.frontier.Frontier; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; import edu.uci.ics.crawler4j.url.URLCanonicalizer; import edu.uci.ics.crawler4j.url.WebURL; import edu.uci.ics.crawler4j.util.IO; import org.apache.log4j.Logger; import java.io.File; import java.util.ArrayList; import java.util.List; /** * The controller that manages a crawling session. This class creates the * crawler threads and monitors their progress. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class CrawlController extends Configurable { private static final Logger logger = Logger.getLogger(CrawlController.class.getName()); /** * The 'customData' object can be used for passing custom crawl-related * configurations to different components of the crawler. */ protected Object customData; /** * Once the crawling session finishes the controller collects the local data * of the crawler threads and stores them in this List. */ protected List<Object> crawlersLocalData = new ArrayList<Object>(); /** * Is the crawling of this session finished? */ protected boolean finished; /** * Is the crawling session set to 'shutdown'. Crawler threads monitor this * flag and when it is set they will no longer process new pages. */ protected boolean shuttingDown; protected PageFetcher pageFetcher; protected RobotstxtServer robotstxtServer; protected Frontier frontier; protected DocIDServer docIdServer; protected final Object waitingLock = new Object(); public CrawlController(CrawlConfig config, PageFetcher pageFetcher, RobotstxtServer robotstxtServer) throws Exception { super(config); config.validate(); File folder = new File(config.getCrawlStorageFolder()); if (!folder.exists()) { if (!folder.mkdirs()) { throw new Exception("Couldn't create this folder: " + folder.getAbsolutePath()); } } boolean resumable = config.isResumableCrawling(); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setAllowCreate(true); envConfig.setTransactional(resumable); envConfig.setLocking(resumable); File envHome = new File(config.getCrawlStorageFolder() + "/frontier"); if (!envHome.exists()) { if (!envHome.mkdir()) { throw new Exception("Couldn't create this folder: " + envHome.getAbsolutePath()); } } if (!resumable) { IO.deleteFolderContents(envHome); } Environment env = new Environment(envHome, envConfig); docIdServer = new DocIDServer(env, config); frontier = new Frontier(env, config, docIdServer); this.pageFetcher = pageFetcher; this.robotstxtServer = robotstxtServer; finished = false; shuttingDown = false; } /** * Start the crawling session and wait for it to finish. * * @param _c * the class that implements the logic for crawler threads * @param numberOfCrawlers * the number of concurrent threads that will be contributing in * this crawling session. */ public <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers) { this.start(_c, numberOfCrawlers, true); } /** * Start the crawling session and return immediately. * * @param _c * the class that implements the logic for crawler threads * @param numberOfCrawlers * the number of concurrent threads that will be contributing in * this crawling session. */ public <T extends WebCrawler> void startNonBlocking(final Class<T> _c, final int numberOfCrawlers) { this.start(_c, numberOfCrawlers, false); } protected <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers, boolean isBlocking) { try { finished = false; crawlersLocalData.clear(); final List<Thread> threads = new ArrayList<Thread>(); final List<T> crawlers = new ArrayList<T>(); for (int i = 1; i <= numberOfCrawlers; i++) { T crawler = _c.newInstance(); Thread thread = new Thread(crawler, "Crawler " + i); crawler.setThread(thread); crawler.init(i, this); thread.start(); crawlers.add(crawler); threads.add(thread); logger.info("Crawler " + i + " started."); } final CrawlController controller = this; Thread monitorThread = new Thread(new Runnable() { @Override public void run() { try { synchronized (waitingLock) { while (true) { sleep(10); boolean someoneIsWorking = false; for (int i = 0; i < threads.size(); i++) { Thread thread = threads.get(i); if (!thread.isAlive()) { if (!shuttingDown) { logger.info("Thread " + i + " was dead, I'll recreate it."); T crawler = _c.newInstance(); thread = new Thread(crawler, "Crawler " + (i + 1)); threads.remove(i); threads.add(i, thread); crawler.setThread(thread); crawler.init(i + 1, controller); thread.start(); crawlers.remove(i); crawlers.add(i, crawler); } } else if (crawlers.get(i).isNotWaitingForNewURLs()) { someoneIsWorking = true; } } if (!someoneIsWorking) { // Make sure again that none of the threads // are // alive. logger.info("It looks like no thread is working, waiting for 10 seconds to make sure..."); sleep(10); someoneIsWorking = false; for (int i = 0; i < threads.size(); i++) { Thread thread = threads.get(i); if (thread.isAlive() && crawlers.get(i).isNotWaitingForNewURLs()) { someoneIsWorking = true; } } if (!someoneIsWorking) { if (!shuttingDown) { long queueLength = frontier.getQueueLength(); if (queueLength > 0) { continue; } logger.info("No thread is working and no more URLs are in queue waiting for another 10 seconds to make sure..."); sleep(10); queueLength = frontier.getQueueLength(); if (queueLength > 0) { continue; } } logger.info("All of the crawlers are stopped. Finishing the process..."); // At this step, frontier notifies the // threads that were // waiting for new URLs and they should // stop frontier.finish(); for (T crawler : crawlers) { crawler.onBeforeExit(); crawlersLocalData.add(crawler.getMyLocalData()); } logger.info("Waiting for 10 seconds before final clean up..."); sleep(10); frontier.close(); docIdServer.close(); pageFetcher.shutDown(); finished = true; waitingLock.notifyAll(); return; } } } } } catch (Exception e) { e.printStackTrace(); } } }); monitorThread.start(); if (isBlocking) { waitUntilFinish(); } } catch (Exception e) { e.printStackTrace(); } } /** * Wait until this crawling session finishes. */ public void waitUntilFinish() { while (!finished) { synchronized (waitingLock) { if (finished) { return; } try { waitingLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * Once the crawling session finishes the controller collects the local data * of the crawler threads and stores them in a List. This function returns * the reference to this list. */ public List<Object> getCrawlersLocalData() { return crawlersLocalData; } protected void sleep(int seconds) { try { Thread.sleep(seconds * 1000); } catch (Exception ignored) { } } /** * Adds a new seed URL. A seed URL is a URL that is fetched by the crawler * to extract new URLs in it and follow them for crawling. * * @param pageUrl * the URL of the seed */ public void addSeed(String pageUrl) { addSeed(pageUrl, -1); } /** * Adds a new seed URL. A seed URL is a URL that is fetched by the crawler * to extract new URLs in it and follow them for crawling. You can also * specify a specific document id to be assigned to this seed URL. This * document id needs to be unique. Also, note that if you add three seeds * with document ids 1,2, and 7. Then the next URL that is found during the * crawl will get a doc id of 8. Also you need to ensure to add seeds in * increasing order of document ids. * * Specifying doc ids is mainly useful when you have had a previous crawl * and have stored the results and want to start a new crawl with seeds * which get the same document ids as the previous crawl. * * @param pageUrl * the URL of the seed * @param docId * the document id that you want to be assigned to this seed URL. * */ public void addSeed(String pageUrl, int docId) { String canonicalUrl = URLCanonicalizer.getCanonicalURL(pageUrl); if (canonicalUrl == null) { logger.error("Invalid seed URL: " + pageUrl); return; } if (docId < 0) { docId = docIdServer.getDocId(canonicalUrl); if (docId > 0) { // This URL is already seen. return; } docId = docIdServer.getNewDocID(canonicalUrl); } else { try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (Exception e) { logger.error("Could not add seed: " + e.getMessage()); } } WebURL webUrl = new WebURL(); webUrl.setURL(canonicalUrl); webUrl.setDocid(docId); webUrl.setDepth((short) 0); if (!robotstxtServer.allows(webUrl)) { logger.info("Robots.txt does not allow this seed: " + pageUrl); } else { frontier.schedule(webUrl); } } /** * This function can called to assign a specific document id to a url. This * feature is useful when you have had a previous crawl and have stored the * Urls and their associated document ids and want to have a new crawl which * is aware of the previously seen Urls and won't re-crawl them. * * Note that if you add three seen Urls with document ids 1,2, and 7. Then * the next URL that is found during the crawl will get a doc id of 8. Also * you need to ensure to add seen Urls in increasing order of document ids. * * @param pageUrl * the URL of the page * @param docId * the document id that you want to be assigned to this URL. * */ public void addSeenUrl(String url, int docId) { String canonicalUrl = URLCanonicalizer.getCanonicalURL(url); if (canonicalUrl == null) { logger.error("Invalid Url: " + url); return; } try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (Exception e) { logger.error("Could not add seen url: " + e.getMessage()); } } public PageFetcher getPageFetcher() { return pageFetcher; } public void setPageFetcher(PageFetcher pageFetcher) { this.pageFetcher = pageFetcher; } public RobotstxtServer getRobotstxtServer() { return robotstxtServer; } public void setRobotstxtServer(RobotstxtServer robotstxtServer) { this.robotstxtServer = robotstxtServer; } public Frontier getFrontier() { return frontier; } public void setFrontier(Frontier frontier) { this.frontier = frontier; } public DocIDServer getDocIdServer() { return docIdServer; } public void setDocIdServer(DocIDServer docIdServer) { this.docIdServer = docIdServer; } public Object getCustomData() { return customData; } public void setCustomData(Object customData) { this.customData = customData; } public boolean isFinished() { return this.finished; } public boolean isShuttingDown() { return shuttingDown; } /** * Set the current crawling session set to 'shutdown'. Crawler threads * monitor the shutdown flag and when it is set to true, they will no longer * process new pages. */ public void Shutdown() { logger.info("Shutting down..."); this.shuttingDown = true; frontier.finish(); } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
Java
asf20
13,015
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; /** * Several core components of crawler4j extend this class * to make them configurable. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public abstract class Configurable { protected CrawlConfig config; protected Configurable(CrawlConfig config) { this.config = config; } public CrawlConfig getConfig() { return config; } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/crawler/Configurable.java
Java
asf20
1,203
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; public class CrawlConfig { /** * The folder which will be used by crawler for storing the intermediate * crawl data. The content of this folder should not be modified manually. */ private String crawlStorageFolder; /** * If this feature is enabled, you would be able to resume a previously * stopped/crashed crawl. However, it makes crawling slightly slower */ private boolean resumableCrawling = false; /** * Maximum depth of crawling For unlimited depth this parameter should be * set to -1 */ private int maxDepthOfCrawling = -1; /** * Maximum number of pages to fetch For unlimited number of pages, this * parameter should be set to -1 */ private int maxPagesToFetch = -1; /** * user-agent string that is used for representing your crawler to web * servers. See http://en.wikipedia.org/wiki/User_agent for more details */ private String userAgentString = "crawler4j (http://code.google.com/p/crawler4j/)"; /** * Politeness delay in milliseconds (delay between sending two requests to * the same host). */ private int politenessDelay = 200; /** * Should we also crawl https pages? */ private boolean includeHttpsPages = false; /** * Should we fetch binary content such as images, audio, ...? */ private boolean includeBinaryContentInCrawling = false; /** * Maximum Connections per host */ private int maxConnectionsPerHost = 100; /** * Maximum total connections */ private int maxTotalConnections = 100; /** * Socket timeout in milliseconds */ private int socketTimeout = 20000; /** * Connection timeout in milliseconds */ private int connectionTimeout = 30000; /** * Max number of outgoing links which are processed from a page */ private int maxOutgoingLinksToFollow = 5000; /** * Max allowed size of a page. Pages larger than this size will not be * fetched. */ private int maxDownloadSize = 1048576; /** * Should we follow redirects? */ private boolean followRedirects = true; /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy host. */ private String proxyHost = null; /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy port. */ private int proxyPort = 80; /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * username. */ private String proxyUsername = null; /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * password. */ private String proxyPassword = null; public CrawlConfig() { } /** * Validates the configs specified by this instance. * * @throws Exception */ public void validate() throws Exception { if (crawlStorageFolder == null) { throw new Exception("Crawl storage folder is not set in the CrawlConfig."); } if (politenessDelay < 0) { throw new Exception("Invalid value for politeness delay: " + politenessDelay); } if (maxDepthOfCrawling < -1) { throw new Exception("Maximum crawl depth should be either a positive number or -1 for unlimited depth."); } if (maxDepthOfCrawling > Short.MAX_VALUE) { throw new Exception("Maximum value for crawl depth is " + Short.MAX_VALUE); } } public String getCrawlStorageFolder() { return crawlStorageFolder; } /** * The folder which will be used by crawler for storing the intermediate * crawl data. The content of this folder should not be modified manually. */ public void setCrawlStorageFolder(String crawlStorageFolder) { this.crawlStorageFolder = crawlStorageFolder; } public boolean isResumableCrawling() { return resumableCrawling; } /** * If this feature is enabled, you would be able to resume a previously * stopped/crashed crawl. However, it makes crawling slightly slower */ public void setResumableCrawling(boolean resumableCrawling) { this.resumableCrawling = resumableCrawling; } public int getMaxDepthOfCrawling() { return maxDepthOfCrawling; } /** * Maximum depth of crawling For unlimited depth this parameter should be * set to -1 */ public void setMaxDepthOfCrawling(int maxDepthOfCrawling) { this.maxDepthOfCrawling = maxDepthOfCrawling; } public int getMaxPagesToFetch() { return maxPagesToFetch; } /** * Maximum number of pages to fetch For unlimited number of pages, this * parameter should be set to -1 */ public void setMaxPagesToFetch(int maxPagesToFetch) { this.maxPagesToFetch = maxPagesToFetch; } public String getUserAgentString() { return userAgentString; } /** * user-agent string that is used for representing your crawler to web * servers. See http://en.wikipedia.org/wiki/User_agent for more details */ public void setUserAgentString(String userAgentString) { this.userAgentString = userAgentString; } public int getPolitenessDelay() { return politenessDelay; } /** * Politeness delay in milliseconds (delay between sending two requests to * the same host). * * @param politenessDelay * the delay in milliseconds. */ public void setPolitenessDelay(int politenessDelay) { this.politenessDelay = politenessDelay; } public boolean isIncludeHttpsPages() { return includeHttpsPages; } /** * Should we also crawl https pages? */ public void setIncludeHttpsPages(boolean includeHttpsPages) { this.includeHttpsPages = includeHttpsPages; } public boolean isIncludeBinaryContentInCrawling() { return includeBinaryContentInCrawling; } /** * Should we fetch binary content such as images, audio, ...? */ public void setIncludeBinaryContentInCrawling(boolean includeBinaryContentInCrawling) { this.includeBinaryContentInCrawling = includeBinaryContentInCrawling; } public int getMaxConnectionsPerHost() { return maxConnectionsPerHost; } /** * Maximum Connections per host */ public void setMaxConnectionsPerHost(int maxConnectionsPerHost) { this.maxConnectionsPerHost = maxConnectionsPerHost; } public int getMaxTotalConnections() { return maxTotalConnections; } /** * Maximum total connections */ public void setMaxTotalConnections(int maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; } public int getSocketTimeout() { return socketTimeout; } /** * Socket timeout in milliseconds */ public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public int getConnectionTimeout() { return connectionTimeout; } /** * Connection timeout in milliseconds */ public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getMaxOutgoingLinksToFollow() { return maxOutgoingLinksToFollow; } /** * Max number of outgoing links which are processed from a page */ public void setMaxOutgoingLinksToFollow(int maxOutgoingLinksToFollow) { this.maxOutgoingLinksToFollow = maxOutgoingLinksToFollow; } public int getMaxDownloadSize() { return maxDownloadSize; } /** * Max allowed size of a page. Pages larger than this size will not be * fetched. */ public void setMaxDownloadSize(int maxDownloadSize) { this.maxDownloadSize = maxDownloadSize; } public boolean isFollowRedirects() { return followRedirects; } /** * Should we follow redirects? */ public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } public String getProxyHost() { return proxyHost; } /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy host. */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public int getProxyPort() { return proxyPort; } /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy port. */ public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } public String getProxyUsername() { return proxyUsername; } /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * username. */ public void setProxyUsername(String proxyUsername) { this.proxyUsername = proxyUsername; } public String getProxyPassword() { return proxyPassword; } /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * password. */ public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Crawl storage folder: " + getCrawlStorageFolder() + "\n"); sb.append("Resumable crawling: " + isResumableCrawling() + "\n"); sb.append("Max depth of crawl: " + getMaxDepthOfCrawling() + "\n"); sb.append("Max pages to fetch: " + getMaxPagesToFetch() + "\n"); sb.append("User agent string: " + getUserAgentString() + "\n"); sb.append("Include https pages: " + isIncludeHttpsPages() + "\n"); sb.append("Include binary content: " + isIncludeBinaryContentInCrawling() + "\n"); sb.append("Max connections per host: " + getMaxConnectionsPerHost() + "\n"); sb.append("Max total connections: " + getMaxTotalConnections() + "\n"); sb.append("Socket timeout: " + getSocketTimeout() + "\n"); sb.append("Max total connections: " + getMaxTotalConnections() + "\n"); sb.append("Max outgoing links to follow: " + getMaxOutgoingLinksToFollow() + "\n"); sb.append("Max download size: " + getMaxDownloadSize() + "\n"); sb.append("Should follow redirects?: " + isFollowRedirects() + "\n"); sb.append("Proxy host: " + getProxyHost() + "\n"); sb.append("Proxy port: " + getProxyPort() + "\n"); sb.append("Proxy username: " + getProxyUsername() + "\n"); sb.append("Proxy password: " + getProxyPassword() + "\n"); return sb.toString(); } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/crawler/CrawlConfig.java
Java
asf20
10,898
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; import edu.uci.ics.crawler4j.fetcher.PageFetchResult; import edu.uci.ics.crawler4j.fetcher.CustomFetchStatus; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.frontier.DocIDServer; import edu.uci.ics.crawler4j.frontier.Frontier; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.parser.ParseData; import edu.uci.ics.crawler4j.parser.Parser; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; import edu.uci.ics.crawler4j.url.WebURL; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; /** * WebCrawler class in the Runnable class that is executed by each crawler * thread. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class WebCrawler implements Runnable { protected static final Logger logger = Logger.getLogger(WebCrawler.class.getName()); /** * The id associated to the crawler thread running this instance */ protected int myId; /** * The controller instance that has created this crawler thread. This * reference to the controller can be used for getting configurations of the * current crawl or adding new seeds during runtime. */ protected CrawlController myController; /** * The thread within which this crawler instance is running. */ private Thread myThread; /** * The parser that is used by this crawler instance to parse the content of * the fetched pages. */ private Parser parser; /** * The fetcher that is used by this crawler instance to fetch the content of * pages from the web. */ private PageFetcher pageFetcher; /** * The RobotstxtServer instance that is used by this crawler instance to * determine whether the crawler is allowed to crawl the content of each * page. */ private RobotstxtServer robotstxtServer; /** * The DocIDServer that is used by this crawler instance to map each URL to * a unique docid. */ private DocIDServer docIdServer; /** * The Frontier object that manages the crawl queue. */ private Frontier frontier; /** * Is the current crawler instance waiting for new URLs? This field is * mainly used by the controller to detect whether all of the crawler * instances are waiting for new URLs and therefore there is no more work * and crawling can be stopped. */ private boolean isWaitingForNewURLs; /** * Initializes the current instance of the crawler * * @param myId * the id of this crawler instance * @param crawlController * the controller that manages this crawling session */ public void init(int myId, CrawlController crawlController) { this.myId = myId; this.pageFetcher = crawlController.getPageFetcher(); this.robotstxtServer = crawlController.getRobotstxtServer(); this.docIdServer = crawlController.getDocIdServer(); this.frontier = crawlController.getFrontier(); this.parser = new Parser(crawlController.getConfig()); this.myController = crawlController; this.isWaitingForNewURLs = false; } /** * Get the id of the current crawler instance * * @return the id of the current crawler instance */ public int getMyId() { return myId; } public CrawlController getMyController() { return myController; } /** * This function is called just before starting the crawl by this crawler * instance. It can be used for setting up the data structures or * initializations needed by this crawler instance. */ public void onStart() { } /** * This function is called just before the termination of the current * crawler instance. It can be used for persisting in-memory data or other * finalization tasks. */ public void onBeforeExit() { } /** * This function is called once the header of a page is fetched. * It can be overwritten by sub-classes to perform custom logic * for different status codes. For example, 404 pages can be logged, etc. */ protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) { } /** * The CrawlController instance that has created this crawler instance will * call this function just before terminating this crawler thread. Classes * that extend WebCrawler can override this function to pass their local * data to their controller. The controller then puts these local data in a * List that can then be used for processing the local data of crawlers (if * needed). */ public Object getMyLocalData() { return null; } public void run() { onStart(); while (true) { List<WebURL> assignedURLs = new ArrayList<WebURL>(50); isWaitingForNewURLs = true; frontier.getNextURLs(50, assignedURLs); isWaitingForNewURLs = false; if (assignedURLs.size() == 0) { if (frontier.isFinished()) { return; } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } else { for (WebURL curURL : assignedURLs) { if (curURL != null) { processPage(curURL); frontier.setProcessed(curURL); } if (myController.isShuttingDown()) { logger.info("Exiting because of controller shutdown."); return; } } } } } /** * Classes that extends WebCrawler can overwrite this function to tell the * crawler whether the given url should be crawled or not. The following * implementation indicates that all urls should be included in the crawl. * * @param url * the url which we are interested to know whether it should be * included in the crawl or not. * @return if the url should be included in the crawl it returns true, * otherwise false is returned. */ public boolean shouldVisit(WebURL url) { return true; } /** * Classes that extends WebCrawler can overwrite this function to process * the content of the fetched and parsed page. * * @param page * the page object that is just fetched and parsed. */ public void visit(Page page) { } private void processPage(WebURL curURL) { if (curURL == null) { return; } PageFetchResult fetchResult = null; try { fetchResult = pageFetcher.fetchHeader(curURL); int statusCode = fetchResult.getStatusCode(); handlePageStatusCode(curURL, statusCode, CustomFetchStatus.getStatusDescription(statusCode)); if (statusCode != HttpStatus.SC_OK) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { if (myController.getConfig().isFollowRedirects()) { String movedToUrl = fetchResult.getMovedToUrl(); if (movedToUrl == null) { return; } int newDocId = docIdServer.getDocId(movedToUrl); if (newDocId > 0) { // Redirect page is already seen return; } else { WebURL webURL = new WebURL(); webURL.setURL(movedToUrl); webURL.setParentDocid(curURL.getParentDocid()); webURL.setParentUrl(curURL.getParentUrl()); webURL.setDepth(curURL.getDepth()); webURL.setDocid(-1); if (shouldVisit(webURL) && robotstxtServer.allows(webURL)) { webURL.setDocid(docIdServer.getNewDocID(movedToUrl)); frontier.schedule(webURL); } } } } else if (fetchResult.getStatusCode() == CustomFetchStatus.PageTooBig) { logger.info("Skipping a page which was bigger than max allowed size: " + curURL.getURL()); } return; } if (!curURL.getURL().equals(fetchResult.getFetchedUrl())) { if (docIdServer.isSeenBefore(fetchResult.getFetchedUrl())) { // Redirect page is already seen return; } curURL.setURL(fetchResult.getFetchedUrl()); curURL.setDocid(docIdServer.getNewDocID(fetchResult.getFetchedUrl())); } Page page = new Page(curURL); int docid = curURL.getDocid(); if (fetchResult.fetchContent(page) && parser.parse(page, curURL.getURL())) { ParseData parseData = page.getParseData(); if (parseData instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) parseData; List<WebURL> toSchedule = new ArrayList<WebURL>(); int maxCrawlDepth = myController.getConfig().getMaxDepthOfCrawling(); for (WebURL webURL : htmlParseData.getOutgoingUrls()) { webURL.setParentDocid(docid); webURL.setParentUrl(curURL.getURL()); int newdocid = docIdServer.getDocId(webURL.getURL()); if (newdocid > 0) { // This is not the first time that this Url is // visited. So, we set the depth to a negative // number. webURL.setDepth((short) -1); webURL.setDocid(newdocid); } else { webURL.setDocid(-1); webURL.setDepth((short) (curURL.getDepth() + 1)); if (maxCrawlDepth == -1 || curURL.getDepth() < maxCrawlDepth) { if (shouldVisit(webURL) && robotstxtServer.allows(webURL)) { webURL.setDocid(docIdServer.getNewDocID(webURL.getURL())); toSchedule.add(webURL); } } } } frontier.scheduleAll(toSchedule); } visit(page); } } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage() + ", while processing: " + curURL.getURL()); } finally { if (fetchResult != null) { fetchResult.discardContentIfNotConsumed(); } } } public Thread getThread() { return myThread; } public void setThread(Thread myThread) { this.myThread = myThread; } public boolean isNotWaitingForNewURLs() { return !isWaitingForNewURLs; } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java
Java
asf20
10,327
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.util; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Util { public static byte[] long2ByteArray(long l) { byte[] array = new byte[8]; int i, shift; for(i = 0, shift = 56; i < 8; i++, shift -= 8) { array[i] = (byte)(0xFF & (l >> shift)); } return array; } public static byte[] int2ByteArray(int value) { byte[] b = new byte[4]; for (int i = 0; i < 4; i++) { int offset = (3 - i) * 8; b[i] = (byte) ((value >>> offset) & 0xFF); } return b; } public static void putIntInByteArray(int value, byte[] buf, int offset) { for (int i = 0; i < 4; i++) { int valueOffset = (3 - i) * 8; buf[offset + i] = (byte) ((value >>> valueOffset) & 0xFF); } } public static int byteArray2Int(byte[] b) { int value = 0; for (int i = 0; i < 4; i++) { int shift = (4 - 1 - i) * 8; value += (b[i] & 0x000000FF) << shift; } return value; } public static long byteArray2Long(byte[] b) { int value = 0; for (int i = 0; i < 8; i++) { int shift = (8 - 1 - i) * 8; value += (b[i] & 0x000000FF) << shift; } return value; } public static boolean hasBinaryContent(String contentType) { if (contentType != null) { String typeStr = contentType.toLowerCase(); if (typeStr.contains("image") || typeStr.contains("audio") || typeStr.contains("video") || typeStr.contains("application")) { return true; } } return false; } public static boolean hasPlainTextContent(String contentType) { if (contentType != null) { String typeStr = contentType.toLowerCase(); if (typeStr.contains("text/plain")) { return true; } } return false; } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/util/Util.java
Java
asf20
2,746
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class IO { public static boolean deleteFolder(File folder) { return deleteFolderContents(folder) && folder.delete(); } public static boolean deleteFolderContents(File folder) { System.out.println("Deleting content of: " + folder.getAbsolutePath()); File[] files = folder.listFiles(); for (File file : files) { if (file.isFile()) { if (!file.delete()) { return false; } } else { if (!deleteFolder(file)) { return false; } } } return true; } public static void writeBytesToFile(byte[] bytes, String destination) { try { FileChannel fc = new FileOutputStream(destination).getChannel(); fc.write(ByteBuffer.wrap(bytes)); fc.close(); } catch (Exception e) { e.printStackTrace(); } } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/util/IO.java
Java
asf20
1,755
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.robotstxt; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpStatus; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.fetcher.PageFetchResult; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.url.WebURL; import edu.uci.ics.crawler4j.util.Util; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class RobotstxtServer { protected RobotstxtConfig config; protected final Map<String, HostDirectives> host2directivesCache = new HashMap<String, HostDirectives>(); protected PageFetcher pageFetcher; public RobotstxtServer(RobotstxtConfig config, PageFetcher pageFetcher) { this.config = config; this.pageFetcher = pageFetcher; } public boolean allows(WebURL webURL) { if (!config.isEnabled()) { return true; } try { URL url = new URL(webURL.getURL()); String host = url.getHost().toLowerCase(); String path = url.getPath(); HostDirectives directives = host2directivesCache.get(host); if (directives != null && directives.needsRefetch()) { synchronized (host2directivesCache) { host2directivesCache.remove(host); directives = null; } } if (directives == null) { directives = fetchDirectives(host); } return directives.allows(path); } catch (MalformedURLException e) { e.printStackTrace(); } return true; } private HostDirectives fetchDirectives(String host) { WebURL robotsTxtUrl = new WebURL(); robotsTxtUrl.setURL("http://" + host + "/robots.txt"); HostDirectives directives = null; PageFetchResult fetchResult = null; try { fetchResult = pageFetcher.fetchHeader(robotsTxtUrl); if (fetchResult.getStatusCode() == HttpStatus.SC_OK) { Page page = new Page(robotsTxtUrl); fetchResult.fetchContent(page); if (Util.hasPlainTextContent(page.getContentType())) { try { String content; if (page.getContentCharset() == null) { content = new String(page.getContentData()); } else { content = new String(page.getContentData(), page.getContentCharset()); } directives = RobotstxtParser.parse(content, config.getUserAgentName()); } catch (Exception e) { e.printStackTrace(); } } } } finally { fetchResult.discardContentIfNotConsumed(); } if (directives == null) { // We still need to have this object to keep track of the time we // fetched it directives = new HostDirectives(); } synchronized (host2directivesCache) { if (host2directivesCache.size() == config.getCacheSize()) { String minHost = null; long minAccessTime = Long.MAX_VALUE; for (Entry<String, HostDirectives> entry : host2directivesCache.entrySet()) { if (entry.getValue().getLastAccessTime() < minAccessTime) { minAccessTime = entry.getValue().getLastAccessTime(); minHost = entry.getKey(); } } host2directivesCache.remove(minHost); } host2directivesCache.put(host, directives); } return directives; } }
zzysiat-mycrawler
src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtServer.java
Java
asf20
4,018