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
|
|---|---|---|---|---|---|
/**
* 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.util.StringTokenizer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class RobotstxtParser {
private static final String PATTERNS_USERAGENT = "(?i)^User-agent:.*";
private static final String PATTERNS_DISALLOW = "(?i)Disallow:.*";
private static final String PATTERNS_ALLOW = "(?i)Allow:.*";
private static final int PATTERNS_USERAGENT_LENGTH = 11;
private static final int PATTERNS_DISALLOW_LENGTH = 9;
private static final int PATTERNS_ALLOW_LENGTH = 6;
public static HostDirectives parse(String content, String myUserAgent) {
HostDirectives directives = null;
boolean inMatchingUserAgent = false;
StringTokenizer st = new StringTokenizer(content, "\n");
while (st.hasMoreTokens()) {
String line = st.nextToken();
int commentIndex = line.indexOf("#");
if (commentIndex > -1) {
line = line.substring(0, commentIndex);
}
// remove any html markup
line = line.replaceAll("<[^>]+>", "");
line = line.trim();
if (line.length() == 0) {
continue;
}
if (line.matches(PATTERNS_USERAGENT)) {
String ua = line.substring(PATTERNS_USERAGENT_LENGTH).trim().toLowerCase();
if (ua.equals("*") || ua.contains(myUserAgent)) {
inMatchingUserAgent = true;
if (directives == null) {
directives = new HostDirectives();
}
} else {
inMatchingUserAgent = false;
}
} else if (line.matches(PATTERNS_DISALLOW)) {
if (!inMatchingUserAgent) {
continue;
}
String path = line.substring(PATTERNS_DISALLOW_LENGTH).trim();
if (path.endsWith("*")) {
path = path.substring(0, path.length() - 1);
}
path = path.trim();
if (path.length() > 0) {
directives.addDisallow(path);
}
} else if (line.matches(PATTERNS_ALLOW)) {
if (!inMatchingUserAgent) {
continue;
}
String path = line.substring(PATTERNS_ALLOW_LENGTH).trim();
if (path.endsWith("*")) {
path = path.substring(0, path.length() - 1);
}
path = path.trim();
directives.addAllow(path);
}
}
return directives;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtParser.java
|
Java
|
asf20
| 2,951
|
/**
* 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.util.SortedSet;
import java.util.TreeSet;
public class RuleSet extends TreeSet<String> {
private static final long serialVersionUID = 1L;
@Override
public boolean add(String str) {
SortedSet<String> sub = headSet(str);
if (!sub.isEmpty() && str.startsWith(sub.last())) {
// no need to add; prefix is already present
return false;
}
boolean retVal = super.add(str);
sub = tailSet(str + "\0");
while (!sub.isEmpty() && sub.first().startsWith(str)) {
// remove redundant entries
sub.remove(sub.first());
}
return retVal;
}
public boolean containsPrefixOf(String s) {
SortedSet<String> sub = headSet(s);
// because redundant prefixes have been eliminated,
// only a test against last item in headSet is necessary
if (!sub.isEmpty() && s.startsWith(sub.last())) {
return true; // prefix substring exists
}
// might still exist exactly (headSet does not contain boundary)
return contains(s);
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/robotstxt/RuleSet.java
|
Java
|
asf20
| 1,806
|
/**
* 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;
public class RobotstxtConfig {
/**
* Should the crawler obey Robots.txt protocol? More info on Robots.txt is
* available at http://www.robotstxt.org/
*/
private boolean enabled = true;
/**
* user-agent name that will be used to determine whether some servers have
* specific rules for this agent name.
*/
private String userAgentName = "crawler4j";
/**
* The maximum number of hosts for which their robots.txt is cached.
*/
private int cacheSize = 500;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getUserAgentName() {
return userAgentName;
}
public void setUserAgentName(String userAgentName) {
this.userAgentName = userAgentName;
}
public int getCacheSize() {
return cacheSize;
}
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtConfig.java
|
Java
|
asf20
| 1,742
|
/**
* 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;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class HostDirectives {
// If we fetched the directives for this host more than
// 24 hours, we have to re-fetch it.
private static final long EXPIRATION_DELAY = 24 * 60 * 1000L;
private RuleSet disallows = new RuleSet();
private RuleSet allows = new RuleSet();
private long timeFetched;
private long timeLastAccessed;
public HostDirectives() {
timeFetched = System.currentTimeMillis();
}
public boolean needsRefetch() {
return (System.currentTimeMillis() - timeFetched > EXPIRATION_DELAY);
}
public boolean allows(String path) {
timeLastAccessed = System.currentTimeMillis();
return !disallows.containsPrefixOf(path) || allows.containsPrefixOf(path);
}
public void addDisallow(String path) {
disallows.add(path);
}
public void addAllow(String path) {
allows.add(path);
}
public long getLastAccessTime() {
return timeLastAccessed;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/robotstxt/HostDirectives.java
|
Java
|
asf20
| 1,804
|
/**
* 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.frontier;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class WorkQueues {
protected Database urlsDB = null;
protected Environment env;
protected boolean resumable;
protected WebURLTupleBinding webURLBinding;
protected final Object mutex = new Object();
public WorkQueues(Environment env, String dbName, boolean resumable) throws DatabaseException {
this.env = env;
this.resumable = resumable;
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(resumable);
dbConfig.setDeferredWrite(!resumable);
urlsDB = env.openDatabase(null, dbName, dbConfig);
webURLBinding = new WebURLTupleBinding();
}
public List<WebURL> get(int max) throws DatabaseException {
synchronized (mutex) {
int matches = 0;
List<WebURL> results = new ArrayList<WebURL>(max);
Cursor cursor = null;
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getFirst(key, value, null);
while (matches < max && result == OperationStatus.SUCCESS) {
if (value.getData().length > 0) {
results.add(webURLBinding.entryToObject(value));
matches++;
}
result = cursor.getNext(key, value, null);
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
return results;
}
}
public void delete(int count) throws DatabaseException {
synchronized (mutex) {
int matches = 0;
Cursor cursor = null;
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getFirst(key, value, null);
while (matches < count && result == OperationStatus.SUCCESS) {
cursor.delete();
matches++;
result = cursor.getNext(key, value, null);
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
}
}
public void put(WebURL url) throws DatabaseException {
/*
* The key that is used for storing URLs determines the order
* they are crawled. Lower key values results in earlier crawling.
* Here our keys are 6 bytes. The first byte comes from the URL priority.
* The second byte comes from depth of crawl at which this URL is first found.
* The rest of the 4 bytes come from the docid of the URL. As a result,
* URLs with lower priority numbers will be crawled earlier. If priority
* numbers are the same, those found at lower depths will be crawled earlier.
* If depth is also equal, those found earlier (therefore, smaller docid) will
* be crawled earlier.
*/
byte[] keyData = new byte[6];
keyData[0] = url.getPriority();
keyData[1] = (url.getDepth() > Byte.MAX_VALUE ? Byte.MAX_VALUE : (byte) url.getDepth());
Util.putIntInByteArray(url.getDocid(), keyData, 2);
DatabaseEntry value = new DatabaseEntry();
webURLBinding.objectToEntry(url, value);
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
urlsDB.put(txn, new DatabaseEntry(keyData), value);
if (resumable) {
if (txn != null) {
txn.commit();
}
}
}
public long getLength() {
try {
return urlsDB.count();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public void sync() {
if (resumable) {
return;
}
if (urlsDB == null) {
return;
}
try {
urlsDB.sync();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
public void close() {
try {
urlsDB.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/frontier/WorkQueues.java
|
Java
|
asf20
| 5,247
|
/**
* 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.frontier;
import org.apache.log4j.Logger;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
/**
* This class maintains the list of pages which are
* assigned to crawlers but are not yet processed.
* It is used for resuming a previous crawl.
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class InProcessPagesDB extends WorkQueues {
private static final Logger logger = Logger.getLogger(InProcessPagesDB.class.getName());
public InProcessPagesDB(Environment env) throws DatabaseException {
super(env, "InProcessPagesDB", true);
long docCount = getLength();
if (docCount > 0) {
logger.info("Loaded " + docCount + " URLs that have been in process in the previous crawl.");
}
}
public boolean removeURL(WebURL webUrl) {
synchronized (mutex) {
try {
DatabaseEntry key = new DatabaseEntry(Util.int2ByteArray(webUrl.getDocid()));
Cursor cursor = null;
OperationStatus result;
DatabaseEntry value = new DatabaseEntry();
Transaction txn = env.beginTransaction(null, null);
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getSearchKey(key, value, null);
if (result == OperationStatus.SUCCESS) {
result = cursor.delete();
if (result == OperationStatus.SUCCESS) {
return true;
}
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/frontier/InProcessPagesDB.java
|
Java
|
asf20
| 2,743
|
/**
* 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.frontier;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class WebURLTupleBinding extends TupleBinding<WebURL> {
@Override
public WebURL entryToObject(TupleInput input) {
WebURL webURL = new WebURL();
webURL.setURL(input.readString());
webURL.setDocid(input.readInt());
webURL.setParentDocid(input.readInt());
webURL.setParentUrl(input.readString());
webURL.setDepth(input.readShort());
webURL.setPriority(input.readByte());
return webURL;
}
@Override
public void objectToEntry(WebURL url, TupleOutput output) {
output.writeString(url.getURL());
output.writeInt(url.getDocid());
output.writeInt(url.getParentDocid());
output.writeString(url.getParentUrl());
output.writeShort(url.getDepth());
output.writeByte(url.getPriority());
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/frontier/WebURLTupleBinding.java
|
Java
|
asf20
| 1,811
|
/**
* 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.frontier;
import org.apache.log4j.Logger;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.util.Util;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class DocIDServer extends Configurable {
protected static final Logger logger = Logger.getLogger(DocIDServer.class.getName());
protected Database docIDsDB = null;
protected final Object mutex = new Object();
protected int lastDocID;
public DocIDServer(Environment env, CrawlConfig config) throws DatabaseException {
super(config);
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(config.isResumableCrawling());
dbConfig.setDeferredWrite(!config.isResumableCrawling());
docIDsDB = env.openDatabase(null, "DocIDs", dbConfig);
if (config.isResumableCrawling()) {
int docCount = getDocCount();
if (docCount > 0) {
logger.info("Loaded " + docCount + " URLs that had been detected in previous crawl.");
lastDocID = docCount;
}
} else {
lastDocID = 0;
}
}
/**
* Returns the docid of an already seen url.
*
* @param url the URL for which the docid is returned.
* @return the docid of the url if it is seen before. Otherwise -1 is returned.
*/
public int getDocId(String url) {
synchronized (mutex) {
if (docIDsDB == null) {
return -1;
}
OperationStatus result;
DatabaseEntry value = new DatabaseEntry();
try {
DatabaseEntry key = new DatabaseEntry(url.getBytes());
result = docIDsDB.get(null, key, value, null);
if (result == OperationStatus.SUCCESS && value.getData().length > 0) {
return Util.byteArray2Int(value.getData());
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
public int getNewDocID(String url) {
synchronized (mutex) {
try {
// Make sure that we have not already assigned a docid for this URL
int docid = getDocId(url);
if (docid > 0) {
return docid;
}
lastDocID++;
docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(lastDocID)));
return lastDocID;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
public void addUrlAndDocId(String url, int docId) throws Exception {
synchronized (mutex) {
if (docId <= lastDocID) {
throw new Exception("Requested doc id: " + docId + " is not larger than: " + lastDocID);
}
// Make sure that we have not already assigned a docid for this URL
int prevDocid = getDocId(url);
if (prevDocid > 0) {
if (prevDocid == docId) {
return;
}
throw new Exception("Doc id: " + prevDocid + " is already assigned to URL: " + url);
}
docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(docId)));
lastDocID = docId;
}
}
public boolean isSeenBefore(String url) {
return getDocId(url) != -1;
}
public int getDocCount() {
try {
return (int) docIDsDB.count();
} catch (DatabaseException e) {
e.printStackTrace();
}
return -1;
}
public void sync() {
if (config.isResumableCrawling()) {
return;
}
if (docIDsDB == null) {
return;
}
try {
docIDsDB.sync();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
public void close() {
try {
docIDsDB.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/frontier/DocIDServer.java
|
Java
|
asf20
| 4,339
|
/**
* 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.frontier;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.util.Util;
import java.util.HashMap;
import java.util.Map;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Counters extends Configurable {
public class ReservedCounterNames {
public final static String SCHEDULED_PAGES = "Scheduled-Pages";
public final static String PROCESSED_PAGES = "Processed-Pages";
}
protected Database statisticsDB = null;
protected Environment env;
protected final Object mutex = new Object();
protected Map<String, Long> counterValues;
public Counters(Environment env, CrawlConfig config) throws DatabaseException {
super(config);
this.env = env;
this.counterValues = new HashMap<String, Long>();
/*
* When crawling is set to be resumable, we have to keep the statistics
* in a transactional database to make sure they are not lost if crawler
* is crashed or terminated unexpectedly.
*/
if (config.isResumableCrawling()) {
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(true);
dbConfig.setDeferredWrite(false);
statisticsDB = env.openDatabase(null, "Statistics", dbConfig);
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction tnx = env.beginTransaction(null, null);
Cursor cursor = statisticsDB.openCursor(tnx, null);
result = cursor.getFirst(key, value, null);
while (result == OperationStatus.SUCCESS) {
if (value.getData().length > 0) {
String name = new String(key.getData());
long counterValue = Util.byteArray2Long(value.getData());
counterValues.put(name, counterValue);
}
result = cursor.getNext(key, value, null);
}
cursor.close();
tnx.commit();
}
}
public long getValue(String name) {
synchronized (mutex) {
Long value = counterValues.get(name);
if (value == null) {
return 0;
}
return value;
}
}
public void setValue(String name, long value) {
synchronized (mutex) {
try {
counterValues.put(name, value);
if (statisticsDB != null) {
Transaction txn = env.beginTransaction(null, null);
statisticsDB.put(txn, new DatabaseEntry(name.getBytes()),
new DatabaseEntry(Util.long2ByteArray(value)));
txn.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void increment(String name) {
increment(name, 1);
}
public void increment(String name, long addition) {
synchronized (mutex) {
long prevValue = getValue(name);
setValue(name, prevValue + addition);
}
}
public void sync() {
if (config.isResumableCrawling()) {
return;
}
if (statisticsDB == null) {
return;
}
try {
statisticsDB.sync();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
public void close() {
try {
if (statisticsDB != null) {
statisticsDB.close();
}
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/frontier/Counters.java
|
Java
|
asf20
| 3,967
|
/**
* 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.frontier;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.frontier.Counters.ReservedCounterNames;
import edu.uci.ics.crawler4j.url.WebURL;
import org.apache.log4j.Logger;
import java.util.List;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Frontier extends Configurable {
protected static final Logger logger = Logger.getLogger(Frontier.class.getName());
protected WorkQueues workQueues;
protected InProcessPagesDB inProcessPages;
protected final Object mutex = new Object();
protected final Object waitingList = new Object();
protected boolean isFinished = false;
protected long scheduledPages;
protected DocIDServer docIdServer;
protected Counters counters;
public Frontier(Environment env, CrawlConfig config, DocIDServer docIdServer) {
super(config);
this.counters = new Counters(env, config);
this.docIdServer = docIdServer;
try {
workQueues = new WorkQueues(env, "PendingURLsDB", config.isResumableCrawling());
if (config.isResumableCrawling()) {
scheduledPages = counters.getValue(ReservedCounterNames.SCHEDULED_PAGES);
inProcessPages = new InProcessPagesDB(env);
long numPreviouslyInProcessPages = inProcessPages.getLength();
if (numPreviouslyInProcessPages > 0) {
logger.info("Rescheduling " + numPreviouslyInProcessPages + " URLs from previous crawl.");
scheduledPages -= numPreviouslyInProcessPages;
while (true) {
List<WebURL> urls = inProcessPages.get(100);
if (urls.size() == 0) {
break;
}
scheduleAll(urls);
inProcessPages.delete(urls.size());
}
}
} else {
inProcessPages = null;
scheduledPages = 0;
}
} catch (DatabaseException e) {
logger.error("Error while initializing the Frontier: " + e.getMessage());
workQueues = null;
}
}
public void scheduleAll(List<WebURL> urls) {
int maxPagesToFetch = config.getMaxPagesToFetch();
synchronized (mutex) {
int newScheduledPage = 0;
for (WebURL url : urls) {
if (maxPagesToFetch > 0 && (scheduledPages + newScheduledPage) >= maxPagesToFetch) {
break;
}
try {
workQueues.put(url);
newScheduledPage++;
} catch (DatabaseException e) {
logger.error("Error while puting the url in the work queue.");
}
}
if (newScheduledPage > 0) {
scheduledPages += newScheduledPage;
counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES, newScheduledPage);
}
synchronized (waitingList) {
waitingList.notifyAll();
}
}
}
public void schedule(WebURL url) {
int maxPagesToFetch = config.getMaxPagesToFetch();
synchronized (mutex) {
try {
if (maxPagesToFetch < 0 || scheduledPages < maxPagesToFetch) {
workQueues.put(url);
scheduledPages++;
counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES);
}
} catch (DatabaseException e) {
logger.error("Error while puting the url in the work queue.");
}
}
}
public void getNextURLs(int max, List<WebURL> result) {
while (true) {
synchronized (mutex) {
if (isFinished) {
return;
}
try {
List<WebURL> curResults = workQueues.get(max);
workQueues.delete(curResults.size());
if (inProcessPages != null) {
for (WebURL curPage : curResults) {
inProcessPages.put(curPage);
}
}
result.addAll(curResults);
} catch (DatabaseException e) {
logger.error("Error while getting next urls: " + e.getMessage());
e.printStackTrace();
}
if (result.size() > 0) {
return;
}
}
try {
synchronized (waitingList) {
waitingList.wait();
}
} catch (InterruptedException ignored) {
}
if (isFinished) {
return;
}
}
}
public void setProcessed(WebURL webURL) {
counters.increment(ReservedCounterNames.PROCESSED_PAGES);
if (inProcessPages != null) {
if (!inProcessPages.removeURL(webURL)) {
logger.warn("Could not remove: " + webURL.getURL() + " from list of processed pages.");
}
}
}
public long getQueueLength() {
return workQueues.getLength();
}
public long getNumberOfAssignedPages() {
return inProcessPages.getLength();
}
public long getNumberOfProcessedPages() {
return counters.getValue(ReservedCounterNames.PROCESSED_PAGES);
}
public void sync() {
workQueues.sync();
docIdServer.sync();
counters.sync();
}
public boolean isFinished() {
return isFinished;
}
public void close() {
sync();
workQueues.close();
counters.close();
}
public void finish() {
isFinished = true;
synchronized (waitingList) {
waitingList.notifyAll();
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/frontier/Frontier.java
|
Java
|
asf20
| 5,659
|
/**
* 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.parser;
public class BinaryParseData implements ParseData {
private static BinaryParseData instance = new BinaryParseData();
public static BinaryParseData getInstance() {
return instance;
}
@Override
public String toString() {
return "[Binary parse data can not be dumped as string]";
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/parser/BinaryParseData.java
|
Java
|
asf20
| 1,139
|
/**
* 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.parser;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
public class HtmlParseData implements ParseData {
private String html;
private String text;
private String title;
private List<WebURL> outgoingUrls;
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<WebURL> getOutgoingUrls() {
return outgoingUrls;
}
public void setOutgoingUrls(List<WebURL> outgoingUrls) {
this.outgoingUrls = outgoingUrls;
}
@Override
public String toString() {
return text;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/parser/HtmlParseData.java
|
Java
|
asf20
| 1,616
|
package edu.uci.ics.crawler4j.parser;
public class ExtractedUrlAnchorPair {
private String href;
private String anchor;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getAnchor() {
return anchor;
}
public void setAnchor(String anchor) {
this.anchor = anchor;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/parser/ExtractedUrlAnchorPair.java
|
Java
|
asf20
| 351
|
/**
* 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.parser;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.html.HtmlParser;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Parser extends Configurable {
private HtmlParser htmlParser;
private ParseContext parseContext;
public Parser(CrawlConfig config) {
super(config);
htmlParser = new HtmlParser();
parseContext = new ParseContext();
}
public boolean parse(Page page, String contextURL) {
if (Util.hasBinaryContent(page.getContentType())) {
if (!config.isIncludeBinaryContentInCrawling()) {
return false;
} else {
page.setParseData(BinaryParseData.getInstance());
return true;
}
} else if (Util.hasPlainTextContent(page.getContentType())) {
try {
TextParseData parseData = new TextParseData();
parseData.setTextContent(new String(page.getContentData(), page.getContentCharset()));
page.setParseData(parseData);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Metadata metadata = new Metadata();
HtmlContentHandler contentHandler = new HtmlContentHandler();
InputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(page.getContentData());
htmlParser.parse(inputStream, contentHandler, metadata, parseContext);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (page.getContentCharset() == null) {
page.setContentCharset(metadata.get("Content-Encoding"));
}
HtmlParseData parseData = new HtmlParseData();
parseData.setText(contentHandler.getBodyText().trim());
parseData.setTitle(metadata.get(Metadata.TITLE));
List<WebURL> outgoingUrls = new ArrayList<WebURL>();
String baseURL = contentHandler.getBaseUrl();
if (baseURL != null) {
contextURL = baseURL;
}
int urlCount = 0;
for (ExtractedUrlAnchorPair urlAnchorPair : contentHandler.getOutgoingUrls()) {
String href = urlAnchorPair.getHref();
href = href.trim();
if (href.length() == 0) {
continue;
}
String hrefWithoutProtocol = href.toLowerCase();
if (href.startsWith("http://")) {
hrefWithoutProtocol = href.substring(7);
}
if (!hrefWithoutProtocol.contains("javascript:") && !hrefWithoutProtocol.contains("@")) {
String url = URLCanonicalizer.getCanonicalURL(href, contextURL);
if (url != null) {
WebURL webURL = new WebURL();
webURL.setURL(url);
webURL.setAnchor(urlAnchorPair.getAnchor());
outgoingUrls.add(webURL);
urlCount++;
if (urlCount > config.getMaxOutgoingLinksToFollow()) {
break;
}
}
}
}
parseData.setOutgoingUrls(outgoingUrls);
try {
if (page.getContentCharset() == null) {
parseData.setHtml(new String(page.getContentData()));
} else {
parseData.setHtml(new String(page.getContentData(), page.getContentCharset()));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
page.setParseData(parseData);
return true;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/parser/Parser.java
|
Java
|
asf20
| 4,467
|
/**
* 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.parser;
public class TextParseData implements ParseData {
private String textContent;
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
@Override
public String toString() {
return textContent;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/parser/TextParseData.java
|
Java
|
asf20
| 1,141
|
/**
* 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.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HtmlContentHandler extends DefaultHandler {
private enum Element {
A, AREA, LINK, IFRAME, FRAME, EMBED, IMG, BASE, META, BODY
}
private static class HtmlFactory {
private static Map<String, Element> name2Element;
static {
name2Element = new HashMap<String, Element>();
for (Element element : Element.values()) {
name2Element.put(element.toString().toLowerCase(), element);
}
}
public static Element getElement(String name) {
return name2Element.get(name);
}
}
private String base;
private String metaRefresh;
private String metaLocation;
private boolean isWithinBodyElement;
private StringBuilder bodyText;
private List<ExtractedUrlAnchorPair> outgoingUrls;
private ExtractedUrlAnchorPair curUrl = null;
private boolean anchorFlag = false;
private StringBuilder anchorText = new StringBuilder();
public HtmlContentHandler() {
isWithinBodyElement = false;
bodyText = new StringBuilder();
outgoingUrls = new ArrayList<ExtractedUrlAnchorPair>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Element element = HtmlFactory.getElement(localName);
if (element == Element.A || element == Element.AREA || element == Element.LINK) {
String href = attributes.getValue("href");
if (href != null) {
anchorFlag = true;
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(href);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.IMG) {
String imgSrc = attributes.getValue("src");
if (imgSrc != null) {
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(imgSrc);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.IFRAME || element == Element.FRAME || element == Element.EMBED) {
String src = attributes.getValue("src");
if (src != null) {
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(src);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.BASE) {
if (base != null) { // We only consider the first occurrence of the
// Base element.
String href = attributes.getValue("href");
if (href != null) {
base = href;
}
}
return;
}
if (element == Element.META) {
String equiv = attributes.getValue("http-equiv");
String content = attributes.getValue("content");
if (equiv != null && content != null) {
equiv = equiv.toLowerCase();
// http-equiv="refresh" content="0;URL=http://foo.bar/..."
if (equiv.equals("refresh") && (metaRefresh == null)) {
int pos = content.toLowerCase().indexOf("url=");
if (pos != -1) {
metaRefresh = content.substring(pos + 4);
}
}
// http-equiv="location" content="http://foo.bar/..."
if (equiv.equals("location") && (metaLocation == null)) {
metaLocation = content;
}
}
return;
}
if (element == Element.BODY) {
isWithinBodyElement = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
Element element = HtmlFactory.getElement(localName);
if (element == Element.A || element == Element.AREA || element == Element.LINK) {
anchorFlag = false;
if (curUrl != null) {
String anchor = anchorText.toString().trim();
if (!anchor.isEmpty()) {
curUrl.setAnchor(anchor);
}
anchorText.delete(0, anchorText.length());
}
curUrl = null;
}
if (element == Element.BODY) {
isWithinBodyElement = false;
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (isWithinBodyElement) {
bodyText.append(ch, start, length);
if (anchorFlag) {
anchorText.append(new String(ch, start, length).replaceAll("\n", "").replaceAll("\t", "").trim());
}
}
}
public String getBodyText() {
return bodyText.toString();
}
public List<ExtractedUrlAnchorPair> getOutgoingUrls() {
return outgoingUrls;
}
public String getBaseUrl() {
return base;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/parser/HtmlContentHandler.java
|
Java
|
asf20
| 5,065
|
/**
* 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.parser;
public interface ParseData {
@Override
public String toString();
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/parser/ParseData.java
|
Java
|
asf20
| 918
|
/**
* 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.fetcher;
import java.util.concurrent.TimeUnit;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
public class IdleConnectionMonitorThread extends Thread {
private final ThreadSafeClientConnManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(ThreadSafeClientConnManager connMgr) {
super("Connection Manager");
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/fetcher/IdleConnectionMonitorThread.java
|
Java
|
asf20
| 1,968
|
/**
* 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.fetcher;
import org.apache.http.HttpStatus;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class CustomFetchStatus {
public static final int PageTooBig = 1001;
public static final int FatalTransportError = 1005;
public static final int UnknownError = 1006;
public static String getStatusDescription(int code) {
switch (code) {
case HttpStatus.SC_OK:
return "OK";
case HttpStatus.SC_CREATED:
return "Created";
case HttpStatus.SC_ACCEPTED:
return "Accepted";
case HttpStatus.SC_NO_CONTENT:
return "No Content";
case HttpStatus.SC_MOVED_PERMANENTLY:
return "Moved Permanently";
case HttpStatus.SC_MOVED_TEMPORARILY:
return "Moved Temporarily";
case HttpStatus.SC_NOT_MODIFIED:
return "Not Modified";
case HttpStatus.SC_BAD_REQUEST:
return "Bad Request";
case HttpStatus.SC_UNAUTHORIZED:
return "Unauthorized";
case HttpStatus.SC_FORBIDDEN:
return "Forbidden";
case HttpStatus.SC_NOT_FOUND:
return "Not Found";
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
return "Internal Server Error";
case HttpStatus.SC_NOT_IMPLEMENTED:
return "Not Implemented";
case HttpStatus.SC_BAD_GATEWAY:
return "Bad Gateway";
case HttpStatus.SC_SERVICE_UNAVAILABLE:
return "Service Unavailable";
case HttpStatus.SC_CONTINUE:
return "Continue";
case HttpStatus.SC_TEMPORARY_REDIRECT:
return "Temporary Redirect";
case HttpStatus.SC_METHOD_NOT_ALLOWED:
return "Method Not Allowed";
case HttpStatus.SC_CONFLICT:
return "Conflict";
case HttpStatus.SC_PRECONDITION_FAILED:
return "Precondition Failed";
case HttpStatus.SC_REQUEST_TOO_LONG:
return "Request Too Long";
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
return "Request-URI Too Long";
case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
return "Unsupported Media Type";
case HttpStatus.SC_MULTIPLE_CHOICES:
return "Multiple Choices";
case HttpStatus.SC_SEE_OTHER:
return "See Other";
case HttpStatus.SC_USE_PROXY:
return "Use Proxy";
case HttpStatus.SC_PAYMENT_REQUIRED:
return "Payment Required";
case HttpStatus.SC_NOT_ACCEPTABLE:
return "Not Acceptable";
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return "Proxy Authentication Required";
case HttpStatus.SC_REQUEST_TIMEOUT:
return "Request Timeout";
case PageTooBig:
return "Page size was too big";
case FatalTransportError:
return "Fatal transport error";
case UnknownError:
return "Unknown error";
default:
return "(" + code + ")";
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/fetcher/CustomFetchStatus.java
|
Java
|
asf20
| 3,354
|
/**
* 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.fetcher;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParamBean;
import org.apache.http.protocol.HttpContext;
import org.apache.log4j.Logger;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class PageFetcher extends Configurable {
protected static final Logger logger = Logger.getLogger(PageFetcher.class);
protected ThreadSafeClientConnManager connectionManager;
protected DefaultHttpClient httpClient;
protected final Object mutex = new Object();
protected long lastFetchTime = 0;
protected IdleConnectionMonitorThread connectionMonitorThread = null;
public PageFetcher(CrawlConfig config) {
super(config);
HttpParams params = new BasicHttpParams();
HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
paramsBean.setVersion(HttpVersion.HTTP_1_1);
paramsBean.setContentCharset("UTF-8");
paramsBean.setUseExpectContinue(false);
params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());
params.setBooleanParameter("http.protocol.handle-redirects", false);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
if (config.isIncludeHttpsPages()) {
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
}
connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
connectionManager.setMaxTotal(config.getMaxTotalConnections());
connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
httpClient = new DefaultHttpClient(connectionManager, params);
if (config.getProxyHost() != null) {
if (config.getProxyUsername() != null) {
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(config.getProxyHost(), config.getProxyPort()),
new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
}
HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(final HttpResponse response, final HttpContext context) throws HttpException,
IOException {
HttpEntity entity = response.getEntity();
Header contentEncoding = entity.getContentEncoding();
if (contentEncoding != null) {
HeaderElement[] codecs = contentEncoding.getElements();
for (HeaderElement codec : codecs) {
if (codec.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
if (connectionMonitorThread == null) {
connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
}
connectionMonitorThread.start();
}
public PageFetchResult fetchHeader(WebURL webUrl) {
PageFetchResult fetchResult = new PageFetchResult();
String toFetchURL = webUrl.getURL();
HttpGet get = null;
try {
get = new HttpGet(toFetchURL);
synchronized (mutex) {
long now = (new Date()).getTime();
if (now - lastFetchTime < config.getPolitenessDelay()) {
Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime));
}
lastFetchTime = (new Date()).getTime();
}
get.addHeader("Accept-Encoding", "gzip");
HttpResponse response = httpClient.execute(get);
fetchResult.setEntity(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
if (statusCode != HttpStatus.SC_NOT_FOUND) {
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
Header header = response.getFirstHeader("Location");
if (header != null) {
String movedToUrl = header.getValue();
movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL);
fetchResult.setMovedToUrl(movedToUrl);
}
fetchResult.setStatusCode(statusCode);
return fetchResult;
}
logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL);
}
fetchResult.setStatusCode(response.getStatusLine().getStatusCode());
return fetchResult;
}
fetchResult.setFetchedUrl(toFetchURL);
String uri = get.getURI().toString();
if (!uri.equals(toFetchURL)) {
if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) {
fetchResult.setFetchedUrl(uri);
}
}
if (fetchResult.getEntity() != null) {
long size = fetchResult.getEntity().getContentLength();
if (size == -1) {
Header length = response.getLastHeader("Content-Length");
if (length == null) {
length = response.getLastHeader("Content-length");
}
if (length != null) {
size = Integer.parseInt(length.getValue());
} else {
size = -1;
}
}
if (size > config.getMaxDownloadSize()) {
fetchResult.setStatusCode(CustomFetchStatus.PageTooBig);
return fetchResult;
}
fetchResult.setStatusCode(HttpStatus.SC_OK);
return fetchResult;
} else {
get.abort();
}
} catch (IOException e) {
logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL
+ " (link found in doc #" + webUrl.getParentDocid() + ")");
fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError);
return fetchResult;
} catch (IllegalStateException e) {
// ignoring exceptions that occur because of not registering https
// and other schemes
} catch (Exception e) {
if (e.getMessage() == null) {
logger.error("Error while fetching " + webUrl.getURL());
} else {
logger.error(e.getMessage() + " while fetching " + webUrl.getURL());
}
} finally {
try {
if (fetchResult.getEntity() == null && get != null) {
get.abort();
}
} catch (Exception e) {
e.printStackTrace();
}
}
fetchResult.setStatusCode(CustomFetchStatus.UnknownError);
return fetchResult;
}
public synchronized void shutDown() {
if (connectionMonitorThread != null) {
connectionManager.shutdown();
connectionMonitorThread.shutdown();
}
}
public HttpClient getHttpClient() {
return httpClient;
}
private static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java
|
Java
|
asf20
| 9,508
|
/**
* 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.fetcher;
import java.io.EOFException;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import edu.uci.ics.crawler4j.crawler.Page;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class PageFetchResult {
protected static final Logger logger = Logger.getLogger(PageFetchResult.class);
protected int statusCode;
protected HttpEntity entity = null;
protected String fetchedUrl = null;
protected String movedToUrl = null;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public HttpEntity getEntity() {
return entity;
}
public void setEntity(HttpEntity entity) {
this.entity = entity;
}
public String getFetchedUrl() {
return fetchedUrl;
}
public void setFetchedUrl(String fetchedUrl) {
this.fetchedUrl = fetchedUrl;
}
public boolean fetchContent(Page page) {
try {
page.load(entity);
return true;
} catch (Exception e) {
logger.info("Exception while fetching content for: " + page.getWebURL().getURL() + " [" + e.getMessage()
+ "]");
}
return false;
}
public void discardContentIfNotConsumed() {
try {
if (entity != null) {
EntityUtils.consume(entity);
}
} catch (EOFException e) {
// We can ignore this exception. It can happen on compressed streams
// which are not
// repeatable
} catch (IOException e) {
// We can ignore this exception. It can happen if the stream is
// closed.
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMovedToUrl() {
return movedToUrl;
}
public void setMovedToUrl(String movedToUrl) {
this.movedToUrl = movedToUrl;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetchResult.java
|
Java
|
asf20
| 2,602
|
/**
* 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.url;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* See http://en.wikipedia.org/wiki/URL_normalization for a reference Note: some
* parts of the code are adapted from: http://stackoverflow.com/a/4057470/405418
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class URLCanonicalizer {
public static String getCanonicalURL(String url) {
return getCanonicalURL(url, null);
}
public static String getCanonicalURL(String href, String context) {
try {
URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href));
String path = canonicalURL.getPath();
/*
* Normalize: no empty segments (i.e., "//"), no segments equal to
* ".", and no segments equal to ".." that are preceded by a segment
* not equal to "..".
*/
path = new URI(path).normalize().toString();
/*
* Convert '//' -> '/'
*/
int idx = path.indexOf("//");
while (idx >= 0) {
path = path.replace("//", "/");
idx = path.indexOf("//");
}
/*
* Drop starting '/../'
*/
while (path.startsWith("/../")) {
path = path.substring(3);
}
/*
* Trim
*/
path = path.trim();
final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery());
final String queryString;
if (params != null && params.size() > 0) {
String canonicalParams = canonicalize(params);
queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);
} else {
queryString = "";
}
/*
* Add starting slash if needed
*/
if (path.length() == 0) {
path = "/" + path;
}
/*
* Drop default port: example.com:80 -> example.com
*/
int port = canonicalURL.getPort();
if (port == canonicalURL.getDefaultPort()) {
port = -1;
}
/*
* Lowercasing protocol and host
*/
String protocol = canonicalURL.getProtocol().toLowerCase();
String host = canonicalURL.getHost().toLowerCase();
String pathAndQueryString = normalizePath(path) + queryString;
URL result = new URL(protocol, host, port, pathAndQueryString);
return result.toExternalForm();
} catch (MalformedURLException ex) {
return null;
} catch (URISyntaxException ex) {
return null;
}
}
/**
* Takes a query string, separates the constituent name-value pairs, and
* stores them in a SortedMap ordered by lexicographical order.
*
* @return Null if there is no query string.
*/
private static SortedMap<String, String> createParameterMap(final String queryString) {
if (queryString == null || queryString.isEmpty()) {
return null;
}
final String[] pairs = queryString.split("&");
final Map<String, String> params = new HashMap<String, String>(pairs.length);
for (final String pair : pairs) {
if (pair.length() == 0) {
continue;
}
String[] tokens = pair.split("=", 2);
switch (tokens.length) {
case 1:
if (pair.charAt(0) == '=') {
params.put("", tokens[0]);
} else {
params.put(tokens[0], "");
}
break;
case 2:
params.put(tokens[0], tokens[1]);
break;
}
}
return new TreeMap<String, String>(params);
}
/**
* Canonicalize the query string.
*
* @param sortedParamMap
* Parameter name-value pairs in lexicographical order.
* @return Canonical form of query string.
*/
private static String canonicalize(final SortedMap<String, String> sortedParamMap) {
if (sortedParamMap == null || sortedParamMap.isEmpty()) {
return "";
}
final StringBuffer sb = new StringBuffer(100);
for (Map.Entry<String, String> pair : sortedParamMap.entrySet()) {
final String key = pair.getKey().toLowerCase();
if (key.equals("jsessionid") || key.equals("phpsessid") || key.equals("aspsessionid")) {
continue;
}
if (sb.length() > 0) {
sb.append('&');
}
sb.append(percentEncodeRfc3986(pair.getKey()));
if (!pair.getValue().isEmpty()) {
sb.append('=');
sb.append(percentEncodeRfc3986(pair.getValue()));
}
}
return sb.toString();
}
/**
* Percent-encode values according the RFC 3986. The built-in Java
* URLEncoder does not encode according to the RFC, so we make the extra
* replacements.
*
* @param string
* Decoded string.
* @return Encoded string per RFC 3986.
*/
private static String percentEncodeRfc3986(String string) {
try {
string = string.replace("+", "%2B");
string = URLDecoder.decode(string, "UTF-8");
string = URLEncoder.encode(string, "UTF-8");
return string.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
} catch (Exception e) {
return string;
}
}
private static String normalizePath(final String path) {
return path.replace("%7E", "~").replace(" ", "%20");
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/url/URLCanonicalizer.java
|
Java
|
asf20
| 5,819
|
/**
* 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.url;
import java.io.Serializable;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
@Entity
public class WebURL implements Serializable {
private static final long serialVersionUID = 1L;
@PrimaryKey
private String url;
private int docid;
private int parentDocid;
private String parentUrl;
private short depth;
private String domain;
private String subDomain;
private String path;
private String anchor;
private byte priority;
/**
* Returns the unique document id assigned to this Url.
*/
public int getDocid() {
return docid;
}
public void setDocid(int docid) {
this.docid = docid;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebURL otherUrl = (WebURL) o;
return url != null && url.equals(otherUrl.getURL());
}
@Override
public String toString() {
return url;
}
/**
* Returns the Url string
*/
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
int domainStartIdx = url.indexOf("//") + 2;
int domainEndIdx = url.indexOf('/', domainStartIdx);
domain = url.substring(domainStartIdx, domainEndIdx);
subDomain = "";
String[] parts = domain.split("\\.");
if (parts.length > 2) {
domain = parts[parts.length - 2] + "." + parts[parts.length - 1];
int limit = 2;
if (TLDList.contains(domain)) {
domain = parts[parts.length - 3] + "." + domain;
limit = 3;
}
for (int i = 0; i < parts.length - limit; i++) {
if (subDomain.length() > 0) {
subDomain += ".";
}
subDomain += parts[i];
}
}
path = url.substring(domainEndIdx);
int pathEndIdx = path.indexOf('?');
if (pathEndIdx >= 0) {
path = path.substring(0, pathEndIdx);
}
}
/**
* Returns the unique document id of the parent page. The parent page is the
* page in which the Url of this page is first observed.
*/
public int getParentDocid() {
return parentDocid;
}
public void setParentDocid(int parentDocid) {
this.parentDocid = parentDocid;
}
/**
* Returns the url of the parent page. The parent page is the page in which
* the Url of this page is first observed.
*/
public String getParentUrl() {
return parentUrl;
}
public void setParentUrl(String parentUrl) {
this.parentUrl = parentUrl;
}
/**
* Returns the crawl depth at which this Url is first observed. Seed Urls
* are at depth 0. Urls that are extracted from seed Urls are at depth 1,
* etc.
*/
public short getDepth() {
return depth;
}
public void setDepth(short depth) {
this.depth = depth;
}
/**
* Returns the domain of this Url. For 'http://www.example.com/sample.htm',
* domain will be 'example.com'
*/
public String getDomain() {
return domain;
}
public String getSubDomain() {
return subDomain;
}
/**
* Returns the path of this Url. For 'http://www.example.com/sample.htm',
* domain will be 'sample.htm'
*/
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
/**
* Returns the anchor string. For example, in <a href="example.com">A sample anchor</a>
* the anchor string is 'A sample anchor'
*/
public String getAnchor() {
return anchor;
}
public void setAnchor(String anchor) {
this.anchor = anchor;
}
/**
* Returns the priority for crawling this URL.
* A lower number results in higher priority.
*/
public byte getPriority() {
return priority;
}
public void setPriority(byte priority) {
this.priority = priority;
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/url/WebURL.java
|
Java
|
asf20
| 4,514
|
/**
* This class is adopted from Htmlunit with the following copyright:
*
* Copyright (c) 2002-2012 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.url;
public final class UrlResolver {
/**
* Resolves a given relative URL against a base URL. See
* <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>
* Section 4 for more details.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
public static String resolveUrl(final String baseUrl, final String relativeUrl) {
if (baseUrl == null) {
throw new IllegalArgumentException("Base URL must not be null");
}
if (relativeUrl == null) {
throw new IllegalArgumentException("Relative URL must not be null");
}
final Url url = resolveUrl(parseUrl(baseUrl.trim()), relativeUrl.trim());
return url.toString();
}
/**
* Returns the index within the specified string of the first occurrence of
* the specified search character.
*
* @param s the string to search
* @param searchChar the character to search for
* @param beginIndex the index at which to start the search
* @param endIndex the index at which to stop the search
* @return the index of the first occurrence of the character in the string or <tt>-1</tt>
*/
private static int indexOf(final String s, final char searchChar, final int beginIndex, final int endIndex) {
for (int i = beginIndex; i < endIndex; i++) {
if (s.charAt(i) == searchChar) {
return i;
}
}
return -1;
}
/**
* Parses a given specification using the algorithm depicted in
* <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>:
*
* Section 2.4: Parsing a URL
*
* An accepted method for parsing URLs is useful to clarify the
* generic-RL syntax of Section 2.2 and to describe the algorithm for
* resolving relative URLs presented in Section 4. This section
* describes the parsing rules for breaking down a URL (relative or
* absolute) into the component parts described in Section 2.1. The
* rules assume that the URL has already been separated from any
* surrounding text and copied to a "parse string". The rules are
* listed in the order in which they would be applied by the parser.
*
* @param spec The specification to parse.
* @return the parsed specification.
*/
private static Url parseUrl(final String spec) {
final Url url = new Url();
int startIndex = 0;
int endIndex = spec.length();
// Section 2.4.1: Parsing the Fragment Identifier
//
// If the parse string contains a crosshatch "#" character, then the
// substring after the first (left-most) crosshatch "#" and up to the
// end of the parse string is the <fragment> identifier. If the
// crosshatch is the last character, or no crosshatch is present, then
// the fragment identifier is empty. The matched substring, including
// the crosshatch character, is removed from the parse string before
// continuing.
//
// Note that the fragment identifier is not considered part of the URL.
// However, since it is often attached to the URL, parsers must be able
// to recognize and set aside fragment identifiers as part of the
// process.
final int crosshatchIndex = indexOf(spec, '#', startIndex, endIndex);
if (crosshatchIndex >= 0) {
url.fragment_ = spec.substring(crosshatchIndex + 1, endIndex);
endIndex = crosshatchIndex;
}
// Section 2.4.2: Parsing the Scheme
//
// If the parse string contains a colon ":" after the first character
// and before any characters not allowed as part of a scheme name (i.e.,
// any not an alphanumeric, plus "+", period ".", or hyphen "-"), the
// <scheme> of the URL is the substring of characters up to but not
// including the first colon. These characters and the colon are then
// removed from the parse string before continuing.
final int colonIndex = indexOf(spec, ':', startIndex, endIndex);
if (colonIndex > 0) {
final String scheme = spec.substring(startIndex, colonIndex);
if (isValidScheme(scheme)) {
url.scheme_ = scheme;
startIndex = colonIndex + 1;
}
}
// Section 2.4.3: Parsing the Network Location/Login
//
// If the parse string begins with a double-slash "//", then the
// substring of characters after the double-slash and up to, but not
// including, the next slash "/" character is the network location/login
// (<net_loc>) of the URL. If no trailing slash "/" is present, the
// entire remaining parse string is assigned to <net_loc>. The double-
// slash and <net_loc> are removed from the parse string before
// continuing.
//
// Note: We also accept a question mark "?" or a semicolon ";" character as
// delimiters for the network location/login (<net_loc>) of the URL.
final int locationStartIndex;
int locationEndIndex;
if (spec.startsWith("//", startIndex)) {
locationStartIndex = startIndex + 2;
locationEndIndex = indexOf(spec, '/', locationStartIndex, endIndex);
if (locationEndIndex >= 0) {
startIndex = locationEndIndex;
}
}
else {
locationStartIndex = -1;
locationEndIndex = -1;
}
// Section 2.4.4: Parsing the Query Information
//
// If the parse string contains a question mark "?" character, then the
// substring after the first (left-most) question mark "?" and up to the
// end of the parse string is the <query> information. If the question
// mark is the last character, or no question mark is present, then the
// query information is empty. The matched substring, including the
// question mark character, is removed from the parse string before
// continuing.
final int questionMarkIndex = indexOf(spec, '?', startIndex, endIndex);
if (questionMarkIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the question mark "?" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = questionMarkIndex;
startIndex = questionMarkIndex;
}
url.query_ = spec.substring(questionMarkIndex + 1, endIndex);
endIndex = questionMarkIndex;
}
// Section 2.4.5: Parsing the Parameters
//
// If the parse string contains a semicolon ";" character, then the
// substring after the first (left-most) semicolon ";" and up to the end
// of the parse string is the parameters (<params>). If the semicolon
// is the last character, or no semicolon is present, then <params> is
// empty. The matched substring, including the semicolon character, is
// removed from the parse string before continuing.
final int semicolonIndex = indexOf(spec, ';', startIndex, endIndex);
if (semicolonIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the semicolon ";" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = semicolonIndex;
startIndex = semicolonIndex;
}
url.parameters_ = spec.substring(semicolonIndex + 1, endIndex);
endIndex = semicolonIndex;
}
// Section 2.4.6: Parsing the Path
//
// After the above steps, all that is left of the parse string is the
// URL <path> and the slash "/" that may precede it. Even though the
// initial slash is not part of the URL path, the parser must remember
// whether or not it was present so that later processes can
// differentiate between relative and absolute paths. Often this is
// done by simply storing the preceding slash along with the path.
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The entire remaining parse string is assigned to the network
// location/login (<net_loc>) of the URL.
locationEndIndex = endIndex;
}
else if (startIndex < endIndex) {
url.path_ = spec.substring(startIndex, endIndex);
}
// Set the network location/login (<net_loc>) of the URL.
if ((locationStartIndex >= 0) && (locationEndIndex >= 0)) {
url.location_ = spec.substring(locationStartIndex, locationEndIndex);
}
return url;
}
/*
* Returns true if specified string is a valid scheme name.
*/
private static boolean isValidScheme(final String scheme) {
final int length = scheme.length();
if (length < 1) {
return false;
}
char c = scheme.charAt(0);
if (!Character.isLetter(c)) {
return false;
}
for (int i = 1; i < length; i++) {
c = scheme.charAt(i);
if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && c != '-') {
return false;
}
}
return true;
}
/**
* Resolves a given relative URL against a base URL using the algorithm
* depicted in <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>:
*
* Section 4: Resolving Relative URLs
*
* This section describes an example algorithm for resolving URLs within
* a context in which the URLs may be relative, such that the result is
* always a URL in absolute form. Although this algorithm cannot
* guarantee that the resulting URL will equal that intended by the
* original author, it does guarantee that any valid URL (relative or
* absolute) can be consistently transformed to an absolute form given a
* valid base URL.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
private static Url resolveUrl(final Url baseUrl, final String relativeUrl) {
final Url url = parseUrl(relativeUrl);
// Step 1: The base URL is established according to the rules of
// Section 3. If the base URL is the empty string (unknown),
// the embedded URL is interpreted as an absolute URL and
// we are done.
if (baseUrl == null) {
return url;
}
// Step 2: Both the base and embedded URLs are parsed into their
// component parts as described in Section 2.4.
// a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (relativeUrl.length() == 0) {
return new Url(baseUrl);
}
// b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (url.scheme_ != null) {
return url;
}
// c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
url.scheme_ = baseUrl.scheme_;
// Step 3: If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
if (url.location_ != null) {
return url;
}
url.location_ = baseUrl.location_;
// Step 4: If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if ((url.path_ != null) && ((url.path_.length() > 0) && ('/' == url.path_.charAt(0)))) {
url.path_ = removeLeadingSlashPoints(url.path_);
return url;
}
// Step 5: If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path,
// and
if (url.path_ == null) {
url.path_ = baseUrl.path_;
// a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (url.parameters_ != null) {
return url;
}
url.parameters_ = baseUrl.parameters_;
// b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (url.query_ != null) {
return url;
}
url.query_ = baseUrl.query_;
return url;
}
// Step 6: The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place. The following operations are
// then applied, in order, to the new path:
final String basePath = baseUrl.path_;
String path = "";
if (basePath != null) {
final int lastSlashIndex = basePath.lastIndexOf('/');
if (lastSlashIndex >= 0) {
path = basePath.substring(0, lastSlashIndex + 1);
}
}
else {
path = "/";
}
path = path.concat(url.path_);
// a) All occurrences of "./", where "." is a complete path
// segment, are removed.
int pathSegmentIndex;
while ((pathSegmentIndex = path.indexOf("/./")) >= 0) {
path = path.substring(0, pathSegmentIndex + 1).concat(path.substring(pathSegmentIndex + 3));
}
// b) If the path ends with "." as a complete path segment,
// that "." is removed.
if (path.endsWith("/.")) {
path = path.substring(0, path.length() - 1);
}
// c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
while ((pathSegmentIndex = path.indexOf("/../")) > 0) {
final String pathSegment = path.substring(0, pathSegmentIndex);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex < 0) {
continue;
}
if (!"..".equals(pathSegment.substring(slashIndex))) {
path = path.substring(0, slashIndex + 1).concat(path.substring(pathSegmentIndex + 4));
}
}
// d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
if (path.endsWith("/..")) {
final String pathSegment = path.substring(0, path.length() - 3);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex >= 0) {
path = path.substring(0, slashIndex + 1);
}
}
path = removeLeadingSlashPoints(path);
url.path_ = path;
// Step 7: The resulting URL components, including any inherited from
// the base URL, are recombined to give the absolute form of
// the embedded URL.
return url;
}
/**
* "/.." at the beginning should be removed as browsers do (not in RFC)
*/
private static String removeLeadingSlashPoints(String path) {
while (path.startsWith("/..")) {
path = path.substring(3);
}
return path;
}
/**
* Class <tt>Url</tt> represents a Uniform Resource Locator.
*
* @author Martin Tamme
*/
private static class Url {
private String scheme_;
private String location_;
private String path_;
private String parameters_;
private String query_;
private String fragment_;
/**
* Creates a <tt>Url</tt> object.
*/
public Url() {
}
/**
* Creates a <tt>Url</tt> object from the specified
* <tt>Url</tt> object.
*
* @param url a <tt>Url</tt> object.
*/
public Url(final Url url) {
scheme_ = url.scheme_;
location_ = url.location_;
path_ = url.path_;
parameters_ = url.parameters_;
query_ = url.query_;
fragment_ = url.fragment_;
}
/**
* Returns a string representation of the <tt>Url</tt> object.
*
* @return a string representation of the <tt>Url</tt> object.
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (scheme_ != null) {
sb.append(scheme_);
sb.append(':');
}
if (location_ != null) {
sb.append("//");
sb.append(location_);
}
if (path_ != null) {
sb.append(path_);
}
if (parameters_ != null) {
sb.append(';');
sb.append(parameters_);
}
if (query_ != null) {
sb.append('?');
sb.append(query_);
}
if (fragment_ != null) {
sb.append('#');
sb.append(fragment_);
}
return sb.toString();
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/url/UrlResolver.java
|
Java
|
asf20
| 19,400
|
package edu.uci.ics.crawler4j.url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class TLDList {
private static Set<String> tldSet;
public static boolean contains(String str) {
return tldSet.contains(str);
}
static {
tldSet = new HashSet<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(TLDList.class.getClassLoader().getResourceAsStream("tld-names.txt")));
String line;
try {
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("//")) {
continue;
}
tldSet.add(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
zzysiat-mycrawler
|
src/main/java/edu/uci/ics/crawler4j/url/TLDList.java
|
Java
|
asf20
| 783
|
package com.zz.normal.framework.library.option;
public final class ZLEnumOption<T extends Enum<T>> extends ZLOption {
private final T myDefaultValue;
private T myValue;
public ZLEnumOption(String group, String optionName, T defaultValue) {
super(group, optionName);
myDefaultValue = defaultValue;
myValue = defaultValue;
}
public T getValue() {
if (!myIsSynchronized) {
final String value = getConfigValue(null);
if (value != null) {
try {
myValue = T.valueOf(myDefaultValue.getDeclaringClass(), value);
} catch (Throwable t) {
}
}
myIsSynchronized = true;
}
return myValue;
}
public void setValue(T value) {
if (myIsSynchronized && (myValue == value)) {
return;
}
myValue = value;
myIsSynchronized = true;
if (value == myDefaultValue) {
unsetConfigValue();
} else {
setConfigValue("" + value.toString());
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLEnumOption.java
|
Java
|
asf20
| 927
|
package com.zz.normal.framework.library.option;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.zz.normal.framework.library.option.base.ZLMiscUtil;
public class ZLStringListOption extends ZLOption {
private final List<String> myDefaultValue;
private List<String> myValue;
public ZLStringListOption(String group, String optionName, List<String> defaultValue) {
super(group, optionName);
myDefaultValue = (defaultValue != null) ? defaultValue : Collections.<String>emptyList();
myValue = myDefaultValue;
}
public List<String> getValue() {
if (!myIsSynchronized) {
final String value = getConfigValue(ZLMiscUtil.listToString(myDefaultValue));
if (value != null) {
myValue = ZLMiscUtil.stringToList(value);
}
myIsSynchronized = true;
}
return Collections.unmodifiableList(myValue);
}
public void setValue(List<String> value) {
if (value == null) {
value = Collections.emptyList();
}
if (myIsSynchronized && (myValue.equals(value))) {
return;
}
myValue = new ArrayList<String>(value);
if (value.equals(myDefaultValue)) {
unsetConfigValue();
} else {
setConfigValue(ZLMiscUtil.listToString(value));
}
myIsSynchronized = true;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLStringListOption.java
|
Java
|
asf20
| 1,240
|
package com.zz.normal.framework.library.option;
public final class ZLIntegerOption extends ZLOption {
private final int myDefaultValue;
private int myValue;
public ZLIntegerOption(String group, String optionName, int defaultValue) {
super(group, optionName);
myDefaultValue = defaultValue;
myValue = defaultValue;
}
public int getValue() {
if (!myIsSynchronized) {
String value = getConfigValue(null);
if (value != null) {
try {
myValue = Integer.parseInt(value);
} catch (NumberFormatException e) {
}
}
myIsSynchronized = true;
}
return myValue;
}
public void setValue(int value) {
if (myIsSynchronized && (myValue == value)) {
return;
}
myValue = value;
myIsSynchronized = true;
if (value == myDefaultValue) {
unsetConfigValue();
} else {
setConfigValue("" + value);
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLIntegerOption.java
|
Java
|
asf20
| 851
|
package com.zz.normal.framework.library.option;
public final class ZLStringOption extends ZLOption {
private final String myDefaultValue;
private String myValue;
public ZLStringOption(String group, String optionName, String defaultValue) {
super(group, optionName);
myDefaultValue = (defaultValue != null) ? defaultValue.intern() : "";
myValue = myDefaultValue;
}
public String getValue() {
if (!myIsSynchronized) {
String value = getConfigValue(myDefaultValue);
if (value != null) {
myValue = value;
}
myIsSynchronized = true;
}
return myValue;
}
public void setValue(String value) {
if (value == null) {
return;
}
value = value.intern();
if (myIsSynchronized && (myValue == value)) {
return;
}
myValue = value;
if (value == myDefaultValue) {
unsetConfigValue();
} else {
setConfigValue(value);
}
myIsSynchronized = true;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLStringOption.java
|
Java
|
asf20
| 899
|
package com.zz.normal.framework.library.option;
import com.zz.normal.framework.library.option.base.ZLBoolean3;
public final class ZLBoolean3Option extends ZLOption {
private ZLBoolean3 myValue;
private final ZLBoolean3 myDefaultValue;
public ZLBoolean3Option(String group, String optionName, ZLBoolean3 defaultValue) {
super(group, optionName);
myDefaultValue = defaultValue;
myValue = myDefaultValue;
}
public ZLBoolean3 getValue() {
if (!myIsSynchronized) {
String value = getConfigValue(null);
if (value != null) {
myValue = ZLBoolean3.getByName(value);
}
myIsSynchronized = true;
}
return myValue;
}
public void setValue(ZLBoolean3 value) {
if (myIsSynchronized && (myValue == value)) {
return;
}
myValue = value;
myIsSynchronized = true;
if (myValue == myDefaultValue) {
unsetConfigValue();
} else {
setConfigValue(myValue.Name);
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLBoolean3Option.java
|
Java
|
asf20
| 906
|
package com.zz.normal.framework.library.option;
public final class ZLBooleanOption extends ZLOption {
private final boolean myDefaultValue;
private boolean myValue;
public ZLBooleanOption(String group, String optionName, boolean defaultValue) {
super(group, optionName);
myDefaultValue = defaultValue;
myValue = defaultValue;
}
public boolean getValue() {
if (!myIsSynchronized) {
String value = getConfigValue(null);
if (value != null) {
if ("true".equals(value)) {
myValue = true;
} else if ("false".equals(value)) {
myValue = false;
}
}
myIsSynchronized = true;
}
return myValue;
}
public void setValue(boolean value) {
if (myIsSynchronized && (myValue == value)) {
return;
}
myValue = value;
myIsSynchronized = true;
if (value == myDefaultValue) {
unsetConfigValue();
} else {
setConfigValue(value ? "true" : "false");
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLBooleanOption.java
|
Java
|
asf20
| 911
|
package com.zz.normal.framework.library.option.base;
public enum ZLBoolean3 {
B3_FALSE("false"),
B3_TRUE("true"),
B3_UNDEFINED("undefined");
public final String Name;
private ZLBoolean3(String name) {
Name = name;
}
public static ZLBoolean3 getByName(String name) {
for (ZLBoolean3 b3 : values()) {
if (b3.Name.equals(name)) {
return b3;
}
}
return B3_UNDEFINED;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/base/ZLBoolean3.java
|
Java
|
asf20
| 398
|
package com.zz.normal.framework.library.option.base;
/**
* class Color. Color is presented as the triple of short's (Red, Green, Blue components)
* Each component should be in the range 0..255
*/
public final class ZLColor {
public final short Red;
public final short Green;
public final short Blue;
public ZLColor(int r, int g, int b) {
Red = (short)(r & 0xFF);
Green = (short)(g & 0xFF);
Blue = (short)(b & 0xFF);
}
public ZLColor(int intValue) {
Red = (short)((intValue >> 16) & 0xFF);
Green = (short)((intValue >> 8) & 0xFF);
Blue = (short)(intValue & 0xFF);
}
public int getIntValue() {
return (Red << 16) + (Green << 8) + Blue;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof ZLColor)) {
return false;
}
ZLColor color = (ZLColor)o;
return (color.Red == Red) && (color.Green == Green) && (color.Blue == Blue);
}
public int hashCode() {
return getIntValue();
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/base/ZLColor.java
|
Java
|
asf20
| 968
|
package com.zz.normal.framework.library.option.base;
import java.util.*;
public abstract class ZLMiscUtil {
public static <T> boolean equals(T o0, T o1) {
return o0 == null ? o1 == null : o0.equals(o1);
}
public static boolean isEmptyString(String s) {
return s == null || "".equals(s);
}
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
public static <T> boolean listsEquals(List<T> list1, List<T> list2) {
if (list1 == null) {
return list2 == null || list2.isEmpty();
}
if (list1.size() != list2.size()) {
return false;
}
return list1.containsAll(list2);
}
public static <KeyT,ValueT> boolean mapsEquals(Map<KeyT,ValueT> map1, Map<KeyT,ValueT> map2) {
if (map1 == null) {
return map2 == null || map2.isEmpty();
}
if (map1.size() != map2.size()
|| !map1.keySet().containsAll(map2.keySet())) {
return false;
}
for (KeyT key: map1.keySet()) {
final ValueT value1 = map1.get(key);
final ValueT value2 = map2.get(key);
if (!equals(value1, value2)) {
return false;
}
}
return true;
}
public static boolean matchesIgnoreCase(String text, String lowerCasePattern) {
return (text.length() >= lowerCasePattern.length()) &&
(text.toLowerCase().indexOf(lowerCasePattern) >= 0);
}
public static String listToString(List<String> list) {
if (list == null || list.isEmpty()) {
return "";
}
final StringBuilder builder = new StringBuilder();
boolean first = true;
for (String s : list) {
if (first) {
first = false;
} else {
builder.append(",");
}
builder.append(s);
}
return builder.toString();
}
public static List<String> stringToList(String str) {
if (str == null || "".equals(str)) {
return Collections.emptyList();
}
return Arrays.asList(str.split(","));
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/base/ZLMiscUtil.java
|
Java
|
asf20
| 1,820
|
package com.zz.normal.framework.library.option;
import com.zz.normal.framework.db.ZLConfig;
public abstract class ZLOption {
public static final String PLATFORM_GROUP = "PlatformOptions";
private final String myGroup;
private final String myOptionName;
protected boolean myIsSynchronized;
protected ZLOption(String group, String optionName) {
myGroup = group.intern();
myOptionName = optionName.intern();
myIsSynchronized = false;
}
protected final String getConfigValue(String defaultValue) {
ZLConfig config = ZLConfig.Instance();
return (config != null) ?
config.getValue(myGroup, myOptionName, defaultValue) : defaultValue;
}
protected final void setConfigValue(String value) {
ZLConfig config = ZLConfig.Instance();
if (config != null) {
config.setValue(myGroup, myOptionName, value);
}
}
protected final void unsetConfigValue() {
ZLConfig config = ZLConfig.Instance();
if (config != null) {
config.unsetValue(myGroup, myOptionName);
}
}
protected final void removeConfigGroup(){
ZLConfig config = ZLConfig.Instance();
if (config != null) {
config.removeGroup(myGroup);
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLOption.java
|
Java
|
asf20
| 1,145
|
package com.zz.normal.framework.library.option;
public final class ZLIntegerRangeOption extends ZLOption {
public final int MinValue;
public final int MaxValue;
private final int myDefaultValue;
private int myValue;
public ZLIntegerRangeOption(String group, String optionName, int minValue, int maxValue, int defaultValue) {
super(group, optionName);
MinValue = minValue;
MaxValue = maxValue;
if (defaultValue < MinValue) {
defaultValue = MinValue;
} else if (defaultValue > MaxValue) {
defaultValue = MaxValue;
}
myDefaultValue = defaultValue;
myValue = defaultValue;
}
public int getValue() {
if (!myIsSynchronized) {
String value = getConfigValue(null);
if (value != null) {
try {
int intValue = Integer.parseInt(value);
if (intValue < MinValue) {
intValue = MinValue;
} else if (intValue > MaxValue) {
intValue = MaxValue;
}
myValue = intValue;
} catch (NumberFormatException e) {
}
}
myIsSynchronized = true;
}
return myValue;
}
public void setValue(int value) {
if (value < MinValue) {
value = MinValue;
} else if (value > MaxValue) {
value = MaxValue;
}
if (myIsSynchronized && (myValue == value)) {
return;
}
myValue = value;
myIsSynchronized = true;
if (value == myDefaultValue) {
unsetConfigValue();
} else {
setConfigValue("" + value);
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLIntegerRangeOption.java
|
Java
|
asf20
| 1,392
|
package com.zz.normal.framework.library.option;
import com.zz.normal.framework.library.option.base.ZLColor;
public final class ZLColorOption extends ZLOption {
private final ZLColor myDefaultValue;
private ZLColor myValue;
public ZLColorOption(String group, String optionName, ZLColor defaultValue) {
super(group, optionName);
myDefaultValue = (defaultValue != null) ? defaultValue : new ZLColor(0);
myValue = myDefaultValue;
}
public ZLColor getValue() {
if (!myIsSynchronized) {
String value = getConfigValue(null);
if (value != null) {
try {
int intValue = Integer.parseInt(value);
if (myValue.getIntValue() != intValue) {
myValue = new ZLColor(intValue);
}
} catch (NumberFormatException e) {
}
}
myIsSynchronized = true;
}
return myValue;
}
public void setValue(ZLColor colorValue) {
if (colorValue != null) {
final boolean sameValue = myValue.equals(colorValue);
if (myIsSynchronized && sameValue) {
return;
}
if (!sameValue) {
myValue = colorValue;
}
myIsSynchronized = true;
if (colorValue.equals(myDefaultValue)) {
unsetConfigValue();
} else {
setConfigValue("" + colorValue.getIntValue());
}
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/library/option/ZLColorOption.java
|
Java
|
asf20
| 1,225
|
package com.zz.normal.framework.db;
import java.util.List;
public abstract class ZLConfig {
public static ZLConfig Instance() {
return ourInstance;
}
private static ZLConfig ourInstance;
protected ZLConfig() {
ourInstance = this;
}
public abstract List<String> listGroups();
public abstract List<String> listNames(String group);
public abstract String getValue(String group, String name, String defaultValue);
public abstract void setValue(String group, String name, String value);
public abstract void unsetValue(String group, String name);
public abstract void removeGroup(String name);
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/db/ZLConfig.java
|
Java
|
asf20
| 612
|
package com.zz.normal.framework.db;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
public final class ZLSQLiteConfig extends ZLConfig {
private final SQLiteDatabase myDatabase;
private final SQLiteStatement myGetValueStatement;
private final SQLiteStatement mySetValueStatement;
private final SQLiteStatement myUnsetValueStatement;
private final SQLiteStatement myDeleteGroupStatement;
public ZLSQLiteConfig(Context context) {
myDatabase = context.openOrCreateDatabase("config.db", Context.MODE_PRIVATE, null);
switch (myDatabase.getVersion()) {
case 0:
myDatabase.execSQL("CREATE TABLE config (groupName VARCHAR, name VARCHAR, value VARCHAR, PRIMARY KEY(groupName, name) )");
break;
case 1:
myDatabase.beginTransaction();
SQLiteStatement removeStatement = myDatabase.compileStatement(
"DELETE FROM config WHERE name = ? AND groupName LIKE ?"
);
removeStatement.bindString(2, "/%");
removeStatement.bindString(1, "Size"); removeStatement.execute();
removeStatement.bindString(1, "Title"); removeStatement.execute();
removeStatement.bindString(1, "Language"); removeStatement.execute();
removeStatement.bindString(1, "Encoding"); removeStatement.execute();
removeStatement.bindString(1, "AuthorSortKey"); removeStatement.execute();
removeStatement.bindString(1, "AuthorDisplayName"); removeStatement.execute();
removeStatement.bindString(1, "EntriesNumber"); removeStatement.execute();
removeStatement.bindString(1, "TagList"); removeStatement.execute();
removeStatement.bindString(1, "Sequence"); removeStatement.execute();
removeStatement.bindString(1, "Number in seq"); removeStatement.execute();
myDatabase.execSQL(
"DELETE FROM config WHERE name LIKE 'Entry%' AND groupName LIKE '/%'"
);
myDatabase.setTransactionSuccessful();
myDatabase.endTransaction();
myDatabase.execSQL("VACUUM");
break;
}
myDatabase.setVersion(2);
myGetValueStatement = myDatabase.compileStatement("SELECT value FROM config WHERE groupName = ? AND name = ?");
mySetValueStatement = myDatabase.compileStatement("INSERT OR REPLACE INTO config (groupName, name, value) VALUES (?, ?, ?)");
myUnsetValueStatement = myDatabase.compileStatement("DELETE FROM config WHERE groupName = ? AND name = ?");
myDeleteGroupStatement = myDatabase.compileStatement("DELETE FROM config WHERE groupName = ?");
/*
final Cursor cursor = myDatabase.rawQuery("SELECT groupName,name FROM config WHERE groupName LIKE ? GROUP BY name", new String[] { "/%" });
while (cursor.moveToNext()) {
println(cursor.getString(0) + " = " + cursor.getString(1));
}
cursor.close();
*/
}
@Override
synchronized public List<String> listGroups() {
final LinkedList<String> list = new LinkedList<String>();
final Cursor cursor = myDatabase.rawQuery("SELECT DISTINCT groupName FROM config", null);
while (cursor.moveToNext()) {
list.add(cursor.getString(0));
}
cursor.close();
return list;
}
@Override
synchronized public List<String> listNames(String group) {
final LinkedList<String> list = new LinkedList<String>();
final Cursor cursor = myDatabase.rawQuery("SELECT name FROM config WHERE groupName = ?", new String[] { group });
while (cursor.moveToNext()) {
list.add(cursor.getString(0));
}
cursor.close();
return list;
}
@Override
synchronized public void removeGroup(String name) {
myDeleteGroupStatement.bindString(1, name);
try {
myDeleteGroupStatement.execute();
} catch (SQLException e) {
}
}
@Override
synchronized public String getValue(String group, String name, String defaultValue) {
String answer = defaultValue;
myGetValueStatement.bindString(1, group);
myGetValueStatement.bindString(2, name);
try {
answer = myGetValueStatement.simpleQueryForString();
} catch (SQLException e) {
}
return answer;
}
@Override
synchronized public void setValue(String group, String name, String value) {
mySetValueStatement.bindString(1, group);
mySetValueStatement.bindString(2, name);
mySetValueStatement.bindString(3, value);
try {
mySetValueStatement.execute();
} catch (SQLException e) {
}
}
@Override
synchronized public void unsetValue(String group, String name) {
myUnsetValueStatement.bindString(1, group);
myUnsetValueStatement.bindString(2, name);
try {
myUnsetValueStatement.execute();
} catch (SQLException e) {
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/db/ZLSQLiteConfig.java
|
Java
|
asf20
| 4,622
|
package com.zz.normal.framework.httpnet;
public class Command {
public short missionId = -1;
public Object params;
public boolean isCancel = false;
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/httpnet/Command.java
|
Java
|
asf20
| 165
|
package com.zz.normal.framework.resource;
public abstract class ZLResourceFile extends ZLFile {
public static ZLResourceFile createResourceFile(String path) {
return ZLibrary.Instance().createResourceFile(path);
}
static ZLResourceFile createResourceFile(ZLResourceFile parent, String name) {
return ZLibrary.Instance().createResourceFile(parent, name);
}
private final String myPath;
protected ZLResourceFile(String path) {
myPath = path;
init();
}
@Override
public String getPath() {
return myPath;
}
@Override
public String getLongName() {
return myPath.substring(myPath.lastIndexOf('/') + 1);
}
@Override
public ZLPhysicalFile getPhysicalFile() {
return null;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLResourceFile.java
|
Java
|
asf20
| 709
|
package com.zz.normal.framework.resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
final class ZLDTDParser {
private static final byte IGNORABLE_WHITESPACE = 0;
private static final byte LANGLE = 1;
private static final byte TAG_PREFIX = 2;
private static final byte COMMENT = 3;
private static final byte END_OF_COMMENT1 = 4;
private static final byte END_OF_COMMENT2 = 5;
private static final byte ENTITY = 6;
private static final byte WAIT_NAME = 7;
private static final byte NAME = 8;
private static final byte WAIT_VALUE = 9;
private static final byte VALUE = 10;
private static final byte WAIT_END_OF_ENTITY = 11;
public void doIt(final InputStream stream, final HashMap<String,char[]> entityMap) throws IOException {
final InputStreamReader streamReader = new InputStreamReader(stream, "us-ascii");
char[] buffer = new char[8192];
int startPosition = 0;
String name = "";
String value = "";
byte state = IGNORABLE_WHITESPACE;
errorLabel:
while (true) {
int count = streamReader.read(buffer);
if (count <= 0) {
streamReader.close();
return;
}
if (count < buffer.length) {
buffer = ZLArrayUtils.createCopy(buffer, count, count);
}
try {
for (int i = -1;;) {
mainSwitchLabel:
switch (state) {
case IGNORABLE_WHITESPACE:
while (true) {
switch (buffer[++i]) {
case '<':
state = LANGLE;
break mainSwitchLabel;
}
}
case LANGLE:
switch (buffer[++i]) {
case '!':
state = TAG_PREFIX;
break mainSwitchLabel;
default:
break errorLabel;
}
case TAG_PREFIX:
switch (buffer[++i]) {
case 'E':
state = ENTITY;
break mainSwitchLabel;
case '-':
state = COMMENT;
break mainSwitchLabel;
default:
break errorLabel;
}
case ENTITY:
while (true) {
switch (buffer[++i]) {
case ' ':
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
state = WAIT_NAME;
break mainSwitchLabel;
}
}
case WAIT_NAME:
while (true) {
switch (buffer[++i]) {
case ' ':
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
break;
default:
state = NAME;
startPosition = i;
break mainSwitchLabel;
}
}
case NAME:
while (true) {
switch (buffer[++i]) {
case ' ':
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
state = WAIT_VALUE;
name += new String(buffer, startPosition, i - startPosition);
break mainSwitchLabel;
}
}
case WAIT_VALUE:
while (true) {
switch (buffer[++i]) {
case ' ':
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
break;
default:
state = VALUE;
startPosition = i;
break mainSwitchLabel;
}
}
case VALUE:
while (true) {
switch (buffer[++i]) {
case '>':
state = IGNORABLE_WHITESPACE;
value += new String(buffer, startPosition, i - startPosition);
final int len = value.length();
if ((len > 2) &&
(value.charAt(0) == '"') &&
(value.charAt(len - 1) == '"')) {
value = value.substring(1, len - 1);
if (value.startsWith("&#") && value.endsWith(";")) {
try {
int number = 0;
if (value.charAt(2) == 'x') {
number = Integer.parseInt(value.substring(3, len - 3), 16);
} else {
for (int j = 2; j < len - 3; ++j) {
number *= 10;
number += value.charAt(j) - 48;
}
}
entityMap.put(name, new char[] { (char)number });
} catch (NumberFormatException e) {
}
} else {
final char[] aValue = new char[len - 2];
value.getChars(0, len - 2, aValue, 0);
entityMap.put(name, aValue);
}
}
name = "";
value = "";
break mainSwitchLabel;
case ' ':
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
state = WAIT_END_OF_ENTITY;
value += new String(buffer, startPosition, i - startPosition);
name = "";
value = "";
break mainSwitchLabel;
}
}
case WAIT_END_OF_ENTITY:
while (true) {
switch (buffer[++i]) {
case '>':
state = IGNORABLE_WHITESPACE;
break mainSwitchLabel;
}
}
case COMMENT:
while (true) {
switch (buffer[++i]) {
case '-':
state = END_OF_COMMENT1;
break mainSwitchLabel;
}
}
case END_OF_COMMENT1:
switch(buffer[++i]) {
case '-':
state = END_OF_COMMENT2;
break mainSwitchLabel;
default:
state = COMMENT;
break mainSwitchLabel;
}
case END_OF_COMMENT2:
switch(buffer[++i]) {
case '>':
state = IGNORABLE_WHITESPACE;
break mainSwitchLabel;
default:
state = COMMENT;
break mainSwitchLabel;
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
switch (state) {
case NAME:
name = new String(buffer, startPosition, count - startPosition);
startPosition = 0;
break;
case VALUE:
value = new String(buffer, startPosition, count - startPosition);
startPosition = 0;
break;
}
}
}
streamReader.close();
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLDTDParser.java
|
Java
|
asf20
| 6,381
|
package com.zz.normal.framework.resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
final class ZLXMLParser {
private static final byte START_DOCUMENT = 0;
private static final byte START_TAG = 1;
private static final byte END_TAG = 2;
private static final byte TEXT = 3;
//private static final byte IGNORABLE_WHITESPACE = 4;
//private static final byte PROCESSING_INSTRUCTION = 5;
private static final byte COMMENT = 6; // tag of form <!-- -->
private static final byte END_OF_COMMENT1 = 7;
private static final byte END_OF_COMMENT2 = 8;
private static final byte EXCL_TAG = 9; // tag of form <! >
private static final byte EXCL_TAG_START = 10;
private static final byte Q_TAG = 11; // tag of form <? ?>
private static final byte END_OF_Q_TAG = 12;
private static final byte LANGLE = 13;
private static final byte WS_AFTER_START_TAG_NAME = 14;
private static final byte WS_AFTER_ATTRIBUTE_VALUE = 15;
//private static final byte WS_AFTER_END_TAG_NAME = 16;
private static final byte WAIT_EQUALS = 17;
private static final byte WAIT_ATTRIBUTE_VALUE = 18;
private static final byte SLASH = 19;
private static final byte ATTRIBUTE_NAME = 20;
private static final byte ATTRIBUTE_VALUE_QUOT = 21;
private static final byte ATTRIBUTE_VALUE_APOS = 22;
private static final byte ENTITY_REF = 23;
private static final byte CDATA = 24; // <![CDATA[...]]>
private static final byte END_OF_CDATA1 = 25;
private static final byte END_OF_CDATA2 = 26;
private static String convertToString(Map<ZLMutableString,String> strings, ZLMutableString container) {
String s = strings.get(container);
if (s == null) {
s = container.toString();
strings.put(new ZLMutableString(container), s);
}
container.clear();
return s;
}
private final InputStreamReader myStreamReader;
private final ZLXMLReader myXMLReader;
private final boolean myProcessNamespaces;
private static HashMap<Integer,Queue<char[]>> ourBufferPool = new HashMap<Integer,Queue<char[]>>();
private static Queue<ZLMutableString> ourStringPool = new LinkedList<ZLMutableString>();
private static synchronized char[] getBuffer(int bufferSize) {
Queue<char[]> queue = ourBufferPool.get(bufferSize);
if (queue != null) {
char[] buffer = queue.poll();
if (buffer != null) {
return buffer;
}
}
return new char[bufferSize];
}
private static synchronized void storeBuffer(char[] buffer) {
Queue<char[]> queue = ourBufferPool.get(buffer.length);
if (queue == null) {
queue = new LinkedList<char[]>();
ourBufferPool.put(buffer.length, queue);
}
queue.add(buffer);
}
private static synchronized ZLMutableString getMutableString() {
ZLMutableString string = ourStringPool.poll();
return (string != null) ? string : new ZLMutableString();
}
private static synchronized void storeString(ZLMutableString string) {
ourStringPool.add(string);
}
private final char[] myBuffer;
private int myBufferDescriptionLength;
private final ZLMutableString myTagName = getMutableString();
private final ZLMutableString myCData = getMutableString();
private final ZLMutableString myAttributeName = getMutableString();
private final ZLMutableString myAttributeValue = getMutableString();
private final ZLMutableString myEntityName = getMutableString();
void finish() {
storeBuffer(myBuffer);
storeString(myTagName);
storeString(myAttributeName);
storeString(myAttributeValue);
storeString(myEntityName);
}
public ZLXMLParser(ZLXMLReader xmlReader, InputStream stream, int bufferSize) throws IOException {
myXMLReader = xmlReader;
myProcessNamespaces = xmlReader.processNamespaces();
String encoding = "utf-8";
final char[] buffer = getBuffer(bufferSize);
myBuffer = buffer;
boolean found = false;
int len = 0;
while (len < 256) {
char c = (char)stream.read();
buffer[len++] = c;
if (c == '>') {
found = true;
break;
}
}
myBufferDescriptionLength = len;
if (found) {
final String xmlDescription = new String(buffer, 0, len).trim();
if (xmlDescription.startsWith("<?xml") && xmlDescription.endsWith("?>")) {
myBufferDescriptionLength = 0;
int index = xmlDescription.indexOf("encoding");
if (index > 0) {
int startIndex = xmlDescription.indexOf('"', index);
if (startIndex > 0) {
int endIndex = xmlDescription.indexOf('"', startIndex + 1);
if (endIndex > 0) {
encoding = xmlDescription.substring(startIndex + 1, endIndex);
}
}
}
}
}
myStreamReader = new InputStreamReader(stream, encoding);
}
private static char[] getEntityValue(HashMap<String,char[]> entityMap, String name) {
char[] value = entityMap.get(name);
if (value == null) {
if ((name.length() > 0) && (name.charAt(0) == '#')) {
try {
int number;
if (name.charAt(1) == 'x') {
number = Integer.parseInt(name.substring(2), 16);
} else {
number = Integer.parseInt(name.substring(1));
}
value = new char[] { (char)number };
entityMap.put(name, value);
} catch (NumberFormatException e) {
}
}
}
return value;
}
private static HashMap<List<String>,HashMap<String,char[]>> ourDTDMaps =
new HashMap<List<String>,HashMap<String,char[]>>();
static synchronized HashMap<String,char[]> getDTDMap(List<String> dtdList) throws IOException {
HashMap<String,char[]> entityMap = ourDTDMaps.get(dtdList);
if (entityMap == null) {
entityMap = new HashMap<String,char[]>();
entityMap.put("amp", new char[] { '&' });
entityMap.put("apos", new char[] { '\'' });
entityMap.put("gt", new char[] { '>' });
entityMap.put("lt", new char[] { '<' });
entityMap.put("quot", new char[] { '\"' });
for (String fileName : dtdList) {
final InputStream stream = ZLResourceFile.createResourceFile(fileName).getInputStream();
if (stream != null) {
new ZLDTDParser().doIt(stream, entityMap);
}
}
ourDTDMaps.put(dtdList, entityMap);
}
return entityMap;
}
void doIt() throws IOException {
final ZLXMLReader xmlReader = myXMLReader;
final HashMap<String,char[]> entityMap = getDTDMap(xmlReader.externalDTDs());
xmlReader.addExternalEntities(entityMap);
final InputStreamReader streamReader = myStreamReader;
final boolean processNamespaces = myProcessNamespaces;
HashMap<String,String> oldNamespaceMap = processNamespaces ? new HashMap<String,String>() : null;
HashMap<String,String> currentNamespaceMap = null;
final ArrayList<HashMap<String,String>> namespaceMapStack = new ArrayList<HashMap<String,String>>();
char[] buffer = myBuffer;
final ZLMutableString tagName = myTagName;
final ZLMutableString cData = myCData;
final ZLMutableString attributeName = myAttributeName;
final ZLMutableString attributeValue = myAttributeValue;
final boolean dontCacheAttributeValues = xmlReader.dontCacheAttributeValues();
final ZLMutableString entityName = myEntityName;
final Map<ZLMutableString,String> strings = new HashMap<ZLMutableString, String>();
final ZLStringMap attributes = new ZLStringMap();
String[] tagStack = new String[10];
int tagStackSize = 0;
byte state = START_DOCUMENT;
byte savedState = START_DOCUMENT;
while (true) {
int count;
if (myBufferDescriptionLength > 0) {
count = myBufferDescriptionLength;
myBufferDescriptionLength = 0;
} else {
count = streamReader.read(buffer);
}
if (count <= 0) {
streamReader.close();
return;
}
int startPosition = 0;
if (count < buffer.length) {
//buffer = ZLArrayUtils.createCopy(buffer, count, count);
startPosition = buffer.length - count;
System.arraycopy(buffer, 0, buffer, startPosition, count);
count = buffer.length;
}
try {
for (int i = startPosition - 1;;) {
mainSwitchLabel:
switch (state) {
case START_DOCUMENT:
while (true) {
switch (buffer[++i]) {
case '<':
state = LANGLE;
startPosition = i + 1;
break mainSwitchLabel;
}
}
case LANGLE:
switch (buffer[++i]) {
case '/':
state = END_TAG;
startPosition = i + 1;
break;
case '!':
state = EXCL_TAG_START;
break;
case '?':
state = Q_TAG;
break;
default:
state = START_TAG;
startPosition = i;
break;
}
break;
case EXCL_TAG_START:
switch (buffer[++i]) {
case '-':
state = COMMENT;
break;
case '[':
state = CDATA;
startPosition = i + 1;
break;
default:
state = EXCL_TAG;
break;
}
break;
case EXCL_TAG:
while (true) {
switch (buffer[++i]) {
case '>':
state = TEXT;
startPosition = i + 1;
break mainSwitchLabel;
}
}
case CDATA:
while (true) {
switch (buffer[++i]) {
case ']':
state = END_OF_CDATA1;
break mainSwitchLabel;
}
}
case END_OF_CDATA1:
if (buffer[++i] == ']') {
state = END_OF_CDATA2;
} else {
state = CDATA;
}
break;
case END_OF_CDATA2:
if (buffer[++i] == '>') {
cData.append(buffer, startPosition, i - startPosition);
int len = cData.myLength;
if (len > 8) {
char data[] = cData.myData;
if (new String(data, 0, 6).equals("CDATA[")) {
xmlReader.characterDataHandler(data, 6, len - 8);
}
}
cData.clear();
state = TEXT;
startPosition = i + 1;
} else {
state = CDATA;
}
break;
case COMMENT:
while (true) {
switch (buffer[++i]) {
case '-':
state = END_OF_COMMENT1;
break mainSwitchLabel;
}
}
case END_OF_COMMENT1:
if (buffer[++i] == '-') {
state = END_OF_COMMENT2;
} else {
state = COMMENT;
}
break mainSwitchLabel;
case END_OF_COMMENT2:
switch (buffer[++i]) {
case '>':
state = TEXT;
startPosition = i + 1;
break;
case '-':
break;
default:
state = COMMENT;
break;
}
break;
case Q_TAG:
while (true) {
switch (buffer[++i]) {
case '?':
state = END_OF_Q_TAG;
break mainSwitchLabel;
}
}
case END_OF_Q_TAG:
if (buffer[++i] == '>') {
state = TEXT;
startPosition = i + 1;
} else {
state = Q_TAG;
}
break mainSwitchLabel;
case START_TAG:
while (true) {
switch (buffer[++i]) {
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
case ' ':
state = WS_AFTER_START_TAG_NAME;
tagName.append(buffer, startPosition, i - startPosition);
break mainSwitchLabel;
case '>':
state = TEXT;
tagName.append(buffer, startPosition, i - startPosition);
{
String stringTagName = convertToString(strings, tagName);
if (tagStackSize == tagStack.length) {
tagStack = ZLArrayUtils.createCopy(tagStack, tagStackSize, tagStackSize << 1);
}
tagStack[tagStackSize++] = stringTagName;
if (processNamespaces) {
if (currentNamespaceMap != null) {
oldNamespaceMap = currentNamespaceMap;
}
namespaceMapStack.add(currentNamespaceMap);
}
if (processStartTag(xmlReader, stringTagName, attributes, currentNamespaceMap)) {
streamReader.close();
return;
}
currentNamespaceMap = null;
}
startPosition = i + 1;
break mainSwitchLabel;
case '/':
state = SLASH;
tagName.append(buffer, startPosition, i - startPosition);
if (processFullTag(xmlReader, convertToString(strings, tagName), attributes)) {
streamReader.close();
return;
}
currentNamespaceMap = null;
break mainSwitchLabel;
case '&':
savedState = START_TAG;
tagName.append(buffer, startPosition, i - startPosition);
state = ENTITY_REF;
startPosition = i + 1;
break mainSwitchLabel;
}
}
case WS_AFTER_START_TAG_NAME:
switch (buffer[++i]) {
case '>':
{
String stringTagName = convertToString(strings, tagName);
if (tagStackSize == tagStack.length) {
tagStack = ZLArrayUtils.createCopy(tagStack, tagStackSize, tagStackSize << 1);
}
tagStack[tagStackSize++] = stringTagName;
if (processNamespaces) {
if (currentNamespaceMap != null) {
oldNamespaceMap = currentNamespaceMap;
}
namespaceMapStack.add(currentNamespaceMap);
}
if (processStartTag(xmlReader, stringTagName, attributes, currentNamespaceMap)) {
streamReader.close();
return;
}
currentNamespaceMap = null;
}
state = TEXT;
startPosition = i + 1;
break;
case '/':
state = SLASH;
if (processFullTag(xmlReader, convertToString(strings, tagName), attributes)) {
streamReader.close();
return;
}
currentNamespaceMap = null;
break;
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
case ' ':
break;
default:
state = ATTRIBUTE_NAME;
startPosition = i;
break;
}
break;
case ATTRIBUTE_NAME:
while (true) {
switch (buffer[++i]) {
case '=':
attributeName.append(buffer, startPosition, i - startPosition);
state = WAIT_ATTRIBUTE_VALUE;
break mainSwitchLabel;
case '&':
attributeName.append(buffer, startPosition, i - startPosition);
savedState = ATTRIBUTE_NAME;
state = ENTITY_REF;
startPosition = i + 1;
break mainSwitchLabel;
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
case ' ':
attributeName.append(buffer, startPosition, i - startPosition);
state = WAIT_EQUALS;
break mainSwitchLabel;
}
}
case WAIT_EQUALS:
while (true) {
switch (buffer[++i]) {
case '=':
state = WAIT_ATTRIBUTE_VALUE;
break mainSwitchLabel;
}
}
case WAIT_ATTRIBUTE_VALUE:
while (true) {
switch (buffer[++i]) {
case '"':
state = ATTRIBUTE_VALUE_QUOT;
startPosition = i + 1;
break mainSwitchLabel;
case '\'':
state = ATTRIBUTE_VALUE_APOS;
startPosition = i + 1;
break mainSwitchLabel;
}
}
case WS_AFTER_ATTRIBUTE_VALUE:
switch (buffer[++i]) {
case 0x0008:
case 0x0009:
case 0x000A:
case 0x000B:
case 0x000C:
case 0x000D:
case ' ':
state = WS_AFTER_START_TAG_NAME;
break;
case '/':
case '>':
state = WS_AFTER_START_TAG_NAME;
--i;
break;
case '"':
if (i != 0) {
attributeValue.append(buffer, i - 1, 1);
}
break mainSwitchLabel;
default:
state = ATTRIBUTE_NAME;
break mainSwitchLabel;
}
final String aName = convertToString(strings, attributeName);
if (processNamespaces && aName.equals("xmlns")) {
if (currentNamespaceMap == null) {
currentNamespaceMap = new HashMap<String,String>(oldNamespaceMap);
}
currentNamespaceMap.put("", attributeValue.toString());
attributeValue.clear();
} else if (processNamespaces && aName.startsWith("xmlns:")) {
if (currentNamespaceMap == null) {
currentNamespaceMap = new HashMap<String,String>(oldNamespaceMap);
}
currentNamespaceMap.put(aName.substring(6), attributeValue.toString());
attributeValue.clear();
} else if (dontCacheAttributeValues) {
attributes.put(aName, attributeValue.toString());
attributeValue.clear();
} else {
attributes.put(aName, convertToString(strings, attributeValue));
}
break;
case ATTRIBUTE_VALUE_QUOT:
while (true) {
switch (buffer[++i]) {
case '"':
attributeValue.append(buffer, startPosition, i - startPosition);
state = WS_AFTER_ATTRIBUTE_VALUE;
break mainSwitchLabel;
case '&':
attributeValue.append(buffer, startPosition, i - startPosition);
savedState = ATTRIBUTE_VALUE_QUOT;
state = ENTITY_REF;
startPosition = i + 1;
break mainSwitchLabel;
}
}
case ATTRIBUTE_VALUE_APOS:
while (true) {
switch (buffer[++i]) {
case '\'':
attributeValue.append(buffer, startPosition, i - startPosition);
state = WS_AFTER_ATTRIBUTE_VALUE;
break mainSwitchLabel;
case '&':
attributeValue.append(buffer, startPosition, i - startPosition);
savedState = ATTRIBUTE_VALUE_APOS;
state = ENTITY_REF;
startPosition = i + 1;
break mainSwitchLabel;
}
}
case ENTITY_REF:
while (true) {
switch (buffer[++i]) {
case ';':
entityName.append(buffer, startPosition, i - startPosition);
state = savedState;
startPosition = i + 1;
final char[] value = getEntityValue(entityMap, convertToString(strings, entityName));
if ((value != null) && (value.length != 0)) {
switch (state) {
case ATTRIBUTE_VALUE_QUOT:
case ATTRIBUTE_VALUE_APOS:
attributeValue.append(value, 0, value.length);
break;
case ATTRIBUTE_NAME:
attributeName.append(value, 0, value.length);
break;
case START_TAG:
//case END_TAG:
tagName.append(value, 0, value.length);
break;
case TEXT:
xmlReader.characterDataHandler(value, 0, value.length);
break;
}
}
break mainSwitchLabel;
}
}
case SLASH:
while (true) {
switch (buffer[++i]) {
case '>':
state = TEXT;
startPosition = i + 1;
break mainSwitchLabel;
}
}
case END_TAG:
while (true) {
switch (buffer[++i]) {
case '>':
//tagName.append(buffer, startPosition, i - startPosition);
if (tagStackSize > 0) {
if (processNamespaces &&
(namespaceMapStack.remove(tagStackSize - 1) != null)) {
for (int j = namespaceMapStack.size() - 1; j >= 0; --j) {
HashMap<String,String> element = namespaceMapStack.get(j);
if (element != null) {
oldNamespaceMap = element;
currentNamespaceMap = oldNamespaceMap;
break;
}
}
}
if (processEndTag(xmlReader, tagStack[--tagStackSize], currentNamespaceMap)) {
streamReader.close();
return;
}
currentNamespaceMap = null;
}
//processEndTag(xmlReader, convertToString(strings, tagName), currentNamespaceMap);
state = TEXT;
startPosition = i + 1;
break mainSwitchLabel;
//case '&':
//tagName.append(buffer, startPosition, i - startPosition);
//savedState = END_TAG;
//state = ENTITY_REF;
//startPosition = i + 1;
//break mainSwitchLabel;
//case 0x0008:
//case 0x0009:
//case 0x000A:
//case 0x000B:
//case 0x000C:
//case 0x000D:
//case ' ':
//tagName.append(buffer, startPosition, i - startPosition);
//state = WS_AFTER_END_TAG_NAME;
//break mainSwitchLabel;
}
}
/*
case WS_AFTER_END_TAG_NAME:
while (true) {
switch (buffer[++i]) {
case '>':
state = TEXT;
if (tagStackSize > 0) {
processEndTag(xmlReader, tagStack[--tagStackSize], currentNamespaceMap);
}
//processEndTag(xmlReader, convertToString(strings, tagName), currentNamespaceMap);
startPosition = i + 1;
break mainSwitchLabel;
}
}
*/
case TEXT:
while (true) {
switch (buffer[++i]) {
case '<':
if (i > startPosition) {
xmlReader.characterDataHandlerFinal(buffer, startPosition, i - startPosition);
}
state = LANGLE;
break mainSwitchLabel;
case '&':
if (i > startPosition) {
xmlReader.characterDataHandler(buffer, startPosition, i - startPosition);
}
savedState = TEXT;
state = ENTITY_REF;
startPosition = i + 1;
break mainSwitchLabel;
}
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
if (count > startPosition) {
switch (state) {
case START_TAG:
//case END_TAG:
tagName.append(buffer, startPosition, count - startPosition);
break;
case ATTRIBUTE_NAME:
attributeName.append(buffer, startPosition, count - startPosition);
break;
case ATTRIBUTE_VALUE_QUOT:
case ATTRIBUTE_VALUE_APOS:
attributeValue.append(buffer, startPosition, count - startPosition);
break;
case ENTITY_REF:
entityName.append(buffer, startPosition, count - startPosition);
break;
case CDATA:
case END_OF_CDATA1:
case END_OF_CDATA2:
cData.append(buffer, startPosition, count - startPosition);
break;
case TEXT:
xmlReader.characterDataHandler(buffer, startPosition, count - startPosition);
break;
}
}
}
}
}
private static boolean processFullTag(ZLXMLReader xmlReader, String tagName, ZLStringMap attributes) {
if (xmlReader.startElementHandler(tagName, attributes)) {
return true;
}
if (xmlReader.endElementHandler(tagName)) {
return true;
}
attributes.clear();
return false;
}
private static boolean processStartTag(ZLXMLReader xmlReader, String tagName, ZLStringMap attributes, HashMap<String,String> currentNamespaceMap) {
if (currentNamespaceMap != null) {
xmlReader.namespaceMapChangedHandler(currentNamespaceMap);
}
if (xmlReader.startElementHandler(tagName, attributes)) {
return true;
}
attributes.clear();
return false;
}
private static boolean processEndTag(ZLXMLReader xmlReader, String tagName, HashMap<String,String> currentNamespaceMap) {
final boolean result = xmlReader.endElementHandler(tagName);
if (currentNamespaceMap != null) {
xmlReader.namespaceMapChangedHandler(currentNamespaceMap);
}
return result;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLXMLParser.java
|
Java
|
asf20
| 23,641
|
package com.zz.normal.framework.resource;
public abstract class ZLArrayUtils {
public static boolean[] createCopy(boolean[] array, int dataSize, int newLength) {
boolean[] newArray = new boolean[newLength];
if (dataSize > 0) {
System.arraycopy(array, 0, newArray, 0, dataSize);
}
return newArray;
}
public static byte[] createCopy(byte[] array, int dataSize, int newLength) {
byte[] newArray = new byte[newLength];
if (dataSize > 0) {
System.arraycopy(array, 0, newArray, 0, dataSize);
}
return newArray;
}
public static char[] createCopy(char[] array, int dataSize, int newLength) {
char[] newArray = new char[newLength];
if (dataSize > 0) {
System.arraycopy(array, 0, newArray, 0, dataSize);
}
return newArray;
}
public static int[] createCopy(int[] array, int dataSize, int newLength) {
int[] newArray = new int[newLength];
if (dataSize > 0) {
System.arraycopy(array, 0, newArray, 0, dataSize);
}
return newArray;
}
public static String[] createCopy(String[] array, int dataSize, int newLength) {
String[] newArray = new String[newLength];
if (dataSize > 0) {
System.arraycopy(array, 0, newArray, 0, dataSize);
}
return newArray;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLArrayUtils.java
|
Java
|
asf20
| 1,207
|
package com.zz.normal.framework.resource;
import java.util.ArrayList;
import java.util.HashMap;
final class ZLTreeResource extends ZLResource {
static ZLTreeResource ourRoot;
private static long ourTimeStamp = 0;
private static String ourLanguage = null;
private static String ourCountry = null;
private boolean myHasValue;
private String myValue;
private HashMap<String,ZLTreeResource> myChildren;
public static void buildTree() {
if (ourRoot == null) {
ourRoot = new ZLTreeResource("", null);
ourLanguage = "zh";
ourCountry = "CN";
loadData();
}
}
private static void updateLanguage() {
// final long timeStamp = System.currentTimeMillis();
// if (timeStamp > ourTimeStamp + 1000) {
// synchronized (ourRoot) {
// if (timeStamp > ourTimeStamp + 1000) {
// ourTimeStamp = timeStamp;
// final String language = Locale.getDefault().getLanguage();
// final String country = Locale.getDefault().getCountry();
// if ((language != null && !language.equals(ourLanguage)) ||
// (country != null && !country.equals(ourCountry))) {
// ourLanguage = language;
// ourCountry = country;
// loadData();
// }
// }
// }
// }
}
private static void loadData(ResourceTreeReader reader, String fileName) {
reader.readDocument(ourRoot, ZLResourceFile.createResourceFile("resources/" + fileName));
}
private static void loadData() {
ResourceTreeReader reader = new ResourceTreeReader();
loadData(reader, ourLanguage + ".xml");
loadData(reader, ourLanguage + "_" + ourCountry + ".xml");
}
private ZLTreeResource(String name, String value) {
super(name);
setValue(value);
}
private void setValue(String value) {
myHasValue = value != null;
myValue = value;
}
public boolean hasValue() {
return myHasValue;
}
public String getValue() {
updateLanguage();
return myHasValue ? myValue : ZLMissingResource.Value;
}
public ZLResource getResource(String key) {
final HashMap<String,ZLTreeResource> children = myChildren;
if (children != null) {
ZLTreeResource child = children.get(key);
if (child != null) {
return child;
}
}
return ZLMissingResource.Instance;
}
private static class ResourceTreeReader extends ZLXMLReaderAdapter {
private static final String NODE = "node";
private final ArrayList<ZLTreeResource> myStack = new ArrayList<ZLTreeResource>();
public void readDocument(ZLTreeResource root, ZLFile file) {
myStack.clear();
myStack.add(root);
read(file);
}
@Override
public boolean dontCacheAttributeValues() {
return true;
}
@Override
public boolean startElementHandler(String tag, ZLStringMap attributes) {
final ArrayList<ZLTreeResource> stack = myStack;
if (!stack.isEmpty() && (NODE.equals(tag))) {
String name = attributes.getValue("name");
if (name != null) {
String value = attributes.getValue("value");
ZLTreeResource peek = stack.get(stack.size() - 1);
ZLTreeResource node;
HashMap<String,ZLTreeResource> children = peek.myChildren;
if (children == null) {
node = null;
children = new HashMap<String,ZLTreeResource>();
peek.myChildren = children;
} else {
node = children.get(name);
}
if (node == null) {
node = new ZLTreeResource(name, value);
children.put(name, node);
} else {
if (value != null) {
node.setValue(value);
}
}
stack.add(node);
}
}
return false;
}
@Override
public boolean endElementHandler(String tag) {
final ArrayList<ZLTreeResource> stack = myStack;
if (!stack.isEmpty() && (NODE.equals(tag))) {
stack.remove(stack.size() - 1);
}
return false;
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLTreeResource.java
|
Java
|
asf20
| 3,778
|
package com.zz.normal.framework.resource;
final class ZLMissingResource extends ZLResource {
static final String Value = "server error";
static final ZLMissingResource Instance = new ZLMissingResource();
private ZLMissingResource() {
super(Value);
}
public ZLResource getResource(String key) {
return this;
}
public boolean hasValue() {
return false;
}
public String getValue() {
return Value;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLMissingResource.java
|
Java
|
asf20
| 421
|
package com.zz.normal.framework.resource;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class ZLXMLReaderAdapter implements ZLXMLReader {
private Map<String,String> myNamespaceMap = Collections.emptyMap();
public boolean read(ZLFile file) {
return ZLXMLProcessor.read(this, file);
}
public boolean read(InputStream stream) {
return ZLXMLProcessor.read(this, stream, 65536);
}
public boolean dontCacheAttributeValues() {
return false;
}
public boolean startElementHandler(String tag, ZLStringMap attributes) {
return false;
}
public boolean endElementHandler(String tag) {
return false;
}
public void characterDataHandler(char[] ch, int start, int length) {
}
public void characterDataHandlerFinal(char[] ch, int start, int length) {
characterDataHandler(ch, start, length);
}
public void startDocumentHandler() {
}
public void endDocumentHandler() {
}
public boolean processNamespaces() {
return false;
}
public void namespaceMapChangedHandler(Map<String,String> namespaces) {
myNamespaceMap = namespaces != null ? namespaces : Collections.<String,String>emptyMap();
}
public String getAttributeValue(ZLStringMap attributes, String namespace, String name) {
if (namespace == null) {
return attributes.getValue(name);
}
final int size = attributes.getSize();
if (size == 0) {
return null;
}
final String postfix = ":" + name;
for (int i = size - 1; i >= 0; --i) {
final String key = attributes.getKey(i);
if (key.endsWith(postfix)) {
final String nsKey = key.substring(0, key.length() - postfix.length());
if (namespace.equals(myNamespaceMap.get(nsKey))) {
return attributes.getValue(i);
}
}
}
return null;
}
interface Predicate {
boolean accepts(String namespace);
}
protected String getAttributeValue(ZLStringMap attributes, Predicate predicate, String name) {
final int size = attributes.getSize();
if (size == 0) {
return null;
}
final String postfix = ":" + name;
for (int i = size - 1; i >= 0; --i) {
final String key = attributes.getKey(i);
if (key.endsWith(postfix)) {
final String ns =
myNamespaceMap.get(key.substring(0, key.length() - postfix.length()));
if (ns != null && predicate.accepts(ns)) {
return attributes.getValue(i);
}
}
}
return null;
}
public void addExternalEntities(HashMap<String,char[]> entityMap) {
}
public List<String> externalDTDs() {
return Collections.emptyList();
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLXMLReaderAdapter.java
|
Java
|
asf20
| 2,580
|
package com.zz.normal.framework.resource;
abstract public class ZLResource {
public final String Name;
public static ZLResource resource(String key) {
ZLTreeResource.buildTree();
if (ZLTreeResource.ourRoot == null) {
return ZLMissingResource.Instance;
}
return ZLTreeResource.ourRoot.getResource(key);
}
protected ZLResource(String name) {
Name = name;
}
abstract public boolean hasValue();
abstract public String getValue();
abstract public ZLResource getResource(String key);
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLResource.java
|
Java
|
asf20
| 506
|
package com.zz.normal.framework.resource;
import java.util.*;
public interface ZLXMLReader {
public boolean dontCacheAttributeValues();
public void startDocumentHandler();
public void endDocumentHandler();
// returns true iff xml processing should be interrupted
public boolean startElementHandler(String tag, ZLStringMap attributes);
public boolean endElementHandler(String tag);
public void characterDataHandler(char[] ch, int start, int length);
public void characterDataHandlerFinal(char[] ch, int start, int length);
boolean processNamespaces();
void namespaceMapChangedHandler(Map<String,String> namespaces);
void addExternalEntities(HashMap<String,char[]> entityMap);
List<String> externalDTDs();
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLXMLReader.java
|
Java
|
asf20
| 724
|
package com.zz.normal.framework.resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import android.app.Application;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
public final class ZLAndroidLibrary extends ZLibrary {
private final Application myApplication;
public ZLAndroidLibrary(Application application) {
myApplication = application;
}
@Override
public ZLResourceFile createResourceFile(String path) {
return new AndroidAssetsFile(path);
}
@Override
public ZLResourceFile createResourceFile(ZLResourceFile parent, String name) {
return new AndroidAssetsFile((AndroidAssetsFile)parent, name);
}
@Override
public String getVersionName() {
try {
return myApplication.getPackageManager().getPackageInfo(myApplication.getPackageName(), 0).versionName;
} catch (Exception e) {
return "";
}
}
@Override
public String getCurrentTimeString() {
return DateFormat.getTimeFormat(myApplication.getApplicationContext()).format(new Date());
}
@Override
public Collection<String> defaultLanguageCodes() {
final TreeSet<String> set = new TreeSet<String>();
set.add(Locale.getDefault().getLanguage());
final TelephonyManager manager = (TelephonyManager)myApplication.getSystemService(Context.TELEPHONY_SERVICE);
if (manager != null) {
final String country0 = manager.getSimCountryIso().toLowerCase();
final String country1 = manager.getNetworkCountryIso().toLowerCase();
for (Locale locale : Locale.getAvailableLocales()) {
final String country = locale.getCountry().toLowerCase();
if (country != null && country.length() > 0 &&
(country.equals(country0) || country.equals(country1))) {
set.add(locale.getLanguage());
}
}
if ("ru".equals(country0) || "ru".equals(country1)) {
set.add("ru");
} else if ("by".equals(country0) || "by".equals(country1)) {
set.add("ru");
} else if ("ua".equals(country0) || "ua".equals(country1)) {
set.add("ru");
}
}
set.add("multi");
return set;
}
private final class AndroidAssetsFile extends ZLResourceFile {
private final AndroidAssetsFile myParent;
AndroidAssetsFile(AndroidAssetsFile parent, String name) {
super(parent.getPath().length() == 0 ? name : parent.getPath() + '/' + name);
myParent = parent;
}
AndroidAssetsFile(String path) {
super(path);
if (path.length() == 0) {
myParent = null;
} else {
final int index = path.lastIndexOf('/');
myParent = new AndroidAssetsFile(index >= 0 ? path.substring(0, path.lastIndexOf('/')) : "");
}
}
@Override
protected List<ZLFile> directoryEntries() {
try {
String[] names = myApplication.getAssets().list(getPath());
if (names != null && names.length != 0) {
ArrayList<ZLFile> files = new ArrayList<ZLFile>(names.length);
for (String n : names) {
files.add(new AndroidAssetsFile(this, n));
}
return files;
}
} catch (IOException e) {
}
return Collections.emptyList();
}
@Override
public boolean isDirectory() {
try {
InputStream stream = myApplication.getAssets().open(getPath());
if (stream == null) {
return true;
}
stream.close();
return false;
} catch (IOException e) {
return true;
}
}
@Override
public boolean exists() {
try {
InputStream stream = myApplication.getAssets().open(getPath());
if (stream != null) {
stream.close();
// file exists
return true;
}
} catch (IOException e) {
}
try {
String[] names = myApplication.getAssets().list(getPath());
if (names != null && names.length != 0) {
// directory exists
return true;
}
} catch (IOException e) {
}
return false;
}
@Override
public long size() {
try {
// TODO: for some files (archives, crt) descriptor cannot be opened
AssetFileDescriptor descriptor = myApplication.getAssets().openFd(getPath());
if (descriptor == null) {
return 0;
}
long length = descriptor.getLength();
descriptor.close();
return length;
} catch (IOException e) {
return 0;
}
}
@Override
public InputStream getInputStream() throws IOException {
return myApplication.getAssets().open(getPath());
}
@Override
public ZLFile getParent() {
return myParent;
}
}
@Override
public void setScreenBrightness(int percent) {
// TODO Auto-generated method stub
}
@Override
public int getScreenBrightness() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getDisplayDPI() {
// TODO Auto-generated method stub
return 0;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLAndroidLibrary.java
|
Java
|
asf20
| 4,896
|
package com.zz.normal.framework.resource;
import java.util.Collections;
import java.util.List;
public abstract class ZLArchiveEntryFile extends ZLFile {
public static String normalizeEntryName(String entryName) {
while (entryName.startsWith("./")) {
entryName = entryName.substring(2);
}
while (true) {
final int index = entryName.lastIndexOf("/./");
if (index == -1) {
break;
}
entryName = entryName.substring(0, index) + entryName.substring(index + 2);
}
while (true) {
final int index = entryName.indexOf("/../");
if (index <= 0) {
break;
}
final int prevIndex = entryName.lastIndexOf('/', index - 1);
if (prevIndex == -1) {
entryName = entryName.substring(index + 4);
break;
}
entryName = entryName.substring(0, prevIndex) + entryName.substring(index + 3);
}
return entryName;
}
public static ZLArchiveEntryFile createArchiveEntryFile(ZLFile archive, String entryName) {
if (archive == null) {
return null;
}
entryName = normalizeEntryName(entryName);
switch (archive.myArchiveType & ArchiveType.ARCHIVE) {
default:
return null;
}
}
static List<ZLFile> archiveEntries(ZLFile archive) {
switch (archive.myArchiveType & ArchiveType.ARCHIVE) {
default:
return Collections.emptyList();
}
}
protected final ZLFile myParent;
protected final String myName;
protected ZLArchiveEntryFile(ZLFile parent, String name) {
myParent = parent;
myName = name;
init();
}
@Override
public boolean exists() {
return myParent.exists();
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public String getPath() {
return myParent.getPath() + ":" + myName;
}
@Override
public String getLongName() {
return myName;
}
@Override
public ZLFile getParent() {
return myParent;
}
@Override
public ZLPhysicalFile getPhysicalFile() {
ZLFile ancestor = myParent;
while ((ancestor != null) && !(ancestor instanceof ZLPhysicalFile)) {
ancestor = ancestor.getParent();
}
return (ZLPhysicalFile)ancestor;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLArchiveEntryFile.java
|
Java
|
asf20
| 2,064
|
package com.zz.normal.framework.resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public abstract class ZLXMLProcessor {
public static Map<String,char[]> getEntityMap(List<String> dtdList) {
try {
return ZLXMLParser.getDTDMap(dtdList);
} catch (IOException e) {
return Collections.emptyMap();
}
}
public static boolean read(ZLXMLReader reader, InputStream stream, int bufferSize) {
ZLXMLParser parser = null;
try {
parser = new ZLXMLParser(reader, stream, bufferSize);
reader.startDocumentHandler();
parser.doIt();
reader.endDocumentHandler();
} catch (IOException e) {
//System.out.println(e);
return false;
} finally {
if (parser != null) {
parser.finish();
}
}
return true;
}
public static boolean read(ZLXMLReader xmlReader, ZLFile file) {
return read(xmlReader, file, 65536);
}
public static boolean read(ZLXMLReader xmlReader, ZLFile file, int bufferSize) {
InputStream stream = null;
try {
stream = file.getInputStream();
} catch (IOException e) {
}
if (stream == null) {
return false;
}
boolean code = read(xmlReader, stream, bufferSize);
try {
stream.close();
} catch (IOException e) {
}
return code;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLXMLProcessor.java
|
Java
|
asf20
| 1,304
|
package com.zz.normal.framework.resource;
// optimized partially implemented map String -> String
// key must be interned
// there is no remove() in this implementation
// put with the same key does not remove old entry
public final class ZLStringMap {
private String[] myKeys;
private String[] myValues;
private int mySize;
public ZLStringMap() {
myKeys = new String[8];
myValues = new String[8];
}
public void put(String key, String value) {
final int size = mySize++;
String[] keys = myKeys;
if (keys.length == size) {
keys = ZLArrayUtils.createCopy(keys, size, size << 1);
myKeys = keys;
myValues = ZLArrayUtils.createCopy(myValues, size, size << 1);
}
keys[size] = key;
myValues[size] = value;
}
/*
* Parameter `key` must be an interned string.
*/
public String getValue(String key) {
int index = mySize;
if (index > 0) {
final String[] keys = myKeys;
while (--index >= 0) {
if (keys[index] == key) {
return myValues[index];
}
}
}
return null;
}
public int getSize() {
return mySize;
}
public String getKey(int index) {
return myKeys[index];
}
String getValue(int index) {
return myValues[index];
}
public void clear() {
mySize = 0;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLStringMap.java
|
Java
|
asf20
| 1,237
|
package com.zz.normal.framework.resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public abstract class ZLFile {
private static final String TAG = "ZLFile";
private final static HashMap<String,ZLFile> ourCachedFiles = new HashMap<String,ZLFile>();
protected interface ArchiveType {
int NONE = 0;
int GZIP = 0x0001;
int BZIP2 = 0x0002;
int COMPRESSED = 0x00ff;
int ZIP = 0x0100;
int TAR = 0x0200;
int ARCHIVE = 0xff00;
};
private String myExtension;
private String myShortName;
protected int myArchiveType;
private boolean myIsCached;
protected void init() {
final String name = getLongName();
final int index = name.lastIndexOf('.');
myExtension = (index > 0) ? name.substring(index + 1).toLowerCase().intern() : "";
myShortName = name.substring(name.lastIndexOf('/') + 1);
int archiveType = ArchiveType.NONE;
if (myExtension == "zip") {
archiveType |= ArchiveType.ZIP;
} else if (myExtension == "oebzip") {
archiveType |= ArchiveType.ZIP;
} else if (myExtension == "epub") {
archiveType |= ArchiveType.ZIP;
} else if (myExtension == "tar") {
archiveType |= ArchiveType.TAR;
//} else if (lowerCaseName.endsWith(".tgz")) {
//nothing to-do myNameWithoutExtension = myNameWithoutExtension.substr(0, myNameWithoutExtension.length() - 3) + "tar";
//myArchiveType = myArchiveType | ArchiveType.TAR | ArchiveType.GZIP;
}else if (myExtension == "txt") {
archiveType |= ArchiveType.ARCHIVE;
}
myArchiveType = archiveType;
}
public static ZLFile createFile(ZLFile parent, String name) {
ZLFile file = null;
if (parent == null) {
ZLFile cached = ourCachedFiles.get(name);
if (cached != null) {
return cached;
}
if (!name.startsWith("/")) {
return ZLResourceFile.createResourceFile(name);
} else {
return new ZLPhysicalFile(name);
}
} else if ((parent instanceof ZLPhysicalFile) && (parent.getParent() == null)) {
// parent is a directory
file = new ZLPhysicalFile(parent.getPath() + '/' + name);
} else if (parent instanceof ZLResourceFile) {
file = ZLResourceFile.createResourceFile((ZLResourceFile)parent, name);
} else {
file = ZLArchiveEntryFile.createArchiveEntryFile(parent, name);
}
if (!ourCachedFiles.isEmpty() && (file != null)) {
ZLFile cached = ourCachedFiles.get(file.getPath());
if (cached != null) {
return cached;
}
}
return file;
}
public static ZLFile createFileByPath(String path) {
if (path == null) {
return null;
}
ZLFile cached = ourCachedFiles.get(path);
if (cached != null) {
return cached;
}
if (!path.startsWith("/")) {
return ZLResourceFile.createResourceFile(path);
}
int index = path.lastIndexOf(':');
if (index > 1) {
return ZLArchiveEntryFile.createArchiveEntryFile(
createFileByPath(path.substring(0, index)), path.substring(index + 1)
);
}
return new ZLPhysicalFile(path);
}
public abstract long size();
public abstract boolean exists();
public abstract boolean isDirectory();
public abstract String getPath();
public abstract ZLFile getParent();
public abstract ZLPhysicalFile getPhysicalFile();
public abstract InputStream getInputStream() throws IOException;
public boolean isReadable() {
return true;
}
public final boolean isCompressed() {
return (0 != (myArchiveType & ArchiveType.COMPRESSED));
}
public final boolean isArchive() {
return (0 != (myArchiveType & ArchiveType.ARCHIVE));
}
public abstract String getLongName();
public final String getShortName() {
return myShortName;
}
public final String getExtension() {
return myExtension;
}
protected List<ZLFile> directoryEntries() {
return Collections.emptyList();
}
public final List<ZLFile> children() {
if (exists()) {
if (isDirectory()) {
return directoryEntries();
} else if (isArchive()) {
return ZLArchiveEntryFile.archiveEntries(this);
}
}
return Collections.emptyList();
}
@Override
public int hashCode() {
return getPath().hashCode();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof ZLFile)) {
return false;
}
return getPath().equals(((ZLFile)o).getPath());
}
protected boolean isCached() {
return myIsCached;
}
public void setCached(boolean cached) {
myIsCached = cached;
if (cached) {
ourCachedFiles.put(getPath(), this);
} else {
ourCachedFiles.remove(getPath());
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLFile.java
|
Java
|
asf20
| 4,528
|
package com.zz.normal.framework.resource;
final class ZLMutableString {
char[] myData;
int myLength;
ZLMutableString(int len) {
myData = new char[len];
}
ZLMutableString() {
this(20);
}
ZLMutableString(ZLMutableString container) {
final int len = container.myLength;
myData = ZLArrayUtils.createCopy(container.myData, len, len);
myLength = len;
}
public void append(char[] buffer, int offset, int count) {
final int len = myLength;
char[] data = myData;
final int newLength = len + count;
if (data.length < newLength) {
data = ZLArrayUtils.createCopy(data, len, newLength);
myData = data;
}
System.arraycopy(buffer, offset, data, len, count);
myLength = newLength;
}
public void clear() {
myLength = 0;
}
public boolean equals(Object o) {
final ZLMutableString container = (ZLMutableString)o;
final int len = myLength;
if (len != container.myLength) {
return false;
}
final char[] data0 = myData;
final char[] data1 = container.myData;
for (int i = len; --i >= 0; ) {
if (data0[i] != data1[i]) {
return false;
}
}
return true;
}
public int hashCode() {
final int len = myLength;
final char[] data = myData;
int code = len * 31;
if (len > 1) {
code += data[0];
code *= 31;
code += data[1];
if (len > 2) {
code *= 31;
code += data[2];
}
} else if (len > 0) {
code += data[0];
}
return code;
}
public String toString() {
return new String(myData, 0, myLength).intern();
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLMutableString.java
|
Java
|
asf20
| 1,504
|
package com.zz.normal.framework.resource;
import java.util.Collection;
public abstract class ZLibrary {
public static ZLibrary Instance() {
return ourImplementation;
}
private static ZLibrary ourImplementation;
protected ZLibrary() {
ourImplementation = this;
}
abstract public ZLResourceFile createResourceFile(String path);
abstract public ZLResourceFile createResourceFile(ZLResourceFile parent, String name);
abstract public String getVersionName();
abstract public String getCurrentTimeString();
abstract public void setScreenBrightness(int percent);
abstract public int getScreenBrightness();
abstract public int getDisplayDPI();
abstract public Collection<String> defaultLanguageCodes();
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLibrary.java
|
Java
|
asf20
| 722
|
package com.zz.normal.framework.resource;
import java.util.*;
import java.io.*;
public final class ZLPhysicalFile extends ZLFile {
private final File myFile;
ZLPhysicalFile(String path) {
this(new File(path));
}
public ZLPhysicalFile(File file) {
myFile = file;
init();
}
@Override
public boolean exists() {
return myFile.exists();
}
@Override
public long size() {
return myFile.length();
}
@Override
public boolean isDirectory() {
return myFile.isDirectory();
}
@Override
public boolean isReadable() {
return myFile.canRead();
}
public boolean delete() {
return myFile.delete();
}
@Override
public String getPath() {
return myFile.getPath();
}
@Override
public String getLongName() {
return isDirectory() ? getPath() : myFile.getName();
}
@Override
public ZLFile getParent() {
return isDirectory() ? null : new ZLPhysicalFile(myFile.getParent());
}
@Override
public ZLPhysicalFile getPhysicalFile() {
return this;
}
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(myFile);
}
protected List<ZLFile> directoryEntries() {
File[] subFiles = myFile.listFiles();
if ((subFiles == null) || (subFiles.length == 0)) {
return Collections.emptyList();
}
ArrayList<ZLFile> entries = new ArrayList<ZLFile>(subFiles.length);
for (File f : subFiles) {
if (!f.getName().startsWith(".")) {
entries.add(new ZLPhysicalFile(f));
}
}
return entries;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/framework/resource/ZLPhysicalFile.java
|
Java
|
asf20
| 1,487
|
package com.zz.normal.util;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.view.Window;
import android.view.WindowManager;
import com.zz.normal.util.callback.AsyncCallable;
import com.zz.normal.util.callback.Callable;
import com.zz.normal.util.callback.Callback;
import com.zz.normal.util.callback.CancelledException;
import com.zz.normal.util.callback.IProgressListener;
import com.zz.normal.util.callback.ProgressCallable;
import com.zz.normal.util.log.Mylog;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:11:54 - 07.03.2011
*/
public class ActivityUtils {
public static void requestFullscreen(final Activity pActivity) {
final Window window = pActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.requestFeature(Window.FEATURE_NO_TITLE);
}
/**
* @param pActivity
* @param pScreenBrightness [0..1]
*/
public static void setScreenBrightness(final Activity pActivity, final float pScreenBrightness) {
final Window window = pActivity.getWindow();
final WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.screenBrightness = pScreenBrightness;
window.setAttributes(windowLayoutParams);
}
public static void keepScreenOn(final Activity pActivity) {
pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public static <T> void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitleResourceID, pMessageResourceID, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitleResourceID, pMessageResourceID, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitleResourceID, pMessageResourceID, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pContext.getString(pTitleResourceID), pContext.getString(pMessageResourceID), pCallable, pCallback, pExceptionCallback, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
new AsyncTask<Void, Void, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable);
if(pCancelable) {
this.mPD.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(final DialogInterface pDialogInterface) {
pExceptionCallback.onCallback(new CancelledException());
pDialogInterface.dismiss();
}
});
}
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call();
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Mylog.e("Error", e);
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Mylog.e("Error", this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResourceID, final int pIconResourceID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doProgressAsync(pContext, pTitleResourceID, pIconResourceID, pCallable, pCallback, null);
}
public static <T> void doProgressAsync(final Context pContext, final CharSequence pTitle, final int pIconResourceID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doProgressAsync(pContext, pTitle, pIconResourceID, pCallable, pCallback, null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResourceID, final int pIconResourceID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doProgressAsync(pContext, pContext.getString(pTitleResourceID), pIconResourceID, pCallable, pCallback, pExceptionCallback);
}
public static <T> void doProgressAsync(final Context pContext, final CharSequence pTitle, final int pIconResourceID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
new AsyncTask<Void, Integer, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = new ProgressDialog(pContext);
this.mPD.setTitle(pTitle);
this.mPD.setIcon(pIconResourceID);
this.mPD.setIndeterminate(false);
this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mPD.show();
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call(new IProgressListener() {
@Override
public void onProgressChanged(final int pProgress) {
onProgressUpdate(pProgress);
}
});
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onProgressUpdate(final Integer... values) {
this.mPD.setProgress(values[0]);
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Mylog.e("Error", e);
/* Nothing. */
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Mylog.e("Error" ,this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pContext.getString(pTitleResourceID), pContext.getString(pMessageResourceID), pAsyncCallable, pCallback, pExceptionCallback);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
final ProgressDialog pd = ProgressDialog.show(pContext, pTitle, pMessage);
pAsyncCallable.call(new Callback<T>() {
@Override
public void onCallback(final T result) {
try {
pd.dismiss();
} catch (final Exception e) {
Mylog.e("Error", e);
/* Nothing. */
}
pCallback.onCallback(result);
}
}, pExceptionCallback);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/ActivityUtils.java
|
Java
|
asf20
| 9,272
|
package com.zz.normal.util;
import java.security.MessageDigest;
public final class Md5Token {
private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static Md5Token instance = null;
private Md5Token() {
}
public synchronized static Md5Token getInstance() {
if(instance==null){
instance=new Md5Token();
}
return instance;
}
public String getShortToken(String arg0) {
return encoder(arg0).substring(8,24);
}
public String getLongToken(String arg0) {
return encoder(arg0).toString();
}
private StringBuffer encoder(String arg){
if(arg==null){
arg="";
}
MessageDigest md5 = null;
try {
md5=MessageDigest.getInstance("MD5");
md5.update(arg.getBytes("utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
return toHex(md5.digest());
}
private StringBuffer toHex(byte[] bytes) {
StringBuffer str = new StringBuffer(32);
int length=bytes.length;
for (int i = 0; i < length; i++) {
str.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
str.append(hexDigits[bytes[i] & 0x0f]);
}
bytes=null;
return str;
}
public static void main(String a[]){
System.out.println(Md5Token.getInstance().getLongToken("123456")+"");
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/Md5Token.java
|
Java
|
asf20
| 1,310
|
package com.zz.normal.util;
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
* when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from
* one file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64 dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as described
* in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rob@iharder.net
* @version 2.2.1
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding. */
public final static int ENCODE = 1;
/** Specify decoding. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed. */
public final static int GZIP = 2;
/** Don't break lines when encoding (violates strict Base64 specification) */
public final static int DONT_BREAK_LINES = 8;
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/* ******** P R I V A T E F I E L D S ******** */
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "UTF-8";
// I think I end up not using the BAD_ENCODING indicator.
//private final static byte BAD_ENCODING = -9; // Indicates error in encoding
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
//private final static byte[] ALPHABET;
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET =
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET =
{
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET =
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET =
{
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET =
{
(byte)'-',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
(byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'_',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET =
{
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet( int options )
{
if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET;
else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET;
else return _STANDARD_ALPHABET;
} // end getAlphabet
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet( int options )
{
if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET;
else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET;
else return _STANDARD_DECODABET;
} // end getAlphabet
/** Defeats instantiation. */
private Base64(){}
/**
* Encodes or decodes two files from the command line;
* <strong>feel free to delete this method (in fact you probably should)
* if you're embedding this code into a larger program.</strong>
*/
public final static void main( String[] args )
{
if( args.length < 3 ){
usage("Not enough arguments.");
} // end if: args.length < 3
else {
String flag = args[0];
String infile = args[1];
String outfile = args[2];
if( flag.equals( "-e" ) ){
Base64.encodeFileToFile( infile, outfile );
} // end if: encode
else if( flag.equals( "-d" ) ) {
Base64.decodeFileToFile( infile, outfile );
} // end else if: decode
else {
usage( "Unknown flag: " + flag );
} // end else
} // end else
} // end main
/**
* Prints command line usage.
*
* @param msg A message to include with usage info.
*/
private final static void usage( String msg )
{
System.err.println( msg );
System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" );
} // end usage
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options )
{
encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
return b4;
} // end encode3to4
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options )
{
byte[] ALPHABET = getAlphabet( options );
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
{
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
{
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.io.ObjectOutputStream oos = null;
java.util.zip.GZIPOutputStream gzos = null;
// Isolate options
int gzip = (options & GZIP);
int dontBreakLines = (options & DONT_BREAK_LINES);
try
{
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
// GZip?
if( gzip == GZIP )
{
gzos = new java.util.zip.GZIPOutputStream( b64os );
oos = new java.io.ObjectOutputStream( gzos );
} // end if: gzip
else
oos = new java.io.ObjectOutputStream( b64os );
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
return null;
} // end catch
finally
{
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try
{
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @since 1.4
*/
public static String encodeBytes( byte[] source )
{
return encodeBytes( source, 0, source.length, NO_OPTIONS );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
*
* @param source The data to convert
* @param options Specified options
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options )
{
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len )
{
return encodeBytes( source, off, len, NO_OPTIONS );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options; alphabet type is pulled from this (standard, url-safe, ordered)
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options )
{
// Isolate options
int dontBreakLines = ( options & DONT_BREAK_LINES );
int gzip = ( options & GZIP );
// Compress?
if( gzip == GZIP )
{
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try
{
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
return null;
} // end catch
finally
{
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try
{
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( baos.toByteArray() );
} // end catch
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else
{
// Convert option to boolean in way that code likes it.
boolean breakLines = dontBreakLines == 0;
int len43 = len * 4 / 3;
byte[] outBuff = new byte[ ( len43 ) // Main 4:3
+ ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
+ (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 )
{
encode3to4( source, d+off, 3, outBuff, e, options );
lineLength += 4;
if( breakLines && lineLength == MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len )
{
encode3to4( source, d+off, len - d, outBuff, e, options );
e += 4;
} // end if: some padding needed
// Return value according to relevant encoding.
try
{
return new String( outBuff, 0, e, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( outBuff, 0, e );
} // end catch
} // end else: don't compress
} // end encodeBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options )
{
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else
{
try{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}catch( Exception e){
System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
return -1;
} // end catch
}
} // end decodeToBytes
/**
* Very low-level access to decoding ASCII characters in
* the form of a byte array. Does not support automatically
* gunzipping or any other "fancy" features.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @return decoded data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len, int options )
{
byte[] DECODABET = getDecodabet( options );
int len34 = len * 3 / 4;
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for( i = off; i < off+len; i++ )
{
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ];
if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
{
if( sbiDecode >= EQUALS_SIGN_ENC )
{
b4[ b4Posn++ ] = sbiCrop;
if( b4Posn > 3 )
{
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( sbiCrop == EQUALS_SIGN )
break;
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else
{
System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
return null;
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @since 1.4
*/
public static byte[] decode( String s )
{
return decode( s, NO_OPTIONS );
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @since 1.4
*/
public static byte[] decode( String s, int options )
{
byte[] bytes;
try
{
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee )
{
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length, options );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
if( bytes != null && bytes.length >= 4 )
{
int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
{
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try
{
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 )
{
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e )
{
// Just return originally-decoded bytes
} // end catch
finally
{
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
{
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try
{
bais = new java.io.ByteArrayInputStream( objBytes );
ois = new java.io.ObjectInputStream( bais );
obj = ois.readObject();
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
obj = null;
} // end catch
catch( java.lang.ClassNotFoundException e )
{
e.printStackTrace();
obj = null;
} // end catch
finally
{
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*
* @since 2.1
*/
public static boolean encodeToFile( byte[] dataToEncode, String filename )
{
boolean success = false;
Base64.OutputStream bos = null;
try
{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
success = true;
} // end try
catch( java.io.IOException e )
{
success = false;
} // end catch: IOException
finally
{
try{ bos.close(); } catch( Exception e ){}
} // end finally
return success;
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*
* @since 2.1
*/
public static boolean decodeToFile( String dataToDecode, String filename )
{
boolean success = false;
Base64.OutputStream bos = null;
try
{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
success = true;
} // end try
catch( java.io.IOException e )
{
success = false;
} // end catch: IOException
finally
{
try{ bos.close(); } catch( Exception e ){}
} // end finally
return success;
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* @param filename Filename for reading encoded data
* @return decoded byte array or null if unsuccessful
*
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
{
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
return null;
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
length += numBytes;
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e )
{
System.err.println( "Error decoding from file " + filename );
} // end catch: IOException
finally
{
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* @param filename Filename for reading binary data
* @return base64-encoded string or null if unsuccessful
*
* @since 2.1
*/
public static String encodeFromFile( String filename )
{
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
length += numBytes;
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e )
{
System.err.println( "Error encoding from file " + filename );
} // end catch: IOException
finally
{
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @since 2.2
*/
public static void encodeFileToFile( String infile, String outfile )
{
String encoded = Base64.encodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
} // end try
catch( java.io.IOException ex ) {
ex.printStackTrace();
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end encodeFileToFile
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @since 2.2
*/
public static void decodeFileToFile( String infile, String outfile )
{
byte[] decoded = Base64.decodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( decoded );
} // end try
catch( java.io.IOException ex ) {
ex.printStackTrace();
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end decodeFileToFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream
{
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] alphabet; // Local copies to avoid extra method calls
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in )
{
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options )
{
super( in );
this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
this.encode = (options & ENCODE) == ENCODE;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
this.options = options; // Record for later, mostly to determine which alphabet to use
this.alphabet = getAlphabet(options);
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
public int read() throws java.io.IOException
{
// Do we need to get data?
if( position < 0 )
{
if( encode )
{
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ )
{
try
{
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 )
{
b3[i] = (byte)b;
numBinaryBytes++;
} // end if: not end of stream
} // end try: read
catch( java.io.IOException e )
{
// Only a problem if we got no data at all.
if( i == 0 )
throw e;
} // end catch
} // end for: each needed input byte
if( numBinaryBytes > 0 )
{
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
numSigBytes = 4;
} // end if: got data
else
{
return -1;
} // end else
} // end if: encoding
// Else decoding
else
{
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ )
{
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 )
break; // Reads a -1 if end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 )
{
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else
{
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 )
{
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes )
return -1;
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
{
lineLength = 0;
return '\n';
} // end if
else
{
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength )
position = -1;
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else
{
// When JDK1.4 is more accepted, use an assertion here.
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
public int read( byte[] dest, int off, int len ) throws java.io.IOException
{
int i;
int b;
for( i = 0; i < len; i++ )
{
b = read();
//if( b < 0 && i == 0 )
// return -1;
if( b >= 0 )
dest[off + i] = (byte)b;
else if( i == 0 )
return -1;
else
break; // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream
{
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] alphabet; // Local copies to avoid extra method calls
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out )
{
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options )
{
super( out );
this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
this.encode = (options & ENCODE) == ENCODE;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.alphabet = getAlphabet(options);
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
public void write(int theByte) throws java.io.IOException
{
// Encoding suspended?
if( suspendEncoding )
{
super.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode )
{
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to encode.
{
out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else
{
// Meaningful Base64 character?
if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC )
{
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to output.
{
int len = Base64.decode4to3( buffer, 0, b4, 0, options );
out.write( b4, 0, len );
//out.write( Base64.decode4to3( buffer ) );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC )
{
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
{
// Encoding suspended?
if( suspendEncoding )
{
super.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ )
{
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
*/
public void flushBase64() throws java.io.IOException
{
if( position > 0 )
{
if( encode )
{
out.write( encode3to4( b4, buffer, position, options ) );
position = 0;
} // end if: encoding
else
{
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
public void close() throws java.io.IOException
{
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException
{
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding()
{
this.suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/Base64.java
|
Java
|
asf20
| 68,454
|
package com.zz.normal.util.callback;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:52:44 - 03.01.2010
*/
public interface Callable<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return the computed result.
* @throws Exception if unable to compute a result.
*/
public T call() throws Exception;
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/callback/Callable.java
|
Java
|
asf20
| 680
|
package com.zz.normal.util.callback;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:52:44 - 03.01.2010
*/
public interface ProgressCallable<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* Computes a result, or throws an exception if unable to do so.
* @param pProgressListener
* @return computed result
* @throws Exception if unable to compute a result
*/
public T call(final IProgressListener pProgressListener) throws Exception;
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/callback/ProgressCallable.java
|
Java
|
asf20
| 749
|
package com.zz.normal.util.callback;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:00:30 - 14.05.2010
* @param <T>
*/
public interface AsyncCallable<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* Computes a result asynchronously, return values and exceptions are to be handled through the callbacks.
* This method is expected to return almost immediately, after starting a {@link Thread} or similar.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
public void call(final Callback<T> pCallback, final Callback<Exception> pExceptionCallback);
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/callback/AsyncCallable.java
|
Java
|
asf20
| 896
|
package com.zz.normal.util.callback;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:07:35 - 09.07.2009
*/
public interface IProgressListener {
// ===========================================================
// Constants
// ===========================================================
public static final int PROGRESS_MIN = 0;
public static final int PROGRESS_MAX = 100;
// ===========================================================
// Methods
// ===========================================================
/**
* @param pProgress between 0 and 100.
*/
public void onProgressChanged(final int pProgress);
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/callback/IProgressListener.java
|
Java
|
asf20
| 678
|
package com.zz.normal.util.callback;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 09:40:55 - 14.12.2009
*/
public interface Callback<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onCallback(final T pCallbackValue);
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/callback/Callback.java
|
Java
|
asf20
| 528
|
package com.zz.normal.util.callback;
/**
* (c) Zynga 2012
*
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @since 16:33:53 - 23.04.2012
*/
public class CancelledException extends Exception {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -78123211381435596L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public CancelledException() {
super();
}
public CancelledException(final String pMessage) {
super(pMessage);
}
public CancelledException(final Throwable pThrowable) {
super(pThrowable);
}
public CancelledException(final String pMessage, final Throwable pThrowable) {
super(pMessage, pThrowable);
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/callback/CancelledException.java
|
Java
|
asf20
| 1,640
|
package com.zz.normal.util.image;
import com.zz.normal.framework.ZConfiguration;
public class Paths {
public static String networkCacheDirectory() {
return cacheDirectory() + "/cache";
}
public static String networkDirectory() {
return ZConfiguration.getInstance().getRootFolder();
}
public static String cacheDirectory() {
return networkDirectory() + "/image";
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/image/Paths.java
|
Java
|
asf20
| 406
|
package com.zz.normal.util.image;
public final class ZLAndroidImageManager extends ZLImageManager {
private static ZLAndroidImageManager instance;
public static ZLAndroidImageManager getInstance() {
if(null == instance){
instance = new ZLAndroidImageManager();
}
return instance;
}
public ZLAndroidImageData getImageData(ZLImage image) {
if (image instanceof ZLSingleImage) {
ZLSingleImage singleImage = (ZLSingleImage)image;
if ("image/palm".equals(singleImage.mimeType())) {
return null;
}
byte[] array = singleImage.byteData();
if (array == null) {
return null;
}
return new ZLAndroidImageData(array);
} else {
return null;
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/image/ZLAndroidImageManager.java
|
Java
|
asf20
| 696
|
package com.zz.normal.util.image;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import com.zz.normal.framework.ZConfiguration;
import com.zz.normal.util.log.Mylog;
public class ZLNetworkManager {
private static ZLNetworkManager ourManager;
public static ZLNetworkManager Instance() {
if (ourManager == null) {
ourManager = new ZLNetworkManager();
}
return ourManager;
}
public final String downloadToFile(String url, final File outFile) {
return downloadToFile(url, outFile, 8192);
}
public final String downloadToFile(String _url, final File outFile,final int bufferSize) {
HttpURLConnection httpConnection = null;
try {
Mylog.d("ZLNetworkManager", "begin download "+_url);
httpConnection = ZConfiguration.getInstance().getHttpURLConnection(_url,"GET","application/x-www-form-urlencoded","");
httpConnection.connect();
int response = httpConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConnection.getInputStream();
OutputStream outStream = new FileOutputStream(outFile);
try {
final byte[] buffer = new byte[bufferSize];
while (true) {
final int size = inputStream.read(buffer);
if (size <= 0) {
break;
}
outStream.write(buffer, 0, size);
}
} finally {
outStream.close();
inputStream.close();
}
Mylog.d("ZLNetworkManager", "success download "+_url);
}else{
Mylog.d("ZLNetworkManager", "fail download "+_url);
}
} catch (IOException e) {
return e.getMessage();
}
return null;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/image/ZLNetworkManager.java
|
Java
|
asf20
| 1,839
|
package com.zz.normal.util.image;
public interface ZLImage {
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/image/ZLImage.java
|
Java
|
asf20
| 67
|
package com.zz.normal.util.image;
public abstract class ZLSingleImage implements ZLImage {
private final String myMimeType;
public ZLSingleImage(final String mimeType) {
myMimeType = mimeType;
}
public abstract byte [] byteData();
public final String mimeType() {
return myMimeType;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/image/ZLSingleImage.java
|
Java
|
asf20
| 320
|
package com.zz.normal.util.image;
public abstract class ZLImageManager {
private static ZLImageManager ourInstance;
public static ZLImageManager Instance() {
return ourInstance;
}
protected ZLImageManager() {
ourInstance = this;
}
public abstract ZLImageData getImageData(ZLImage image);
/* protected final static class Color {
public final byte Red;
public final byte Green;
public final byte Blue;
public Color(final byte red, final byte green, final byte blue) {
Red = red;
Green = green;
Blue = blue;
}
}
*/
protected final static class PalmImageHeader {
public final int Width;
public final int Height;
public final int BytesPerRow;
public final int Flags;
public final byte BitsPerPixel;
public final byte CompressionType;
public PalmImageHeader(byte [] byteData) {
Width = uShort(byteData, 0);
Height = uShort(byteData, 2);
BytesPerRow = uShort(byteData, 4);
Flags = uShort(byteData, 6);
BitsPerPixel = byteData[8];
CompressionType = (byte) (((Flags & 0x8000) != 0) ? byteData[13] : 0xFF);
}
}
protected static int PalmImage8bitColormap[][] = {
{255, 255, 255 }, { 255, 204, 255 }, { 255, 153, 255 }, { 255, 102, 255 },
{ 255, 51, 255 }, { 255, 0, 255 }, { 255, 255, 204 }, { 255, 204, 204 },
{ 255, 153, 204 }, { 255, 102, 204 }, { 255, 51, 204 }, { 255, 0, 204 },
{ 255, 255, 153 }, { 255, 204, 153 }, { 255, 153, 153 }, { 255, 102, 153 },
{ 255, 51, 153 }, { 255, 0, 153 }, { 204, 255, 255 }, { 204, 204, 255 },
{ 204, 153, 255 }, { 204, 102, 255 }, { 204, 51, 255 }, { 204, 0, 255 },
{ 204, 255, 204 }, { 204, 204, 204 }, { 204, 153, 204 }, { 204, 102, 204 },
{ 204, 51, 204 }, { 204, 0, 204 }, { 204, 255, 153 }, { 204, 204, 153 },
{ 204, 153, 153 }, { 204, 102, 153 }, { 204, 51, 153 }, { 204, 0, 153 },
{ 153, 255, 255 }, { 153, 204, 255 }, { 153, 153, 255 }, { 153, 102, 255 },
{ 153, 51, 255 }, { 153, 0, 255 }, { 153, 255, 204 }, { 153, 204, 204 },
{ 153, 153, 204 }, { 153, 102, 204 }, { 153, 51, 204 }, { 153, 0, 204 },
{ 153, 255, 153 }, { 153, 204, 153 }, { 153, 153, 153 }, { 153, 102, 153 },
{ 153, 51, 153 }, { 153, 0, 153 }, { 102, 255, 255 }, { 102, 204, 255 },
{ 102, 153, 255 }, { 102, 102, 255 }, { 102, 51, 255 }, { 102, 0, 255 },
{ 102, 255, 204 }, { 102, 204, 204 }, { 102, 153, 204 }, { 102, 102, 204 },
{ 102, 51, 204 }, { 102, 0, 204 }, { 102, 255, 153 }, { 102, 204, 153 },
{ 102, 153, 153 }, { 102, 102, 153 }, { 102, 51, 153 }, { 102, 0, 153 },
{ 51, 255, 255 }, { 51, 204, 255 }, { 51, 153, 255 }, { 51, 102, 255 },
{ 51, 51, 255 }, { 51, 0, 255 }, { 51, 255, 204 }, { 51, 204, 204 },
{ 51, 153, 204 }, { 51, 102, 204 }, { 51, 51, 204 }, { 51, 0, 204 },
{ 51, 255, 153 }, { 51, 204, 153 }, { 51, 153, 153 }, { 51, 102, 153 },
{ 51, 51, 153 }, { 51, 0, 153 }, { 0, 255, 255 }, { 0, 204, 255 },
{ 0, 153, 255 }, { 0, 102, 255 }, { 0, 51, 255 }, { 0, 0, 255 },
{ 0, 255, 204 }, { 0, 204, 204 }, { 0, 153, 204 }, { 0, 102, 204 },
{ 0, 51, 204 }, { 0, 0, 204 }, { 0, 255, 153 }, { 0, 204, 153 },
{ 0, 153, 153 }, { 0, 102, 153 }, { 0, 51, 153 }, { 0, 0, 153 },
{ 255, 255, 102 }, { 255, 204, 102 }, { 255, 153, 102 }, { 255, 102, 102 },
{ 255, 51, 102 }, { 255, 0, 102 }, { 255, 255, 51 }, { 255, 204, 51 },
{ 255, 153, 51 }, { 255, 102, 51 }, { 255, 51, 51 }, { 255, 0, 51 },
{ 255, 255, 0 }, { 255, 204, 0 }, { 255, 153, 0 }, { 255, 102, 0 },
{ 255, 51, 0 }, { 255, 0, 0 }, { 204, 255, 102 }, { 204, 204, 102 },
{ 204, 153, 102 }, { 204, 102, 102 }, { 204, 51, 102 }, { 204, 0, 102 },
{ 204, 255, 51 }, { 204, 204, 51 }, { 204, 153, 51 }, { 204, 102, 51 },
{ 204, 51, 51 }, { 204, 0, 51 }, { 204, 255, 0 }, { 204, 204, 0 },
{ 204, 153, 0 }, { 204, 102, 0 }, { 204, 51, 0 }, { 204, 0, 0 },
{ 153, 255, 102 }, { 153, 204, 102 }, { 153, 153, 102 }, { 153, 102, 102 },
{ 153, 51, 102 }, { 153, 0, 102 }, { 153, 255, 51 }, { 153, 204, 51 },
{ 153, 153, 51 }, { 153, 102, 51 }, { 153, 51, 51 }, { 153, 0, 51 },
{ 153, 255, 0 }, { 153, 204, 0 }, { 153, 153, 0 }, { 153, 102, 0 },
{ 153, 51, 0 }, { 153, 0, 0 }, { 102, 255, 102 }, { 102, 204, 102 },
{ 102, 153, 102 }, { 102, 102, 102 }, { 102, 51, 102 }, { 102, 0, 102 },
{ 102, 255, 51 }, { 102, 204, 51 }, { 102, 153, 51 }, { 102, 102, 51 },
{ 102, 51, 51 }, { 102, 0, 51 }, { 102, 255, 0 }, { 102, 204, 0 },
{ 102, 153, 0 }, { 102, 102, 0 }, { 102, 51, 0 }, { 102, 0, 0 },
{ 51, 255, 102 }, { 51, 204, 102 }, { 51, 153, 102 }, { 51, 102, 102 },
{ 51, 51, 102 }, { 51, 0, 102 }, { 51, 255, 51 }, { 51, 204, 51 },
{ 51, 153, 51 }, { 51, 102, 51 }, { 51, 51, 51 }, { 51, 0, 51 },
{ 51, 255, 0 }, { 51, 204, 0 }, { 51, 153, 0 }, { 51, 102, 0 },
{ 51, 51, 0 }, { 51, 0, 0 }, { 0, 255, 102 }, { 0, 204, 102 },
{ 0, 153, 102 }, { 0, 102, 102 }, { 0, 51, 102 }, { 0, 0, 102 },
{ 0, 255, 51 }, { 0, 204, 51 }, { 0, 153, 51 }, { 0, 102, 51 },
{ 0, 51, 51 }, { 0, 0, 51 }, { 0, 255, 0 }, { 0, 204, 0 },
{ 0, 153, 0 }, { 0, 102, 0 }, { 0, 51, 0 }, { 17, 17, 17 },
{ 34, 34, 34 }, { 68, 68, 68 }, { 85, 85, 85 }, { 119, 119, 119 },
{ 136, 136, 136 }, { 170, 170, 170 }, { 187, 187, 187 }, { 221, 221, 221 },
{ 238, 238, 238 }, { 192, 192, 192 }, { 128, 0, 0 }, { 128, 0, 128 },
{ 0, 128, 0 }, { 0, 128, 128 }, { 0, 0, 0 }, { 0, 0, 0 },
{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 },
{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 },
{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 },
{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 },
{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 },
{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }
};
private static int uShort(byte [] byteData, int offset) {
return ((byteData[offset] & 0xFF) << 8) + (byteData[offset + 1] & 0xFF);
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/image/ZLImageManager.java
|
Java
|
asf20
| 6,275
|
/*
* Copyright (C) 2007-2010 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package com.zz.normal.util.image;
public interface ZLImageData {
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/util/image/ZLImageData.java
|
Java
|
asf20
| 868
|
package com.zz.normal.ui.widgt.pullrefresh.intnal;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.zz.normal.R;
import com.zz.normal.ui.widgt.pullrefresh.PullToRefreshBase;
public class LoadingLayout extends FrameLayout {
static final int DEFAULT_ROTATION_ANIMATION_DURATION = 150;
private final ImageView headerImage;
private final ProgressBar headerProgress;
private final TextView headerText;
private final TextView mRefreshViewLastUpdated;
private String pullLabel;
private String refreshingLabel;
private String releaseLabel;
private final Animation rotateAnimation, resetRotateAnimation;
public LoadingLayout(Context context, final int mode, String releaseLabel, String pullLabel, String refreshingLabel) {
super(context);
ViewGroup header = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.pull_to_refresh_header, this);
headerText = (TextView) header.findViewById(R.id.pull_to_refresh_text);
headerImage = (ImageView) header.findViewById(R.id.pull_to_refresh_image);
headerProgress = (ProgressBar) header.findViewById(R.id.pull_to_refresh_progress);
mRefreshViewLastUpdated =
(TextView) header.findViewById(R.id.pull_to_refresh_updated_at);
final Interpolator interpolator = new LinearInterpolator();
rotateAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotateAnimation.setInterpolator(interpolator);
rotateAnimation.setDuration(DEFAULT_ROTATION_ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);
resetRotateAnimation = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
resetRotateAnimation.setInterpolator(interpolator);
resetRotateAnimation.setDuration(DEFAULT_ROTATION_ANIMATION_DURATION);
resetRotateAnimation.setFillAfter(true);
this.releaseLabel = releaseLabel;
this.pullLabel = pullLabel;
this.refreshingLabel = refreshingLabel;
switch (mode) {
case PullToRefreshBase.MODE_PULL_UP_TO_REFRESH:
headerImage.setImageResource(R.drawable.refresharrow);
break;
case PullToRefreshBase.MODE_PULL_DOWN_TO_REFRESH:
default:
headerImage.setImageResource(R.drawable.refresharrow);
break;
}
}
public void reset() {
headerText.setText(pullLabel);
headerImage.setVisibility(View.VISIBLE);
headerProgress.setVisibility(View.GONE);
}
public void releaseToRefresh() {
headerText.setText(releaseLabel);
headerImage.clearAnimation();
headerImage.startAnimation(rotateAnimation);
}
public void setPullLabel(String pullLabel) {
this.pullLabel = pullLabel;
}
public void refreshing() {
headerText.setText(refreshingLabel);
headerImage.clearAnimation();
headerImage.setVisibility(View.INVISIBLE);
headerProgress.setVisibility(View.VISIBLE);
}
public void setRefreshingLabel(String refreshingLabel) {
this.refreshingLabel = refreshingLabel;
}
public void setReleaseLabel(String releaseLabel) {
this.releaseLabel = releaseLabel;
}
public void pullToRefresh() {
headerText.setText(pullLabel);
headerImage.clearAnimation();
headerImage.startAnimation(resetRotateAnimation);
}
public void setTextColor(int color) {
headerText.setTextColor(color);
}
public void setShowtime(String time){
mRefreshViewLastUpdated.setText(time);
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/ui/widgt/pullrefresh/intnal/LoadingLayout.java
|
Java
|
asf20
| 3,734
|
package com.zz.normal.ui.widgt.pullrefresh.intnal;
import android.view.View;
import android.widget.ImageView;
/**
* Interface that allows PullToRefreshBase to hijack the call to
* AdapterView.setEmptyView()
*
* @author chris
*/
public interface EmptyViewMethodAccessor {
/**
* Calls upto AdapterView.setEmptyView()
*
* @param View
* to set as Empty View
*/
public void setEmptyViewInternal(View emptyView);
/**
* Should call PullToRefreshBase.setEmptyView() which will then
* automatically call through to setEmptyViewInternal()
*
* @param View
* to set as Empty View
*/
public void setEmptyView(View emptyView);
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/ui/widgt/pullrefresh/intnal/EmptyViewMethodAccessor.java
|
Java
|
asf20
| 680
|
package com.zz.normal.ui.widgt.pullrefresh;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.zz.normal.ui.widgt.pullrefresh.intnal.EmptyViewMethodAccessor;
public abstract class PullToRefreshAdapterViewBase<T extends AbsListView> extends PullToRefreshBase<T> implements
OnScrollListener {
private int lastSavedFirstVisibleItem = -1;
private OnScrollListener onScrollListener;
private OnLastItemVisibleListener onLastItemVisibleListener;
private View emptyView;
private FrameLayout refreshableViewHolder;
private ImageView mTopImageView;
public PullToRefreshAdapterViewBase(Context context) {
super(context);
refreshableView.setOnScrollListener(this);
}
public PullToRefreshAdapterViewBase(Context context, int mode) {
super(context, mode);
refreshableView.setOnScrollListener(this);
}
public PullToRefreshAdapterViewBase(Context context, AttributeSet attrs) {
super(context, attrs);
refreshableView.setOnScrollListener(this);
}
abstract public ContextMenuInfo getContextMenuInfo();
public final void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
final int totalItemCount) {
if (null != onLastItemVisibleListener) {
// detect if last item is visible
if (visibleItemCount > 0 && (firstVisibleItem + visibleItemCount == totalItemCount)) {
// only process first event
if (firstVisibleItem != lastSavedFirstVisibleItem) {
lastSavedFirstVisibleItem = firstVisibleItem;
onLastItemVisibleListener.onLastItemVisible();
}
}
}
if (null != onScrollListener) {
onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
}
public final void onScrollStateChanged(final AbsListView view, final int scrollState) {
if (null != onScrollListener) {
onScrollListener.onScrollStateChanged(view, scrollState);
}
}
public void setBackToTopView(ImageView mTopImageView){
this.mTopImageView = mTopImageView;
mTopImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (refreshableView instanceof ListView ) {
((ListView)refreshableView).setSelection(0);
}else if(refreshableView instanceof GridView){
((GridView)refreshableView).setSelection(0);
}
}
});
}
/**
* Sets the Empty View to be used by the Adapter View.
*
* We need it handle it ourselves so that we can Pull-to-Refresh when the
* Empty View is shown.
*
* Please note, you do <strong>not</strong> usually need to call this method
* yourself. Calling setEmptyView on the AdapterView will automatically call
* this method and set everything up. This includes when the Android
* Framework automatically sets the Empty View based on it's ID.
*
* @param newEmptyView
* - Empty View to be used
*/
public final void setEmptyView(View newEmptyView) {
// If we already have an Empty View, remove it
if (null != emptyView) {
refreshableViewHolder.removeView(emptyView);
}
if (null != newEmptyView) {
ViewParent newEmptyViewParent = newEmptyView.getParent();
if (null != newEmptyViewParent && newEmptyViewParent instanceof ViewGroup) {
((ViewGroup) newEmptyViewParent).removeView(newEmptyView);
}
this.refreshableViewHolder.addView(newEmptyView, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
}
if (refreshableView instanceof EmptyViewMethodAccessor) {
((EmptyViewMethodAccessor) refreshableView).setEmptyViewInternal(newEmptyView);
} else {
this.refreshableView.setEmptyView(newEmptyView);
}
}
public final void setOnLastItemVisibleListener(OnLastItemVisibleListener listener) {
onLastItemVisibleListener = listener;
}
public final void setOnScrollListener(OnScrollListener listener) {
onScrollListener = listener;
}
protected void addRefreshableView(Context context, T refreshableView) {
refreshableViewHolder = new FrameLayout(context);
refreshableViewHolder.addView(refreshableView, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
addView(refreshableViewHolder, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0, 1.0f));
};
protected boolean isReadyForPullDown() {
return isFirstItemVisible();
}
protected boolean isReadyForPullUp() {
return isLastItemVisible();
}
private boolean isFirstItemVisible() {
if (this.refreshableView.getCount() == 0) {
return true;
} else if (refreshableView.getFirstVisiblePosition() == 0) {
final View firstVisibleChild = refreshableView.getChildAt(0);
if (firstVisibleChild != null) {
return firstVisibleChild.getTop() >= refreshableView.getTop();
}
}
return false;
}
private boolean isLastItemVisible() {
final int count = this.refreshableView.getCount();
final int lastVisiblePosition = refreshableView.getLastVisiblePosition();
if (count == 0) {
return true;
} else if (lastVisiblePosition == count - 1) {
final int childIndex = lastVisiblePosition - refreshableView.getFirstVisiblePosition();
final View lastVisibleChild = refreshableView.getChildAt(childIndex);
if (lastVisibleChild != null) {
return lastVisibleChild.getBottom() <= refreshableView.getBottom();
}
}
return false;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/ui/widgt/pullrefresh/PullToRefreshAdapterViewBase.java
|
Java
|
asf20
| 5,677
|
package com.zz.normal.ui.widgt.pullrefresh;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import com.zz.normal.R;
import com.zz.normal.ui.widgt.pullrefresh.intnal.LoadingLayout;
import com.zz.normal.util.Tools;
public abstract class PullToRefreshBase<T extends View> extends LinearLayout {
public static String LAST_UPDATETIME = Tools.getTime();
final class SmoothScrollRunnable implements Runnable {
static final int ANIMATION_DURATION_MS = 190;
static final int ANIMATION_FPS = 1000 / 60;
private final Interpolator interpolator;
private final int scrollToY;
private final int scrollFromY;
private final Handler handler;
private boolean continueRunning = true;
private long startTime = -1;
private int currentY = -1;
public SmoothScrollRunnable(Handler handler, int fromY, int toY) {
this.handler = handler;
this.scrollFromY = fromY;
this.scrollToY = toY;
this.interpolator = new AccelerateDecelerateInterpolator();
}
@Override
public void run() {
/**
* Only set startTime if this is the first time we're starting, else
* actually calculate the Y delta
*/
if (startTime == -1) {
startTime = System.currentTimeMillis();
} else {
/**
* We do do all calculations in long to reduce software float
* calculations. We use 1000 as it gives us good accuracy and
* small rounding errors
*/
long normalizedTime = (1000 * (System.currentTimeMillis() - startTime)) / ANIMATION_DURATION_MS;
normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
final int deltaY = Math.round((scrollFromY - scrollToY)
* interpolator.getInterpolation(normalizedTime / 1000f));
this.currentY = scrollFromY - deltaY;
setHeaderScroll(currentY);
}
// If we're not at the target Y, keep going...
if (continueRunning && scrollToY != currentY) {
handler.postDelayed(this, ANIMATION_FPS);
}
}
public void stop() {
this.continueRunning = false;
this.handler.removeCallbacks(this);
}
};
// ===========================================================
// Constants
// ===========================================================
static final float FRICTION = 2.0f;
static final int PULL_TO_REFRESH = 0x0;
static final int RELEASE_TO_REFRESH = 0x1;
static final int REFRESHING = 0x2;
static final int MANUAL_REFRESHING = 0x3;
public static final int MODE_PULL_DOWN_TO_REFRESH = 0x1;
public static final int MODE_PULL_UP_TO_REFRESH = 0x2;
public static final int MODE_BOTH = 0x3;
// ===========================================================
// Fields
// ===========================================================
private int touchSlop;
private float initialMotionY;
private float lastMotionX;
private float lastMotionY;
private boolean isBeingDragged = false;
private int state = PULL_TO_REFRESH;
private int mode = MODE_PULL_DOWN_TO_REFRESH;
private int currentMode;
private boolean disableScrollingWhileRefreshing = true;
T refreshableView;
private boolean isPullToRefreshEnabled = true;
private LoadingLayout headerLayout;
private LoadingLayout footerLayout;
private int headerHeight;
private final Handler handler = new Handler();
private OnRefreshListener onRefreshListener;
private SmoothScrollRunnable currentSmoothScrollRunnable;
// ===========================================================
// Constructors
// ===========================================================
public PullToRefreshBase(Context context) {
super(context);
init(context, null);
}
public PullToRefreshBase(Context context, int mode) {
super(context);
this.mode = mode;
init(context, null);
}
public PullToRefreshBase(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* Deprecated. Use {@link #getRefreshableView()} from now on.
*
* @deprecated
* @return The Refreshable View which is currently wrapped
*/
public final T getAdapterView() {
return refreshableView;
}
/**
* Get the Wrapped Refreshable View. Anything returned here has already been
* added to the content view.
*
* @return The View which is currently wrapped
*/
public final T getRefreshableView() {
return refreshableView;
}
/**
* Whether Pull-to-Refresh is enabled
*
* @return enabled
*/
public final boolean isPullToRefreshEnabled() {
return isPullToRefreshEnabled;
}
/**
* Returns whether the widget has disabled scrolling on the Refreshable View
* while refreshing.
*
* @param true if the widget has disabled scrolling while refreshing
*/
public final boolean isDisableScrollingWhileRefreshing() {
return disableScrollingWhileRefreshing;
}
/**
* Returns whether the Widget is currently in the Refreshing state
*
* @return true if the Widget is currently refreshing
*/
public final boolean isRefreshing() {
return state == REFRESHING || state == MANUAL_REFRESHING;
}
/**
* By default the Widget disabled scrolling on the Refreshable View while
* refreshing. This method can change this behaviour.
*
* @param disableScrollingWhileRefreshing
* - true if you want to disable scrolling while refreshing
*/
public final void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing) {
this.disableScrollingWhileRefreshing = disableScrollingWhileRefreshing;
}
/**
* Mark the current Refresh as complete. Will Reset the UI and hide the
* Refreshing View
*/
public final void onRefreshComplete() {
if (state != PULL_TO_REFRESH) {
resetHeader();
}
}
/**
* Set OnRefreshListener for the Widget
*
* @param listener
* - Listener to be used when the Widget is set to Refresh
*/
public final void setOnRefreshListener(OnRefreshListener listener) {
onRefreshListener = listener;
}
/**
* A mutator to enable/disable Pull-to-Refresh for the current View
*
* @param enable
* Whether Pull-To-Refresh should be used
*/
public final void setPullToRefreshEnabled(boolean enable) {
this.isPullToRefreshEnabled = enable;
}
/**
* Set Text to show when the Widget is being pulled, and will refresh when
* released
*
* @param releaseLabel
* - String to display
*/
public void setReleaseLabel(String releaseLabel) {
if (null != headerLayout) {
headerLayout.setReleaseLabel(releaseLabel);
}
if (null != footerLayout) {
footerLayout.setReleaseLabel(releaseLabel);
}
}
/**
* Set Text to show when the Widget is being Pulled
*
* @param pullLabel
* - String to display
*/
public void setPullLabel(String pullLabel) {
if (null != headerLayout) {
headerLayout.setPullLabel(pullLabel);
}
if (null != footerLayout) {
footerLayout.setPullLabel(pullLabel);
}
}
/**
* Set Text to show when the Widget is refreshing
*
* @param refreshingLabel
* - String to display
*/
public void setRefreshingLabel(String refreshingLabel) {
if (null != headerLayout) {
headerLayout.setRefreshingLabel(refreshingLabel);
}
if (null != footerLayout) {
footerLayout.setRefreshingLabel(refreshingLabel);
}
}
public final void setRefreshing() {
this.setRefreshing(true);
}
/**
* Sets the Widget to be in the refresh state. The UI will be updated to
* show the 'Refreshing' view.
*
* @param doScroll
* - true if you want to force a scroll to the Refreshing view.
*/
public final void setRefreshing(boolean doScroll) {
if (!isRefreshing()) {
setRefreshingInternal(doScroll);
state = MANUAL_REFRESHING;
}
}
public final boolean hasPullFromTop() {
return currentMode != MODE_PULL_UP_TO_REFRESH;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public final boolean onTouchEvent(MotionEvent event) {
if (!isPullToRefreshEnabled) {
return false;
}
if (isRefreshing() && disableScrollingWhileRefreshing) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() != 0) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE: {
if(headerLayout!=null){
headerLayout.setShowtime(getResources().getString(R.string.string_flush_lasttime)+LAST_UPDATETIME);
}
if(footerLayout!=null){
footerLayout.setShowtime("");
}
if (isBeingDragged) {
lastMotionY = event.getY();
this.pullEvent();
return true;
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
lastMotionY = initialMotionY = event.getY();
return true;
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
LAST_UPDATETIME = Tools.getTime();
if (isBeingDragged) {
isBeingDragged = false;
if(state == REFRESHING || state == MANUAL_REFRESHING){
smoothScrollTo(currentMode == MODE_PULL_DOWN_TO_REFRESH ? -headerHeight : headerHeight);
}else{
if (state == RELEASE_TO_REFRESH && null != onRefreshListener) {
setRefreshingInternal(true);
onRefreshListener.onRefresh();
} else {
smoothScrollTo(0);
}
}
return true;
}
break;
}
}
return false;
}
@Override
public final boolean onInterceptTouchEvent(MotionEvent event) {
if (!isPullToRefreshEnabled) {
return false;
}
if (isRefreshing() && disableScrollingWhileRefreshing) {
return true;
}
final int action = event.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
isBeingDragged = false;
return false;
}
if (action != MotionEvent.ACTION_DOWN && isBeingDragged) {
return true;
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
if (isReadyForPull()) {
final float y = event.getY();
final float dy = y - lastMotionY;
final float yDiff = Math.abs(dy);
final float xDiff = Math.abs(event.getX() - lastMotionX);
if (yDiff > touchSlop && yDiff > xDiff) {
if ((mode == MODE_PULL_DOWN_TO_REFRESH || mode == MODE_BOTH) && dy >= 0.0001f
&& isReadyForPullDown()) {
lastMotionY = y;
isBeingDragged = true;
if (mode == MODE_BOTH) {
currentMode = MODE_PULL_DOWN_TO_REFRESH;
}
} else if ((mode == MODE_PULL_UP_TO_REFRESH || mode == MODE_BOTH) && dy <= 0.0001f
&& isReadyForPullUp()) {
lastMotionY = y;
isBeingDragged = true;
if (mode == MODE_BOTH) {
currentMode = MODE_PULL_UP_TO_REFRESH;
}
}
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
lastMotionY = initialMotionY = event.getY();
lastMotionX = event.getX();
isBeingDragged = false;
}
break;
}
}
return isBeingDragged;
}
protected void addRefreshableView(Context context, T refreshableView) {
addView(refreshableView, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0, 1.0f));
}
/**
* This is implemented by derived classes to return the created View. If you
* need to use a custom View (such as a custom ListView), override this
* method and return an instance of your custom class.
*
* Be sure to set the ID of the view in this method, especially if you're
* using a ListActivity or ListFragment.
*
* @param context
* @param attrs
* AttributeSet from wrapped class. Means that anything you
* include in the XML layout declaration will be routed to the
* created View
* @return New instance of the Refreshable View
*/
protected abstract T createRefreshableView(Context context, AttributeSet attrs);
public final int getCurrentMode() {
return currentMode;
}
protected final LoadingLayout getFooterLayout() {
return footerLayout;
}
protected final LoadingLayout getHeaderLayout() {
return headerLayout;
}
protected final int getHeaderHeight() {
return headerHeight;
}
protected final int getMode() {
return mode;
}
/**
* Implemented by derived class to return whether the View is in a state
* where the user can Pull to Refresh by scrolling down.
*
* @return true if the View is currently the correct state (for example, top
* of a ListView)
*/
protected abstract boolean isReadyForPullDown();
/**
* Implemented by derived class to return whether the View is in a state
* where the user can Pull to Refresh by scrolling up.
*
* @return true if the View is currently in the correct state (for example,
* bottom of a ListView)
*/
protected abstract boolean isReadyForPullUp();
// ===========================================================
// Methods
// ===========================================================
protected void resetHeader() {
state = PULL_TO_REFRESH;
isBeingDragged = false;
if (null != headerLayout) {
headerLayout.reset();
}
if (null != footerLayout) {
footerLayout.reset();
}
smoothScrollTo(0);
}
protected void setRefreshingInternal(boolean doScroll) {
state = REFRESHING;
if (null != headerLayout) {
headerLayout.refreshing();
}
if (null != footerLayout) {
footerLayout.refreshing();
}
if (doScroll) {
smoothScrollTo(currentMode == MODE_PULL_DOWN_TO_REFRESH ? -headerHeight : headerHeight);
}
}
protected final void setHeaderScroll(int y) {
scrollTo(0, y);
}
protected final void smoothScrollTo(int y) {
if (null != currentSmoothScrollRunnable) {
currentSmoothScrollRunnable.stop();
}
if (this.getScrollY() != y) {
this.currentSmoothScrollRunnable = new SmoothScrollRunnable(handler, getScrollY(), y);
handler.post(currentSmoothScrollRunnable);
}
}
private void init(Context context, AttributeSet attrs) {
setOrientation(LinearLayout.VERTICAL);
touchSlop = ViewConfiguration.getTouchSlop();
// Styleables from XML
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
if (a.hasValue(R.styleable.PullToRefresh_mode)) {
mode = a.getInteger(R.styleable.PullToRefresh_mode, MODE_PULL_DOWN_TO_REFRESH);
}
// Refreshable View
// By passing the attrs, we can add ListView/GridView params via XML
refreshableView = this.createRefreshableView(context, attrs);
this.addRefreshableView(context, refreshableView);
// Loading View Strings
String pullLabel = context.getString(R.string.pull_to_refresh_pull_label);
String refreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_label);
String releaseLabel = context.getString(R.string.pull_to_refresh_release_label);
// Add Loading Views
if (mode == MODE_PULL_DOWN_TO_REFRESH || mode == MODE_BOTH) {
headerLayout = new LoadingLayout(context, MODE_PULL_DOWN_TO_REFRESH, releaseLabel, pullLabel,
refreshingLabel);
headerLayout.setShowtime(getResources().getString(R.string.string_flush_lasttime)+LAST_UPDATETIME);
addView(headerLayout, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(headerLayout);
headerHeight = headerLayout.getMeasuredHeight();
}
if (mode == MODE_PULL_UP_TO_REFRESH || mode == MODE_BOTH) {
pullLabel = context.getString(R.string.pull_to_refresh_refreshing_moreload);
refreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_moreload);
releaseLabel = context.getString(R.string.pull_to_refresh_refreshing_moreload);
footerLayout = new LoadingLayout(context, MODE_PULL_UP_TO_REFRESH, releaseLabel, pullLabel, refreshingLabel);
footerLayout.setShowtime("");
addView(footerLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(footerLayout);
headerHeight = footerLayout.getMeasuredHeight();
}
// Styleables from XML
if (a.hasValue(R.styleable.PullToRefresh_headerTextColor)) {
final int color = a.getColor(R.styleable.PullToRefresh_headerTextColor, Color.BLACK);
if (null != headerLayout) {
headerLayout.setTextColor(color);
}
if (null != footerLayout) {
footerLayout.setTextColor(color);
}
}
if (a.hasValue(R.styleable.PullToRefresh_headerBackground)) {
this.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_headerBackground, Color.WHITE));
}
if (a.hasValue(R.styleable.PullToRefresh_adapterViewBackground)) {
refreshableView.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_adapterViewBackground,
Color.WHITE));
}
a.recycle();
// Hide Loading Views
switch (mode) {
case MODE_BOTH:
setPadding(0, -headerHeight, 0, -headerHeight);
break;
case MODE_PULL_UP_TO_REFRESH:
setPadding(0, 0, 0, -headerHeight);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
setPadding(0, -headerHeight, 0, 0);
break;
}
// If we're not using MODE_BOTH, then just set currentMode to current
// mode
if (mode != MODE_BOTH) {
currentMode = mode;
}
}
private 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);
}
/**
* Actions a Pull Event
*
* @return true if the Event has been handled, false if there has been no
* change
*/
private boolean pullEvent() {
final int newHeight;
final int oldHeight = this.getScrollY();
switch (currentMode) {
case MODE_PULL_UP_TO_REFRESH:
newHeight = Math.round(Math.max(initialMotionY - lastMotionY, 0) / FRICTION);
// newHeight = Math.round((initialMotionY - lastMotionY) / FRICTION);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
newHeight = Math.round(Math.min(initialMotionY - lastMotionY, 0) / FRICTION);
// newHeight = Math.round((initialMotionY - lastMotionY) / FRICTION);
break;
}
setHeaderScroll(newHeight);
if (newHeight != 0) {
if (state == PULL_TO_REFRESH && headerHeight < Math.abs(newHeight)) {
state = RELEASE_TO_REFRESH;
switch (currentMode) {
case MODE_PULL_UP_TO_REFRESH:
footerLayout.releaseToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
headerLayout.releaseToRefresh();
break;
}
return true;
} else if (state == RELEASE_TO_REFRESH && headerHeight >= Math.abs(newHeight)) {
state = PULL_TO_REFRESH;
switch (currentMode) {
case MODE_PULL_UP_TO_REFRESH:
footerLayout.pullToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
headerLayout.pullToRefresh();
break;
}
return true;
}
}
return oldHeight != newHeight;
}
private boolean isReadyForPull() {
switch (mode) {
case MODE_PULL_DOWN_TO_REFRESH:
return isReadyForPullDown();
case MODE_PULL_UP_TO_REFRESH:
return isReadyForPullUp();
case MODE_BOTH:
return isReadyForPullUp() || isReadyForPullDown();
}
return false;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface OnRefreshListener {
public void onRefresh();
}
public static interface OnLastItemVisibleListener {
public void onLastItemVisible();
}
@Override
public void setLongClickable(boolean longClickable) {
getRefreshableView().setLongClickable(longClickable);
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/ui/widgt/pullrefresh/PullToRefreshBase.java
|
Java
|
asf20
| 20,359
|
package com.zz.normal.ui.widgt.pullrefresh;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.ListView;
import com.zz.normal.ui.widgt.pullrefresh.intnal.EmptyViewMethodAccessor;
public class PullToRefreshListView extends PullToRefreshAdapterViewBase<ListView> {
class InternalListView extends ListView implements EmptyViewMethodAccessor {
public InternalListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setEmptyView(View emptyView) {
PullToRefreshListView.this.setEmptyView(emptyView);
}
@Override
public void setEmptyViewInternal(View emptyView) {
super.setEmptyView(emptyView);
}
public ContextMenuInfo getContextMenuInfo() {
return super.getContextMenuInfo();
}
}
public PullToRefreshListView(Context context) {
super(context);
this.setDisableScrollingWhileRefreshing(false);
}
public PullToRefreshListView(Context context, int mode) {
super(context, mode);
this.setDisableScrollingWhileRefreshing(false);
}
public PullToRefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setDisableScrollingWhileRefreshing(false);
}
@Override
public ContextMenuInfo getContextMenuInfo() {
return ((InternalListView) getRefreshableView()).getContextMenuInfo();
}
@Override
protected final ListView createRefreshableView(Context context, AttributeSet attrs) {
ListView lv = new InternalListView(context, attrs);
// Set it to this so it can be used in ListActivity/ListFragment
lv.setId(android.R.id.list);
return lv;
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/ui/widgt/pullrefresh/PullToRefreshListView.java
|
Java
|
asf20
| 1,684
|
package com.zz.normal.ui.widgt.pullrefresh;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
import com.zz.normal.R;
public class PullToRefreshScrollView extends PullToRefreshBase<ScrollView> {
private final OnRefreshListener defaultOnRefreshListener = new OnRefreshListener() {
@Override
public void onRefresh() {
}
};
public PullToRefreshScrollView(Context context) {
super(context);
/**
* Added so that by default, Pull-to-Refresh refreshes the page
*/
setOnRefreshListener(defaultOnRefreshListener);
}
public PullToRefreshScrollView(Context context, int mode) {
super(context, mode);
/**
* Added so that by default, Pull-to-Refresh refreshes the page
*/
setOnRefreshListener(defaultOnRefreshListener);
}
public PullToRefreshScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
/**
* Added so that by default, Pull-to-Refresh refreshes the page
*/
setOnRefreshListener(defaultOnRefreshListener);
}
@Override
protected ScrollView createRefreshableView(Context context, AttributeSet attrs) {
ScrollView scrollView = new ScrollView(context, attrs);
scrollView.setId(R.id.webview);
return scrollView;
}
@Override
protected boolean isReadyForPullDown() {
return refreshableView.getScrollY() == 0;
}
@Override
protected boolean isReadyForPullUp() {
ScrollView view = getRefreshableView();
int off=view.getScrollY()+view.getHeight()-view.getChildAt(0).getHeight();
if(off==0){
return true;
}else{
return false;
}
}
}
|
zz-music-release
|
trunk/zz-normal-net/src/com/zz/normal/ui/widgt/pullrefresh/PullToRefreshScrollView.java
|
Java
|
asf20
| 1,586
|
package net.srcz.android.screencast;
import java.io.IOException;
import net.srcz.android.screencast.api.injector.Injector;
import net.srcz.android.screencast.app.SwingApplication;
import net.srcz.android.screencast.ui.JDialogDeviceList;
import net.srcz.android.screencast.ui.JFrameMain;
import net.srcz.android.screencast.ui.JSplashScreen;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
public class Main extends SwingApplication {
JFrameMain jf;
Injector injector;
IDevice device;
public Main(boolean nativeLook) throws IOException {
super(nativeLook);
JSplashScreen jw = new JSplashScreen("");
try {
initialize(jw);
} finally {
jw.setVisible(false);
jw = null;
}
}
private void initialize(JSplashScreen jw) throws IOException {
jw.setText("Getting devices list...");
jw.setVisible(true);
AndroidDebugBridge bridge = AndroidDebugBridge.createBridge();
waitDeviceList(bridge);
IDevice devices[] = bridge.getDevices();
jw.setVisible(false);
// Let the user choose the device
if(devices.length == 1) {
device = devices[0];
} else {
JDialogDeviceList jd = new JDialogDeviceList(devices);
jd.setVisible(true);
device = jd.getDevice();
}
if(device == null) {
System.exit(0);
return;
}
// Start showing the device screen
jf = new JFrameMain(device);
jf.setTitle(""+device);
// Show window
jf.setVisible(true);
// Starting injector
jw.setText("Starting input injector...");
jw.setVisible(true);
injector = new Injector(device);
injector.start();
jf.setInjector(injector);
}
private void waitDeviceList(AndroidDebugBridge bridge) {
int count = 0;
while (bridge.hasInitialDeviceList() == false) {
try {
Thread.sleep(100);
count++;
} catch (InterruptedException e) {
// pass
}
// let's not wait > 10 sec.
if (count > 300) {
throw new RuntimeException("Timeout getting device list!");
}
}
}
protected void close() {
System.out.println("cleaning up...");
if(injector != null)
injector.close();
if(device != null) {
synchronized (device) {
AndroidDebugBridge.terminate();
}
}
System.out.println("cleanup done, exiting...");
super.close();
}
public static void main(String args[]) throws IOException {
boolean nativeLook = args.length == 0 || !args[0].equalsIgnoreCase("nonativelook");
new Main(nativeLook);
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/Main.java
|
Java
|
asf20
| 2,554
|
package net.srcz.android.screencast.app;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import net.srcz.android.screencast.ui.JDialogError;
public class SwingApplication extends Application {
JDialogError jd = null;
public SwingApplication(boolean nativeLook) {
try {
if(nativeLook)
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
protected void close() {
super.close();
}
@Override
protected void handleException(Thread thread, Throwable ex) {
try {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
if(sw.toString().contains("SynthTreeUI"))
return;
ex.printStackTrace(System.err);
if(jd != null && jd.isVisible())
return;
jd = new JDialogError(ex);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jd.setVisible(true);
}
});
} catch(Exception ex2) {
// ignored
}
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/app/SwingApplication.java
|
Java
|
asf20
| 1,085
|
package net.srcz.android.screencast.app;
import java.lang.Thread.UncaughtExceptionHandler;
public class Application {
public Application() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
close();
}
});
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread arg0, Throwable ex) {
try {
handleException(arg0,ex);
} catch(Exception ex2) {
// ignored
ex2.printStackTrace();
}
}
});
}
protected void handleException(Thread thread, Throwable ex) {
}
protected void close() {
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/app/Application.java
|
Java
|
asf20
| 624
|
package net.srcz.android.screencast.ui;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JWindow;
public class JSplashScreen extends JWindow {
JLabel label = new JLabel("Loading...",
new ImageIcon(JFrameMain.class.getResource("icon.png")),
(int)JLabel.CENTER_ALIGNMENT);
public JSplashScreen(String text) {
initialize();
setText(text);
}
public void setText(String text) {
label.setText(text);
pack();
setLocationRelativeTo(null);
}
private void initialize() {
setLayout(new BorderLayout());
label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//createLineBorder(Color.BLACK));
add(label,BorderLayout.CENTER);
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/JSplashScreen.java
|
Java
|
asf20
| 794
|
package net.srcz.android.screencast.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.srcz.android.screencast.api.AndroidDevice;
import net.srcz.android.screencast.api.injector.ConstEvtKey;
import net.srcz.android.screencast.api.injector.ConstEvtMotion;
import net.srcz.android.screencast.api.injector.Injector;
import net.srcz.android.screencast.api.injector.KeyCodeConverter;
import net.srcz.android.screencast.api.injector.ScreenCaptureThread.ScreenCaptureListener;
import net.srcz.android.screencast.ui.explorer.JFrameExplorer;
import com.android.ddmlib.IDevice;
public class JFrameMain extends JFrame {
private JPanelScreen jp = new JPanelScreen();
private JToolBar jtb = new JToolBar();
private JToolBar jtbHardkeys = new JToolBar();
private JToggleButton jtbRecord = new JToggleButton("Record");
private JButton jbOpenUrl = new JButton("Open Url");
JScrollPane jsp;
private JButton jbExplorer = new JButton("Explore");
private JButton jbKbHome = new JButton("Home");
private JButton jbKbMenu = new JButton("Menu");
private JButton jbKbBack = new JButton("Back");
private JButton jbKbSearch = new JButton("Search");
private JButton jbKbPhoneOn = new JButton("Call");
private JButton jbKbPhoneOff = new JButton("End call");
public class KbActionListener implements ActionListener {
int key;
public KbActionListener(int key) {
this.key = key;
}
public void actionPerformed(ActionEvent e) {
if (injector == null)
return;
injector.injectKeycode(ConstEvtKey.ACTION_DOWN, key);
injector.injectKeycode(ConstEvtKey.ACTION_UP, key);
}
}
private IDevice device;
private Injector injector;
private Dimension oldImageDimension = null;
public void setInjector(Injector injector) {
this.injector = injector;
injector.screencapture.setListener(new ScreenCaptureListener() {
public void handleNewImage(Dimension size, BufferedImage image,
boolean landscape) {
if(oldImageDimension == null ||
!size.equals(oldImageDimension)) {
jsp.setPreferredSize(size);
JFrameMain.this.pack();
oldImageDimension = size;
}
jp.handleNewImage(size, image, landscape);
}
});
}
public JFrameMain(IDevice device) throws IOException {
this.device = device;
initialize();
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (!JFrameMain.this.isActive())
return false;
if (injector == null)
return false;
if (e.getID() == KeyEvent.KEY_PRESSED) {
int code = KeyCodeConverter.getKeyCode(e);
injector.injectKeycode(ConstEvtKey.ACTION_DOWN,
code);
}
if (e.getID() == KeyEvent.KEY_RELEASED) {
int code = KeyCodeConverter.getKeyCode(e);
injector.injectKeycode(ConstEvtKey.ACTION_UP, code);
}
return false;
}
});
}
public void initialize() throws IOException {
jtb.setFocusable(false);
jbExplorer.setFocusable(false);
jtbRecord.setFocusable(false);
jbOpenUrl.setFocusable(false);
jbKbHome.setFocusable(false);
jbKbMenu.setFocusable(false);
jbKbBack.setFocusable(false);
jbKbSearch.setFocusable(false);
jbKbPhoneOn.setFocusable(false);
jbKbPhoneOff.setFocusable(false);
jbKbHome.addActionListener(new KbActionListener(
ConstEvtKey.KEYCODE_HOME));
jbKbMenu.addActionListener(new KbActionListener(
ConstEvtKey.KEYCODE_MENU));
jbKbBack.addActionListener(new KbActionListener(
ConstEvtKey.KEYCODE_BACK));
jbKbSearch.addActionListener(new KbActionListener(
ConstEvtKey.KEYCODE_SEARCH));
jbKbPhoneOn.addActionListener(new KbActionListener(
ConstEvtKey.KEYCODE_CALL));
jbKbPhoneOff.addActionListener(new KbActionListener(
ConstEvtKey.KEYCODE_ENDCALL));
jtbHardkeys.add(jbKbHome);
jtbHardkeys.add(jbKbMenu);
jtbHardkeys.add(jbKbBack);
jtbHardkeys.add(jbKbSearch);
jtbHardkeys.add(jbKbPhoneOn);
jtbHardkeys.add(jbKbPhoneOff);
setIconImage(Toolkit.getDefaultToolkit().getImage(
getClass().getResource("icon.png")));
setDefaultCloseOperation(3);
setLayout(new BorderLayout());
add(jtb, BorderLayout.NORTH);
add(jtbHardkeys, BorderLayout.SOUTH);
jsp = new JScrollPane(jp);
add(jsp, BorderLayout.CENTER);
jsp.setPreferredSize(new Dimension(100, 100));
pack();
setLocationRelativeTo(null);
/*
* jp.addKeyListener(new KeyAdapter() {
*
* @Override public void keyPressed(KeyEvent e) { if(injector == null)
* return; try { int code = KeyCodeConverter.getKeyCode(e);
* injector.injectKeycode(ConstEvtKey.ACTION_DOWN,code); } catch
* (IOException e1) { throw new RuntimeException(e1); } }
*
* @Override public void keyReleased(KeyEvent e) { if(injector == null)
* return; try { int code = KeyCodeConverter.getKeyCode(e);
* injector.injectKeycode(ConstEvtKey.ACTION_UP,code); } catch
* (IOException e1) { throw new RuntimeException(e1); } }
*
*
* });
*/
MouseAdapter ma = new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent arg0) {
if (injector == null)
return;
try {
Point p2 = jp.getRawPoint(arg0.getPoint());
injector
.injectMouse(ConstEvtMotion.ACTION_MOVE, p2.x, p2.y);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void mousePressed(MouseEvent arg0) {
if (injector == null)
return;
try {
Point p2 = jp.getRawPoint(arg0.getPoint());
injector
.injectMouse(ConstEvtMotion.ACTION_DOWN, p2.x, p2.y);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void mouseReleased(MouseEvent arg0) {
if (injector == null)
return;
try {
if (arg0.getButton() == MouseEvent.BUTTON3) {
injector.screencapture.toogleOrientation();
arg0.consume();
return;
}
Point p2 = jp.getRawPoint(arg0.getPoint());
injector.injectMouse(ConstEvtMotion.ACTION_UP, p2.x, p2.y);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void mouseWheelMoved(MouseWheelEvent arg0) {
if (injector == null)
return;
try {
// injector.injectKeycode(ConstEvtKey.ACTION_DOWN,code);
// injector.injectKeycode(ConstEvtKey.ACTION_UP,code);
injector.injectTrackball(arg0.getWheelRotation() < 0 ? -1f
: 1f);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
jp.addMouseMotionListener(ma);
jp.addMouseListener(ma);
jp.addMouseWheelListener(ma);
jtbRecord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (jtbRecord.isSelected()) {
startRecording();
} else {
stopRecording();
}
}
});
jtb.add(jtbRecord);
jbExplorer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFrameExplorer jf = new JFrameExplorer(device);
jf.setIconImage(getIconImage());
jf.setVisible(true);
}
});
jtb.add(jbExplorer);
jbOpenUrl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JDialogUrl jdUrl = new JDialogUrl();
jdUrl.setVisible(true);
if (!jdUrl.result)
return;
String url = jdUrl.jtfUrl.getText();
new AndroidDevice(device).openUrl(url);
}
});
jtb.add(jbOpenUrl);
}
private void startRecording() {
JFileChooser jFileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Vidéo file", "mov");
jFileChooser.setFileFilter(filter);
int returnVal = jFileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
injector.screencapture.startRecording(jFileChooser
.getSelectedFile());
}
}
private void stopRecording() {
injector.screencapture.stopRecording();
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/JFrameMain.java
|
Java
|
asf20
| 8,839
|
package net.srcz.android.screencast.ui.pm;
public class JFrameApps {
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/pm/JFrameApps.java
|
Java
|
asf20
| 73
|
package net.srcz.android.screencast.ui;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import javax.swing.JPanel;
public class JPanelScreen extends JPanel {
public float coef = 1;
double origX;
double origY;
boolean landscape;
Dimension size = null;
Image image = null;
public JPanelScreen() {
this.setFocusable(true);
}
public void handleNewImage(Dimension size, Image image, boolean landscape) {
this.landscape = landscape;
this.size = size;
this.image = image;
repaint();
}
protected void paintComponent(Graphics g) {
if(size == null)
return;
if(size.height == 0)
return;
g.clearRect(0, 0, getWidth(), getHeight());
double width = Math.min(getWidth(), size.width*getHeight()/size.height);
coef = (float)width / (float)size.width;
double height = width*size.height/size.width;
origX = (getWidth() - width) / 2;
origY = (getHeight() - height) / 2;
g.drawImage(image, (int)origX, (int)origY, (int)width, (int)height, this);
}
public Point getRawPoint(Point p1) {
Point p2 = new Point();
p2.x = (int)((p1.x - origX)/coef);
p2.y = (int)((p1.y - origY)/coef);
return p2;
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/JPanelScreen.java
|
Java
|
asf20
| 1,251
|
package net.srcz.android.screencast.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import com.android.ddmlib.IDevice;
public class JDialogDeviceList extends JDialog implements ActionListener {
private static final String DEFAULT_HOST = "127.0.0.1";
private static final int DEFAULT_PORT = 1324;
JTextField jtfHost = new JTextField(DEFAULT_HOST);
JFormattedTextField jftfPort = new JFormattedTextField(DEFAULT_PORT);
JList jlDevices = new JList();
JScrollPane jspDevices = new JScrollPane(jlDevices);
JPanel jpAgent = new JPanel();
JPanel jpButtons = new JPanel();
JButton jbOk = new JButton("OK");
JButton jbQuit = new JButton("Quit");
boolean cancelled = false;
IDevice[] devices;
public JDialogDeviceList(IDevice[] devices) {
super();
setModal(true);
this.devices = devices;
initialize();
}
private void initialize() {
setTitle("Please select a device");
jlDevices.setListData(devices);
jlDevices.setPreferredSize(new Dimension(400,300));
if(devices.length != 0)
jlDevices.setSelectedIndex(0);
jbOk.setEnabled(!jlDevices.isSelectionEmpty());
jpAgent.setBorder(BorderFactory.createTitledBorder("Agent"));
jpAgent.setLayout(new BorderLayout(10,10));
jpAgent.add(jtfHost, BorderLayout.CENTER);
jpAgent.add(jftfPort, BorderLayout.EAST);
jpButtons.setLayout(new FlowLayout(FlowLayout.RIGHT));
jpButtons.add(jbOk,BorderLayout.CENTER);
jpButtons.add(jbQuit,BorderLayout.SOUTH);
JPanel jpBottom = new JPanel();
jpBottom.setLayout(new BorderLayout());
jpBottom.add(jpAgent,BorderLayout.CENTER);
jpBottom.add(jpButtons,BorderLayout.SOUTH);
setLayout(new BorderLayout());
add(jlDevices,BorderLayout.CENTER);
add(jpBottom,BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
jbOk.addActionListener(this);
jbQuit.addActionListener(this);
jlDevices.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2) {
int index = jlDevices.locationToIndex(e.getPoint());
ListModel dlm = jlDevices.getModel();
Object item = dlm.getElementAt(index);;
jlDevices.ensureIndexIsVisible(index);
cancelled = false;
setVisible(false);
}
}
});
}
public IDevice getDevice() {
if(cancelled)
return null;
return (IDevice)jlDevices.getSelectedValue();
}
public void actionPerformed(ActionEvent arg0) {
cancelled = arg0.getSource() == jbQuit;
setVisible(false);
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/JDialogDeviceList.java
|
Java
|
asf20
| 2,953
|
package net.srcz.android.screencast.ui.explorer;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeModel;
import net.srcz.android.screencast.ui.worker.SwingWorker;
public abstract class LazyLoadingTreeNode extends DefaultMutableTreeNode implements TreeWillExpandListener {
private static final String ESCAPE_ACTION_NAME = "escape";
private static final KeyStroke ESCAPE_KEY =
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
/**
* ActionMap can only store one Action for the same key,
* This Action Stores the list of SwingWorker to be canceled if the escape
* key is pressed.
* @author Thierry LEFORT
* 3 mars 08
*
*/
protected static class CancelWorkersAction extends AbstractAction {
/** the SwingWorkers */
private Vector<SwingWorker<MutableTreeNode[], ?>> workers =
new Vector<SwingWorker<MutableTreeNode[],?>>();
/** Default constructor */
private CancelWorkersAction() {
super(ESCAPE_ACTION_NAME);
}
/** Add a Cancelable SwingWorker */
public void addSwingWorker(SwingWorker<MutableTreeNode[], ?> worker) {
workers.add(worker);
}
/** Remove a SwingWorker */
public void removeSwingWorker(SwingWorker<MutableTreeNode[], ?> worker) {
workers.remove(worker);
}
/** Do the Cancel */
public void actionPerformed(ActionEvent e) {
Iterator<SwingWorker<MutableTreeNode[], ?>> it = workers.iterator();
while (it.hasNext()) {
SwingWorker<MutableTreeNode[], ?> worker = (SwingWorker<MutableTreeNode[], ?>) it.next();
worker.cancel(true);
}
}
}
/** The JTree containing this Node */
private JTree tree;
/** Can the worker be Canceled ? */
private boolean cancelable;
/**
* Default Constructor
* @param userObject an Object provided by the user that constitutes
* the node's data
* @param tree the JTree containing this Node
* @param cancelable
*/
public LazyLoadingTreeNode(Object userObject,
JTree tree,
boolean cancelable) {
super(userObject);
tree.addTreeWillExpandListener(this);
this.tree = tree;
this.cancelable = cancelable;
setAllowsChildren(true);
}
/**
* Default empty implementation, do nothing on collapse event.
*/
public void treeWillCollapse(TreeExpansionEvent event)
throws ExpandVetoException { }
/**
* set the loading state
*/
private void setLoading() {
setChildren(createLoadingNode());
TreeModel model = tree.getModel();
if (model instanceof DefaultTreeModel) {
DefaultTreeModel defaultModel = (DefaultTreeModel) model;
int[] indices = new int[getChildCount()];
for (int i= 0; i < indices.length; i++) {
indices[i] = i;
}
defaultModel.nodesWereInserted(LazyLoadingTreeNode.this, indices);
}
}
/**
* Node will expand, it's time to retreive nodes
*/
public void treeWillExpand(TreeExpansionEvent event)
throws ExpandVetoException {
if (this.equals(event.getPath().getLastPathComponent())) {
if (areChildrenLoaded()) {
return;
}
setLoading();
SwingWorker<MutableTreeNode[], ?> worker = createSwingWorker(tree, cancelable);
worker.execute();
}
}
/**
* Define nodes children
* @param nodes new nodes
*/
protected void setChildren(MutableTreeNode...nodes) {
if (nodes == null) {
}
TreeModel model = tree.getModel();
if (model instanceof DefaultTreeModel) {
DefaultTreeModel defaultModel = (DefaultTreeModel) model;
int childCount = getChildCount();
if (childCount > 0) {
for (int i = 0; i < childCount; i++) {
defaultModel.removeNodeFromParent((MutableTreeNode) getChildAt(0));
}
}
for (int i = 0; i < nodes.length; i++) {
defaultModel.insertNodeInto(nodes[i], this, i);
}
}
}
/**
* Create worker that will load the nodes
* @param tree the tree
* @param cancelable if the worker should be cancelable
* @return the newly created SwingWorker
*/
protected SwingWorker<MutableTreeNode[], ?> createSwingWorker(
final JTree tree,
boolean cancelable) {
SwingWorker<MutableTreeNode[], ?> worker =
new SwingWorker<MutableTreeNode[], Object>() {
@Override
protected void done() {
try {
if (!isCancelled()) {
MutableTreeNode[] nodes = get();
setAllowsChildren(nodes.length > 0);
setChildren(nodes);
unRegisterSwingWorkerForCancel(tree, this);
} else {
reset();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected MutableTreeNode[] doInBackground() throws Exception {
return loadChildren(tree);
}
};
registerSwingWorkerForCancel(tree, worker);
return worker;
}
/**
* If the node is cancelable an escape Action is registered in the tree's
* InputMap and ActionMap that will cancel the execution
* @param tree the tree
* @param worker the worker to cancel
*/
protected void registerSwingWorkerForCancel(JTree tree, SwingWorker<MutableTreeNode[], ?> worker) {
if (!cancelable) {
return;
}
tree.getInputMap().put(ESCAPE_KEY, ESCAPE_ACTION_NAME);
Action action = tree.getActionMap().get(ESCAPE_ACTION_NAME);
if (action == null) {
CancelWorkersAction cancelWorkerAction = new CancelWorkersAction();
cancelWorkerAction.addSwingWorker(worker);
tree.getActionMap().put(ESCAPE_ACTION_NAME, cancelWorkerAction);
} else {
if (action instanceof CancelWorkersAction) {
CancelWorkersAction cancelAction = (CancelWorkersAction) action;
cancelAction.addSwingWorker(worker);
}
}
}
/**
* Remove the swingWorker from the cancellable task of the tree
* @param tree
* @param worker
*/
protected void unRegisterSwingWorkerForCancel(JTree tree, SwingWorker<MutableTreeNode[], ?> worker) {
if (!cancelable) {
return;
}
Action action = tree.getActionMap().get(ESCAPE_ACTION_NAME);
if (action != null && action instanceof CancelWorkersAction) {
CancelWorkersAction cancelWorkerAction = new CancelWorkersAction();
cancelWorkerAction.removeSwingWorker(worker);
}
}
/**
* Need some improvement ...
* This method should restore the Node initial state if the worker if canceled
*/
protected void reset() {
DefaultTreeModel defaultModel = (DefaultTreeModel) tree.getModel();
int childCount = getChildCount();
if (childCount > 0) {
for (int i = 0; i < childCount; i++) {
defaultModel.removeNodeFromParent((MutableTreeNode) getChildAt(0));
}
}
setAllowsChildren(true);
}
/**
*
* @return <code>true</code> if there are some childrens
*/
protected boolean areChildrenLoaded() {
return getChildCount() > 0 && getAllowsChildren();
}
/**
* If the
* @see #getAllowsChildren()
* @return false, this node can't be a leaf
*/
@Override
public boolean isLeaf() {
return !getAllowsChildren();
}
/**
* This method will be executed in a background thread.
* If you have to do some GUI stuff use {@link SwingUtilities#invokeLater(Runnable)}
* @param tree the tree
* @return the Created nodes
*/
public abstract MutableTreeNode[] loadChildren(JTree tree);
/**
*
* @return a new Loading please wait node
*/
protected MutableTreeNode createLoadingNode() {
return new DefaultMutableTreeNode("Loading Please Wait ...", false);
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/explorer/LazyLoadingTreeNode.java
|
Java
|
asf20
| 7,927
|
package net.srcz.android.screencast.ui.explorer;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.ListModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import net.srcz.android.screencast.api.AndroidDevice;
import net.srcz.android.screencast.api.file.FileInfo;
import com.android.ddmlib.IDevice;
public class JFrameExplorer extends JFrame {
JTree jt;
JSplitPane jSplitPane;
IDevice device;
JList jListFichiers;
Map<String,List<FileInfo>> cache = new LinkedHashMap<String,List<FileInfo>>();
private class FileTreeNode extends DefaultMutableTreeNode {
FileInfo fi;
public FileTreeNode(FileInfo fi) {
super(fi.name);
this.fi = fi;
}
}
private class FolderTreeNode extends LazyMutableTreeNode {
String name;
String path;
public FolderTreeNode(String name, String path) {
this.name = name;
this.path = path;
}
@Override
public void initChildren() {
List<FileInfo> fileInfos = cache.get(path);
if(fileInfos == null)
fileInfos = new AndroidDevice(device).list(path);
for (FileInfo fi : fileInfos) {
if (fi.directory)
add(new FolderTreeNode(fi.name, path + fi.name + "/"));
//else
//add(new FileTreeNode(fi));
}
}
public String toString() {
return name;
}
}
public JFrameExplorer(IDevice device) {
this.device = device;
setTitle("Explorer");
setLayout(new BorderLayout());
jt = new JTree(new DefaultMutableTreeNode("Test"));
jt.setModel(new DefaultTreeModel(new FolderTreeNode("Device", "/")));
jt.setRootVisible(true);
jt.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
TreePath tp = e.getPath();
if (tp == null)
return;
if (!(tp.getLastPathComponent() instanceof FolderTreeNode))
return;
FolderTreeNode node = (FolderTreeNode) tp
.getLastPathComponent();
displayFolder(node.path);
}
});
JScrollPane jsp = new JScrollPane(jt);
jListFichiers = new JList();
jListFichiers.setListData(new Object[] {});
jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
jsp, new JScrollPane(jListFichiers));
add(jSplitPane, BorderLayout.CENTER);
setSize(640, 480);
setLocationRelativeTo(null);
jListFichiers.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = jListFichiers.locationToIndex(e.getPoint());
ListModel dlm = jListFichiers.getModel();
FileInfo item = (FileInfo)dlm.getElementAt(index);;
launchFile(item);
}
}
});
}
private void displayFolder(String path) {
List<FileInfo> fileInfos = cache.get(path);
if(fileInfos == null)
fileInfos = new AndroidDevice(device).list(path);
List<FileInfo> files = new Vector<FileInfo>();
for(FileInfo fi2 : fileInfos) {
if(fi2.directory)
continue;
files.add(fi2);
}
jListFichiers.setListData(files.toArray());
}
private void launchFile(FileInfo node) {
try {
File tempFile = node.downloadTemporary();
Desktop.getDesktop().open(tempFile);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/explorer/JFrameExplorer.java
|
Java
|
asf20
| 3,703
|
package net.srcz.android.screencast.ui.explorer;
import javax.swing.tree.DefaultMutableTreeNode;
public abstract class LazyMutableTreeNode extends DefaultMutableTreeNode {
protected boolean _loaded = false;
public LazyMutableTreeNode() {
super();
}
public LazyMutableTreeNode(Object userObject) {
super(userObject);
}
public LazyMutableTreeNode(Object userObject, boolean allowsChildren) {
super(userObject, allowsChildren);
}
@Override
public int getChildCount() {
synchronized (this) {
if (!_loaded) {
_loaded = true;
initChildren();
}
}
return super.getChildCount();
}
public void clear() {
removeAllChildren();
_loaded = false;
}
public boolean isLoaded() {
return _loaded;
}
protected abstract void initChildren();
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/explorer/LazyMutableTreeNode.java
|
Java
|
asf20
| 779
|
package net.srcz.android.screencast.ui;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.StringTokenizer;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import javax.swing.plaf.basic.BasicLabelUI;
public class MultiLineLabelUI extends BasicLabelUI
{
static {
labelUI = new MultiLineLabelUI();
}
protected String layoutCL(
JLabel label,
FontMetrics fontMetrics,
String text,
Icon icon,
Rectangle viewR,
Rectangle iconR,
Rectangle textR)
{
String s = layoutCompoundLabel(
(JComponent) label,
fontMetrics,
splitStringByLines(text),
icon,
label.getVerticalAlignment(),
label.getHorizontalAlignment(),
label.getVerticalTextPosition(),
label.getHorizontalTextPosition(),
viewR,
iconR,
textR,
label.getIconTextGap());
if( s.equals("") )
return text;
return s;
}
static final int LEADING = SwingConstants.LEADING;
static final int TRAILING = SwingConstants.TRAILING;
static final int LEFT = SwingConstants.LEFT;
static final int RIGHT = SwingConstants.RIGHT;
static final int TOP = SwingConstants.TOP;
static final int CENTER = SwingConstants.CENTER;
/**
* Compute and return the location of the icons origin, the
* location of origin of the text baseline, and a possibly clipped
* version of the compound labels string. Locations are computed
* relative to the viewR rectangle.
* The JComponents orientation (LEADING/TRAILING) will also be taken
* into account and translated into LEFT/RIGHT values accordingly.
*/
public static String layoutCompoundLabel(JComponent c,
FontMetrics fm,
String[] text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap)
{
boolean orientationIsLeftToRight = true;
int hAlign = horizontalAlignment;
int hTextPos = horizontalTextPosition;
if (c != null) {
if (!(c.getComponentOrientation().isLeftToRight())) {
orientationIsLeftToRight = false;
}
}
// Translate LEADING/TRAILING values in horizontalAlignment
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalAlignment) {
case LEADING:
hAlign = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hAlign = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
// Translate LEADING/TRAILING values in horizontalTextPosition
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalTextPosition) {
case LEADING:
hTextPos = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hTextPos = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
return layoutCompoundLabel(fm,
text,
icon,
verticalAlignment,
hAlign,
verticalTextPosition,
hTextPos,
viewR,
iconR,
textR,
textIconGap);
}
/**
* Compute and return the location of the icons origin, the
* location of origin of the text baseline, and a possibly clipped
* version of the compound labels string. Locations are computed
* relative to the viewR rectangle.
* This layoutCompoundLabel() does not know how to handle LEADING/TRAILING
* values in horizontalTextPosition (they will default to RIGHT) and in
* horizontalAlignment (they will default to CENTER).
* Use the other version of layoutCompoundLabel() instead.
*/
public static String layoutCompoundLabel(
FontMetrics fm,
String[] text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap)
{
/* Initialize the icon bounds rectangle iconR.
*/
if (icon != null) {
iconR.width = icon.getIconWidth();
iconR.height = icon.getIconHeight();
}
else {
iconR.width = iconR.height = 0;
}
/* Initialize the text bounds rectangle textR. If a null
* or and empty String was specified we substitute "" here
* and use 0,0,0,0 for textR.
*/
// Fix for textIsEmpty sent by Paulo Santos
boolean textIsEmpty = (text == null) || (text.length == 0)
|| (text.length == 1 && ( (text[0]==null) || text[0].equals("") ));
String rettext = "";
if (textIsEmpty) {
textR.width = textR.height = 0;
}
else {
Dimension dim = computeMultiLineDimension( fm, text );
textR.width = dim.width;
textR.height = dim.height;
}
/* Unless both text and icon are non-null, we effectively ignore
* the value of textIconGap. The code that follows uses the
* value of gap instead of textIconGap.
*/
int gap = (textIsEmpty || (icon == null)) ? 0 : textIconGap;
if (!textIsEmpty) {
/* If the label text string is too wide to fit within the available
* space "..." and as many characters as will fit will be
* displayed instead.
*/
int availTextWidth;
if (horizontalTextPosition == CENTER) {
availTextWidth = viewR.width;
}
else {
availTextWidth = viewR.width - (iconR.width + gap);
}
if (textR.width > availTextWidth && text.length == 1) {
String clipString = "...";
int totalWidth = SwingUtilities.computeStringWidth(fm,clipString);
int nChars;
for(nChars = 0; nChars < text[0].length(); nChars++) {
totalWidth += fm.charWidth(text[0].charAt(nChars));
if (totalWidth > availTextWidth) {
break;
}
}
rettext = text[0].substring(0, nChars) + clipString;
textR.width = SwingUtilities.computeStringWidth(fm,rettext);
}
}
/* Compute textR.x,y given the verticalTextPosition and
* horizontalTextPosition properties
*/
if (verticalTextPosition == TOP) {
if (horizontalTextPosition != CENTER) {
textR.y = 0;
}
else {
textR.y = -(textR.height + gap);
}
}
else if (verticalTextPosition == CENTER) {
textR.y = (iconR.height / 2) - (textR.height / 2);
}
else { // (verticalTextPosition == BOTTOM)
if (horizontalTextPosition != CENTER) {
textR.y = iconR.height - textR.height;
}
else {
textR.y = (iconR.height + gap);
}
}
if (horizontalTextPosition == LEFT) {
textR.x = -(textR.width + gap);
}
else if (horizontalTextPosition == CENTER) {
textR.x = (iconR.width / 2) - (textR.width / 2);
}
else { // (horizontalTextPosition == RIGHT)
textR.x = (iconR.width + gap);
}
/* labelR is the rectangle that contains iconR and textR.
* Move it to its proper position given the labelAlignment
* properties.
*
* To avoid actually allocating a Rectangle, Rectangle.union
* has been inlined below.
*/
int labelR_x = Math.min(iconR.x, textR.x);
int labelR_width = Math.max(iconR.x + iconR.width,
textR.x + textR.width) - labelR_x;
int labelR_y = Math.min(iconR.y, textR.y);
int labelR_height = Math.max(iconR.y + iconR.height,
textR.y + textR.height) - labelR_y;
int dx, dy;
if (verticalAlignment == TOP) {
dy = viewR.y - labelR_y;
}
else if (verticalAlignment == CENTER) {
dy = (viewR.y + (viewR.height / 2)) - (labelR_y + (labelR_height / 2));
}
else { // (verticalAlignment == BOTTOM)
dy = (viewR.y + viewR.height) - (labelR_y + labelR_height);
}
if (horizontalAlignment == LEFT) {
dx = viewR.x - labelR_x;
}
else if (horizontalAlignment == RIGHT) {
dx = (viewR.x + viewR.width) - (labelR_x + labelR_width);
}
else { // (horizontalAlignment == CENTER)
dx = (viewR.x + (viewR.width / 2)) -
(labelR_x + (labelR_width / 2));
}
/* Translate textR and glypyR by dx,dy.
*/
textR.x += dx;
textR.y += dy;
iconR.x += dx;
iconR.y += dy;
return rettext;
}
protected void paintEnabledText(JLabel l, Graphics g, String s, int textX, int textY)
{
int accChar = l.getDisplayedMnemonic();
g.setColor(l.getForeground());
drawString(g, s, accChar, textX, textY);
}
protected void paintDisabledText(JLabel l, Graphics g, String s, int textX, int textY)
{
int accChar = l.getDisplayedMnemonic();
g.setColor(l.getBackground());
drawString(g, s, accChar, textX, textY);
}
protected void drawString( Graphics g, String s, int accChar, int textX, int textY )
{
if( s.indexOf('\n') == -1 )
BasicGraphicsUtils.drawString(g, s, accChar, textX, textY);
else
{
String[] strs = splitStringByLines( s );
int height = g.getFontMetrics().getHeight();
// Only the first line can have the accel char
BasicGraphicsUtils.drawString(g, strs[0], accChar, textX, textY);
for( int i = 1; i < strs.length; i++ )
g.drawString( strs[i], textX, textY + (height*i) );
}
}
public static Dimension computeMultiLineDimension( FontMetrics fm, String[] strs )
{
int i, c, width = 0;
for(i=0, c=strs.length ; i < c ; i++)
width = Math.max( width, SwingUtilities.computeStringWidth(fm,strs[i]) );
return new Dimension( width, fm.getHeight() * strs.length );
}
protected String str;
protected String[] strs;
public String[] splitStringByLines( String str )
{
if( str.equals(this.str) )
return strs;
this.str = str;
int lines = 1;
int i, c;
for(i=0, c=str.length() ; i < c ; i++) {
if( str.charAt(i) == '\n' )
lines++;
}
strs = new String[lines];
StringTokenizer st = new StringTokenizer( str, "\n" );
int line = 0;
while( st.hasMoreTokens() )
strs[line++] = st.nextToken();
return strs;
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/MultiLineLabelUI.java
|
Java
|
asf20
| 12,476
|
package net.srcz.android.screencast.ui;
import java.awt.BorderLayout;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.swing.JDialog;
import javax.swing.JTextArea;
public class JDialogError extends JDialog {
public JDialogError(Throwable ex) {
getRootPane().setLayout(new BorderLayout());
JTextArea l = new JTextArea();
StringWriter w = new StringWriter();
if(ex.getClass() == RuntimeException.class && ex.getCause() != null)
ex = ex.getCause();
ex.printStackTrace(new PrintWriter(w));
l.setText(w.toString());
getRootPane().add(l,BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setAlwaysOnTop(true);
setAlwaysOnTop(false);
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/JDialogError.java
|
Java
|
asf20
| 720
|
package net.srcz.android.screencast.ui.worker;
/*
* $Id: AccumulativeRunnable.java,v 1.3 2008/07/25 19:32:29 idk Exp $
*
* Copyright � 2005 Sun Microsystems, Inc. All rights
* reserved. Use is subject to license terms.
*/
import java.util.*;
import javax.swing.SwingUtilities;
/**
* An abstract class to be used in the cases where we need {@code Runnable}
* to perform some actions on an appendable set of data.
* The set of data might be appended after the {@code Runnable} is
* sent for the execution. Usually such {@code Runnables} are sent to
* the EDT.
*
* <p>
* Usage example:
*
* <p>
* Say we want to implement JLabel.setText(String text) which sends
* {@code text} string to the JLabel.setTextImpl(String text) on the EDT.
* In the event JLabel.setText is called rapidly many times off the EDT
* we will get many updates on the EDT but only the last one is important.
* (Every next updates overrides the previous one.)
* We might want to implement this {@code setText} in a way that only
* the last update is delivered.
* <p>
* Here is how one can do this using {@code AccumulativeRunnable}:
* <pre>
* AccumulativeRunnable<String> doSetTextImpl =
* new AccumulativeRunnable<String>() {
* @Override
* protected void run(List<String> args) {
* //set to the last string being passed
* setTextImpl(args.get(args.size() - 1);
* }
* }
* void setText(String text) {
* //add text and send for the execution if needed.
* doSetTextImpl.add(text);
* }
* </pre>
*
* <p>
* Say we want want to implement addDirtyRegion(Rectangle rect)
* which sends this region to the
* handleDirtyRegions(List<Rect> regions) on the EDT.
* addDirtyRegions better be accumulated before handling on the EDT.
*
* <p>
* Here is how it can be implemented using AccumulativeRunnable:
* <pre>
* AccumulativeRunnable<Rectangle> doHandleDirtyRegions =
* new AccumulativeRunnable<Rectangle>() {
* @Override
* protected void run(List<Rectangle> args) {
* handleDirtyRegions(args);
* }
* };
* void addDirtyRegion(Rectangle rect) {
* doHandleDirtyRegions.add(rect);
* }
* </pre>
*
* @author Igor Kushnirskiy
* @version $Revision: 1.3 $ $Date: 2008/07/25 19:32:29 $
*
* @param <T> the type this {@code Runnable} accumulates
*
*/
abstract class AccumulativeRunnable<T> implements Runnable {
private List<T> arguments = null;
/**
* Equivalent to {@code Runnable.run} method with the
* accumulated arguments to process.
*
* @param args accumulated arguments to process.
*/
protected abstract void run(List<T> args);
/**
* {@inheritDoc}
*
* <p>
* This implementation calls {@code run(List<T> args)} method
* with the list of accumulated arguments.
*/
public final void run() {
run(flush());
}
/**
* prepends or appends arguments and sends this {@code Runnable} for the
* execution if needed.
* <p>
* This implementation uses {@see #submit} to send this
* {@code Runnable} for execution.
* @param isPrepend prepend or append
* @param args the arguments to add
*/
public final synchronized void add(boolean isPrepend, T... args) {
boolean isSubmitted = true;
if (arguments == null) {
isSubmitted = false;
arguments = new ArrayList<T>();
}
if (isPrepend) {
arguments.addAll(0, Arrays.asList(args));
} else {
Collections.addAll(arguments, args);
}
if (!isSubmitted) {
submit();
}
}
/**
* appends arguments and sends this {@code Runnable} for the
* execution if needed.
* <p>
* This implementation uses {@see #submit} to send this
* {@code Runnable} for execution.
* @param args the arguments to accumulate
*/
public final void add(T... args) {
add(false, args);
}
/**
* Sends this {@code Runnable} for the execution
*
* <p>
* This method is to be executed only from {@code add} method.
*
* <p>
* This implementation uses {@code SwingWorker.invokeLater}.
*/
protected void submit() {
SwingUtilities.invokeLater(this);
}
/**
* Returns accumulated arguments and flashes the arguments storage.
*
* @return accumulated arguments
*/
private final synchronized List<T> flush() {
List<T> list = arguments;
arguments = null;
return list;
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/worker/AccumulativeRunnable.java
|
Java
|
asf20
| 4,804
|
/*
* $Id: SwingWorker.java,v 1.6 2008/07/25 19:32:29 idk Exp $
*
* Copyright � 2005 Sun Microsystems, Inc. All rights
* reserved. Use is subject to license terms.
*/
package net.srcz.android.screencast.ui.worker;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeEvent;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
/**
* An abstract class to perform lengthy GUI-interacting tasks in a
* dedicated thread.
*
* <p>
* When writing a multi-threaded application using Swing, there are
* two constraints to keep in mind:
* (refer to
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">
* How to Use Threads
* </a> for more details):
* <ul>
* <li> Time-consuming tasks should not be run on the <i>Event
* Dispatch Thread</i>. Otherwise the application becomes unresponsive.
* </li>
* <li> Swing components should be accessed on the <i>Event
* Dispatch Thread</i> only.
* </li>
* </ul>
*
* <p>
*
* <p>
* These constraints mean that a GUI application with time intensive
* computing needs at least two threads: 1) a thread to perform the lengthy
* task and 2) the <i>Event Dispatch Thread</i> (EDT) for all GUI-related
* activities. This involves inter-thread communication which can be
* tricky to implement.
*
* <p>
* {@code SwingWorker} is designed for situations where you need to have a long
* running task run in a background thread and provide updates to the UI
* either when done, or while processing.
* Subclasses of {@code SwingWorker} must implement
* the {@see #doInBackground} method to perform the background computation.
*
*
* <p>
* <b>Workflow</b>
* <p>
* There are three threads involved in the life cycle of a
* {@code SwingWorker} :
* <ul>
* <li>
* <p>
* <i>Current</i> thread: The {@link #execute} method is
* called on this thread. It schedules {@code SwingWorker} for the execution on a
* <i>worker</i>
* thread and returns immediately. One can wait for the {@code SwingWorker} to
* complete using the {@link #get get} methods.
* <li>
* <p>
* <i>Worker</i> thread: The {@link #doInBackground}
* method is called on this thread.
* This is where all background activities should happen. To notify
* {@code PropertyChangeListeners} about bound properties changes use the
* {@link #firePropertyChange firePropertyChange} and
* {@link #getPropertyChangeSupport} methods. By default there are two bound
* properties available: {@code state} and {@code progress}.
* <li>
* <p>
* <i>Event Dispatch Thread</i>: All Swing related activities occur
* on this thread. {@code SwingWorker} invokes the
* {@link #process process} and {@link #done} methods and notifies
* any {@code PropertyChangeListeners} on this thread.
* </ul>
*
* <p>
* Often, the <i>Current</i> thread is the <i>Event Dispatch
* Thread</i>.
*
*
* <p>
* Before the {@code doInBackground} method is invoked on a <i>worker</i> thread,
* {@code SwingWorker} notifies any {@code PropertyChangeListeners} about the
* {@code state} property change to {@code StateValue.STARTED}. After the
* {@code doInBackground} method is finished the {@code done} method is
* executed. Then {@code SwingWorker} notifies any {@code PropertyChangeListeners}
* about the {@code state} property change to {@code StateValue.DONE}.
*
* <p>
* {@code SwingWorker} is only designed to be executed once. Executing a
* {@code SwingWorker} more than once will not result in invoking the
* {@code doInBackground} method twice.
*
* <p>
* <b>Sample Usage</b>
* <p>
* The following example illustrates the simplest use case. Some
* processing is done in the background and when done you update a Swing
* component.
*
* <p>
* Say we want to find the "Meaning of Life" and display the result in
* a {@code JLabel}.
*
* <pre>
* final JLabel label;
* class MeaningOfLifeFinder extends SwingWorker<String, Object> {
* {@code @Override}
* public String doInBackground() {
* return findTheMeaningOfLife();
* }
*
* {@code @Override}
* protected void done() {
* try {
* label.setText(get());
* } catch (Exception ignore) {
* }
* }
* }
*
* (new MeaningOfLifeFinder()).execute();
* </pre>
*
* <p>
* The next example is useful in situations where you wish to process data
* as it is ready on the <i>Event Dispatch Thread</i>.
*
* <p>
* Now we want to find the first N prime numbers and display the results in a
* {@code JTextArea}. While this is computing, we want to update our
* progress in a {@code JProgressBar}. Finally, we also want to print
* the prime numbers to {@code System.out}.
* <pre>
* class PrimeNumbersTask extends
* SwingWorker<List<Integer>, Integer> {
* PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
* //initialize
* }
*
* {@code @Override}
* public List<Integer> doInBackground() {
* while (! enough && ! isCancelled()) {
* number = nextPrimeNumber();
* publish(number);
* setProgress(100 * numbers.size() / numbersToFind);
* }
* }
* return numbers;
* }
*
* {@code @Override}
* protected void process(List<Integer> chunks) {
* for (int number : chunks) {
* textArea.append(number + "\n");
* }
* }
* }
*
* JTextArea textArea = new JTextArea();
* final JProgressBar progressBar = new JProgressBar(0, 100);
* PrimeNumbersTask task = new PrimeNumbersTask(textArea, N);
* task.addPropertyChangeListener(
* new PropertyChangeListener() {
* public void propertyChange(PropertyChangeEvent evt) {
* if ("progress".equals(evt.getPropertyName())) {
* progressBar.setValue((Integer)evt.getNewValue());
* }
* }
* });
*
* task.execute();
* System.out.println(task.get()); //prints all prime numbers we have got
* </pre>
*
* <p>
* Because {@code SwingWorker} implements {@code Runnable}, a
* {@code SwingWorker} can be submitted to an
* {@link java.util.concurrent.Executor} for execution.
*
* @author Igor Kushnirskiy
* @version $Revision: 1.6 $ $Date: 2008/07/25 19:32:29 $
*
* @param <T> the result type returned by this {@code SwingWorker's}
* {@code doInBackground} and {@code get} methods
* @param <V> the type used for carrying out intermediate results by this
* {@code SwingWorker's} {@code publish} and {@code process} methods
*
*/
public abstract class SwingWorker<T, V> implements Future<T>, Runnable {
/**
* number of worker threads.
*/
private static final int MAX_WORKER_THREADS = 10;
/**
* current progress.
*/
private volatile int progress;
/**
* current state.
*/
private volatile StateValue state;
/**
* everything is run inside this FutureTask. Also it is used as
* a delegatee for the Future API.
*/
private final FutureTask<T> future;
/**
* all propertyChangeSupport goes through this.
*/
private final PropertyChangeSupport propertyChangeSupport;
/**
* handler for {@code process} method.
*/
private AccumulativeRunnable<V> doProcess;
/**
* handler for progress property change notifications.
*/
private AccumulativeRunnable<Integer> doNotifyProgressChange;
private static final AccumulativeRunnable<Runnable> doSubmit =
new DoSubmitAccumulativeRunnable();
private static ExecutorService executorService = null;
/**
* Values for the {@code state} bound property.
*/
public enum StateValue {
/**
* Initial {@code SwingWorker} state.
*/
PENDING,
/**
* {@code SwingWorker} is {@code STARTED}
* before invoking {@code doInBackground}.
*/
STARTED,
/**
* {@code SwingWorker} is {@code DONE}
* after {@code doInBackground} method
* is finished.
*/
DONE
};
/**
* Constructs this {@code SwingWorker}.
*/
public SwingWorker() {
Callable<T> callable =
new Callable<T>() {
public T call() throws Exception {
setState(StateValue.STARTED);
return doInBackground();
}
};
future = new FutureTask<T>(callable) {
@Override
protected void done() {
doneEDT();
setState(StateValue.DONE);
}
};
state = StateValue.PENDING;
propertyChangeSupport = new SwingWorkerPropertyChangeSupport(this);
doProcess = null;
doNotifyProgressChange = null;
}
/**
* Computes a result, or throws an exception if unable to do so.
*
* <p>
* Note that this method is executed only once.
*
* <p>
* Note: this method is executed in a background thread.
*
*
* @return the computed result
* @throws Exception if unable to compute a result
*
*/
protected abstract T doInBackground() throws Exception ;
/**
* Sets this {@code Future} to the result of computation unless
* it has been cancelled.
*/
public final void run() {
future.run();
}
/**
* Sends data chunks to the {@link #process} method. This method is to be
* used from inside the {@code doInBackground} method to deliver
* intermediate results
* for processing on the <i>Event Dispatch Thread</i> inside the
* {@code process} method.
*
* <p>
* Because the {@code process} method is invoked asynchronously on
* the <i>Event Dispatch Thread</i>
* multiple invocations to the {@code publish} method
* might occur before the {@code process} method is executed. For
* performance purposes all these invocations are coalesced into one
* invocation with concatenated arguments.
*
* <p>
* For example:
*
* <pre>
* publish("1");
* publish("2", "3");
* publish("4", "5", "6");
* </pre>
*
* might result in:
*
* <pre>
* process("1", "2", "3", "4", "5", "6")
* </pre>
*
* <p>
* <b>Sample Usage</b>. This code snippet loads some tabular data and
* updates {@code DefaultTableModel} with it. Note that it safe to mutate
* the tableModel from inside the {@code process} method because it is
* invoked on the <i>Event Dispatch Thread</i>.
*
* <pre>
* class TableSwingWorker extends
* SwingWorker<DefaultTableModel, Object[]> {
* private final DefaultTableModel tableModel;
*
* public TableSwingWorker(DefaultTableModel tableModel) {
* this.tableModel = tableModel;
* }
*
* {@code @Override}
* protected DefaultTableModel doInBackground() throws Exception {
* for (Object[] row = loadData();
* ! isCancelled() && row != null;
* row = loadData()) {
* publish((Object[]) row);
* }
* return tableModel;
* }
*
* {@code @Override}
* protected void process(List<Object[]> chunks) {
* for (Object[] row : chunks) {
* tableModel.addRow(row);
* }
* }
* }
* </pre>
*
* @param chunks intermediate results to process
*
* @see #process
*
*/
protected final void publish(V... chunks) {
synchronized (this) {
if (doProcess == null) {
doProcess = new AccumulativeRunnable<V>() {
@Override
public void run(List<V> args) {
process(args);
}
@Override
protected void submit() {
doSubmit.add(this);
}
};
}
}
doProcess.add(chunks);
}
/**
* Receives data chunks from the {@code publish} method asynchronously on the
* <i>Event Dispatch Thread</i>.
*
* <p>
* Please refer to the {@link #publish} method for more details.
*
* @param chunks intermediate results to process
*
* @see #publish
*
*/
protected void process(List<V> chunks) {
}
/**
* Executed on the <i>Event Dispatch Thread</i> after the {@code doInBackground}
* method is finished. The default
* implementation does nothing. Subclasses may override this method to
* perform completion actions on the <i>Event Dispatch Thread</i>. Note
* that you can query status inside the implementation of this method to
* determine the result of this task or whether this task has been cancelled.
*
* @see #doInBackground
* @see #isCancelled()
* @see #get
*/
protected void done() {
}
/**
* Sets the {@code progress} bound property.
* The value should be from 0 to 100.
*
* <p>
* Because {@code PropertyChangeListener}s are notified asynchronously on
* the <i>Event Dispatch Thread</i> multiple invocations to the
* {@code setProgress} method might occur before any
* {@code PropertyChangeListeners} are invoked. For performance purposes
* all these invocations are coalesced into one invocation with the last
* invocation argument only.
*
* <p>
* For example, the following invocations:
*
* <pre>
* setProgress(1);
* setProgress(2);
* setProgress(3);
* </pre>
*
* might result in a single {@code PropertyChangeListener} notification with
* the value {@code 3}.
*
* @param progress the progress value to set
* @throws IllegalArgumentException is value not from 0 to 100
*/
protected final void setProgress(int progress) {
if (progress < 0 || progress > 100) {
throw new IllegalArgumentException("the value should be from 0 to 100");
}
if (this.progress == progress) {
return;
}
int oldProgress = this.progress;
this.progress = progress;
if (! getPropertyChangeSupport().hasListeners("progress")) {
return;
}
synchronized (this) {
if (doNotifyProgressChange == null) {
doNotifyProgressChange =
new AccumulativeRunnable<Integer>() {
@Override
public void run(List<Integer> args) {
firePropertyChange("progress",
args.get(0),
args.get(args.size() - 1));
}
@Override
protected void submit() {
doSubmit.add(this);
}
};
}
}
doNotifyProgressChange.add(oldProgress, progress);
}
/**
* Returns the {@code progress} bound property.
*
* @return the progress bound property.
*/
public final int getProgress() {
return progress;
}
/**
* Schedules this {@code SwingWorker} for execution on a <i>worker</i>
* thread. There are a number of <i>worker</i> threads available. In the
* event all <i>worker</i> threads are busy handling other
* {@code SwingWorkers} this {@code SwingWorker} is placed in a waiting
* queue.
*
* <p>
* Note:
* {@code SwingWorker} is only designed to be executed once. Executing a
* {@code SwingWorker} more than once will not result in invoking the
* {@code doInBackground} method twice.
*/
public final void execute() {
getWorkersExecutorService().execute(this);
}
// Future methods START
/**
* {@inheritDoc}
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
/**
* {@inheritDoc}
*/
public final boolean isCancelled() {
return future.isCancelled();
}
/**
* {@inheritDoc}
*/
public final boolean isDone() {
return future.isDone();
}
/**
* {@inheritDoc}
* <p>
* Note: calling {@code get} on the <i>Event Dispatch Thread</i> blocks
* <i>all</i> events, including repaints, from being processed until this
* {@code SwingWorker} is complete.
*
* <p>
* When you want the {@code SwingWorker} to block on the <i>Event
* Dispatch Thread</i> we recommend that you use a <i>modal dialog</i>.
*
* <p>
* For example:
*
* <pre>
* class SwingWorkerCompletionWaiter implements PropertyChangeListener {
* private JDialog dialog;
*
* public SwingWorkerCompletionWaiter(JDialog dialog) {
* this.dialog = dialog;
* }
*
* public void propertyChange(PropertyChangeEvent event) {
* if ("state".equals(event.getPropertyName())
* && SwingWorker.StateValue.DONE == event.getNewValue()) {
* dialog.setVisible(false);
* dialog.dispose();
* }
* }
* }
* JDialog dialog = new JDialog(owner, true);
* swingWorker.addPropertyChangeListener(
* new SwingWorkerCompletionWaiter(dialog));
* swingWorker.execute();
* //the dialog will be visible until the SwingWorker is done
* dialog.setVisible(true);
* </pre>
*/
public final T get() throws InterruptedException, ExecutionException {
return future.get();
}
/**
* {@inheritDoc}
* <p>
* Please refer to {@link #get} for more details.
*/
public final T get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return future.get(timeout, unit);
}
// Future methods END
// PropertyChangeSupports methods START
/**
* Adds a {@code PropertyChangeListener} to the listener list. The listener
* is registered for all properties. The same listener object may be added
* more than once, and will be called as many times as it is added. If
* {@code listener} is {@code null}, no exception is thrown and no action is taken.
*
* <p>
* Note: This is merely a convenience wrapper. All work is delegated to
* {@code PropertyChangeSupport} from {@link #getPropertyChangeSupport}.
*
* @param listener the {@code PropertyChangeListener} to be added
*/
public final void addPropertyChangeListener(PropertyChangeListener listener) {
getPropertyChangeSupport().addPropertyChangeListener(listener);
}
/**
* Removes a {@code PropertyChangeListener} from the listener list. This
* removes a {@code PropertyChangeListener} that was registered for all
* properties. If {@code listener} was added more than once to the same
* event source, it will be notified one less time after being removed. If
* {@code listener} is {@code null}, or was never added, no exception is
* thrown and no action is taken.
*
* <p>
* Note: This is merely a convenience wrapper. All work is delegated to
* {@code PropertyChangeSupport} from {@link #getPropertyChangeSupport}.
*
* @param listener the {@code PropertyChangeListener} to be removed
*/
public final void removePropertyChangeListener(PropertyChangeListener listener) {
getPropertyChangeSupport().removePropertyChangeListener(listener);
}
/**
* Reports a bound property update to any registered listeners. No event is
* fired if {@code old} and {@code new} are equal and non-null.
*
* <p>
* This {@code SwingWorker} will be the source for
* any generated events.
*
* <p>
* When called off the <i>Event Dispatch Thread</i>
* {@code PropertyChangeListeners} are notified asynchronously on
* the <i>Event Dispatch Thread</i>.
* <p>
* Note: This is merely a convenience wrapper. All work is delegated to
* {@code PropertyChangeSupport} from {@link #getPropertyChangeSupport}.
*
*
* @param propertyName the programmatic name of the property that was
* changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
*/
public final void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
getPropertyChangeSupport().firePropertyChange(propertyName,
oldValue, newValue);
}
/**
* Returns the {@code PropertyChangeSupport} for this {@code SwingWorker}.
* This method is used when flexible access to bound properties support is
* needed.
* <p>
* This {@code SwingWorker} will be the source for
* any generated events.
*
* <p>
* Note: The returned {@code PropertyChangeSupport} notifies any
* {@code PropertyChangeListener}s asynchronously on the <i>Event Dispatch
* Thread</i> in the event that {@code firePropertyChange} or
* {@code fireIndexedPropertyChange} are called off the <i>Event Dispatch
* Thread</i>.
*
* @return {@code PropertyChangeSupport} for this {@code SwingWorker}
*/
public final PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
// PropertyChangeSupports methods END
/**
* Returns the {@code SwingWorker} state bound property.
*
* @return the current state
*/
public final StateValue getState() {
/*
* DONE is a special case
* to keep getState and isDone is sync
*/
if (isDone()) {
return StateValue.DONE;
} else {
return state;
}
}
/**
* Sets this {@code SwingWorker} state bound property.
* @param the state state to set
*/
private void setState(StateValue state) {
StateValue old = this.state;
this.state = state;
firePropertyChange("state", old, state);
}
/**
* Invokes {@code done} on the EDT.
*/
private void doneEDT() {
Runnable doDone =
new Runnable() {
public void run() {
done();
}
};
if (SwingUtilities.isEventDispatchThread()) {
doDone.run();
} else {
doSubmit.add(doDone);
}
}
/**
* returns workersExecutorService.
*
* returns the service stored in the appContext or creates it if
* necessary. If the last one it triggers autoShutdown thread to
* get started.
*
* @return ExecutorService for the {@code SwingWorkers}
* @see #startAutoShutdownThread
*/
private static synchronized ExecutorService getWorkersExecutorService() {
if (executorService == null) {
//this creates non-daemon threads.
ThreadFactory threadFactory =
new ThreadFactory() {
final AtomicInteger threadNumber = new AtomicInteger(1);
public Thread newThread(final Runnable r) {
StringBuilder name =
new StringBuilder("SwingWorker-pool-");
name.append(System.identityHashCode(this));
name.append("-thread-");
name.append(threadNumber.getAndIncrement());
Thread t = new Thread(r, name.toString());;
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
};
/*
* We want a to have no more than MAX_WORKER_THREADS
* running threads.
*
* We want a worker thread to wait no longer than 1 second
* for new tasks before terminating.
*/
executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS,
5L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory) {
private final ReentrantLock pauseLock = new ReentrantLock();
private final Condition unpaused = pauseLock.newCondition();
private boolean isPaused = false;
private final ReentrantLock executeLock = new ReentrantLock();
@Override
public void execute(Runnable command) {
/*
* ThreadPoolExecutor first tries to run task
* in a corePool. If all threads are busy it
* tries to add task to the waiting queue. If it
* fails it run task in maximumPool.
*
* We want corePool to be 0 and
* maximumPool to be MAX_WORKER_THREADS
* We need to change the order of the execution.
* First try corePool then try maximumPool
* pool and only then store to the waiting
* queue. We can not do that because we would
* need access to the private methods.
*
* Instead we enlarge corePool to
* MAX_WORKER_THREADS before the execution and
* shrink it back to 0 after.
* It does pretty much what we need.
*
* While we changing the corePoolSize we need
* to stop running worker threads from accepting new
* tasks.
*/
//we need atomicity for the execute method.
executeLock.lock();
try {
pauseLock.lock();
try {
isPaused = true;
} finally {
pauseLock.unlock();
}
setCorePoolSize(MAX_WORKER_THREADS);
super.execute(command);
setCorePoolSize(0);
pauseLock.lock();
try {
isPaused = false;
unpaused.signalAll();
} finally {
pauseLock.unlock();
}
} finally {
executeLock.unlock();
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
pauseLock.lock();
try {
while(isPaused) {
unpaused.await();
}
} catch(InterruptedException ignore) {
} finally {
pauseLock.unlock();
}
}
};
}
return executorService;
}
private static class DoSubmitAccumulativeRunnable
extends AccumulativeRunnable<Runnable> implements ActionListener {
private final static int DELAY = (int) (1000 / 30);
@Override
protected void run(List<Runnable> args) {
int i = 0;
try {
for (Runnable runnable : args) {
i++;
runnable.run();
}
} finally {
if (i < args.size()) {
/* there was an exception
* schedule all the unhandled items for the next time
*/
Runnable argsTail[] = new Runnable[args.size() - i];
for (int j = 0; j < argsTail.length; j++) {
argsTail[j] = args.get(i + j);
}
add(true, argsTail);
}
}
}
@Override
protected void submit() {
Timer timer = new Timer(DELAY, this);
timer.setRepeats(false);
timer.start();
}
public void actionPerformed(ActionEvent event) {
run();
}
}
private class SwingWorkerPropertyChangeSupport
extends PropertyChangeSupport {
SwingWorkerPropertyChangeSupport(Object source) {
super(source);
}
@Override
public void firePropertyChange(final PropertyChangeEvent evt) {
if (SwingUtilities.isEventDispatchThread()) {
super.firePropertyChange(evt);
} else {
doSubmit.add(
new Runnable() {
public void run() {
SwingWorkerPropertyChangeSupport.this
.firePropertyChange(evt);
}
});
}
}
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/worker/SwingWorker.java
|
Java
|
asf20
| 31,664
|
package net.srcz.android.screencast.ui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JTextField;
public class JDialogUrl extends JDialog {
JTextField jtfUrl = new JTextField();
JButton jbOk = new JButton("Ok");
boolean result = false;
public JDialogUrl() {
setModal(true);
setTitle("Open url");
setLayout(new BorderLayout());
add(jbOk,BorderLayout.SOUTH);
add(jtfUrl,BorderLayout.CENTER);
jtfUrl.setColumns(50);
jbOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
result = true;
JDialogUrl.this.setVisible(false);
}
});
jbOk.setDefaultCapable(true);
getRootPane().setDefaultButton(jbOk);
pack();
setLocationRelativeTo(null);
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/ui/JDialogUrl.java
|
Java
|
asf20
| 869
|
package net.srcz.android.screencast.api;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtils {
public static void transfert(InputStream is, OutputStream os) {
try {
while(true) {
int val = is.read();
if(val <= -1)
break;
os.write(val);
}
} catch(IOException io) {
throw new RuntimeException(io);
}
}
public static void transfertResource(Class c, String resourceName, File output) {
InputStream resStream = c.getResourceAsStream(resourceName);
if(resStream == null)
throw new RuntimeException("Cannot find resource "+resourceName);
try {
FileOutputStream fos = new FileOutputStream(output);
transfert(resStream,fos);
fos.close();
resStream.close();
} catch(Exception ex) {
throw new RuntimeException(ex);
}
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/StreamUtils.java
|
Java
|
asf20
| 891
|
package net.srcz.android.screencast.api.recording;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.*;
import java.util.Date;
import java.util.LinkedList;
import javax.imageio.*;
import javax.imageio.stream.*;
public class QuickTimeOutputStream {
/**
* Output stream of the QuickTimeOutputStream.
*/
private ImageOutputStream out;
/**
* Supported video formats.
*/
public static enum VideoFormat {
RAW, JPG, PNG;
}
/**
* Current video format.
*/
private VideoFormat videoFormat;
/**
* Quality of JPEG encoded video frames.
*/
private float quality = 0.9f;
/**
* Creation time of the movie output stream.
*/
private Date creationTime;
/**
* Width of the video frames. All frames must have the same width.
* The value -1 is used to mark unspecified width.
*/
private int imgWidth = -1;
/**
* Height of the video frames. All frames must have the same height.
* The value -1 is used to mark unspecified height.
*/
private int imgHeight = -1;
/**
* The timeScale of the movie.
* A time value that indicates the time scale for this media—that is,
* the number of time units that pass per second in its time coordinate
* system.
*/
private int timeScale = 600;
/**
* The states of the movie output stream.
*/
private static enum States {
STARTED, FINISHED, CLOSED;
}
/**
* The current state of the movie output stream.
*/
private States state = States.FINISHED;
/**
* QuickTime stores media data in samples.
* A sample is a single element in a sequence of time-ordered data.
* Samples are stored in the mdat atom.
*/
private static class Sample {
/** Offset of the sample relative to the start of the QuickTime file.
*/
long offset;
/** Data length of the sample. */
long length;
/**
* The duration of the sample in time scale units.
*/
int duration;
/**
* Creates a new sample.
* @param duration
* @param offset
* @param length
*/
public Sample(int duration, long offset, long length) {
this.duration = duration;
this.offset = offset;
this.length = length;
}
}
/**
* List of video frames.
*/
private LinkedList<Sample> videoFrames;
/**
* This atom holds the movie frames.
*/
private WideDataAtom mdatAtom;
/**
* Atom base class.
*/
private abstract class Atom {
/**
* The type of the atom. A String with the length of 4 characters.
*/
protected String type;
/**
* The offset of the atom relative to the start of the
* ImageOutputStream.
*/
protected long offset;
/**
* Creates a new Atom at the current position of the ImageOutputStream.
* @param type The type of the atom. A string with a length of 4 characters.
*/
public Atom(String type) throws IOException {
this.type = type;
offset = out.getStreamPosition();
}
/**
* Writes the atom to the ImageOutputStream and disposes it.
*/
public abstract void finish() throws IOException;
/**
* Returns the size of the atom including the size of the atom header.
* @return The size of the atom.
*/
public abstract long size();
}
/**
* A CompositeAtom contains an ordered list of Atoms.
*/
private class CompositeAtom extends Atom {
private LinkedList<Atom> children;
private boolean finished;
/**
* Creates a new CompositeAtom at the current position of the
* ImageOutputStream.
* @param type The type of the atom.
*/
public CompositeAtom(String type) throws IOException {
super(type);
out.writeLong(0); // make room for the atom header
children = new LinkedList<Atom>();
}
public void add(Atom child) throws IOException {
if (children.size() > 0) {
children.getLast().finish();
}
children.add(child);
}
/**
* Writes the atom and all its children to the ImageOutputStream
* and disposes of all resources held by the atom.
* @throws java.io.IOException
*/
public void finish() throws IOException {
if (!finished) {
if (size() > 0xffffffffL) {
throw new IOException("CompositeAtom \"" + type + "\" is too large: " + size());
}
long pointer = out.getStreamPosition();
out.seek(offset);
DataAtomOutputStream headerData = new DataAtomOutputStream(new FilterImageOutputStream(out));
headerData.writeInt((int) size());
headerData.writeType(type);
for (Atom child : children) {
child.finish();
}
out.seek(pointer);
finished = true;
}
}
public long size() {
long length = 8;
for (Atom child : children) {
length += child.size();
}
return length;
}
}
/**
* Data Atom.
*/
protected class DataAtom extends Atom {
private DataAtomOutputStream data;
private boolean finished;
/**
* Creates a new DataAtom at the current position of the
* ImageOutputStream.
* @param type The type of the atom.
*/
public DataAtom(String name) throws IOException {
super(name);
out.writeLong(0); // make room for the atom header
data = new DataAtomOutputStream(new FilterImageOutputStream(out));
}
public DataAtomOutputStream getOutputStream() {
if (finished) {
throw new IllegalStateException("DataAtom is finished");
}
return data;
}
/**
* Returns the offset of this atom to the beginning of the random access file
* @return
*/
public long getOffset() {
return offset;
}
@Override
public void finish() throws IOException {
if (!finished) {
long sizeBefore = size();
if (size() > 0xffffffffL) {
throw new IOException("DataAtom \"" + type + "\" is too large: " + size());
}
long pointer = out.getStreamPosition();
out.seek(offset);
DataAtomOutputStream headerData = new DataAtomOutputStream(new FilterImageOutputStream(out));
headerData.writeUInt(size());
headerData.writeType(type);
out.seek(pointer);
finished = true;
long sizeAfter = size();
if (sizeBefore != sizeAfter) {
System.err.println("size mismatch " + sizeBefore + ".." + sizeAfter);
}
}
}
@Override
public long size() {
return 8 + data.size();
}
}
/**
* WideDataAtom can grow larger then 4 gigabytes.
*/
protected class WideDataAtom extends Atom {
private DataAtomOutputStream data;
private boolean finished;
/**
* Creates a new DataAtom at the current position of the
* ImageOutputStream.
* @param type The type of the atom.
*/
public WideDataAtom(String type) throws IOException {
super(type);
out.writeLong(0); // make room for the atom header
out.writeLong(0); // make room for the atom header
data = new DataAtomOutputStream(new FilterImageOutputStream(out));
}
public DataAtomOutputStream getOutputStream() {
if (finished) {
throw new IllegalStateException("Atom is finished");
}
return data;
}
/**
* Returns the offset of this atom to the beginning of the random access file
* @return
*/
public long getOffset() {
return offset;
}
@Override
public void finish() throws IOException {
if (!finished) {
long pointer = out.getStreamPosition();
out.seek(offset);
DataAtomOutputStream headerData = new DataAtomOutputStream(new FilterImageOutputStream(out));
if (size() <= 0xffffffffL) {
headerData.writeUInt(8);
headerData.writeType("wide");
headerData.writeUInt(size());
headerData.writeType(type);
} else {
headerData.writeInt(1); // special value for extended size atoms
headerData.writeType(type);
headerData.writeLong(size());
}
out.seek(pointer);
finished = true;
}
}
@Override
public long size() {
long size = 8 + data.size();
return (size > 0xffffffffL) ? size + 8 : size;
}
}
/**
* Creates a new output stream with the specified image videoFormat and
* framerate.
*
* @param file the output file
* @param format Selects an encoder for the video format "JPG" or "PNG".
* @exception IllegalArgumentException if videoFormat is null or if
* framerate is <= 0
*/
public QuickTimeOutputStream(File file, VideoFormat format) throws IOException {
if (file.exists()) {
file.delete();
}
out = new FileImageOutputStream(file);
if (format == null) {
throw new IllegalArgumentException("format must not be null");
}
this.videoFormat = format;
this.videoFrames = new LinkedList<Sample>();
}
/**
* Sets the time scale for this media, that is, the number of time units
* that pass per second in its time coordinate system.
* <p>
* The default value is 600.
*
* @param newValue
*/
public void setTimeScale(int newValue) {
if (newValue <= 0) {
throw new IllegalArgumentException("timeScale must be greater 0");
}
this.timeScale = newValue;
}
/**
* Returns the time scale of this media.
*
* @return time scale
*/
public int getTimeScale() {
return timeScale;
}
/**
* Sets the compression quality of the video track.
* A value of 0 stands for "high compression is important" a value of
* 1 for "high image quality is important".
* <p>
* Changing this value affects frames which are subsequently written
* to the QuickTimeOutputStream. Frames which have already been written
* are not changed.
* <p>
* This value has no effect on videos encoded with the PNG format.
* <p>
* The default value is 0.9.
*
* @param newValue
*/
public void setVideoCompressionQuality(float newValue) {
this.quality = newValue;
}
/**
* Returns the video compression quality.
*
* @return video compression quality
*/
public float getVideoCompressionQuality() {
return quality;
}
/**
* Sets the dimension of the video track.
* <p>
* You need to explicitly set the dimension, if you add all frames from
* files or input streams.
* <p>
* If you add frames from buffered images, then QuickTimeOutputStream
* can determine the video dimension from the image width and height.
*
* @param width
* @param height
*/
public void setVideoDimension(int width, int height) {
if (width < 1 || height < 1) {
throw new IllegalArgumentException("width and height must be greater zero.");
}
this.imgWidth = width;
this.imgHeight = height;
}
/**
* Sets the state of the QuickTimeOutpuStream to started.
* <p>
* If the state is changed by this method, the prolog is
* written.
*/
private void ensureStarted() throws IOException {
if (state != States.STARTED) {
creationTime = new Date();
writeProlog();
mdatAtom = new WideDataAtom("mdat");
state = States.STARTED;
}
}
/**
* Writes a frame to the video track.
* <p>
* If the dimension of the video track has not been specified yet, it
* is derived from the first buffered image added to the QuickTimeOutputStream.
*
* @param image The frame image.
* @param duration The duration of the frame in time scale units.
*
* @throws IllegalArgumentException if the duration is less than 1, or
* if the dimension of the frame does not match the dimension of the video
* track.
* @throws IOException if writing the image failed.
*/
public void writeFrame(BufferedImage image, int duration) throws IOException {
if (duration <= 0) {
throw new IllegalArgumentException("duration must be greater 0");
}
ensureOpen();
ensureStarted();
// Get the dimensions of the first image
if (imgWidth == -1) {
imgWidth = image.getWidth();
imgHeight = image.getHeight();
} else {
// The dimension of the image must match the dimension of the video track
if (imgWidth != image.getWidth() || imgHeight != image.getHeight()) {
throw new IllegalArgumentException("Dimensions of image[" + videoFrames.size() +
"] (width=" + image.getWidth() + ", height=" + image.getHeight() +
") differs from image[0] (width=" +
imgWidth + ", height=" + imgHeight);
}
}
long offset = out.getStreamPosition();
switch (videoFormat) {
case RAW: {
WritableRaster raster = image.getRaster();
int[] raw = new int[imgWidth * 3]; // holds a scanline of raw image data with 3 channels of 32 bit data
byte[] bytes = new byte[imgWidth * 3]; // holds a scanline of raw image data with 3 channels of 8 bit data
for (int y = 0; y < imgHeight; y++) {
raster.getPixels(0, y, imgWidth, 1, raw);
for (int k = 0, n = imgWidth * 3; k < n; k++) {
bytes[k] = (byte) raw[k];
}
mdatAtom.getOutputStream().write(bytes);
}
break;
}
case JPG: {
ImageWriter iw = (ImageWriter) ImageIO.getImageWritersByMIMEType("image/jpeg").next();
ImageWriteParam iwParam = iw.getDefaultWriteParam();
iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwParam.setCompressionQuality(quality);
MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(mdatAtom.getOutputStream());
iw.setOutput(imgOut);
IIOImage img = new IIOImage(image, null, null);
iw.write(null, img, iwParam);
iw.dispose();
break;
}
case PNG:
default: {
ImageWriter iw = (ImageWriter) ImageIO.getImageWritersByMIMEType("image/png").next();
ImageWriteParam iwParam = iw.getDefaultWriteParam();
MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(mdatAtom.getOutputStream());
iw.setOutput(imgOut);
IIOImage img = new IIOImage(image, null, null);
iw.write(null, img, iwParam);
iw.dispose();
break;
}
}
long length = out.getStreamPosition() - offset;
videoFrames.add(new Sample(duration, offset, length));
}
/**
* Writes a frame from a file to the video track.
* <p>
* This method does not inspect the contents of the file. The contents
* has to match the video format. For example, it is your responsibility to
* only add JPG files if you have chosen the JPEG video format.
* <p>
* If you add all frames from files or from input streams, then you
* have to explicitly set the dimension of the video track before you
* call finish() or close().
*
* @param file The file which holds the image data.
* @param duration The duration of the frame in time scale units.
*
* @throws IllegalStateException if the duration is less than 1.
* @throws IOException if writing the image failed.
*/
public void writeFrame(File file, int duration) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream(file);
writeFrame(in, duration);
} finally {
if (in != null) {
in.close();
}
}
}
/**
* Writes a frame to the video track.
* <p>
* This method does not inspect the contents of the input stream. The
* contents has to match the video format. For example, it is your
* responsibility to only add JPG files if you have chosen the JPEG video
* format.
* <p>
* If you add all frames from files or from input streams, then you
* have to explicitly set the dimension of the video track before you
* call finish() or close().
*
* @param in The input stream which holds the image data.
* @param duration The duration of the frame in time scale units.
*
* @throws IllegalArgumentException if the duration is less than 1.
* @throws IOException if writing the image failed.
*/
public void writeFrame(InputStream in, int duration) throws IOException {
if (duration <= 0) {
throw new IllegalArgumentException("duration must be greater 0");
}
ensureOpen();
ensureStarted();
long offset = out.getStreamPosition();
OutputStream mdatOut = mdatAtom.getOutputStream();
byte[] buf = new byte[512];
int len;
while ((len = in.read(buf)) != -1) {
mdatOut.write(buf, 0, len);
}
long length = out.getStreamPosition() - offset;
videoFrames.add(new Sample(duration, offset, length));
}
/**
* Closes the movie file as well as the stream being filtered.
*
* @exception IOException if an I/O error has occurred
*/
public void close() throws IOException {
if (state == States.STARTED) {
finish();
}
if (state != States.CLOSED) {
out.close();
state = States.CLOSED;
}
}
/**
* Finishes writing the contents of the QuickTime output stream without closing
* the underlying stream. Use this method when applying multiple filters
* in succession to the same output stream.
*
* @exception IllegalStateException if the dimension of the video track
* has not been specified or determined yet.
* @exception IOException if an I/O exception has occurred
*/
public void finish() throws IOException {
ensureOpen();
if (state != States.FINISHED) {
if (imgWidth == -1 || imgHeight == -1) {
throw new IllegalStateException("image width and height must be specified");
}
mdatAtom.finish();
writeEpilog();
state = States.FINISHED;
imgWidth = imgHeight = -1;
}
}
/**
* Check to make sure that this stream has not been closed
*/
private void ensureOpen() throws IOException {
if (state == States.CLOSED) {
throw new IOException("Stream closed");
}
}
private void writeProlog() throws IOException {
/* File type atom
*
typedef struct {
magic brand;
bcd4 versionYear;
bcd2 versionMonth;
bcd2 versionMinor;
magic[4] compatibleBrands;
} ftypAtom;
*/
DataAtom ftypAtom = new DataAtom("ftyp");
DataAtomOutputStream d = ftypAtom.getOutputStream();
d.writeType("qt "); // brand
d.writeBCD4(2005); // versionYear
d.writeBCD2(3); // versionMonth
d.writeBCD2(0); // versionMinor
d.writeType("qt "); // compatibleBrands
d.writeInt(0); // compatibleBrands (0 is used to denote no value)
d.writeInt(0); // compatibleBrands (0 is used to denote no value)
d.writeInt(0); // compatibleBrands (0 is used to denote no value)
ftypAtom.finish();
}
private void writeEpilog() throws IOException {
Date modificationTime = new Date();
int duration = 0;
for (Sample s : videoFrames) {
duration += s.duration;
}
DataAtom leaf;
/* Movie Atom ========= */
CompositeAtom moovAtom = new CompositeAtom("moov");
/* Movie Header Atom -------------
* The data contained in this atom defines characteristics of the entire
* QuickTime movie, such as time scale and duration. It has an atom type
* value of 'mvhd'.
*
* typedef struct {
byte version;
byte[3] flags;
mactimestamp creationTime;
mactimestamp modificationTime;
int timeScale;
int duration;
int preferredRate;
short preferredVolume;
byte[10] reserved;
int[9] matrix;
int previewTime;
int previewDuration;
int posterTime;
int selectionTime;
int selectionDuration;
int currentTime;
int nextTrackId;
} movieHeaderAtom;
*/
leaf = new DataAtom("mvhd");
moovAtom.add(leaf);
DataAtomOutputStream d = leaf.getOutputStream();
d.writeByte(0); // version
// A 1-byte specification of the version of this movie header atom.
d.writeByte(0); // flags[0]
d.writeByte(0); // flags[1]
d.writeByte(0); // flags[2]
// Three bytes of space for future movie header flags.
d.writeMacTimestamp(creationTime); // creationTime
// A 32-bit integer that specifies the calendar date and time (in
// seconds since midnight, January 1, 1904) when the movie atom was
// created. It is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeMacTimestamp(modificationTime); // modificationTime
// A 32-bit integer that specifies the calendar date and time (in
// seconds since midnight, January 1, 1904) when the movie atom was
// changed. BooleanIt is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeInt(timeScale); // timeScale
// A time value that indicates the time scale for this movie—that is,
// the number of time units that pass per second in its time coordinate
// system. A time coordinate system that measures time in sixtieths of a
// second, for example, has a time scale of 60.
d.writeInt(duration); // duration
// A time value that indicates the duration of the movie in time scale
// units. Note that this property is derived from the movie’s tracks.
// The value of this field corresponds to the duration of the longest
// track in the movie.
d.writeFixed16D16(1d); // preferredRate
// A 32-bit fixed-point number that specifies the rate at which to play
// this movie. A value of 1.0 indicates normal rate.
d.writeShort(256); // preferredVolume
// A 16-bit fixed-point number that specifies how loud to play this
// movie’s sound. A value of 1.0 indicates full volume.
d.write(new byte[10]); // reserved;
// Ten bytes reserved for use by Apple. Set to 0.
d.writeFixed16D16(1f); // matrix[0]
d.writeFixed16D16(0f); // matrix[1]
d.writeFixed2D30(0f); // matrix[2]
d.writeFixed16D16(0f); // matrix[3]
d.writeFixed16D16(1f); // matrix[4]
d.writeFixed2D30(0); // matrix[5]
d.writeFixed16D16(0); // matrix[6]
d.writeFixed16D16(0); // matrix[7]
d.writeFixed2D30(1f); // matrix[8]
// The matrix structure associated with this movie. A matrix shows how
// to map points from one coordinate space into another. See “Matrices”
// for a discussion of how display matrices are used in QuickTime:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap4/chapter_5_section_4.html#//apple_ref/doc/uid/TP40000939-CH206-18737
d.writeInt(0); // previewTime
// The time value in the movie at which the preview begins.
d.writeInt(0); // previewDuration
// The duration of the movie preview in movie time scale units.
d.writeInt(0); // posterTime
// The time value of the time of the movie poster.
d.writeInt(0); // selectionTime
// The time value for the start time of the current selection.
d.writeInt(0); // selectionDuration
// The duration of the current selection in movie time scale units.
d.writeInt(0); // currentTime;
// The time value for current time position within the movie.
d.writeInt(2); // nextTrackId
// A 32-bit integer that indicates a value to use for the track ID
// number of the next track added to this movie. Note that 0 is not a
// valid track ID value.
/* Track Atom ======== */
CompositeAtom trakAtom = new CompositeAtom("trak");
moovAtom.add(trakAtom);
/* Track Header Atom -----------
* The track header atom specifies the characteristics of a single track
* within a movie. A track header atom contains a size field that
* specifies the number of bytes and a type field that indicates the
* format of the data (defined by the atom type 'tkhd').
*
typedef struct {
byte version;
byte flag0;
byte flag1;
byte set TrackHeaderFlags flag2;
mactimestamp creationTime;
mactimestamp modificationTime;
int trackId;
byte[4] reserved;
int duration;
byte[8] reserved;
short layer;
short alternateGroup;
short volume;
byte[2] reserved;
int[9] matrix;
int trackWidth;
int trackHeight;
} trackHeaderAtom; */
leaf = new DataAtom("tkhd");
trakAtom.add(leaf);
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this track header.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0xf); // flag[2]
// Three bytes that are reserved for the track header flags. These flags
// indicate how the track is used in the movie. The following flags are
// valid (all flags are enabled when set to 1):
//
// Track enabled
// Indicates that the track is enabled. Flag value is 0x0001.
// Track in movie
// Indicates that the track is used in the movie. Flag value is
// 0x0002.
// Track in preview
// Indicates that the track is used in the movie’s preview. Flag
// value is 0x0004.
// Track in poster
// Indicates that the track is used in the movie’s poster. Flag
// value is 0x0008.
d.writeMacTimestamp(creationTime); // creationTime
// A 32-bit integer that indicates the calendar date and time (expressed
// in seconds since midnight, January 1, 1904) when the track header was
// created. It is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeMacTimestamp(modificationTime); // modificationTime
// A 32-bit integer that indicates the calendar date and time (expressed
// in seconds since midnight, January 1, 1904) when the track header was
// changed. It is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeInt(1); // trackId
// A 32-bit integer that uniquely identifies the track. The value 0
// cannot be used.
d.writeInt(0); // reserved;
// A 32-bit integer that is reserved for use by Apple. Set this field to 0.
d.writeInt(duration); // duration
// A time value that indicates the duration of this track (in the
// movie’s time coordinate system). Note that this property is derived
// from the track’s edits. The value of this field is equal to the sum
// of the durations of all of the track’s edits. If there is no edit
// list, then the duration is the sum of the sample durations, converted
// into the movie timescale.
d.writeLong(0); // reserved
// An 8-byte value that is reserved for use by Apple. Set this field to 0.
d.writeShort(0); // layer;
// A 16-bit integer that indicates this track’s spatial priority in its
// movie. The QuickTime Movie Toolbox uses this value to determine how
// tracks overlay one another. Tracks with lower layer values are
// displayed in front of tracks with higher layer values.
d.writeShort(0); // alternate group
// A 16-bit integer that specifies a collection of movie tracks that
// contain alternate data for one another. QuickTime chooses one track
// from the group to be used when the movie is played. The choice may be
// based on such considerations as playback quality, language, or the
// capabilities of the computer.
d.writeShort(0); // volume
// A 16-bit fixed-point value that indicates how loudly this track’s
// sound is to be played. A value of 1.0 indicates normal volume.
d.writeShort(0); // reserved
// A 16-bit integer that is reserved for use by Apple. Set this field to 0.
d.writeFixed16D16(1f); // matrix[0]
d.writeFixed16D16(0f); // matrix[1]
d.writeFixed2D30(0f); // matrix[2]
d.writeFixed16D16(0f); // matrix[3]
d.writeFixed16D16(1f); // matrix[4]
d.writeFixed2D30(0); // matrix[5]
d.writeFixed16D16(0); // matrix[6]
d.writeFixed16D16(0); // matrix[7]
d.writeFixed2D30(1f); // matrix[8]
// The matrix structure associated with this track.
// See Figure 2-8 for an illustration of a matrix structure:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap2/chapter_3_section_3.html#//apple_ref/doc/uid/TP40000939-CH204-32967
d.writeFixed16D16(imgWidth); // width
// A 32-bit fixed-point number that specifies the width of this track in pixels.
d.writeFixed16D16(imgHeight); // height
// A 32-bit fixed-point number that indicates the height of this track in pixels.
/* Media Atom ========= */
CompositeAtom mdiaAtom = new CompositeAtom("mdia");
trakAtom.add(mdiaAtom);
/* Media Header atom -------
typedef struct {
byte version;
byte[3] flags;
mactimestamp creationTime;
mactimestamp modificationTime;
int timeScale;
int duration;
short language;
short quality;
} mediaHeaderAtom;*/
leaf = new DataAtom("mdhd");
mdiaAtom.add(leaf);
d = leaf.getOutputStream();
d.write(0); // version
// One byte that specifies the version of this header atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// Three bytes of space for media header flags. Set this field to 0.
d.writeMacTimestamp(creationTime); // creationTime
// A 32-bit integer that specifies (in seconds since midnight, January
// 1, 1904) when the media atom was created. It is strongly recommended
// that this value should be specified using coordinated universal time
// (UTC).
d.writeMacTimestamp(modificationTime); // modificationTime
// A 32-bit integer that specifies (in seconds since midnight, January
// 1, 1904) when the media atom was changed. It is strongly recommended
// that this value should be specified using coordinated universal time
// (UTC).
d.writeInt(timeScale); // timeScale
// A time value that indicates the time scale for this media—that is,
// the number of time units that pass per second in its time coordinate
// system.
d.writeInt(duration); // duration
// The duration of this media in units of its time scale.
d.writeShort(0); // language;
// A 16-bit integer that specifies the language code for this media.
// See “Language Code Values” for valid language codes:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap4/chapter_5_section_2.html#//apple_ref/doc/uid/TP40000939-CH206-27005
d.writeShort(0); // quality
// A 16-bit integer that specifies the media’s playback quality—that is,
// its suitability for playback in a given environment.
/** Media Handler Atom ------- */
leaf = new DataAtom("hdlr");
mdiaAtom.add(leaf);
/*typedef struct {
byte version;
byte[3] flags;
magic componentType;
magic componentSubtype;
magic componentManufacturer;
int componentFlags;
int componentFlagsMask;
cstring componentName;
} handlerReferenceAtom;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this handler information.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for handler information flags. Set this field to 0.
d.writeType("mhlr"); // componentType
// A four-character code that identifies the type of the handler. Only
// two values are valid for this field: 'mhlr' for media handlers and
// 'dhlr' for data handlers.
d.writeType("vide"); // componentSubtype
// A four-character code that identifies the type of the media handler
// or data handler. For media handlers, this field defines the type of
// data—for example, 'vide' for video data or 'soun' for sound data.
//
// For data handlers, this field defines the data reference type—for
// example, a component subtype value of 'alis' identifies a file alias.
d.writeInt(0); // componentManufacturer
// Reserved. Set to 0.
d.writeInt(0); // componentFlags
// Reserved. Set to 0.
d.writeInt(0); // componentFlagsMask
// Reserved. Set to 0.
d.write(0); // componentName (empty string)
// A (counted) string that specifies the name of the component—that is,
// the media handler used when this media was created. This field may
// contain a zero-length (empty) string.
/* Media Information atom ========= */
CompositeAtom minfAtom = new CompositeAtom("minf");
mdiaAtom.add(minfAtom);
/* Video media information atom -------- */
leaf = new DataAtom("vmhd");
minfAtom.add(leaf);
/*typedef struct {
byte version;
byte flag1;
byte flag2;
byte set vmhdFlags flag3;
short graphicsMode;
ushort[3] opcolor;
} videoMediaInformationHeaderAtom;*/
d = leaf.getOutputStream();
d.write(0); // version
// One byte that specifies the version of this header atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0x1); // flag[2]
// Three bytes of space for media header flags.
// This is a compatibility flag that allows QuickTime to distinguish
// between movies created with QuickTime 1.0 and newer movies. You
// should always set this flag to 1, unless you are creating a movie
// intended for playback using version 1.0 of QuickTime. This flag’s
// value is 0x0001.
d.writeShort(0x40); // graphicsMode (0x40 = ditherCopy)
// A 16-bit integer that specifies the transfer mode. The transfer mode
// specifies which Boolean operation QuickDraw should perform when
// drawing or transferring an image from one location to another.
// See “Graphics Modes” for a list of graphics modes supported by
// QuickTime:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap4/chapter_5_section_5.html#//apple_ref/doc/uid/TP40000939-CH206-18741
d.writeUShort(0); // opcolor[0]
d.writeUShort(0); // opcolor[1]
d.writeUShort(0); // opcolor[2]
// Three 16-bit values that specify the red, green, and blue colors for
// the transfer mode operation indicated in the graphics mode field.
/* Handle reference atom -------- */
// The handler reference atom specifies the media handler component that
// is to be used to interpret the media’s data. The handler reference
// atom has an atom type value of 'hdlr'.
leaf = new DataAtom("hdlr");
minfAtom.add(leaf);
/*typedef struct {
byte version;
byte[3] flags;
magic componentType;
magic componentSubtype;
magic componentManufacturer;
int componentFlags;
int componentFlagsMask;
cstring componentName;
} handlerReferenceAtom;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this handler information.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for handler information flags. Set this field to 0.
d.writeType("dhlr"); // componentType
// A four-character code that identifies the type of the handler. Only
// two values are valid for this field: 'mhlr' for media handlers and
// 'dhlr' for data handlers.
d.writeType("alis"); // componentSubtype
// A four-character code that identifies the type of the media handler
// or data handler. For media handlers, this field defines the type of
// data—for example, 'vide' for video data or 'soun' for sound data.
// For data handlers, this field defines the data reference type—for
// example, a component subtype value of 'alis' identifies a file alias.
d.writeInt(0); // componentManufacturer
// Reserved. Set to 0.
d.writeInt(0); // componentFlags
// Reserved. Set to 0.
d.writeInt(0); // componentFlagsMask
// Reserved. Set to 0.
d.write(0); // componentName (empty string)
// A (counted) string that specifies the name of the component—that is,
// the media handler used when this media was created. This field may
// contain a zero-length (empty) string.
/* Data information atom ===== */
CompositeAtom dinfAtom = new CompositeAtom("dinf");
minfAtom.add(dinfAtom);
/* Data reference atom ----- */
// Data reference atoms contain tabular data that instructs the data
// handler component how to access the media’s data.
leaf = new DataAtom("dref");
dinfAtom.add(leaf);
/*typedef struct {
ubyte version;
ubyte[3] flags;
int numberOfEntries;
dataReferenceEntry dataReference[numberOfEntries];
} dataReferenceAtom;
set {
dataRefSelfReference=1 // I am not shure if this is the correct value for this flag
} drefEntryFlags;
typedef struct {
int size;
magic type;
byte version;
ubyte flag1;
ubyte flag2;
ubyte set drefEntryFlags flag3;
byte[size - 12] data;
} dataReferenceEntry;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this data reference atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for data reference flags. Set this field to 0.
d.writeInt(1); // numberOfEntries
// A 32-bit integer containing the count of data references that follow.
d.writeInt(12); // dataReference.size
// A 32-bit integer that specifies the number of bytes in the data
// reference.
d.writeType("alis"); // dataReference.type
// A 32-bit integer that specifies the type of the data in the data
// reference. Table 2-4 lists valid type values:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap2/chapter_3_section_4.html#//apple_ref/doc/uid/TP40000939-CH204-38840
d.write(0); // dataReference.version
// A 1-byte specification of the version of the data reference.
d.write(0); // dataReference.flag1
d.write(0); // dataReference.flag2
d.write(0x1); // dataReference.flag3
// A 3-byte space for data reference flags. There is one defined flag.
//
// Self reference
// This flag indicates that the media’s data is in the same file as
// the movie atom. On the Macintosh, and other file systems with
// multifork files, set this flag to 1 even if the data resides in
// a different fork from the movie atom. This flag’s value is
// 0x0001.
/* Sample Table atom ========= */
CompositeAtom stblAtom = new CompositeAtom("stbl");
minfAtom.add(stblAtom);
/* Sample Description atom ------- */
// The sample description atom stores information that allows you to
// decode samples in the media. The data stored in the sample
// description varies, depending on the media type. For example, in the
// case of video media, the sample descriptions are image description
// structures. The sample description information for each media type is
// explained in “Media Data Atom Types”:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap3/chapter_4_section_1.html#//apple_ref/doc/uid/TP40000939-CH205-SW1
leaf = new DataAtom("stsd");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
sampleDescriptionEntry sampleDescriptionTable[numberOfEntries];
} sampleDescriptionAtom;
typedef struct {
int size;
magic type;
byte[6] reserved; // six bytes that must be zero
short dataReferenceIndex; // A 16-bit integer that contains the index of the data reference to use to retrieve data associated with samples that use this sample description. Data references are stored in data reference atoms.
byte[size - 16] data;
} sampleDescriptionEntry;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this sample description atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for sample description flags. Set this field to 0.
d.writeInt(1); // number of Entries
// A 32-bit integer containing the number of sample descriptions that follow.
// A 32-bit integer indicating the number of bytes in the sample description.
switch (videoFormat) {
case RAW: {
d.writeInt(86); // sampleDescriptionTable[0].size
d.writeType("raw "); // sampleDescriptionTable[0].type
// A 32-bit integer indicating the format of the stored data.
// This depends on the media type, but is usually either the
// compression format or the media type.
d.write(new byte[6]); // sampleDescriptionTable[0].reserved
// Six bytes that must be set to 0.
d.writeShort(1); // sampleDescriptionTable[0].dataReferenceIndex
// A 16-bit integer that contains the index of the data
// reference to use to retrieve data associated with samples
// that use this sample description. Data references are stored
// in data reference atoms.
// Video Sample Description
// ------------------------
// The format of the following fields is described here:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap3/chapter_4_section_2.html#//apple_ref/doc/uid/TP40000939-CH205-BBCGICBJ
d.writeShort(0); // sampleDescriptionTable.videoSampleDescription.version
// A 16-bit integer indicating the version number of the
// compressed data. This is set to 0, unless a compressor has
// changed its data format.
d.writeShort(0); // sampleDescriptionTable.videoSampleDescription.revisionLevel
// A 16-bit integer that must be set to 0.
d.writeType("java"); // sampleDescriptionTable.videoSampleDescription.manufacturer
// A 32-bit integer that specifies the developer of the
// compressor that generated the compressed data. Often this
// field contains 'appl' to indicate Apple Computer, Inc.
d.writeInt(0); // sampleDescriptionTable.videoSampleDescription.temporalQuality
// A 32-bit integer containing a value from 0 to 1023 indicating
// the degree of temporal compression.
d.writeInt(512); // sampleDescriptionTable.videoSampleDescription.spatialQuality
// A 32-bit integer containing a value from 0 to 1024 indicating
// the degree of spatial compression.
d.writeUShort(imgWidth); // sampleDescriptionTable.videoSampleDescription.width
// A 16-bit integer that specifies the width of the source image
// in pixels.
d.writeUShort(imgHeight); // sampleDescriptionTable.videoSampleDescription.height
// A 16-bit integer that specifies the height of the source image in pixels.
d.writeFixed16D16(72.0); // sampleDescriptionTable.videoSampleDescription.horizontalResolution
// A 32-bit fixed-point number containing the horizontal
// resolution of the image in pixels per inch.
d.writeFixed16D16(72.0); // sampleDescriptionTable.videoSampleDescription.verticalResolution
// A 32-bit fixed-point number containing the vertical
// resolution of the image in pixels per inch.
d.writeInt(0); // sampleDescriptionTable.videoSampleDescription.dataSize
// A 32-bit integer that must be set to 0.
d.writeShort(1); // sampleDescriptionTable.videoSampleDescription.frameCount
// A 16-bit integer that indicates how many frames of compressed
// data are stored in each sample. Usually set to 1.
d.writePString("None", 32); // sampleDescriptionTable.videoSampleDescription.compressorName
// A 32-byte Pascal string containing the name of the compressor
// that created the image, such as "jpeg".
d.writeShort(24); // sampleDescriptionTable.videoSampleDescription.depth
// A 16-bit integer that indicates the pixel depth of the
// compressed image. Values of 1, 2, 4, 8 ,16, 24, and 32
// indicate the depth of color images. The value 32 should be
// used only if the image contains an alpha channel. Values of
// 34, 36, and 40 indicate 2-, 4-, and 8-bit grayscale,
// respectively, for grayscale images.
d.writeShort(-1); // sampleDescriptionTable.videoSampleDescription.colorTableID
// A 16-bit integer that identifies which color table to use.
// If this field is set to –1, the default color table should be
// used for the specified depth. For all depths below 16 bits
// per pixel, this indicates a standard Macintosh color table
// for the specified depth. Depths of 16, 24, and 32 have no
// color table.
break;
}
case JPG: {
d.writeInt(86); // sampleDescriptionTable[0].size
d.writeType("jpeg"); // sampleDescriptionTable[0].type
// A 32-bit integer indicating the format of the stored data.
// This depends on the media type, but is usually either the
// compression format or the media type.
d.write(new byte[6]); // sampleDescriptionTable[0].reserved
// Six bytes that must be set to 0.
d.writeShort(1); // sampleDescriptionTable[0].dataReferenceIndex
// A 16-bit integer that contains the index of the data
// reference to use to retrieve data associated with samples
// that use this sample description. Data references are stored
// in data reference atoms.
// Video Sample Description
// ------------------------
// The format of the following fields is described here:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap3/chapter_4_section_2.html#//apple_ref/doc/uid/TP40000939-CH205-BBCGICBJ
d.writeShort(0); // sampleDescriptionTable.videoSampleDescription.version
// A 16-bit integer indicating the version number of the
// compressed data. This is set to 0, unless a compressor has
// changed its data format.
d.writeShort(0); // sampleDescriptionTable.videoSampleDescription.revisionLevel
// A 16-bit integer that must be set to 0.
d.writeType("java"); // sampleDescriptionTable.videoSampleDescription.manufacturer
// A 32-bit integer that specifies the developer of the
// compressor that generated the compressed data. Often this
// field contains 'appl' to indicate Apple Computer, Inc.
d.writeInt(0); // sampleDescriptionTable.videoSampleDescription.temporalQuality
// A 32-bit integer containing a value from 0 to 1023 indicating
// the degree of temporal compression.
d.writeInt(512); // sampleDescriptionTable.videoSampleDescription.spatialQuality
// A 32-bit integer containing a value from 0 to 1024 indicating
// the degree of spatial compression.
d.writeUShort(imgWidth); // sampleDescriptionTable.videoSampleDescription.width
// A 16-bit integer that specifies the width of the source image
// in pixels.
d.writeUShort(imgHeight); // sampleDescriptionTable.videoSampleDescription.height
// A 16-bit integer that specifies the height of the source image in pixels.
d.writeFixed16D16(72.0); // sampleDescriptionTable.videoSampleDescription.horizontalResolution
// A 32-bit fixed-point number containing the horizontal
// resolution of the image in pixels per inch.
d.writeFixed16D16(72.0); // sampleDescriptionTable.videoSampleDescription.verticalResolution
// A 32-bit fixed-point number containing the vertical
// resolution of the image in pixels per inch.
d.writeInt(0); // sampleDescriptionTable.videoSampleDescription.dataSize
// A 32-bit integer that must be set to 0.
d.writeShort(1); // sampleDescriptionTable.videoSampleDescription.frameCount
// A 16-bit integer that indicates how many frames of compressed
// data are stored in each sample. Usually set to 1.
d.writePString("Photo - JPEG", 32); // sampleDescriptionTable.videoSampleDescription.compressorName
// A 32-byte Pascal string containing the name of the compressor
// that created the image, such as "jpeg".
d.writeShort(24); // sampleDescriptionTable.videoSampleDescription.depth
// A 16-bit integer that indicates the pixel depth of the
// compressed image. Values of 1, 2, 4, 8 ,16, 24, and 32
// indicate the depth of color images. The value 32 should be
// used only if the image contains an alpha channel. Values of
// 34, 36, and 40 indicate 2-, 4-, and 8-bit grayscale,
// respectively, for grayscale images.
d.writeShort(-1); // sampleDescriptionTable.videoSampleDescription.colorTableID
// A 16-bit integer that identifies which color table to use.
// If this field is set to –1, the default color table should be
// used for the specified depth. For all depths below 16 bits
// per pixel, this indicates a standard Macintosh color table
// for the specified depth. Depths of 16, 24, and 32 have no
// color table.
break;
}
case PNG: {
d.writeInt(86); // sampleDescriptionTable[0].size
d.writeType("png "); // sampleDescriptionTable[0].type
// A 32-bit integer indicating the format of the stored data.
// This depends on the media type, but is usually either the
// compression format or the media type.
d.write(new byte[6]); // sampleDescriptionTable[0].reserved
// Six bytes that must be set to 0.
d.writeShort(1); // sampleDescriptionTable[0].dataReferenceIndex
// A 16-bit integer that contains the index of the data
// reference to use to retrieve data associated with samples
// that use this sample description. Data references are stored
// in data reference atoms.
// Video Sample Description
// ------------------------
// The format of the following fields is described here:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap3/chapter_4_section_2.html#//apple_ref/doc/uid/TP40000939-CH205-BBCGICBJ
d.writeShort(0); // sampleDescriptionTable.videoSampleDescription.version
// A 16-bit integer indicating the version number of the
// compressed data. This is set to 0, unless a compressor has
// changed its data format.
d.writeShort(0); // sampleDescriptionTable.videoSampleDescription.revisionLevel
// A 16-bit integer that must be set to 0.
d.writeType("java"); // sampleDescriptionTable.videoSampleDescription.manufacturer
// A 32-bit integer that specifies the developer of the
// compressor that generated the compressed data. Often this
// field contains 'appl' to indicate Apple Computer, Inc.
d.writeInt(0); // sampleDescriptionTable.videoSampleDescription.temporalQuality
// A 32-bit integer containing a value from 0 to 1023 indicating
// the degree of temporal compression.
d.writeInt(512); // sampleDescriptionTable.videoSampleDescription.spatialQuality
// A 32-bit integer containing a value from 0 to 1024 indicating
// the degree of spatial compression.
d.writeUShort(imgWidth); // sampleDescriptionTable.videoSampleDescription.width
// A 16-bit integer that specifies the width of the source image
// in pixels.
d.writeUShort(imgHeight); // sampleDescriptionTable.videoSampleDescription.height
// A 16-bit integer that specifies the height of the source image in pixels.
d.writeFixed16D16(72.0); // sampleDescriptionTable.videoSampleDescription.horizontalResolution
// A 32-bit fixed-point number containing the horizontal
// resolution of the image in pixels per inch.
d.writeFixed16D16(72.0); // sampleDescriptionTable.videoSampleDescription.verticalResolution
// A 32-bit fixed-point number containing the vertical
// resolution of the image in pixels per inch.
d.writeInt(0); // sampleDescriptionTable.videoSampleDescription.dataSize
// A 32-bit integer that must be set to 0.
d.writeShort(1); // sampleDescriptionTable.videoSampleDescription.frameCount
// A 16-bit integer that indicates how many frames of compressed
// data are stored in each sample. Usually set to 1.
d.writePString("PNG", 32); // sampleDescriptionTable.videoSampleDescription.compressorName
// A 32-byte Pascal string containing the name of the compressor
// that created the image, such as "jpeg".
d.writeShort(24); // sampleDescriptionTable.videoSampleDescription.depth
// A 16-bit integer that indicates the pixel depth of the
// compressed image. Values of 1, 2, 4, 8 ,16, 24, and 32
// indicate the depth of color images. The value 32 should be
// used only if the image contains an alpha channel. Values of
// 34, 36, and 40 indicate 2-, 4-, and 8-bit grayscale,
// respectively, for grayscale images.
d.writeShort(-1); // sampleDescriptionTable.videoSampleDescription.colorTableID
// A 16-bit integer that identifies which color table to use.
// If this field is set to –1, the default color table should be
// used for the specified depth. For all depths below 16 bits
// per pixel, this indicates a standard Macintosh color table
// for the specified depth. Depths of 16, 24, and 32 have no
// color table.
break;
}
}
/* Time to Sample atom ---- */
// Time-to-sample atoms store duration information for a media’s
// samples, providing a mapping from a time in a media to the
// corresponding data sample. The time-to-sample atom has an atom type
// of 'stts'.
leaf = new DataAtom("stts");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
timeToSampleTable timeToSampleTable[numberOfEntries];
} timeToSampleAtom;
typedef struct {
int sampleCount;
int sampleDuration;
} timeToSampleTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
// count runs of video frame durations
int runCount = 1;
int prevDuration = videoFrames.size() == 0 ? 0 : videoFrames.get(0).duration;
for (Sample s : videoFrames) {
if (s.duration != prevDuration) {
runCount++;
prevDuration = s.duration;
}
}
d.writeInt(runCount); // numberOfEntries
// A 32-bit integer containing the count of entries in the
// time-to-sample table.
int runLength = 0;
prevDuration = videoFrames.size() == 0 ? 0 : videoFrames.get(0).duration;
for (Sample s : videoFrames) {
if (s.duration != prevDuration) {
if (runLength > 0) {
d.writeInt(runLength); // timeToSampleTable[0].sampleCount
// A 32-bit integer that specifies the number of consecutive
// samples that have the same duration.
d.writeInt(prevDuration); // timeToSampleTable[0].sampleDuration
// A 32-bit integer that specifies the duration of each
// sample.
}
prevDuration = s.duration;
runLength = 1;
} else {
runLength++;
}
}
if (runLength > 0) {
d.writeInt(runLength); // timeToSampleTable[0].sampleCount
// A 32-bit integer that specifies the number of consecutive
// samples that have the same duration.
d.writeInt(prevDuration); // timeToSampleTable[0].sampleDuration
// A 32-bit integer that specifies the duration of each
// sample.
}
/* sample to chunk atom -------- */
// The sample-to-chunk atom contains a table that maps samples to chunks
// in the media data stream. By examining the sample-to-chunk atom, you
// can determine the chunk that contains a specific sample.
leaf = new DataAtom("stsc");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
sampleToChunkTable sampleToChunkTable[numberOfEntries];
} sampleToChunkAtom;
typedef struct {
int firstChunk;
int samplesPerChunk;
int sampleDescription;
} sampleToChunkTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeInt(1); // number of entries
// A 32-bit integer containing the count of entries in the sample-to-chunk table.
d.writeInt(1); // first chunk
// The first chunk number using this table entry.
d.writeInt(1); // samples per chunk
// The number of samples in each chunk.
d.writeInt(1); // sample description
// The identification number associated with the sample description for
// the sample. For details on sample description atoms, see “Sample
// Description Atoms.”:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap2/chapter_3_section_5.html#//apple_ref/doc/uid/TP40000939-CH204-25691
/* sample size atom -------- */
// The sample size atom contains the sample count and a table giving the
// size of each sample. This allows the media data itself to be
// unframed. The total number of samples in the media is always
// indicated in the sample count. If the default size is indicated, then
// no table follows.
leaf = new DataAtom("stsz");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int sampleSize;
int numberOfEntries;
sampleSizeTable sampleSizeTable[numberOfEntries];
} sampleSizeAtom;
typedef struct {
int size;
} sampleSizeTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeUInt(0); // sample size
// A 32-bit integer specifying the sample size. If all the samples are
// the same size, this field contains that size value. If this field is
// set to 0, then the samples have different sizes, and those sizes are
// stored in the sample size table.
d.writeUInt(videoFrames.size()); // number of entries
// A 32-bit integer containing the count of entries in the sample size
// table.
for (Sample s : videoFrames) {
d.writeUInt(s.length); // sample size
// The size field contains the size, in bytes, of the sample in
// question. The table is indexed by sample number—the first entry
// corresponds to the first sample, the second entry is for the
// second sample, and so on.
}
//
/* chunk offset atom -------- */
// The chunk-offset table gives the index of each chunk into the
// containing file. There are two variants, permitting the use of
// 32-bit or 64-bit offsets. The latter is useful when managing very
// large movies. Only one of these variants occurs in any single
// instance of a sample table atom.
if (videoFrames.size() == 0 || videoFrames.getLast().offset <= 0xffffffffL) {
/* 32-bit chunk offset atom -------- */
leaf = new DataAtom("stco");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
chunkOffsetTable chunkOffsetTable[numberOfEntries];
} chunkOffsetAtom;
typedef struct {
int offset;
} chunkOffsetTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeUInt(videoFrames.size()); // number of entries
// A 32-bit integer containing the count of entries in the chunk
// offset table.
for (Sample s : videoFrames) {
d.writeUInt(s.offset); // offset
// The offset contains the byte offset from the beginning of the
// data stream to the chunk. The table is indexed by chunk
// number—the first table entry corresponds to the first chunk,
// the second table entry is for the second chunk, and so on.
}
} else {
/* 64-bit chunk offset atom -------- */
leaf = new DataAtom("co64");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
chunkOffsetTable chunkOffset64Table[numberOfEntries];
} chunkOffset64Atom;
typedef struct {
long offset;
} chunkOffset64Table;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeUInt(videoFrames.size()); // number of entries
// A 32-bit integer containing the count of entries in the chunk
// offset table.
for (Sample s : videoFrames) {
d.writeLong(s.offset); // offset
// The offset contains the byte offset from the beginning of the
// data stream to the chunk. The table is indexed by chunk
// number—the first table entry corresponds to the first chunk,
// the second table entry is for the second chunk, and so on.
}
}
//
moovAtom.finish();
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/recording/QuickTimeOutputStream.java
|
Java
|
asf20
| 69,678
|
package net.srcz.android.screencast.api.recording;
import java.io.*;
import javax.imageio.stream.ImageOutputStream;
public class FilterImageOutputStream extends FilterOutputStream {
private ImageOutputStream imgOut;
public FilterImageOutputStream(ImageOutputStream iOut) {
super(null);
this.imgOut = iOut;
}
/**
* Writes the specified <code>byte</code> to this output stream.
* <p>
* The <code>write</code> method of <code>FilterOutputStream</code>
* calls the <code>write</code> method of its underlying output stream,
* that is, it performs <tt>out.write(b)</tt>.
* <p>
* Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
@Override
public void write(int b) throws IOException {
imgOut.write(b);
}
/**
* Writes <code>len</code> bytes from the specified
* <code>byte</code> array starting at offset <code>off</code> to
* this output stream.
* <p>
* The <code>write</code> method of <code>FilterOutputStream</code>
* calls the <code>write</code> method of one argument on each
* <code>byte</code> to output.
* <p>
* Note that this method does not call the <code>write</code> method
* of its underlying input stream with the same arguments. Subclasses
* of <code>FilterOutputStream</code> should provide a more efficient
* implementation of this method.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#write(int)
*/
@Override
public void write(byte b[], int off, int len) throws IOException {
imgOut.write(b, off, len);
}
/**
* Flushes this output stream and forces any buffered output bytes
* to be written out to the stream.
* <p>
* The <code>flush</code> method of <code>FilterOutputStream</code>
* calls the <code>flush</code> method of its underlying output stream.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
@Override
public void flush() throws IOException {
//System.err.println(this+" discarded flush");
//imgOut.flush();
}
/**
* Closes this output stream and releases any system resources
* associated with the stream.
* <p>
* The <code>close</code> method of <code>FilterOutputStream</code>
* calls its <code>flush</code> method, and then calls the
* <code>close</code> method of its underlying output stream.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#flush()
* @see java.io.FilterOutputStream#out
*/
@Override
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
imgOut.close();
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/recording/FilterImageOutputStream.java
|
Java
|
asf20
| 3,134
|
package net.srcz.android.screencast.api.recording;
import java.io.*;
import java.util.Date;
import java.util.GregorianCalendar;
public class DataAtomOutputStream extends FilterOutputStream {
protected static final long MAC_TIMESTAMP_EPOCH = new GregorianCalendar(1904, GregorianCalendar.JANUARY, 1).getTimeInMillis();
/**
* The number of bytes written to the data output stream so far.
* If this counter overflows, it will be wrapped to Integer.MAX_VALUE.
*/
protected long written;
public DataAtomOutputStream(OutputStream out) {
super(out);
}
/**
* Writes an Atom Type identifier (4 bytes).
* @param s A string with a length of 4 characters.
*/
public void writeType(String s) throws IOException {
if (s.length() != 4) {
throw new IllegalArgumentException("type string must have 4 characters");
}
try {
out.write(s.getBytes("ASCII"), 0, 4);
incCount(4);
} catch (UnsupportedEncodingException e) {
throw new InternalError(e.toString());
}
}
/**
* Writes out a <code>byte</code> to the underlying output stream as
* a 1-byte value. If no exception is thrown, the counter
* <code>written</code> is incremented by <code>1</code>.
*
* @param v a <code>byte</code> value to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public final void writeByte(int v) throws IOException {
out.write(v);
incCount(1);
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to the underlying output stream.
* If no exception is thrown, the counter <code>written</code> is
* incremented by <code>len</code>.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
@Override
public synchronized void write(byte b[], int off, int len)
throws IOException {
out.write(b, off, len);
incCount(len);
}
/**
* Writes the specified byte (the low eight bits of the argument
* <code>b</code>) to the underlying output stream. If no exception
* is thrown, the counter <code>written</code> is incremented by
* <code>1</code>.
* <p>
* Implements the <code>write</code> method of <code>OutputStream</code>.
*
* @param b the <code>byte</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
@Override
public synchronized void write(int b) throws IOException {
out.write(b);
incCount(1);
}
/**
* Writes an <code>int</code> to the underlying output stream as four
* bytes, high byte first. If no exception is thrown, the counter
* <code>written</code> is incremented by <code>4</code>.
*
* @param v an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public void writeInt(int v) throws IOException {
out.write((v >>> 24) & 0xff);
out.write((v >>> 16) & 0xff);
out.write((v >>> 8) & 0xff);
out.write((v >>> 0) & 0xff);
incCount(4);
}
/**
* Writes an unsigned 32 bit integer value.
*
* @param v The value
* @throws java.io.IOException
*/
public void writeUInt(long v) throws IOException {
out.write((int) ((v >>> 24) & 0xff));
out.write((int) ((v >>> 16) & 0xff));
out.write((int) ((v >>> 8) & 0xff));
out.write((int) ((v >>> 0) & 0xff));
incCount(4);
}
/**
* Writes a signed 16 bit integer value.
*
* @param v The value
* @throws java.io.IOException
*/
public void writeShort(int v) throws IOException {
out.write((int) ((v >> 8) & 0xff));
out.write((int) ((v >>> 0) & 0xff));
incCount(2);
}
/**
* Writes a <code>BCD2</code> to the underlying output stream.
*
* @param v an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public void writeBCD2(int v) throws IOException {
out.write(((v % 100 / 10) << 4) | (v % 10));
incCount(1);
}
/**
* Writes a <code>BCD4</code> to the underlying output stream.
*
* @param v an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public void writeBCD4(int v) throws IOException {
out.write(((v % 10000 / 1000) << 4) | (v % 1000 / 100));
out.write(((v % 100 / 10) << 4) | (v % 10));
incCount(2);
}
/**
* Writes a 32-bit Mac timestamp (seconds since 1902).
* @param date
* @throws java.io.IOException
*/
public void writeMacTimestamp(Date date) throws IOException {
long millis = date.getTime();
long qtMillis = millis - MAC_TIMESTAMP_EPOCH;
long qtSeconds = qtMillis / 1000;
writeUInt(qtSeconds);
}
/**
* Writes 32-bit fixed-point number divided as 16.16.
*
* @param f an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public void writeFixed16D16(double f) throws IOException {
double v = (f >= 0) ? f : -f;
int wholePart = (int) v;
int fractionPart = (int) ((v - wholePart) * 65536);
int t = (wholePart << 16) + fractionPart;
if (f < 0) {
t = t - 1;
}
writeInt(t);
}
/**
* Writes 32-bit fixed-point number divided as 2.30.
*
* @param f an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public void writeFixed2D30(double f) throws IOException {
double v = (f >= 0) ? f : -f;
int wholePart = (int) v;
int fractionPart = (int) ((v - wholePart) *1073741824);
int t = (wholePart << 30) + fractionPart;
if (f < 0) {
t = t - 1;
}
writeInt(t);
}
/**
* Writes 16-bit fixed-point number divided as 8.8.
*
* @param f an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public void writeFixed8D8(float f) throws IOException {
float v = (f >= 0) ? f : -f;
int wholePart = (int) v;
int fractionPart = (int) ((v - wholePart) * 256);
int t = (wholePart << 8) + fractionPart;
if (f < 0) {
t = t - 1;
}
writeUShort(t);
}
/**
* Writes a Pascal String.
*
* @param s
* @throws java.io.IOException
*/
public void writePString(String s) throws IOException {
if (s.length() > 0xffff) {
throw new IllegalArgumentException("String too long for PString");
}
if (s.length() < 256) {
out.write(s.length());
} else {
out.write(0);
writeShort(s.length()); // increments +2
}
for (int i=0; i < s.length(); i++) {
out.write(s.charAt(i));
}
incCount(1 + s.length());
}
/**
* Writes a Pascal String padded to the specified fixed size in bytes
*
* @param s
* @param length the fixed size in bytes
* @throws java.io.IOException
*/
public void writePString(String s, int length) throws IOException {
if (s.length() > length) {
throw new IllegalArgumentException("String too long for PString of length "+length);
}
if (s.length() < 256) {
out.write(s.length());
} else {
out.write(0);
writeShort(s.length()); // increments +2
}
for (int i=0; i < s.length(); i++) {
out.write(s.charAt(i));
}
// write pad bytes
for (int i=1 + s.length(); i < length; i++) {
out.write(0);
}
incCount(length);
}
public void writeLong(long v) throws IOException {
out.write((int) (v >>> 56) & 0xff);
out.write((int) (v >>> 48) & 0xff);
out.write((int) (v >>> 40) & 0xff);
out.write((int) (v >>> 32) & 0xff);
out.write((int) (v >>> 24) & 0xff);
out.write((int) (v >>> 16) & 0xff);
out.write((int) (v >>> 8) & 0xff);
out.write((int) (v >>> 0) & 0xff);
incCount(8);
}
public void writeUShort(int v) throws IOException {
out.write((int) ((v >> 8) & 0xff));
out.write((int) ((v >>> 0) & 0xff));
incCount(2);
}
/**
* Increases the written counter by the specified value
* until it reaches Long.MAX_VALUE.
*/
protected void incCount(int value) {
long temp = written + value;
if (temp < 0) {
temp = Long.MAX_VALUE;
}
written = temp;
}
/**
* Returns the current value of the counter <code>written</code>,
* the number of bytes written to this data output stream so far.
* If the counter overflows, it will be wrapped to Integer.MAX_VALUE.
*
* @return the value of the <code>written</code> field.
* @see java.io.DataOutputStream#written
*/
public final long size() {
return written;
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/recording/DataAtomOutputStream.java
|
Java
|
asf20
| 9,940
|
package net.srcz.android.screencast.api.injector;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.swing.SwingUtilities;
import net.srcz.android.screencast.api.recording.QuickTimeOutputStream;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.RawImage;
public class ScreenCaptureThread extends Thread {
private BufferedImage image;
private Dimension size;
private IDevice device;
private QuickTimeOutputStream qos = null;
private boolean landscape = false;
private ScreenCaptureListener listener = null;
public ScreenCaptureListener getListener() {
return listener;
}
public void setListener(ScreenCaptureListener listener) {
this.listener = listener;
}
public interface ScreenCaptureListener {
public void handleNewImage(Dimension size, BufferedImage image,
boolean landscape);
}
public ScreenCaptureThread(IDevice device) {
super("Screen capture");
this.device = device;
image = null;
size = new Dimension();
}
public Dimension getPreferredSize() {
return size;
}
public void run() {
do {
try {
boolean ok = fetchImage();
if(!ok)
break;
} catch (java.nio.channels.ClosedByInterruptException ciex) {
break;
} catch (IOException e) {
System.err.println((new StringBuilder()).append(
"Exception fetching image: ").append(e.toString())
.toString());
}
} while (true);
}
public void startRecording(File f) {
try {
if(!f.getName().toLowerCase().endsWith(".mov"))
f = new File(f.getAbsolutePath()+".mov");
qos = new QuickTimeOutputStream(f,
QuickTimeOutputStream.VideoFormat.JPG);
} catch (IOException e) {
throw new RuntimeException(e);
}
qos.setVideoCompressionQuality(1f);
qos.setTimeScale(30); // 30 fps
}
public void stopRecording() {
try {
QuickTimeOutputStream o = qos;
qos = null;
o.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private boolean fetchImage() throws IOException {
if (device == null) {
// device not ready
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return false;
}
return true;
}
// System.out.println("Getting initial screenshot through ADB");
RawImage rawImage = null;
synchronized (device) {
rawImage = device.getScreenshot();
}
if (rawImage != null) {
// System.out.println("screenshot through ADB ok");
display(rawImage);
} else {
System.out.println("failed getting screenshot through ADB ok");
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
return false;
}
return true;
}
public void toogleOrientation() {
landscape = !landscape;
}
public void display(RawImage rawImage) {
int width2 = landscape ? rawImage.height : rawImage.width;
int height2 = landscape ? rawImage.width : rawImage.height;
if (image == null) {
image = new BufferedImage(width2, height2,
BufferedImage.TYPE_INT_RGB);
size.setSize(image.getWidth(), image.getHeight());
} else {
if (image.getHeight() != height2 || image.getWidth() != width2) {
image = new BufferedImage(width2, height2,
BufferedImage.TYPE_INT_RGB);
size.setSize(image.getWidth(), image.getHeight());
}
}
int index = 0;
int indexInc = rawImage.bpp >> 3;
for (int y = 0; y < rawImage.height; y++) {
for (int x = 0; x < rawImage.width; x++, index += indexInc) {
int value = rawImage.getARGB(index);
if (landscape)
image.setRGB(y, rawImage.width - x - 1, value);
else
image.setRGB(x, y, value);
}
}
try {
if (qos != null)
qos.writeFrame(image, 10);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (listener != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
listener.handleNewImage(size, image, landscape);
// jp.handleNewImage(size, image, landscape);
}
});
}
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/injector/ScreenCaptureThread.java
|
Java
|
asf20
| 3,957
|