diff --git a/README.md b/README.md index 5727a530..34aa7fe9 120000 --- a/README.md +++ b/README.md @@ -1 +1 @@ -dist/README.md \ No newline at end of file +dist/README.txt \ No newline at end of file diff --git a/commons/pom.xml b/commons/pom.xml index f3619a26..b9b049b5 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -3,7 +3,7 @@ org.archive heritrix - 3.2.0-SNAPSHOT + 3.3.0-SNAPSHOT 4.0.0 org.archive.heritrix @@ -17,37 +17,8 @@ - - true - always - warn - - - true - never - fail - - oracleReleases - Oracle Released Java Packages + download.oracle.com,maven http://download.oracle.com/maven - default - - - - - true - always - warn - - - true - never - fail - - internetarchive - Internet Archive Maven Repository - http://builds.archive.org:8080/maven2 - default @@ -153,12 +124,6 @@ 3.8.2 compile - - fastutil - fastutil - 5.0.7 - compile - net.java.dev.jets3t jets3t @@ -202,11 +167,6 @@ spring-expression 3.0.5.RELEASE - - joda-time - joda-time - 1.6 - org.json json @@ -247,7 +207,7 @@ org.archive ia-web-commons - 1.0-SNAPSHOT + 1.1.1-SNAPSHOT commons-httpclient diff --git a/commons/src/main/java/org/archive/bdb/BdbModule.java b/commons/src/main/java/org/archive/bdb/BdbModule.java index 1ca6312c..88e39721 100644 --- a/commons/src/main/java/org/archive/bdb/BdbModule.java +++ b/commons/src/main/java/org/archive/bdb/BdbModule.java @@ -22,6 +22,7 @@ package org.archive.bdb; import java.io.Closeable; import java.io.File; import java.io.FileFilter; +import java.io.FilenameFilter; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; @@ -46,6 +47,7 @@ import org.archive.util.FilesystemLinkMaker; import org.archive.util.IdentityCacheable; import org.archive.util.ObjectIdentityBdbManualCache; import org.archive.util.ObjectIdentityCache; +import org.archive.util.TextUtils; import org.archive.util.bdbje.EnhancedEnvironment; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.annotation.Autowired; @@ -440,7 +442,7 @@ public class BdbModule implements Lifecycle, Checkpointable, Closeable, Disposab public void startCheckpoint(Checkpoint checkpointInProgress) {} - public void doCheckpoint(Checkpoint checkpointInProgress) throws IOException { + public void doCheckpoint(final Checkpoint checkpointInProgress) throws IOException { // First sync objectCaches for (@SuppressWarnings("rawtypes") ObjectIdentityCache oic : oiCaches.values()) { oic.sync(); @@ -499,6 +501,19 @@ public class BdbModule implements Lifecycle, Checkpointable, Closeable, Disposab } catch (DatabaseException e) { throw new IOException(e); } + + if (checkpointInProgress.getForgetAllButLatest()) { + File[] oldEnvCpDirs = dir.getFile().listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return !name.equals(checkpointInProgress.getName()) + && TextUtils.matches("cp\\d{5}-\\d{14}", name); + } + }); + for (File d: oldEnvCpDirs) { + FileUtils.deleteDirectory(d); + } + } } @SuppressWarnings("unchecked") diff --git a/commons/src/main/java/org/archive/checkpointing/Checkpoint.java b/commons/src/main/java/org/archive/checkpointing/Checkpoint.java index 3daf8a73..671f84e3 100644 --- a/commons/src/main/java/org/archive/checkpointing/Checkpoint.java +++ b/commons/src/main/java/org/archive/checkpointing/Checkpoint.java @@ -173,4 +173,12 @@ public class Checkpoint implements InitializingBean { public static boolean hasValidStamp(File checkpointDirectory) { return (new File(checkpointDirectory,Checkpoint.VALIDITY_STAMP_FILENAME)).exists(); } + + protected boolean forgetAllButLatest = false; + public void setForgetAllButLatest(boolean b) { + this.forgetAllButLatest = b; + } + public boolean getForgetAllButLatest() { + return forgetAllButLatest; + } } \ No newline at end of file diff --git a/commons/src/main/java/org/archive/httpclient/ConfigurableX509TrustManager.java b/commons/src/main/java/org/archive/httpclient/ConfigurableX509TrustManager.java deleted file mode 100644 index 45a89ba6..00000000 --- a/commons/src/main/java/org/archive/httpclient/ConfigurableX509TrustManager.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.httpclient; - -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.logging.Logger; - -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -/** - * A configurable trust manager built on X509TrustManager. - * - * If set to 'open' trust, the default, will get us into sites for whom we do - * not have the CA or any of intermediary CAs that go to make up the cert chain - * of trust. Will also get us past selfsigned and expired certs. 'loose' - * trust will get us into sites w/ valid certs even if they are just - * selfsigned. 'normal' is any valid cert not including selfsigned. 'strict' - * means cert must be valid and the cert DN must match server name. - * - *

Based on pointers in - * SSL - * Guide, - * and readings done in JSSE - * Guide. - * - *

TODO: Move to an ssl subpackage when we have other classes other than - * just this one. - * - * @author stack - * @version $Id$ - */ -public class ConfigurableX509TrustManager implements X509TrustManager -{ - /** - * Logging instance. - */ - protected static Logger logger = Logger.getLogger( - "org.archive.httpclient.ConfigurableX509TrustManager"); - - public static enum TrustLevel { - /** - * Trust anything given us. - * - * Default setting. - * - *

See - * e502. Disabling Certificate Validation in an HTTPS Connection from - * the java almanac for how to trust all. - */ - OPEN, - - /** - * Trust any valid cert including self-signed certificates. - */ - LOOSE, - - /** - * Normal jsse behavior. - * - * Seemingly any certificate that supplies valid chain of trust. - */ - NORMAL, - - /** - * Strict trust. - * - * Ensure server has same name as cert DN. - */ - STRICT, - } - - /** - * Default setting for trust level. - */ - public final static TrustLevel DEFAULT = TrustLevel.OPEN; - - /** - * Trust level. - */ - private TrustLevel trustLevel = DEFAULT; - - - /** - * An instance of the SUNX509TrustManager that we adapt variously - * depending upon passed configuration. - * - * We have it do all the work we don't want to. - */ - private X509TrustManager standardTrustManager = null; - - - public ConfigurableX509TrustManager() - throws NoSuchAlgorithmException, KeyStoreException { - this(DEFAULT); - } - - /** - * Constructor. - * - * @param level Level of trust to effect. - * - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - */ - public ConfigurableX509TrustManager(TrustLevel level) - throws NoSuchAlgorithmException, KeyStoreException { - super(); - TrustManagerFactory factory = TrustManagerFactory. - getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - // Pass in a null (Trust) KeyStore. Null says use the 'default' - // 'trust' keystore (KeyStore class is used to hold keys and to hold - // 'trusts' (certs)). See 'X509TrustManager Interface' in this doc: - // http://java.sun.com - // /j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html#Introduction - factory.init((KeyStore)null); - TrustManager[] trustmanagers = factory.getTrustManagers(); - if (trustmanagers.length == 0) { - throw new NoSuchAlgorithmException(TrustManagerFactory. - getDefaultAlgorithm() + " trust manager not supported"); - } - this.standardTrustManager = (X509TrustManager)trustmanagers[0]; - - this.trustLevel = level; - } - - public void checkClientTrusted(X509Certificate[] certificates, String type) - throws CertificateException { - if (this.trustLevel.equals(TrustLevel.OPEN)) { - return; - } - - this.standardTrustManager.checkClientTrusted(certificates, type); - } - - public void checkServerTrusted(X509Certificate[] certificates, String type) - throws CertificateException { - if (this.trustLevel.equals(TrustLevel.OPEN)) { - return; - } - - try { - this.standardTrustManager.checkServerTrusted(certificates, type); - if (this.trustLevel.equals(TrustLevel.STRICT)) { - logger.severe(TrustLevel.STRICT + " not implemented."); - } - } catch (CertificateException e) { - if (this.trustLevel.equals(TrustLevel.LOOSE) && - certificates != null && certificates.length == 1) - { - // If only one cert and its valid and it caused a - // CertificateException, assume its selfsigned. - X509Certificate certificate = certificates[0]; - certificate.checkValidity(); - } else { - // If we got to here, then we're probably NORMAL. Rethrow. - throw e; - } - } - } - - public X509Certificate[] getAcceptedIssuers() { - return this.standardTrustManager.getAcceptedIssuers(); - } -} diff --git a/commons/src/main/java/org/archive/httpclient/package.html b/commons/src/main/java/org/archive/httpclient/package.html deleted file mode 100644 index 87ae77ed..00000000 --- a/commons/src/main/java/org/archive/httpclient/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - -org.archive.httpclient package - -Provides specializations on - apache jakarta - commons httpclient. - -

HttpRecorderGetMethod

-

Class that the passed HttpRecorder w/ boundary between - HTTP header and content. Also forces a close on the response on - call to releaseConnection.

- -

ConfigurableTrustManagerProtocolSocketFactory

-

A protocol socket factory that allows setting of trust level on - construction.

- -

References

-

JavaTM Secure Socket Extension (JSSE): Reference Guide

- - - diff --git a/commons/src/main/java/org/archive/io/ArchiveFileConstants.java b/commons/src/main/java/org/archive/io/ArchiveFileConstants.java deleted file mode 100644 index b1a39194..00000000 --- a/commons/src/main/java/org/archive/io/ArchiveFileConstants.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -@Deprecated -public interface ArchiveFileConstants extends org.archive.format.ArchiveFileConstants { -} diff --git a/commons/src/main/java/org/archive/io/ArchiveReader.java b/commons/src/main/java/org/archive/io/ArchiveReader.java deleted file mode 100644 index 66056d33..00000000 --- a/commons/src/main/java/org/archive/io/ArchiveReader.java +++ /dev/null @@ -1,761 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import java.io.BufferedInputStream; -import java.io.BufferedWriter; -import java.io.Closeable; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.archive.util.MimetypeUtils; -import org.archive.util.zip.GZIPMembersInputStream; - -import com.google.common.io.CountingInputStream; - - -/** - * Reader for an Archive file of Archive {@link ArchiveRecord}s. - * @author stack - * @version $Date$ $Version$ - */ -public abstract class ArchiveReader implements ArchiveFileConstants, Iterable, Closeable { - /** - * Is this Archive file compressed? - */ - private boolean compressed = false; - - /** - * Should we digest as we read? - */ - private boolean digest = true; - - /** - * Should the parse be strict? - */ - private boolean strict = false; - - /** - * Archive file input stream. - * - * Keep it around so we can close it when done. - * - *

Set in constructor. Should support at least 1 byte mark/reset. - * Make it protected so subclasses have access. - */ - protected InputStream in = null; - - /** - * Maximum amount of recoverable exceptions in a row. - * If more than this amount in a row, we'll let out the exception rather - * than go back in for yet another retry. - */ - public static final int MAX_ALLOWED_RECOVERABLES = 10; - - - /** - * The Record currently being read. - * - * Keep this ongoing reference so we'll close the record even if the caller - * doesn't. - */ - private ArchiveRecord currentRecord = null; - - /** - * Descriptive string for the Archive file we're going against: - * full path, url, etc. -- depends on context in which file was made. - */ - private String identifier = null; - - /** - * Archive file version. - */ - private String version = null; - - - protected ArchiveReader() { - super(); - } - - /** - * Convenience method used by subclass constructors. - * @param i Identifier for Archive file this reader goes against. - */ - protected void initialize(final String i) { - setReaderIdentifier(i); - } - - /** - * Convenience method for constructors. - * - * @param f File to read. - * @param offset Offset at which to start reading. - * @return InputStream to read from. - * @throws IOException If failed open or fail to get a memory - * mapped byte buffer on file. - */ - protected InputStream getInputStream(final File f, final long offset) - throws IOException { - FileInputStream fin = new FileInputStream(f); - return new BufferedInputStream(fin); - } - - public boolean isCompressed() { - return this.compressed; - } - - /** - * Get record at passed offset. - * - * @param offset Byte index into file at which a record starts. - * @return An Archive Record reference. - * @throws IOException - */ - public ArchiveRecord get(long offset) throws IOException { - cleanupCurrentRecord(); - long posn = positionForRecord(in); - if(offset>=posn) { - in.skip(offset-posn); - } else { - throw new UnsupportedOperationException("no reverse seeking: at "+posn+" requested "+offset); - } - return createArchiveRecord(this.in, offset); - } - - /** - * @return Return Archive Record created against current offset. - * @throws IOException - */ - public ArchiveRecord get() throws IOException { - return createArchiveRecord(this.in, positionForRecord(in)); - } - - public void close() throws IOException { - if (this.in != null) { - this.in.close(); - this.in = null; - } - } - - /** - * Cleanout the current record if there is one. - * @throws IOException - */ - protected void cleanupCurrentRecord() throws IOException { - if (this.currentRecord != null) { - this.currentRecord.close(); - gotoEOR(this.currentRecord); - this.currentRecord = null; - } - } - - /** - * Return an Archive Record homed on offset into - * is. - * @param is Stream to read Record from. - * @param offset Offset to find Record at. - * @return ArchiveRecord instance. - * @throws IOException - */ - protected abstract ArchiveRecord createArchiveRecord(InputStream is, - long offset) - throws IOException; - - /** - * Skip over any trailing new lines at end of the record so we're lined up - * ready to read the next. - * @param record - * @throws IOException - */ - protected abstract void gotoEOR(ArchiveRecord record) throws IOException; - - public abstract String getFileExtension(); - public abstract String getDotFileExtension(); - - /** - * @return Version of this Archive file. - */ - public String getVersion() { - return this.version; - } - - /** - * Validate the Archive file. - * - * This method iterates over the file throwing exception if it fails - * to successfully parse any record. - * - *

Assumes the stream is at the start of the file. - * @return List of all read Archive Headers. - * - * @throws IOException - */ - public List validate() throws IOException { - return validate(-1); - } - - /** - * Validate the Archive file. - * - * This method iterates over the file throwing exception if it fails - * to successfully parse. - * - *

We start validation from wherever we are in the stream. - * - * @param numRecords Number of records expected. Pass -1 if number is - * unknown. - * - * @return List of all read metadatas. As we validate records, we add - * a reference to the read metadata. - * - * @throws IOException - */ - public List validate(int numRecords) - throws IOException { - List hdrList = new ArrayList(); - int recordCount = 0; - setStrict(true); - for (Iterator i = iterator(); i.hasNext();) { - recordCount++; - ArchiveRecord r = i.next(); - if (r.getHeader().getLength() <= 0 - && r.getHeader().getMimetype(). - equals(MimetypeUtils.NO_TYPE_MIMETYPE)) { - throw new IOException("record content is empty."); - } - r.close(); - hdrList.add(r.getHeader()); - } - - if (numRecords != -1) { - if (recordCount != numRecords) { - throw new IOException("Count of records, " - + Integer.toString(recordCount) - + " is not equal to expected " - + Integer.toString(numRecords)); - } - } - - return hdrList; - } - - /** - * Test Archive file is valid. - * Assumes the stream is at the start of the file. Be aware that this - * method makes a pass over the whole file. - * @return True if file can be successfully parsed. - */ - public boolean isValid() { - boolean valid = false; - try { - validate(); - valid = true; - } catch(Exception e) { - // File is not valid if exception thrown parsing. - valid = false; - } - - return valid; - } - - /** - * @return Returns the strict. - */ - public boolean isStrict() { - return this.strict; - } - - /** - * @param s The strict to set. - */ - public void setStrict(boolean s) { - this.strict = s; - } - - /** - * @param d True if we're to digest. - */ - public void setDigest(boolean d) { - this.digest = d; - } - - /** - * @return True if we're digesting as we read. - */ - public boolean isDigest() { - return this.digest; - } - - protected Logger getLogger() { - return Logger.getLogger(this.getClass().getName()); - } - - /** - * Returns an ArchiveRecord iterator. - * Of note, on IOException, especially if ZipException reading compressed - * ARCs, rather than fail the iteration, try moving to the next record. - * If {@link ArchiveReader#strict} is not set, this will usually succeed. - * @return An iterator over ARC records. - */ - public Iterator iterator() { - // Eat up any record outstanding. - try { - cleanupCurrentRecord(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return new ArchiveRecordIterator(); - } - - protected void setCompressed(boolean compressed) { - this.compressed = compressed; - } - - /** - * @return The current ARC record or null if none. - * After construction has the arcfile header record. - * @see #get() - */ - protected ArchiveRecord getCurrentRecord() { - return this.currentRecord; - } - - protected ArchiveRecord currentRecord(final ArchiveRecord r) { - this.currentRecord = r; - return r; - } - - protected InputStream getIn() { - return in; - } - - protected void setIn(InputStream in) { - this.in = in; - } - - protected void setVersion(String version) { - this.version = version; - } - - public String getReaderIdentifier() { - return this.identifier; - } - - protected void setReaderIdentifier(final String i) { - this.identifier = i; - } - - /** - * Log on stderr. - * Logging should go via the logging system. This method - * bypasses the logging system going direct to stderr. - * Should not generally be used. Its used for rare messages - * that come of cmdline usage of ARCReader ERRORs and WARNINGs. - * Override if using ARCReader in a context where no stderr or - * where you'd like to redirect stderr to other than System.err. - * @param level Level to log message at. - * @param message Message to log. - */ - public void logStdErr(Level level, String message) { - System.err.println(level.toString() + " " + message); - } - -// /** -// * Add buffering to RandomAccessInputStream. -// */ -// protected class RandomAccessBufferedInputStream -// extends BufferedInputStream implements RepositionableStream { -// -// public RandomAccessBufferedInputStream(RandomAccessInputStream is) -// throws IOException { -// super(is); -// } -// -// public RandomAccessBufferedInputStream(RandomAccessInputStream is, int size) -// throws IOException { -// super(is, size); -// } -// -// public long position() throws IOException { -// // Current position is the underlying files position -// // minus the amount thats in the buffer yet to be read. -// return ((RandomAccessInputStream)this.in).position() - -// (this.count - this.pos); -// } -// -// public void position(long position) throws IOException { -// // Force refill of buffer whenever there's been a seek. -// this.pos = 0; -// this.count = 0; -// ((RandomAccessInputStream)this.in).position(position); -// } -// -// public int available() throws IOException { -// // Avoid overflow on large datastreams -// long amount = (long)in.available() + (long)(count - pos); -// return (amount >= Integer.MAX_VALUE)? Integer.MAX_VALUE: (int)amount; -// } -// } - - /** - * Inner ArchiveRecord Iterator class. - * Throws RuntimeExceptions in {@link #hasNext()} and {@link #next()} if - * trouble pulling record from underlying stream. - * @author stack - */ - protected class ArchiveRecordIterator implements Iterator { - private final Logger logger = - Logger.getLogger(this.getClass().getName()); - /** - * @return True if we have more records to read. - * @exception RuntimeException Can throw an IOException wrapped in a - * RuntimeException if a problem reading underlying stream (Corrupted - * gzip, etc.). - */ - public boolean hasNext() { - // Call close on any extant record. This will scoot us past - // any content not yet read. - try { - cleanupCurrentRecord(); - } catch (IOException e) { - if (isStrict()) { - throw new RuntimeException(e); - } - if (e instanceof EOFException) { - logger.warning("Premature EOF cleaning up " + - currentRecord.getHeader().toString() + ": " + - e.getMessage()); - return false; - } - // If not strict, try going again. We might be able to skip - // over the bad record. - logger.log(Level.WARNING,"Trying skip of failed record cleanup of " + - currentRecord.getHeader().toString() + ": " + - e.getMessage(), e); - } - return innerHasNext(); - } - - protected boolean innerHasNext(){ - try { - getIn().mark(1); - int c = getIn().read(); - getIn().reset(); - return c > -1; - } catch (IOException e) { - logger.log(Level.WARNING,"problem probing for more content",e); - return false; - } - } - - /** - * Tries to move to next record if we get - * {@link RecoverableIOException}. If not strict - * tries to move to next record if we get an - * {@link IOException}. - * @return Next object. - * @exception RuntimeException Throws a runtime exception, - * usually a wrapping of an IOException, if trouble getting - * a record (Throws exception rather than return null). - */ - public ArchiveRecord next() { - long offset = -1; - try { - offset = positionForRecord(getIn()); - return exceptionNext(); - } catch (IOException e) { - if (!isStrict()) { - // Retry though an IOE. Maybe we will succeed reading - // subsequent record. - try { - if (hasNext()) { - getLogger().warning("Bad Record. Trying skip " + - "(Record start " + offset + "): " + - e.getMessage()); - return exceptionNext(); - } - // Else we are at last record. Iterator#next is - // expecting value. We do not have one. Throw exception. - throw new RuntimeException("Retried but no next " + - "record (Record start " + offset + ")", e); - } catch (IOException e1) { - throw new RuntimeException("After retry (Offset " + - offset + ")", e1); - } - } - throw new RuntimeException("(Record start " + offset + ")", e); - } - } - - /** - * A next that throws exceptions and has handling of - * recoverable exceptions moving us to next record. Can call - * hasNext which itself may throw exceptions. - * @return Next record. - * @throws IOException - * @throws RuntimeException Thrown when we've reached maximum - * retries. - */ - protected ArchiveRecord exceptionNext() - throws IOException, RuntimeException { - ArchiveRecord result = null; - IOException ioe = null; - for (int i = MAX_ALLOWED_RECOVERABLES; i > 0 && - result == null; i--) { - ioe = null; - try { - result = innerNext(); - } catch (RecoverableIOException e) { - ioe = e; - getLogger().warning(e.getMessage()); - if (hasNext()) { - continue; - } - // No records left. Throw exception rather than - // return null. The caller is expecting to get - // back a record since they've just called - // hasNext. - break; - } - } - if (ioe != null) { - // Then we did MAX_ALLOWED_RECOVERABLES retries. Throw - // the recoverable ioe wrapped in a RuntimeException so - // it goes out pass checks for IOE. - throw new RuntimeException("Retried " + - MAX_ALLOWED_RECOVERABLES + " times in a row", ioe); - } - return result; - } - - protected ArchiveRecord innerNext() throws IOException { - return get(positionForRecord(getIn())); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - } - - protected static long positionForRecord(InputStream in) { - return (in instanceof GZIPMembersInputStream) - ? ((GZIPMembersInputStream)in).getCurrentMemberStart() - : ((CountingInputStream)in).getCount(); - } - - protected static String stripExtension(final String name, - final String ext) { - return (!name.endsWith(ext))? name: - name.substring(0, name.length() - ext.length()); - } - - /** - * @return short name of Archive file. - */ - public String getFileName() { - return (new File(getReaderIdentifier())).getName(); - } - - /** - * @return short name of Archive file. - */ - public String getStrippedFileName() { - return getStrippedFileName(getFileName(), - getDotFileExtension()); - } - - /** - * @param name Name of ARCFile. - * @param dotFileExtension '.arc' or '.warc', etc. - * @return short name of Archive file. - */ - public static String getStrippedFileName(String name, - final String dotFileExtension) { - name = stripExtension(name, - ArchiveFileConstants.DOT_COMPRESSED_FILE_EXTENSION); - return stripExtension(name, dotFileExtension); - } - - /** - * @param value Value to test. - * @return True if value is 'true', else false. - */ - protected static boolean getTrueOrFalse(final String value) { - if (value == null || value.length() <= 0) { - return false; - } - return Boolean.TRUE.toString().equals(value.toLowerCase()); - } - - /** - * @param format Format to use outputting. - * @throws IOException - * @throws java.text.ParseException - * @return True if handled. - */ - protected boolean output(final String format) - throws IOException, java.text.ParseException { - boolean result = true; - // long start = System.currentTimeMillis(); - - // Write output as pseudo-CDX file. See - // http://www.archive.org/web/researcher/cdx_legend.php - // and http://www.archive.org/web/researcher/example_cdx.php. - // Hash is hard-coded straight SHA-1 hash of content. - if (format.equals(DUMP)) { - // No point digesting dumping. - setDigest(false); - dump(false); - } else if (format.equals(GZIP_DUMP)) { - // No point digesting dumping. - setDigest(false); - dump(true); - } else if (format.equals(CDX)) { - cdxOutput(false); - } else if (format.equals(CDX_FILE)) { - cdxOutput(true); - } else { - result = false; - } - return result; - } - - protected void cdxOutput(boolean toFile) - throws IOException { - BufferedWriter cdxWriter = null; - if (toFile) { - String cdxFilename = stripExtension(getReaderIdentifier(), - DOT_COMPRESSED_FILE_EXTENSION); - cdxFilename = stripExtension(cdxFilename, getDotFileExtension()); - cdxFilename += ('.' + CDX); - cdxWriter = new BufferedWriter(new FileWriter(cdxFilename)); - } - - String header = "CDX b e a m s c " + ((isCompressed()) ? "V" : "v") - + " n g"; - if (toFile) { - cdxWriter.write(header); - cdxWriter.newLine(); - } else { - System.out.println(header); - } - - String strippedFileName = getStrippedFileName(); - try { - for (Iterator ii = iterator(); ii.hasNext();) { - ArchiveRecord r = ii.next(); - if (toFile) { - cdxWriter.write(r.outputCdx(strippedFileName)); - cdxWriter.newLine(); - } else { - System.out.println(r.outputCdx(strippedFileName)); - } - } - } finally { - if (toFile) { - cdxWriter.close(); - } - } - } - - /** - * Output passed record using passed format specifier. - * @param format What format to use outputting. - * @throws IOException - * @return True if handled. - */ - public boolean outputRecord(final String format) - throws IOException { - boolean result = true; - if (format.equals(CDX)) { - System.out.println(get().outputCdx(getStrippedFileName())); - } else if(format.equals(ArchiveFileConstants.DUMP)) { - // No point digesting if dumping content. - setDigest(false); - get().dump(); - } else { - result = false; - } - return result; - } - - /** - * Dump this file on STDOUT - * @throws compress True if dumped output is compressed. - * @throws IOException - * @throws java.text.ParseException - */ - public abstract void dump(final boolean compress) - throws IOException, java.text.ParseException; - - /** - * @return an ArchiveReader that will delete a local file on close. Used - * when we bring Archive files local and need to clean up afterward. - */ - public abstract ArchiveReader getDeleteFileOnCloseReader(final File f); - - /** - * Output passed record using passed format specifier. - * @param r ARCReader instance to output. - * @param format What format to use outputting. - * @throws IOException - */ - protected static void outputRecord(final ArchiveReader r, - final String format) - throws IOException { - if (!r.outputRecord(format)) { - throw new IOException("Unsupported format" + - " (or unsupported on a single record): " + format); - } - } - - /** - * @return Base Options object filled out with help, digest, strict, etc. - * options. - */ - protected static Options getOptions() { - Options options = new Options(); - options.addOption(new Option("h","help", false, - "Prints this message and exits.")); - options.addOption(new Option("o","offset", true, - "Outputs record at this offset into file.")); - options.addOption(new Option("d","digest", true, - "Pass true|false. Expensive. Default: true (SHA-1).")); - options.addOption(new Option("s","strict", false, - "Strict mode. Fails parse if incorrectly formatted file.")); - options.addOption(new Option("f","format", true, - "Output options: 'cdx', cdxfile', 'dump', 'gzipdump'," + - "'or 'nohead'. Default: 'cdx'.")); - return options; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/ArchiveReaderFactory.java b/commons/src/main/java/org/archive/io/ArchiveReaderFactory.java deleted file mode 100644 index 54cb65fc..00000000 --- a/commons/src/main/java/org/archive/io/ArchiveReaderFactory.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; - -import org.archive.io.arc.ARCReaderFactory; -import org.archive.io.warc.WARCReaderFactory; -import org.archive.net.UURI; -import org.archive.net.md5.Md5URLConnection; -import org.archive.net.rsync.RsyncURLConnection; -import org.archive.util.FileUtils; - - -/** - * Factory that returns an Archive file Reader. - * Returns Readers for ARCs or WARCs. - * @author stack - * @version $Date$ $Revision$ - */ -public class ArchiveReaderFactory implements ArchiveFileConstants { - // Static block to enable S3 URLs - static { - if (System.getProperty("java.protocol.handler.pkgs") != null) { - System.setProperty("java.protocol.handler.pkgs", - System.getProperty("java.protocol.handler.pkgs") - + "|" + "org.archive.net"); - } else { - System.setProperty("java.protocol.handler.pkgs", "org.archive.net"); - } - } - - private static final ArchiveReaderFactory factory = - new ArchiveReaderFactory(); - - /** - * Shutdown any public access to default constructor. - */ - protected ArchiveReaderFactory() { - super(); - } - - /** - * Get an Archive file Reader on passed path or url. - * Does primitive heuristic figuring if path or URL. - * @param arcFileOrUrl File path or URL pointing at an Archive file. - * @return An Archive file Reader. - * @throws IOException - * @throws MalformedURLException - * @throws IOException - */ - public static ArchiveReader get(final String arcFileOrUrl) - throws MalformedURLException, IOException { - return ArchiveReaderFactory.factory.getArchiveReader(arcFileOrUrl); - } - - protected ArchiveReader getArchiveReader(final String arcFileOrUrl) - throws MalformedURLException, IOException { - return getArchiveReader(arcFileOrUrl, 0); - } - - protected ArchiveReader getArchiveReader(final String arcFileOrUrl, - final long offset) - throws MalformedURLException, IOException { - return UURI.hasScheme(arcFileOrUrl) && arcFileOrUrl.indexOf(":")>1? - get(new URL(arcFileOrUrl), offset): - get(new File(arcFileOrUrl), offset); - } - - /** - * @param f An Archive file to read. - * @return An ArchiveReader - * @throws IOException - */ - public static ArchiveReader get(final File f) throws IOException { - return ArchiveReaderFactory.factory.getArchiveReader(f); - } - - protected ArchiveReader getArchiveReader(final File f) - throws IOException { - return getArchiveReader(f, 0); - } - - /** - * @param f An Archive file to read. - * @param offset Have returned Reader set to start reading at this offset. - * @return An ArchiveReader - * @throws IOException - */ - public static ArchiveReader get(final File f, final long offset) - throws IOException { - return ArchiveReaderFactory.factory.getArchiveReader(f, offset); - } - - protected ArchiveReader getArchiveReader(final File f, - final long offset) - throws IOException { - if (ARCReaderFactory.isARCSuffix(f.getName())) { - return ARCReaderFactory.get(f, true, offset); - } else if (WARCReaderFactory.isWARCSuffix(f.getName())) { - return WARCReaderFactory.get(f, offset); - } - throw new IOException("Unknown file extension (Not ARC nor WARC): " - + f.getName()); - } - - /** - * Wrap a Reader around passed Stream. - * @param s Identifying String for this Stream used in error messages. - * Must be a string that ends with the name of the file we're to put - * an ArchiveReader on. This code looks at file endings to figure - * whether to return an ARC or WARC reader. - * @param is Stream. Stream will be wrapped with implementation of - * RepositionableStream unless already supported. - * @param atFirstRecord Are we at first Record? - * @return ArchiveReader. - * @throws IOException - */ - public static ArchiveReader get(final String s, final InputStream is, - final boolean atFirstRecord) - throws IOException { - return ArchiveReaderFactory.factory.getArchiveReader(s, is, - atFirstRecord); - } - - protected ArchiveReader getArchiveReader(final String id, - final InputStream is, final boolean atFirstRecord) - throws IOException { - final InputStream stream = is; - if (ARCReaderFactory.isARCSuffix(id)) { - return ARCReaderFactory.get(id, stream, atFirstRecord); - } else if (WARCReaderFactory.isWARCSuffix(id)) { - return WARCReaderFactory.get(id, stream, atFirstRecord); - } - throw new IOException("Unknown extension (Not ARC nor WARC): " + id); - } - - /** - * Get an Archive Reader aligned at offset. - * This version of get will not bring the file local but will try to - * stream across the net making an HTTP 1.1 Range request on remote - * http server (RFC1435 Section 14.35). - * @param u HTTP URL for an Archive file. - * @param offset Offset into file at which to start fetching. - * @return An ArchiveReader aligned at offset. - * @throws IOException - */ - public static ArchiveReader get(final URL u, final long offset) - throws IOException { - return ArchiveReaderFactory.factory.getArchiveReader(u, offset); - } - - protected ArchiveReader getArchiveReader(final URL f, final long offset) - throws IOException { - // Get URL connection. - URLConnection connection = f.openConnection(); - if (connection instanceof HttpURLConnection) { - addUserAgent((HttpURLConnection)connection); - } - if (offset != 0) { - // Use a Range request (Assumes HTTP 1.1 on other end). If - // length >= 0, add open-ended range header to the request. Else, - // because end-byte is inclusive, subtract 1. - connection.addRequestProperty("Range", "bytes=" + offset + "-"); - // TODO: should actually verify that server respected 'Range' request - // (spec allows them to ignore; 206 response or Content-Range header - // should be present if Range satisfied; multipart/byteranges could be - // a problem). - } - - return getArchiveReader(f.toString(), connection.getInputStream(), (offset == 0)); - } - - /** - * Get an ARCReader. - * Pulls the ARC local into whereever the System Property - * java.io.tmpdir points. It then hands back an ARCReader that - * points at this local copy. A close on this ARCReader instance will - * remove the local copy. - * @param u An URL that points at an ARC. - * @return An ARCReader. - * @throws IOException - */ - public static ArchiveReader get(final URL u) - throws IOException { - return ArchiveReaderFactory.factory.getArchiveReader(u); - } - - protected ArchiveReader getArchiveReader(final URL u) - throws IOException { - // If url represents a local file then return file it points to. - if (u.getPath() != null) { - // TODO: Add scheme check and host check. - File f = new File(u.getPath()); - if (f.exists()) { - return get(f, 0); - } - } - - String scheme = u.getProtocol(); - if (scheme.startsWith("http") || scheme.equals("s3")) { - // Try streaming if http or s3 URLs rather than copying local - // and then reading (Passing an offset will get us an Reader - // that wraps a Stream). - return get(u, 0); - } - - return makeARCLocal(u.openConnection()); - } - - protected ArchiveReader makeARCLocal(final URLConnection connection) - throws IOException { - File localFile = null; - if (connection instanceof HttpURLConnection) { - // If http url connection, bring down the resource local. - String p = connection.getURL().getPath(); - int index = p.lastIndexOf('/'); - if (index >= 0) { - // Name file for the file we're making local. - localFile = File.createTempFile("",p.substring(index + 1)); - if (localFile.exists()) { - // If file of same name already exists in TMPDIR, then - // clean it up (Assuming only reason a file of same name in - // TMPDIR is because we failed a previous download). - localFile.delete(); - } - } else { - localFile = File.createTempFile(ArchiveReader.class.getName(), - ".tmp"); - } - addUserAgent((HttpURLConnection)connection); - connection.connect(); - try { - FileUtils.readFullyToFile(connection.getInputStream(), localFile); - } catch (IOException ioe) { - localFile.delete(); - throw ioe; - } - } else if (connection instanceof RsyncURLConnection) { - // Then, connect and this will create a local file. - // See implementation of the rsync handler. - connection.connect(); - localFile = ((RsyncURLConnection)connection).getFile(); - } else if (connection instanceof Md5URLConnection) { - // Then, connect and this will create a local file. - // See implementation of the md5 handler. - connection.connect(); - localFile = ((Md5URLConnection)connection).getFile(); - } else { - throw new UnsupportedOperationException("No support for " + - connection); - } - - ArchiveReader reader = null; - try { - reader = get(localFile, 0); - } catch (IOException e) { - localFile.delete(); - throw e; - } - - // Return a delegate that does cleanup of downloaded file on close. - return reader.getDeleteFileOnCloseReader(localFile); - } - - protected void addUserAgent(final HttpURLConnection connection) { - connection.addRequestProperty("User-Agent", this.getClass().getName()); - } - - /** - * @param f File to test. - * @return True if f is compressed. - * @throws IOException - */ - protected boolean isCompressed(final File f) throws IOException { - return f.getName().toLowerCase(). - endsWith(DOT_COMPRESSED_FILE_EXTENSION); - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/ArchiveRecord.java b/commons/src/main/java/org/archive/io/ArchiveRecord.java deleted file mode 100644 index 63bfe628..00000000 --- a/commons/src/main/java/org/archive/io/ArchiveRecord.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.logging.Level; - -import org.archive.util.Base32; - -/** - * Archive file Record. - * @author stack - * @version $Date$ $Version$ - */ -public abstract class ArchiveRecord extends InputStream { - - /** - * Minimal http response or request header length. - * - * I've seen in arcs content length of 1 with no header. - */ - protected static final long MIN_HTTP_HEADER_LENGTH = - Math.min("HTTP/1.1 200 OK\r\n".length(), "GET / HTTP/1.0\n\r".length()); - - protected ArchiveRecordHeader header = null; - - /** - * Stream to read this record from. - * - * Stream can only be read sequentially. Will only return this records' - * content returning a -1 if you try to read beyond the end of the current - * record. - * - *

Streams can be markable or not. If they are, we'll be able to roll - * back when we've read too far. If not markable, assumption is that - * the underlying stream is managing our not reading too much (This pertains - * to the skipping over the end of the ARCRecord. See {@link #skip()}. - */ - protected InputStream in = null; - - /** - * Position w/i the Record content, within in. - * This position is relative within this Record. Its not same as the - * Archive file position. - */ - protected long position = 0; - - /** - * Set flag when we've reached the end-of-record. - */ - protected boolean eor = false; - - /** - * Compute digest on what we read and add to metadata when done. - * - * Currently hardcoded as sha-1. TODO: Remove when archive records - * digest or else, add a facility that allows the arc reader to - * compare the calculated digest to that which is recorded in - * the arc. - * - *

Protected instead of private so subclasses can update and complete - * the digest. - */ - protected MessageDigest digest = null; - private String digestStr = null; - - protected boolean strict = false; - - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the record this instance - * is to represent. - * @throws IOException - */ - public ArchiveRecord(InputStream in) - throws IOException { - this(in, null, 0, true, false); - } - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the record this instance - * is to represent. - * @param header Header data. - * @throws IOException - */ - public ArchiveRecord(InputStream in, ArchiveRecordHeader header) - throws IOException { - this(in, header, 0, true, false); - } - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the record this instance - * is to represent. - * @param header Header data. - * @param bodyOffset Offset into the body. Usually 0. - * @param digest True if we're to calculate digest for this record. Not - * digesting saves about ~15% of cpu during an ARC parse. - * @param strict Be strict parsing (Parsing stops if ARC inproperly - * formatted). - * @throws IOException - */ - public ArchiveRecord(InputStream in, ArchiveRecordHeader header, - int bodyOffset, boolean digest, boolean strict) - throws IOException { - this.in = in; - this.header = header; - this.position = bodyOffset; - if (digest) { - try { - this.digest = MessageDigest.getInstance("SHA1"); - } catch (NoSuchAlgorithmException e) { - // Convert to IOE because thats more amenable to callers - // -- they are dealing with it anyways. - throw new IOException(e.getMessage()); - } - } - this.strict = strict; - } - - public boolean markSupported() { - return false; - } - - /** - * @return Header data for this record. - */ - public ArchiveRecordHeader getHeader() { - return this.header; - } - - protected void setHeader(ArchiveRecordHeader header) { - this.header = header; - } - - /** - * Calling close on a record skips us past this record to the next record - * in the stream. - * - * It does not actually close the stream. The underlying steam is probably - * being used by the next arc record. - * - * @throws IOException - */ - public void close() throws IOException { - if (this.in != null) { - skip(); - this.in = null; - if (this.digest != null) { - this.digestStr = Base32.encode(this.digest.digest()); - } - } - } - - /** - * @return Next character in this Record content else -1 if at EOR. - * @throws IOException - */ - public int read() throws IOException { - int c = -1; - if (available() > 0) { - c = this.in.read(); - if (c == -1) { - throw new IOException("Premature EOF before end-of-record."); - } - if (this.digest != null) { - this.digest.update((byte) c); - } - incrementPosition(); - } - return c; - } - - public int read(byte[] b, int offset, int length) throws IOException { - int read = Math.min(length, available()); - if (read == -1 || read == 0) { - read = -1; - } else { - read = this.in.read(b, offset, read); - if (read == -1) { - String msg = "Premature EOF before end-of-record: " - + getHeader().getHeaderFields(); - if (isStrict()) { - throw new IOException(msg); - } - setEor(true); - System.err.println(Level.WARNING.toString() + " " + msg); - } - if (this.digest != null && read >= 0) { - this.digest.update(b, offset, read); - } - incrementPosition(read); - } - return read; - } - - /** - * This available is not the stream's available. Its an available based on - * what the stated Archive record length is minus what we've read to date. - * - * @return True if bytes remaining in record content. - */ - public int available() { - long amount = getHeader().getLength() - getPosition(); - return (amount > Integer.MAX_VALUE? Integer.MAX_VALUE: (int)amount); - } - - /** - * Skip over this records content. - * - * @throws IOException - */ - protected void skip() throws IOException { - if (this.eor) { - return; - } - - // Read to the end of the body of the record. Exhaust the stream. - // Can't skip direct to end because underlying stream may be compressed - // and we're calculating the digest for the record. - int r = available(); - while (r > 0 && !this.eor) { - skip(r); - r = available(); - } - } - - public long skip(long n) throws IOException { - final int SKIP_BUFFERSIZE = 1024 * 4; - byte[] b = new byte[SKIP_BUFFERSIZE]; - long total = 0; - for (int read = 0; (total < n) && (read != -1);) { - read = Math.min(SKIP_BUFFERSIZE, (int) (n - total)); - // TODO: Interesting is that reading from compressed stream, we only - // read about 500 characters at a time though we ask for 4k. - // Look at this sometime. - read = read(b, 0, read); - if (read <= 0) { - read = -1; - } else { - total += read; - } - } - return total; - } - - /** - * @return Returns the strict. - */ - public boolean isStrict() { - return this.strict; - } - - /** - * @param strict The strict to set. - */ - public void setStrict(boolean strict) { - this.strict = strict; - } - - protected InputStream getIn() { - return this.in; - } - - public String getDigestStr() { - return this.digestStr; - } - - protected void incrementPosition() { - this.position++; - } - - protected void incrementPosition(final long incr) { - this.position += incr; - } - - public long getPosition() { - return this.position; - } - - protected boolean isEor() { - return eor; - } - - protected void setEor(boolean eor) { - this.eor = eor; - } - - protected String getStatusCode4Cdx(final ArchiveRecordHeader h) { - return "-"; - } - - protected String getIp4Cdx(final ArchiveRecordHeader h) { - return "-"; - } - - protected String getDigest4Cdx(final ArchiveRecordHeader h) { - return getDigestStr() == null? "-": getDigestStr(); - } - - protected String getMimetype4Cdx(final ArchiveRecordHeader h) { - return h.getMimetype(); - } - - protected String outputCdx(final String strippedFileName) - throws IOException { - // Read the whole record so we get out a hash. Should be safe calling - // close on already closed Record. - close(); - ArchiveRecordHeader h = getHeader(); - StringBuilder buffer = - new StringBuilder(ArchiveFileConstants.CDX_LINE_BUFFER_SIZE); - buffer.append(h.getDate()); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(getIp4Cdx(h)); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(h.getUrl()); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(getMimetype4Cdx(h)); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(getStatusCode4Cdx(h)); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(getDigest4Cdx(h)); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(h.getOffset()); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(h.getLength()); - buffer.append(ArchiveFileConstants.SINGLE_SPACE); - buffer.append(strippedFileName != null? strippedFileName: '-'); - return buffer.toString(); - } - - /** - * Writes output on STDOUT. - * @throws IOException - */ - public void dump() - throws IOException { - dump(System.out); - } - - /** - * Writes output on passed os. - * @throws IOException - */ - public void dump(final OutputStream os) - throws IOException { - final byte [] outputBuffer = new byte [16*1024]; - int read = outputBuffer.length; - while ((read = read(outputBuffer, 0, outputBuffer.length)) != -1) { - os.write(outputBuffer, 0, read); - } - os.flush(); - } - - /** - * Is it likely that this record contains headers? - * This method will return true if the body is a http response that includes - * http response headers or the body is a http request that includes request - * headers, etc. Be aware that headers in content are distinct from - * {@link ArchiveRecordHeader} 'headers'. - * @return True if this Record's content has headers: - */ - public boolean hasContentHeaders() { - final String url = getHeader().getUrl(); - if (url == null) { - return false; - } - - if (!url.toLowerCase().startsWith("http")) { - return false; - } - - if (getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) { - return false; - } - - return true; - } - - protected void setBodyOffset(int bodyOffset) { - this.position = bodyOffset; - } -} diff --git a/commons/src/main/java/org/archive/io/ArchiveRecordHeader.java b/commons/src/main/java/org/archive/io/ArchiveRecordHeader.java deleted file mode 100644 index 953537b1..00000000 --- a/commons/src/main/java/org/archive/io/ArchiveRecordHeader.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.util.Map; -import java.util.Set; - -/** - * Archive Record Header. - * @author stack - * @version $Date$ $Version$ - */ -public interface ArchiveRecordHeader { - /** - * Get the time when the record was created. - * @return Date in 14 digit time format (UTC). - * @see org.archive.util.ArchiveUtils#parse14DigitDate(String) - */ - public abstract String getDate(); - - /** - * @return Return length of record. - */ - public abstract long getLength(); - - /** - * @return Return Content-Length of the contents of the record - */ - public abstract long getContentLength(); - - - /** - * @return Record subject-url. - */ - public abstract String getUrl(); - - /** - * @return Record mimetype. - */ - public abstract String getMimetype(); - - /** - * @return Record version. - */ - public abstract String getVersion(); - - /** - * @return Offset into Archive file at which this record begins. - */ - public abstract long getOffset(); - - /** - * @param key Key to use looking up field value. - * @return value for passed key of null if no such entry. - */ - public abstract Object getHeaderValue(final String key); - - /** - * @return Header field name keys. - */ - public abstract Set getHeaderFieldKeys(); - - /** - * @return Map of header fields. - */ - public abstract Map getHeaderFields(); - - /** - * @return Returns identifier for current Archive file. Be aware this - * may not be a file name or file path. It may just be an URL. Depends - * on how Archive file was made. - */ - public abstract String getReaderIdentifier(); - - /** - * @return Identifier for the record. If ARC, the URL + date. If WARC, - * the GUID assigned. - */ - public abstract String getRecordIdentifier(); - - /** - * @return Returns digest as String for this record. Only available after - * the record has been read in totality. - */ - public abstract String getDigest(); - - /** - * Offset at which the content begins. - * For ARCs, its used to delimit where http headers end and content begins. - * For WARCs, its end of Named Fields before payload starts. - */ - public int getContentBegin(); - - public abstract String toString(); -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/ArraySeekInputStream.java b/commons/src/main/java/org/archive/io/ArraySeekInputStream.java deleted file mode 100644 index 5b30747e..00000000 --- a/commons/src/main/java/org/archive/io/ArraySeekInputStream.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; - - -/** - * A repositionable stream backed by an array. - * - * @author pjack - */ -public class ArraySeekInputStream extends SeekInputStream { - - - /** - * The array of bytes to read from. - */ - private byte[] array; - - - /** - * The offset in the array of the next byte to read. - */ - private int offset; - - - /** - * Constructor. Note that changes to the given array will be reflected - * in the stream. - * - * @param array The array to read bytes from. - */ - public ArraySeekInputStream(byte[] array) { - this.array = array; - this.offset = 0; - } - - - @Override - public int read() { - if (offset >= array.length) { - return -1; - } - int r = array[offset] & 0xFF; - offset++; - return r; - } - - - @Override - public int read(byte[] buf, int ofs, int len) { - if (offset >= array.length) { - return 0; - } - len = Math.min(len, array.length - offset); - System.arraycopy(array, offset, buf, ofs, len); - offset += len; - return len; - } - - - @Override - public int read(byte[] buf) { - return read(buf, 0, buf.length); - } - - - /** - * Returns the position of the stream. - */ - public long position() { - return offset; - } - - - /** - * Repositions the stream. - * - * @param p the new position for the stream - * @throws IOException if the given position is out of bounds - */ - public void position(long p) throws IOException { - if ((p < 0) || (p > array.length)) { - throw new IOException("Invalid position: " + p); - } - offset = (int)p; - } - -} diff --git a/commons/src/main/java/org/archive/io/BufferedSeekInputStream.java b/commons/src/main/java/org/archive/io/BufferedSeekInputStream.java deleted file mode 100644 index 2fdc72b7..00000000 --- a/commons/src/main/java/org/archive/io/BufferedSeekInputStream.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import java.io.IOException; - - -/** - * Buffers data from some other SeekInputStream. - * - * @author pjack - */ -public class BufferedSeekInputStream extends SeekInputStream { - - - /** - * The underlying input stream. - */ - final private SeekInputStream input; - - - /** - * The buffered data. - */ - final private byte[] buffer; - - - /** - * The maximum offset of valid data in the buffer. Usually the same - * as buffer.length, but may be shorter if we're in the last region - * of the stream. - */ - private int maxOffset; - - - /** - * The offset of within the buffer of the next byte to read. - */ - private int offset; - - - /** - * Constructor. - * - * @param input the underlying input stream - * @param capacity the size of the buffer - * @throws IOException if an IO occurs filling the first buffer - */ - public BufferedSeekInputStream(SeekInputStream input, int capacity) - throws IOException { - this.input = input; - this.buffer = new byte[capacity]; - buffer(); - } - - /** - * Fills the buffer. - * - * @throws IOException if an IO error occurs - */ - private void buffer() throws IOException { - int remaining = buffer.length; - while (remaining > 0) { - int r = input.read(buffer, buffer.length - remaining, remaining); - if (r <= 0) { - // Not enough information to fill the buffer - offset = 0; - maxOffset = buffer.length - remaining; - return; - } - remaining -= r; - } - maxOffset = buffer.length; - offset = 0; - } - - - /** - * Ensures that the buffer is valid. - * - * @throws IOException if an IO error occurs - */ - private void ensureBuffer() throws IOException { - if (offset >= maxOffset) { - buffer(); - } - } - - - /** - * Returns the number of unread bytes in the current buffer. - * - * @return the remaining bytes - */ - private int remaining() { - return maxOffset - offset; - } - - - @Override - public int read() throws IOException { - ensureBuffer(); - if (maxOffset == 0) { - return -1; - } - int ch = buffer[offset] & 0xFF; - offset++; - return ch; - } - - - @Override - public int read(byte[] buf, int ofs, int len) throws IOException { - ensureBuffer(); - if (maxOffset == 0) { - return 0; - } - len = Math.min(len, remaining()); - System.arraycopy(buffer, offset, buf, ofs, len); - offset += len; - return len; - } - - - @Override - public int read(byte[] buf) throws IOException { - return read(buf, 0, buf.length); - } - - - @Override - public long skip(long c) throws IOException { - ensureBuffer(); - if (maxOffset == 0) { - return 0; - } - int count = (c > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)c; - int skip = Math.min(count, remaining()); - offset += skip; - return skip; - } - - - /** - * Returns the stream's current position. - * - * @return the current position - */ - public long position() throws IOException { - return input.position() - buffer.length + offset; - } - - - /** - * Seeks to the given position. This method avoids re-filling the buffer - * if at all possible. - * - * @param p the position to set - * @throws IOException if an IO error occurs - */ - public void position(long p) throws IOException { - long blockStart = (input.position() - maxOffset) - / buffer.length * buffer.length; - long blockEnd = blockStart + maxOffset; - if ((p >= blockStart) && (p < blockEnd)) { - // Desired position is somewhere inside current buffer - long adj = p - blockStart; - offset = (int)adj; - return; - } - positionDirect(p); - } - - - /** - * Positions the underlying stream at the given position, then refills - * the buffer. - * - * @param p the position to set - * @throws IOException if an IO error occurs - */ - private void positionDirect(long p) throws IOException { - long newBlockStart = p / buffer.length * buffer.length; - input.position(newBlockStart); - buffer(); - offset = (int)(p % buffer.length); - } - - /** - * Close the stream, including the wrapped input stream. - */ - public void close() throws IOException { - super.close(); - if(this.input!=null) { - this.input.close(); - } - } - - -} diff --git a/commons/src/main/java/org/archive/io/CharSubSequence.java b/commons/src/main/java/org/archive/io/CharSubSequence.java deleted file mode 100644 index 1e89da56..00000000 --- a/commons/src/main/java/org/archive/io/CharSubSequence.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -/** - * Provides a subsequence view onto a CharSequence. - * - * @author gojomo - * @version $Revision$, $Date$ - */ -public class CharSubSequence implements CharSequence { - - protected CharSequence inner; - protected int start; - protected int end; - - public CharSubSequence(CharSequence inner, int start, int end) { - if (end < start) { - throw new IllegalArgumentException("Start " + start + " is > " + - " than end " + end); - } - - if (end < 0 || start < 0) { - throw new IllegalArgumentException("Start " + start + " or end " + - end + " is < 0."); - } - - if (inner == null) { - throw new NullPointerException("Passed charsequence is null."); - } - - this.inner = inner; - this.start = start; - this.end = end; - } - - /* - * (non-Javadoc) - * @see java.lang.CharSequence#length() - */ - public int length() { - return this.end - this.start; - } - - /* - * (non-Javadoc) - * @see java.lang.CharSequence#charAt(int) - */ - public char charAt(int index) { - return this.inner.charAt(this.start + index); - } - - /* - * (non-Javadoc) - * @see java.lang.CharSequence#subSequence(int, int) - */ - public CharSequence subSequence(int begin, int finish) { - return new CharSubSequence(this, begin, finish); - } - - /* - * (non-Javadoc) - * @see java.lang.CharSequence#toString() - */ - public String toString() { - StringBuffer sb = new StringBuffer(length()); - // could use StringBuffer.append(CharSequence) if willing to do 1.5 & up - for (int i = 0;i filenames; - - /* (non-Javadoc) - * @see java.io.InputStream#read() - */ - public int read() throws IOException { - int c = super.read(); - if( c == -1 && filenames.hasNext() ) { - cueStream(); - return read(); - } - return c; - } - /* (non-Javadoc) - * @see java.io.InputStream#read(byte[], int, int) - */ - public int read(byte[] b, int off, int len) throws IOException { - int c = super.read(b, off, len); - if( c == -1 && filenames.hasNext() ) { - cueStream(); - return read(b,off,len); - } - return c; - } - /* (non-Javadoc) - * @see java.io.InputStream#read(byte[]) - */ - public int read(byte[] b) throws IOException { - int c = super.read(b); - if( c == -1 && filenames.hasNext() ) { - cueStream(); - return read(b); - } - return c; - } - - /* (non-Javadoc) - * @see java.io.InputStream#skip(long) - */ - public long skip(long n) throws IOException { - long s = super.skip(n); - if( s files) throws IOException { - super(null); - filenames = files.iterator(); - cueStream(); - } - - private void cueStream() throws IOException { - if(filenames.hasNext()) { - this.in = new FileInputStream(filenames.next()); - } - } - -} diff --git a/commons/src/main/java/org/archive/io/CompositeFileReader.java b/commons/src/main/java/org/archive/io/CompositeFileReader.java deleted file mode 100644 index 14b56219..00000000 --- a/commons/src/main/java/org/archive/io/CompositeFileReader.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.List; - - -/** - * @author gojomo - */ -public class CompositeFileReader extends InputStreamReader { - - /** - * @param filenames - * @throws IOException - */ - public CompositeFileReader(List filenames) throws IOException { - super(new CompositeFileInputStream(filenames)); - } - -} diff --git a/commons/src/main/java/org/archive/io/CrawlerJournal.java b/commons/src/main/java/org/archive/io/CrawlerJournal.java index aee9f0f3..2575e29c 100644 --- a/commons/src/main/java/org/archive/io/CrawlerJournal.java +++ b/commons/src/main/java/org/archive/io/CrawlerJournal.java @@ -25,17 +25,21 @@ import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; +import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; +import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import org.apache.commons.lang.StringUtils; import org.archive.checkpointing.Checkpoint; import org.archive.util.ArchiveUtils; import org.archive.util.FileUtils; +import org.archive.util.TextUtils; /** * Utility class for a crawler journal/log that is compressed and @@ -196,12 +200,40 @@ public class CrawlerJournal implements Closeable { return; } close(); - // Rename gzipFile with the checkpoint name as suffix. + File newName = new File(this.gzipFile.getParentFile(), this.gzipFile.getName() + "." + checkpointInProgress.getName()); try { FileUtils.moveAsideIfExists(newName); - this.gzipFile.renameTo(newName); + if (checkpointInProgress.getForgetAllButLatest()) { + // merge any earlier checkpointed files into new checkpoint + // file, taking advantage of the legality of concatenating gzips + + File[] oldCheckpointeds = this.gzipFile.getParentFile().listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + String regex = "^" + Pattern.quote(gzipFile.getName()) + "\\.cp\\d{5}-\\d{14}$"; + return TextUtils.matches(regex, name); + } + }); + Arrays.sort(oldCheckpointeds); + + for (int i = 1; i < oldCheckpointeds.length; i++) { + FileUtils.appendTo(oldCheckpointeds[0], oldCheckpointeds[i]); + oldCheckpointeds[i].delete(); + } + + if (oldCheckpointeds.length > 0) { + FileUtils.appendTo(oldCheckpointeds[0], this.gzipFile); + this.gzipFile.delete(); + oldCheckpointeds[0].renameTo(newName); + } else { + this.gzipFile.renameTo(newName); + } + } else { + this.gzipFile.renameTo(newName); + } + // Open new gzip file. this.out = initialize(this.gzipFile); } catch (IOException ioe) { diff --git a/commons/src/main/java/org/archive/io/Endian.java b/commons/src/main/java/org/archive/io/Endian.java deleted file mode 100644 index f6d89aaa..00000000 --- a/commons/src/main/java/org/archive/io/Endian.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - - -/** - * Reads integers stored in big or little endian streams. - * - * @author pjack - */ -public class Endian { - - - /** - * Static utility class. - */ - private Endian() { - } - - - /** - * Reads the next little-endian unsigned 16 bit integer from the - * given stream. - * - * @param input the input stream to read from - * @return the next 16-bit little-endian integer - * @throws IOException if an IO error occurs - */ - public static char littleChar(InputStream input) throws IOException { - int lo = input.read(); - if (lo < 0) { - throw new EOFException(); - } - int hi = input.read(); - if (hi < 0) { - throw new EOFException(); - } - return (char)((hi << 8) | lo); - } - - - /** - * Reads the next little-endian signed 16-bit integer from the - * given stream. - * - * @param input the input stream to read from - * @return the next 16-bit little-endian integer - * @throws IOException if an IO error occurs - */ - public static short littleShort(InputStream input) throws IOException { - return (short)littleChar(input); - } - - - /** - * Reads the next little-endian signed 32-bit integer from the - * given stream. - * - * @param input the input stream to read from - * @return the next 32-bit little-endian integer - * @throws IOException if an IO error occurs - */ - public static int littleInt(InputStream input) throws IOException { - char lo = littleChar(input); - char hi = littleChar(input); - return (hi << 16) | lo; - } - - - /** - * Reads the next big-endian unsigned 16 bit integer from the - * given stream. - * - * @param input the input stream to read from - * @return the next 16-bit big-endian integer - * @throws IOException if an IO error occurs - */ - public static char bigChar(InputStream input) throws IOException { - int hi = input.read(); - if (hi < 0) { - throw new EOFException(); - } - int lo = input.read(); - if (lo < 0) { - throw new EOFException(); - } - return (char)((hi << 8) | lo); - } - - - /** - * Reads the next big-endian signed 32-bit integer from the - * given stream. - * - * @param input the input stream to read from - * @return the next 32-bit big-endian integer - * @throws IOException if an IO error occurs - */ - public static int bigInt(InputStream input) throws IOException { - char hi = bigChar(input); - char lo = bigChar(input); - return (hi << 16) | lo; - } -} diff --git a/commons/src/main/java/org/archive/io/GZIPMembersInputStream.java b/commons/src/main/java/org/archive/io/GZIPMembersInputStream.java deleted file mode 100644 index 35fb9e90..00000000 --- a/commons/src/main/java/org/archive/io/GZIPMembersInputStream.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * @deprecated use {@link org.archive.util.zip.GZIPMembersInputStream} - */ -@Deprecated -public class GZIPMembersInputStream extends org.archive.util.zip.GZIPMembersInputStream { - - public GZIPMembersInputStream(InputStream in) throws IOException { - super(in); - } - - public GZIPMembersInputStream(InputStream in, int size) throws IOException { - super(in, size); - } - -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/GenerationFileHandler.java b/commons/src/main/java/org/archive/io/GenerationFileHandler.java deleted file mode 100644 index 747d9de0..00000000 --- a/commons/src/main/java/org/archive/io/GenerationFileHandler.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.logging.FileHandler; -import java.util.logging.Formatter; -import java.util.logging.LogRecord; - -import org.archive.util.FileUtils; - - -/** - * FileHandler with support for rotating the current file to - * an archival name with a specified integer suffix, and - * provision of a new replacement FileHandler with the current - * filename. - * - * @author gojomo - */ -public class GenerationFileHandler extends FileHandler { - private LinkedList filenameSeries = new LinkedList(); - private boolean shouldManifest = false; - - /** - * @return Returns the filenameSeries. - */ - public List getFilenameSeries() { - return filenameSeries; - } - - /** - * Constructor. - * @param pattern - * @param append - * @param shouldManifest - * @throws IOException - * @throws SecurityException - */ - public GenerationFileHandler(String pattern, boolean append, - boolean shouldManifest) - throws IOException, SecurityException { - super(pattern, append); - filenameSeries.addFirst(pattern); - this.shouldManifest = shouldManifest; - } - - /** - * @param filenameSeries - * @param shouldManifest - * @throws IOException - */ - public GenerationFileHandler(LinkedList filenameSeries, - boolean shouldManifest) - throws IOException { - super((String)filenameSeries.getFirst(), false); // Never append in this case - this.filenameSeries = filenameSeries; - this.shouldManifest = shouldManifest; - } - - /** - * Move the current file to a new filename with the storeSuffix in place - * of the activeSuffix; continuing logging to a new file under the - * original filename. - * - * @param storeSuffix Suffix to put in place of activeSuffix - * @param activeSuffix Suffix to replace with storeSuffix. - * @return GenerationFileHandler instance. - * @throws IOException - */ - public GenerationFileHandler rotate(String storeSuffix, - String activeSuffix) - throws IOException { - close(); - String filename = (String)filenameSeries.getFirst(); - if (!filename.endsWith(activeSuffix)) { - throw new FileNotFoundException("Active file does not have" + - " expected suffix"); - } - String storeFilename = filename.substring(0, - filename.length() - activeSuffix.length()) + - storeSuffix; - File activeFile = new File(filename); - File storeFile = new File(storeFilename); - FileUtils.moveAsideIfExists(storeFile); - if (!activeFile.renameTo(storeFile)) { - throw new IOException("Unable to move " + filename + " to " + - storeFilename); - } - filenameSeries.add(1, storeFilename); - GenerationFileHandler newGfh = - new GenerationFileHandler(filenameSeries, shouldManifest); - newGfh.setFormatter(this.getFormatter()); - return newGfh; - } - - /** - * @return True if should manifest. - */ - public boolean shouldManifest() { - return this.shouldManifest; - } - - /** - * Constructor-helper that rather than clobbering any existing - * file, moves it aside with a timestamp suffix. - * - * @param filename - * @param append - * @param shouldManifest - * @return - * @throws SecurityException - * @throws IOException - */ - public static GenerationFileHandler makeNew(String filename, boolean append, boolean shouldManifest) throws SecurityException, IOException { - FileUtils.moveAsideIfExists(new File(filename)); - return new GenerationFileHandler(filename, append, shouldManifest); - } - - @Override - public void publish(LogRecord record) { - // when possible preformat outside synchronized superclass method - // (our most involved UriProcessingFormatter can cache result) - Formatter f = getFormatter(); - if(!(f instanceof Preformatter)) { - super.publish(record); - } else { - try { - ((Preformatter)f).preformat(record); - super.publish(record); - } finally { - ((Preformatter)f).clear(); - } - } - } -// -// TODO: determine if there's another way to have this optimization without -// negative impact on log-following (esp. in web UI) -// /** -// * Flush only 1/100th of the usual once-per-record, to reduce the time -// * spent holding the synchronization lock. (Flush is primarily called in -// * a superclass's synchronized publish()). -// * -// * The eventual close calls a direct flush on the target writer, so all -// * rotates/ends will ultimately be fully flushed. -// * -// * @see java.util.logging.StreamHandler#flush() -// */ -// @Override -// public synchronized void flush() { -// flushCount++; -// if(flushCount==100) { -// super.flush(); -// flushCount=0; -// } -// } -// int flushCount; - -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java b/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java deleted file mode 100644 index 1af3922b..00000000 --- a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java +++ /dev/null @@ -1,412 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.CharBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.text.NumberFormat; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.apache.commons.io.IOUtils; -import org.archive.util.DevUtils; - -import com.google.common.base.Charsets; -import com.google.common.primitives.Ints; - -/** - * (Replay)CharSequence view on recorded streams. - * - * For small streams, use {@link InMemoryReplayCharSequence}. - * - *

Call {@link close()} on this class when done to clean up resources. - * - * @contributor stack - * @contributor nlevitt - * @version $Revision$, $Date$ - */ -public class GenericReplayCharSequence implements ReplayCharSequence { - - protected static Logger logger = Logger - .getLogger(GenericReplayCharSequence.class.getName()); - - /** - * Name of the encoding we use writing out concatenated decoded prefix - * buffer and decoded backing file. - * - *

This define is also used as suffix for the file that holds the - * decodings. The name of the file that holds the decoding is the name - * of the backing file w/ this encoding for a suffix. - * - *

See Encoding. - */ - public static final Charset WRITE_ENCODING = Charsets.UTF_16BE; - - private static final long MAP_MAX_BYTES = 64 * 1024 * 1024; // 64M - - /** - * When the memory map moves away from the beginning of the file - * (to the "right") in order to reach a certain index, it will - * map up to this many bytes preceding (to the left of) the target character. - * Consequently it will map up to - * MAP_MAX_BYTES - MAP_TARGET_LEFT_PADDING - * bytes to the right of the target. - */ - private static final long MAP_TARGET_LEFT_PADDING_BYTES = (long) (MAP_MAX_BYTES * 0.01); - - /** - * Total length of character stream to replay minus the HTTP headers - * if present. - * - * If the backing file is larger than Integer.MAX_VALUE (i.e. 2gb), - * only the first Integer.MAX_VALUE characters are available through this API. - * We're overriding java.lang.CharSequence so that we can use - * java.util.regex directly on the data, and the CharSequence - * API uses int for the length and index. - */ - protected int length; - - /** counter of decoding exceptions for report at end */ - protected long decodingExceptions = 0; - protected CharacterCodingException codingException = null; - - /** - * Byte offset into the file where the memory mapped portion begins. - */ - private long mapByteOffset; - - // XXX do we need to keep the input stream around? - private FileInputStream backingFileIn = null; - - private FileChannel backingFileChannel = null; - - private long bytesPerChar; - - private CharBuffer mappedBuffer = null; - - /** - * File that has decoded content. - * - * Keep it around so we can remove on close. - */ - private File decodedFile = null; - - /* - * This portion of the CharSequence precedes what's in the backing file. In - * cases where we decodeToFile(), this is always empty, because we decode - * the entire input stream. - */ - private CharBuffer prefixBuffer = null; - - private boolean isOpen = true; - - protected Charset charset = null; - - /** - * Constructor. - * - * @param contentReplayInputStream inputStream of content - * @param charset Encoding to use reading the passed prefix - * buffer and backing file. Must not be null. - * @param backingFilename Path to backing file with content in excess of - * whats in buffer. - * - * @throws IOException - */ - public GenericReplayCharSequence(InputStream contentReplayInputStream, - int prefixMax, - String backingFilename, - Charset charset) throws IOException { - super(); - logger.fine("characterEncoding=" + charset + " backingFilename=" - + backingFilename); - - if(charset==null) { - charset = ReplayCharSequence.FALLBACK_CHARSET; - } - // decodes only up to Integer.MAX_VALUE characters - decode(contentReplayInputStream, prefixMax, backingFilename, charset); - - this.bytesPerChar = 2; - - if(length>prefixBuffer.position()) { - this.backingFileIn = new FileInputStream(decodedFile); - this.backingFileChannel = backingFileIn.getChannel(); - this.mapByteOffset = 0; - updateMemoryMappedBuffer(); - } - } - - private void updateMemoryMappedBuffer() { - long charLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters - long mapSize = Math.min((charLength * bytesPerChar) - mapByteOffset, MAP_MAX_BYTES); - logger.fine("updateMemoryMappedBuffer: mapOffset=" - + NumberFormat.getInstance().format(mapByteOffset) - + " mapSize=" + NumberFormat.getInstance().format(mapSize)); - try { - // TODO: stress-test without these possibly-costly requests! -// System.gc(); -// System.runFinalization(); - // TODO: Confirm the READ_ONLY works. I recall it not working. - // The buffers seem to always say that the buffer is writable. - mappedBuffer = backingFileChannel.map( - FileChannel.MapMode.READ_ONLY, mapByteOffset, mapSize) - .asReadOnlyBuffer().asCharBuffer(); - } catch (IOException e) { - // TODO convert this to a runtime error? - DevUtils.logger.log(Level.SEVERE, - " backingFileChannel.map() mapByteOffset=" + mapByteOffset - + " mapSize=" + mapSize + "\n" + "decodedFile=" - + decodedFile + " length=" + length + "\n" - + DevUtils.extraInfo(), e); - throw new RuntimeException(e); - } - } - - /** - * Converts the first Integer.MAX_VALUE characters from the - * file backingFilename from encoding encoding to - * encoding WRITE_ENCODING and saves as - * this.decodedFile, which is named backingFilename - * + "." + WRITE_ENCODING. - * - * @throws IOException - */ - protected void decode(InputStream inStream, int prefixMax, - String backingFilename, Charset charset) throws IOException { - - this.charset = charset; - - // TODO: consider if BufferedReader is helping any - // TODO: consider adding TBW 'LimitReader' to stop reading at - // Integer.MAX_VALUE characters because of charAt(int) limit - BufferedReader reader = new BufferedReader(new InputStreamReader( - inStream, charset)); - - logger.fine("backingFilename=" + backingFilename + " encoding=" - + charset + " decodedFile=" + decodedFile); - - this.prefixBuffer = CharBuffer.allocate(prefixMax); - - long count = 0; - while(count < prefixMax) { - int read = reader.read(prefixBuffer); - if(read<0) { - break; - } - count += read; - } - - int ch = reader.read(); - if(ch >= 0) { - count++; - - // more to decode to file overflow - this.decodedFile = new File(backingFilename + "." + WRITE_ENCODING); - - FileOutputStream fos; - try { - fos = new FileOutputStream(this.decodedFile); - } catch (FileNotFoundException e) { - // Windows workaround attempt - System.gc(); - System.runFinalization(); - this.decodedFile = new File(decodedFile.getAbsolutePath()+".win"); - logger.info("Windows 'file with a user-mapped section open' " - + "workaround gc/finalization/name-extension performed."); - // try again - fos = new FileOutputStream(this.decodedFile); - } - - Writer writer = new OutputStreamWriter(fos,WRITE_ENCODING); - writer.write(ch); - count += IOUtils.copyLarge(reader, writer); - writer.close(); - reader.close(); - } - - this.length = Ints.saturatedCast(count); - if(count>Integer.MAX_VALUE) { - logger.warning("input stream is longer than Integer.MAX_VALUE=" - + NumberFormat.getInstance().format(Integer.MAX_VALUE) - + " characters -- only first " - + NumberFormat.getInstance().format(Integer.MAX_VALUE) - + " are accessible through this GenericReplayCharSequence"); - } - - logger.fine("decode: decoded " + count + " characters" + - ((decodedFile==null) ? "" - : " ("+(count-prefixBuffer.length())+" to "+decodedFile+")")); - } - - /** - * Get character at passed absolute position. - * @param index Index into content - * @return Character at offset index. - */ - public char charAt(int index) { - if (index < 0 || index >= this.length()) { - throw new IndexOutOfBoundsException("index=" + index - + " - should be between 0 and length()=" + this.length()); - } - - // is it in the buffer - if (index < prefixBuffer.limit()) { - return prefixBuffer.get(index); - } - - // otherwise we gotta get it from disk via memory map - long charFileIndex = (long) index - (long) prefixBuffer.limit(); - long charFileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters - if (charFileIndex * bytesPerChar < mapByteOffset) { - logger.log(Level.WARNING,"left-fault; probably don't want to use CharSequence that far backward"); - } - if (charFileIndex * bytesPerChar < mapByteOffset - || charFileIndex - (mapByteOffset / bytesPerChar) >= mappedBuffer.limit()) { - // fault - /* - * mapByteOffset is bounded by 0 and file size +/- size of the map, - * and starts as close to fileIndex - - * MAP_TARGET_LEFT_PADDING_BYTES as it can while also not - * being smaller than it needs to be. - */ - mapByteOffset = Math.min(charFileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES, - charFileLength * bytesPerChar - MAP_MAX_BYTES); - mapByteOffset = Math.max(0, mapByteOffset); - updateMemoryMappedBuffer(); - } - - return mappedBuffer.get((int)(charFileIndex-(mapByteOffset/bytesPerChar))); - } - - public CharSequence subSequence(int start, int end) { - return new CharSubSequence(this, start, end); - } - - private void deleteFile(File fileToDelete) { - deleteFile(fileToDelete, null); - } - - private void deleteFile(File fileToDelete, final Exception e) { - if (e != null) { - // Log why the delete to help with debug of - // java.io.FileNotFoundException: - // ....tt53http.ris.UTF-16BE. - logger.severe("Deleting " + fileToDelete + " because of " - + e.toString()); - } - if (fileToDelete != null && fileToDelete.exists()) { - logger.fine("deleting file: " + fileToDelete); - fileToDelete.delete(); - } - } - - - @Override - public boolean isOpen() { - return this.isOpen; - } - - public void close() throws IOException { - this.isOpen = false; - - logger.fine("closing"); - - if (this.backingFileChannel != null && this.backingFileChannel.isOpen()) { - this.backingFileChannel.close(); - } - if (backingFileIn != null) { - backingFileIn.close(); - } - - deleteFile(this.decodedFile); - - // clear decodedFile -- so that double-close (as in finalize()) won't - // delete a later instance with same name see bug [ 1218961 ] - // "failed get of replay" in ExtractorHTML... usu: UTF-16BE - this.decodedFile = null; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#finalize() - */ - protected void finalize() throws Throwable { - super.finalize(); - logger.fine("finalizing"); - close(); - } - - /** - * Convenience method for getting a substring. - * - * @deprecated please use subSequence() and then toString() directly - */ - public String substring(int offset, int len) { - return subSequence(offset, offset + len).toString(); - } - - public String toString() { - StringBuilder sb = new StringBuilder(this.length()); - sb.append(this); - return sb.toString(); - } - - public int length() { - return length; - } - - /* (non-Javadoc) - * @see org.archive.io.ReplayCharSequence#getDecodeExceptionCount() - */ - @Override - public long getDecodeExceptionCount() { - return decodingExceptions; - } - - - /* (non-Javadoc) - * @see org.archive.io.ReplayCharSequence#getCodingException() - */ - @Override - public CharacterCodingException getCodingException() { - return codingException; - } - - /* (non-Javadoc) - * @see org.archive.io.ReplayCharSequence#getCharset() - */ - public Charset getCharset() { - return charset; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/GzipHeader.java b/commons/src/main/java/org/archive/io/GzipHeader.java deleted file mode 100644 index 6b8263bc..00000000 --- a/commons/src/main/java/org/archive/io/GzipHeader.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -/** - * @deprecated use {@link org.archive.util.zip.GzipHeader} - */ -@Deprecated -public class GzipHeader extends org.archive.util.zip.GzipHeader { -} diff --git a/commons/src/main/java/org/archive/io/HeaderedArchiveRecord.java b/commons/src/main/java/org/archive/io/HeaderedArchiveRecord.java deleted file mode 100644 index 3cce595b..00000000 --- a/commons/src/main/java/org/archive/io/HeaderedArchiveRecord.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpParser; -import org.apache.commons.httpclient.StatusLine; -import org.apache.commons.httpclient.util.EncodingUtil; -import org.archive.io.arc.ARCConstants; -import org.archive.util.LaxHttpParser; - -/** - * An ArchiveRecord whose content has a preamble of RFC822-like headers: e.g. - * The ArchiveRecord is a http response that leads off with http response - * headers. Use this ArchiveRecord Decorator to get at the content headers and - * the header/content demarcation. - * - * @author stack - * @author Olaf Freyer - */ -public class HeaderedArchiveRecord extends ArchiveRecord { - private int contentHeadersLength = -1; - private int statusCode = -1; - - /** - * Http header bytes. - * - * If non-null and bytes available, give out its contents before we - * go back to the underlying stream. - */ - private InputStream contentHeaderStream = null; - - /** - * Content headers. - * - * Only available after the reading of headers. - */ - private Header [] contentHeaders = null; - - - public HeaderedArchiveRecord(final ArchiveRecord ar) throws IOException { - super(ar); - } - - public HeaderedArchiveRecord(final ArchiveRecord ar, - final boolean readContentHeader) throws IOException { - super(ar); - if (readContentHeader) { - this.contentHeaderStream = readContentHeaders(); - } - } - - /** - * Skip over the the content headers if present. - * - * Subsequent reads will get the body. - * - *

Calling this method in the midst of reading the header - * will make for strange results. Otherwise, safe to call - * at any time though before reading any of the record - * content is only time that it makes sense. - * - *

After calling this method, you can call - * {@link #getContentHeaders()} to get the read http header. - * - * @throws IOException - */ - public void skipHttpHeader() throws IOException { - if (this.contentHeaderStream == null) { - return; - } - // Empty the contentHeaderStream - for (int available = this.contentHeaderStream.available(); - this.contentHeaderStream != null - && (available = this.contentHeaderStream.available()) > 0;) { - // We should be in this loop once only we should only do this - // buffer allocation once. - byte[] buffer = new byte[available]; - // The read nulls out httpHeaderStream when done with it so - // need check for null in the loop control line. - read(buffer, 0, available); - } - } - - public void dumpHttpHeader() throws IOException { - dumpHttpHeader(System.out); - } - - public void dumpHttpHeader(final PrintStream stream) throws IOException { - if (this.contentHeaderStream == null) { - return; - } - // Dump the httpHeaderStream to STDOUT - for (int available = this.contentHeaderStream.available(); - this.contentHeaderStream != null - && (available = this.contentHeaderStream.available()) > 0;) { - // We should be in this loop only once and should do this - // buffer allocation once. - byte[] buffer = new byte[available]; - // The read nulls out httpHeaderStream when done with it so - // need check for null in the loop control line. - int read = read(buffer, 0, available); - stream.write(buffer, 0, read); - } - } - - /** - * Read header if present. Technique borrowed from HttpClient HttpParse - * class. Using http parser code for now. Later move to more generic header - * parsing code if there proves a need. - * - * @return ByteArrayInputStream with the http header in it or null if no - * http header. - * @throws IOException - */ - private InputStream readContentHeaders() throws IOException { - // If judged a record that doesn't have an http header, return - // immediately. - if (!hasContentHeaders()) { - return null; - } - byte [] statusBytes = LaxHttpParser.readRawLine(getIn()); - int eolCharCount = getEolCharsCount(statusBytes); - if (eolCharCount <= 0) { - throw new IOException("Failed to read raw lie where one " + - " was expected: " + new String(statusBytes)); - } - String statusLine = EncodingUtil.getString(statusBytes, 0, - statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING); - if (statusLine == null) { - throw new NullPointerException("Expected status line is null"); - } - // TODO: Tighten up this test. - boolean isHttpResponse = StatusLine.startsWithHTTP(statusLine); - boolean isHttpRequest = false; - if (!isHttpResponse) { - isHttpRequest = statusLine.toUpperCase().startsWith("GET") || - !statusLine.toUpperCase().startsWith("POST"); - } - if (!isHttpResponse && !isHttpRequest) { - throw new UnexpectedStartLineIOException("Failed parse of " + - "status line: " + statusLine); - } - this.statusCode = isHttpResponse? - (new StatusLine(statusLine)).getStatusCode(): -1; - - // Save off all bytes read. Keep them as bytes rather than - // convert to strings so we don't have to worry about encodings - // though this should never be a problem doing http headers since - // its all supposed to be ascii. - ByteArrayOutputStream baos = - new ByteArrayOutputStream(statusBytes.length + 4 * 1024); - baos.write(statusBytes); - - // Now read rest of the header lines looking for the separation - // between header and body. - for (byte [] lineBytes = null; true;) { - lineBytes = LaxHttpParser.readRawLine(getIn()); - eolCharCount = getEolCharsCount(lineBytes); - if (eolCharCount <= 0) { - throw new IOException("Failed reading headers: " + - ((lineBytes != null)? new String(lineBytes): null)); - } - // Save the bytes read. - baos.write(lineBytes); - if ((lineBytes.length - eolCharCount) <= 0) { - // We've finished reading the http header. - break; - } - } - - byte [] headerBytes = baos.toByteArray(); - // Save off where content body, post content headers, starts. - this.contentHeadersLength = headerBytes.length; - ByteArrayInputStream bais = - new ByteArrayInputStream(headerBytes); - if (!bais.markSupported()) { - throw new IOException("ByteArrayInputStream does not support mark"); - } - bais.mark(headerBytes.length); - // Read the status line. Don't let it into the parseHeaders function. - // It doesn't know what to do with it. - bais.read(statusBytes, 0, statusBytes.length); - this.contentHeaders = LaxHttpParser.parseHeaders(bais, - ARCConstants.DEFAULT_ENCODING); - bais.reset(); - return bais; - } - - public static class UnexpectedStartLineIOException - extends RecoverableIOException { - private static final long serialVersionUID = 1L; - - public UnexpectedStartLineIOException(final String reason) { - super(reason); - } - } - - /** - * @param bytes Array of bytes to examine for an EOL. - * @return Count of end-of-line characters or zero if none. - */ - private int getEolCharsCount(byte [] bytes) { - int count = 0; - if (bytes != null && bytes.length >=1 && - bytes[bytes.length - 1] == '\n') { - count++; - if (bytes.length >=2 && bytes[bytes.length -2] == '\r') { - count++; - } - } - return count; - } - - /** - * @return If headers are for a http response AND the headers have been - * read, return status code. Else return -1. - */ - public int getStatusCode() { - return this.statusCode; - } - - /** - * @return Returns length of content headers or -1 if headers have - * not yet been read. - */ - public int getContentHeadersLength() { - return this.contentHeadersLength; - } - - public Header[] getContentHeaders() { - return contentHeaders; - } - - /** - * @return Next character in this ARCRecord's content else -1 if at end of - * this record. - * @throws IOException - */ - public int read() throws IOException { - int c = -1; - if (this.contentHeaderStream != null && - (this.contentHeaderStream.available() > 0)) { - // If http header, return bytes from it before we go to underlying - // stream. - c = this.contentHeaderStream.read(); - // If done with the header stream, null it out. - if (this.contentHeaderStream.available() <= 0) { - this.contentHeaderStream = null; - } - // do not increment position - - // the underlying ArchiveRecord stream allready did this - // incrementPosition(); - } else { - c = super.read(); - } - return c; - } - - public int read(byte [] b, int offset, int length) throws IOException { - int read = -1; - if (this.contentHeaderStream != null && - (this.contentHeaderStream.available() > 0)) { - // If http header, return bytes from it before we go to underlying - // stream. - read = Math.min(length, this.contentHeaderStream.available()); - if (read == 0) { - read = -1; - } else { - read = this.contentHeaderStream.read(b, offset, read); - } - // If done with the header stream, null it out. - if (this.contentHeaderStream.available() <= 0) { - this.contentHeaderStream = null; - } - // do not increment position - - // the underlying ArchiveRecord stream allready did this - //incrementPosition(); - } else { - read = super.read(b, offset, length); - } - return read; - } - - @Override - public int available() { - return ((ArchiveRecord)this.in).available(); - } - - @Override - public void close() throws IOException { - ((ArchiveRecord)this.in).close(); - } - - @Override - public void dump() throws IOException { - ((ArchiveRecord)this.in).dump(); - } - - @Override - public void dump(OutputStream os) throws IOException { - ((ArchiveRecord)this.in).dump(os); - } - - @Override - protected String getDigest4Cdx(ArchiveRecordHeader h) { - return ((ArchiveRecord)this.in).getDigest4Cdx(h); - } - - @Override - public String getDigestStr() { - return ((ArchiveRecord)this.in).getDigestStr(); - } - - @Override - public ArchiveRecordHeader getHeader() { - return ((ArchiveRecord)this.in).getHeader(); - } - - @Override - protected String getIp4Cdx(ArchiveRecordHeader h) { - return ((ArchiveRecord)this.in).getIp4Cdx(h); - } - - @Override - protected String getMimetype4Cdx(ArchiveRecordHeader h) { - return ((ArchiveRecord)this.in).getMimetype4Cdx(h); - } - - @Override - public long getPosition() { - return ((ArchiveRecord)this.in).getPosition(); - } - - @Override - protected String getStatusCode4Cdx(ArchiveRecordHeader h) { - return ((ArchiveRecord)this.in).getStatusCode4Cdx(h); - } - - @Override - public boolean hasContentHeaders() { - return ((ArchiveRecord)this.in).hasContentHeaders(); - } - - @Override - protected void incrementPosition() { - ((ArchiveRecord)this.in).incrementPosition(); - } - - @Override - protected void incrementPosition(long incr) { - ((ArchiveRecord)this.in).incrementPosition(incr); - } - - @Override - protected boolean isEor() { - return ((ArchiveRecord)this.in).isEor(); - } - - @Override - public boolean isStrict() { - return ((ArchiveRecord)this.in).isStrict(); - } - - @Override - public boolean markSupported() { - return ((ArchiveRecord)this.in).markSupported(); - } - - @Override - protected String outputCdx(String strippedFileName) throws IOException { - return ((ArchiveRecord)this.in).outputCdx(strippedFileName); - } - - @Override - protected void setEor(boolean eor) { - ((ArchiveRecord)this.in).setEor(eor); - } - - @Override - protected void setHeader(ArchiveRecordHeader header) { - ((ArchiveRecord)this.in).setHeader(header); - } - - @Override - public void setStrict(boolean strict) { - ((ArchiveRecord)this.in).setStrict(strict); - } - - @Override - protected void skip() throws IOException { - ((ArchiveRecord)this.in).skip(); - } - - @Override - public long skip(long n) throws IOException { - return ((ArchiveRecord)this.in).skip(n); - } -} diff --git a/commons/src/main/java/org/archive/io/LoudObjectOutputStream.java b/commons/src/main/java/org/archive/io/LoudObjectOutputStream.java deleted file mode 100644 index 959c2620..00000000 --- a/commons/src/main/java/org/archive/io/LoudObjectOutputStream.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Logger; - -/** - * ObjectOutputStream that logs class name of each object that is written - * to the stream. Useful for tracking down sources of NotSerializableException. - * - * @author pjack - * - */ -public class LoudObjectOutputStream extends ObjectOutputStream { - - - final private static Logger LOGGER = Logger.getLogger( - LoudObjectOutputStream.class.getName()); - - // Only log each class name once - private Set alreadyLogged = new HashSet(); - - public LoudObjectOutputStream(OutputStream out) throws IOException { - super(out); - this.enableReplaceObject(true); - } - - - @Override - protected Object replaceObject(Object obj) throws IOException { - if (obj != null) { - String name = obj.getClass().getName(); - if (alreadyLogged.add(name)) { - LOGGER.info("WROTE: " + name); - } - } - return obj; - } - - -} diff --git a/commons/src/main/java/org/archive/io/MiserOutputStream.java b/commons/src/main/java/org/archive/io/MiserOutputStream.java deleted file mode 100644 index f10ac9ca..00000000 --- a/commons/src/main/java/org/archive/io/MiserOutputStream.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * A filter stream that both counts bytes written, and optionally swallows - * flush() requests. - * - * @contributor gojomo - */ -public class MiserOutputStream extends FilterOutputStream { - protected long count; - protected boolean passFlushes; - - /** - * Wraps another output stream, counting the number of bytes written. - * - * @param out the output stream to be wrapped - */ - public MiserOutputStream(OutputStream out) { - this(out,true); - } - - /** - * Wraps another output stream, counting the number of bytes written. - * - * @param out the output stream to be wrapped - */ - public MiserOutputStream(OutputStream out, boolean passFlushes) { - super(out); - this.passFlushes = passFlushes; - } - - /** Returns the number of bytes written. */ - public long getCount() { - return count; - } - - @Override public void write(byte[] b, int off, int len) throws IOException { - out.write(b, off, len); - count += len; - } - - @Override public void write(int b) throws IOException { - out.write(b); - count++; - } - - @Override - public void close() throws IOException { - passFlushes = true; - super.close(); - } - - @Override - public void flush() throws IOException { - if(passFlushes) { - super.flush(); - } - } -} diff --git a/commons/src/main/java/org/archive/io/NoGzipMagicException.java b/commons/src/main/java/org/archive/io/NoGzipMagicException.java deleted file mode 100644 index 27d1058a..00000000 --- a/commons/src/main/java/org/archive/io/NoGzipMagicException.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -/** - * @deprecated use {@link org.archive.util.zip.NoGzipMagicException} - */ -@Deprecated -public class NoGzipMagicException extends org.archive.util.zip.NoGzipMagicException { -} diff --git a/commons/src/main/java/org/archive/io/ObjectPlusFilesInputStream.java b/commons/src/main/java/org/archive/io/ObjectPlusFilesInputStream.java deleted file mode 100644 index 892860ed..00000000 --- a/commons/src/main/java/org/archive/io/ObjectPlusFilesInputStream.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.util.Iterator; -import java.util.LinkedList; - -import org.archive.util.FileUtils; - - -/** - * Enhanced ObjectOutputStream with support for restoring - * files that had been saved, in parallel with object - * serialization. - * - * @author gojomo - * - */ -public class ObjectPlusFilesInputStream extends ObjectInputStream { - protected LinkedList auxiliaryDirectoryStack = new LinkedList(); - protected LinkedList postRestoreTasks = new LinkedList(); - - /** - * Instantiate over the given stream and using the supplied - * auxiliary storage directory. - * - * @param in - * @param storeDir - * @throws IOException - */ - public ObjectPlusFilesInputStream(InputStream in, File storeDir) - throws IOException { - super(in); - auxiliaryDirectoryStack.addFirst(storeDir); - } - - /** - * Push another default storage directory for use - * until popped. - * - * @param dir - */ - public void pushAuxiliaryDirectory(String dir) { - auxiliaryDirectoryStack. - addFirst(new File(getAuxiliaryDirectory(), dir)); - } - - /** - * Discard the top auxiliary directory. - */ - public void popAuxiliaryDirectory() { - auxiliaryDirectoryStack.removeFirst(); - } - - /** - * Return the top auxiliary directory, from - * which saved files are restored. - * - * @return Auxillary directory. - */ - public File getAuxiliaryDirectory() { - return (File)auxiliaryDirectoryStack.getFirst(); - } - - /** - * Restore a file from storage, using the name and length - * info on the serialization stream and the file from the - * current auxiliary directory, to the given File. - * - * @param destination - * @throws IOException - */ - public void restoreFile(File destination) throws IOException { - String nameAsStored = readUTF(); - long lengthAtStoreTime = readLong(); - File storedFile = new File(getAuxiliaryDirectory(),nameAsStored); - FileUtils.copyFile(storedFile, destination, lengthAtStoreTime); - } - - /** - * Restore a file from storage, using the name and length - * info on the serialization stream and the file from the - * current auxiliary directory, to the given File. - * - * @param directory - * @throws IOException - */ - public void restoreFileTo(File directory) throws IOException { - String nameAsStored = readUTF(); - long lengthAtStoreTime = readLong(); - File storedFile = new File(getAuxiliaryDirectory(),nameAsStored); - File destination = new File(directory,nameAsStored); - FileUtils.copyFile(storedFile, destination, lengthAtStoreTime); - } - - /** - * Register a task to be done when the ObjectPlusFilesInputStream - * is closed. - * - * @param task - */ - public void registerFinishTask(Runnable task) { - postRestoreTasks.addFirst(task); - } - - private void doFinishTasks() { - Iterator iter = postRestoreTasks.iterator(); - while(iter.hasNext()) { - ((Runnable)iter.next()).run(); - } - } - - /** - * In addition to default, do any registered cleanup tasks. - * - * @see java.io.InputStream#close() - */ - public void close() throws IOException { - super.close(); - doFinishTasks(); - } -} diff --git a/commons/src/main/java/org/archive/io/ObjectPlusFilesOutputStream.java b/commons/src/main/java/org/archive/io/ObjectPlusFilesOutputStream.java deleted file mode 100644 index 224f24e7..00000000 --- a/commons/src/main/java/org/archive/io/ObjectPlusFilesOutputStream.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.util.LinkedList; - -import org.archive.util.FileUtils; - - -/** - * Enhanced ObjectOutputStream which maintains (a stack of) auxiliary - * directories and offers convenience methods for serialized objects - * to save their related disk files alongside their serialized version. - * - * @author gojomo - */ -public class ObjectPlusFilesOutputStream extends ObjectOutputStream { - protected LinkedList auxiliaryDirectoryStack = new LinkedList(); - - /** - * Constructor - * - * @param out - * @param topDirectory - * @throws java.io.IOException - */ - public ObjectPlusFilesOutputStream(OutputStream out, File topDirectory) throws IOException { - super(out); - auxiliaryDirectoryStack.addFirst(topDirectory); - } - - /** - * Add another subdirectory for any file-capture needs during the - * current serialization. - * - * @param dir - */ - public void pushAuxiliaryDirectory(String dir) { - auxiliaryDirectoryStack.addFirst(new File(getAuxiliaryDirectory(),dir)); - } - - /** - * Remove the top subdirectory. - * - */ - public void popAuxiliaryDirectory() { - auxiliaryDirectoryStack.removeFirst(); - } - - /** - * Return the current auxiliary directory for storing - * files associated with serialized objects. - * - * @return Auxillary directory. - */ - public File getAuxiliaryDirectory() { - return (File)auxiliaryDirectoryStack.getFirst(); - } - - /** - * Store a snapshot of an object's supporting file to the - * current auxiliary directory. Should only be used for - * files which are strictly appended-to, because it tries - * to use a "hard link" where possible (meaning that - * future edits to the original file's contents will - * also affect the snapshot). - * - * Remembers current file extent to allow a future restore - * to ignore subsequent appended data. - * - * @param file - * @throws IOException - */ - public void snapshotAppendOnlyFile(File file) throws IOException { - // write filename - String name = file.getName(); - writeUTF(name); - // write current file length - writeLong(file.length()); - File auxDir = getAuxiliaryDirectory(); - if(!auxDir.exists()) { - FileUtils.ensureWriteableDirectory(auxDir); - } - File destination = new File(auxDir,name); - hardlinkOrCopy(file, destination); - } - - /** - * Create a backup of this given file, first by trying a "hard - * link", then by using a copy if hard linking is unavailable - * (either because it is unsupported or the origin and checkpoint - * directories are on different volumes). - * - * @param file - * @param destination - * @throws IOException - */ - private void hardlinkOrCopy(File file, File destination) throws IOException { - // For Linux/UNIX, try a hard link first. - Process link = Runtime.getRuntime().exec("ln "+file.getAbsolutePath()+" "+destination.getAbsolutePath()); - // TODO NTFS also supports hard links; add appropriate try - try { - link.waitFor(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if(link.exitValue()!=0) { - // hard link failed - FileUtils.copyFile(file,destination); - } - } - -} diff --git a/commons/src/main/java/org/archive/io/OriginSeekInputStream.java b/commons/src/main/java/org/archive/io/OriginSeekInputStream.java deleted file mode 100644 index 00605d82..00000000 --- a/commons/src/main/java/org/archive/io/OriginSeekInputStream.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import java.io.IOException; - - -/** - * Alters the origin of some other SeekInputStream. This class allows you - * to completely ignore everything in the underlying stream before a specified - * position, the origin position. - * - *

With the exception of {@link #position()} and {@link position(long)}, - * all of the methods in this class simply delegate to the underlying input - * stream. The position methods adjust the position of the - * underlying stream relative to the origin specified at construction time. - * - * @author pjack - */ -public class OriginSeekInputStream extends SeekInputStream { - - - /** - * The underlying stream. - */ - final private SeekInputStream input; - - - /** - * The origin position. In other words, this.position(0) - * resolves to input.position(start). - */ - final private long origin; - - - /** - * Constructor. - * - * @param input the underlying stream - * @param origin the origin position - * @throws IOException if an IO error occurs - */ - public OriginSeekInputStream(SeekInputStream input, long origin) - throws IOException { - this.input = input; - this.origin = origin; - input.position(origin); - } - - - @Override - public int available() throws IOException { - return input.available(); - } - - - @Override - public int read() throws IOException { - return input.read(); - } - - - @Override - public int read(byte[] buf, int ofs, int len) throws IOException { - return input.read(buf, ofs, len); - } - - - @Override - public int read(byte[] buf) throws IOException { - return input.read(buf); - } - - - @Override - public long skip(long count) throws IOException { - return input.skip(count); - } - - - /** - * Returns the position of the underlying stream relative to the origin. - * - * @return the relative position - * @throws IOException if an IO error occurs - */ - public long position() throws IOException { - return input.position() - origin; - } - - - /** - * Positions the underlying stream relative to the origin. - * In other words, this.position(0) resolves to input.position(origin), - * where input is underlying stream and origin is the origin specified - * at construction time. - * - * @param p the new position for this stream - * @throws IOException if an IO error occurs - */ - public void position(long p) throws IOException { - input.position(p + origin); - } -} diff --git a/commons/src/main/java/org/archive/io/Preformatter.java b/commons/src/main/java/org/archive/io/Preformatter.java deleted file mode 100644 index dcd31bb6..00000000 --- a/commons/src/main/java/org/archive/io/Preformatter.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.util.logging.LogRecord; - -/** - * Interface indicating a logging Formatter can preformat a record (outside - * the standard-implementation synchronized block) and cache it, returning it - * for the next request for formatting from the same thread. - * @contributor gojomo - */ -public interface Preformatter { - public void preformat(LogRecord record); - public void clear(); -} diff --git a/commons/src/main/java/org/archive/io/RandomAccessInputStream.java b/commons/src/main/java/org/archive/io/RandomAccessInputStream.java deleted file mode 100644 index d8dd260b..00000000 --- a/commons/src/main/java/org/archive/io/RandomAccessInputStream.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; - - -/** - * Wraps a RandomAccessFile with an InputStream interface. - * - * @author gojomo - */ -public class RandomAccessInputStream extends SeekInputStream { - - /** - * Reference to the random access file this stream is reading from. - */ - private RandomAccessFile raf = null; - - /** - * When mark is called, save here the current position so we can go back - * on reset. - */ - private long markpos = -1; - - /** - * True if we are to close the underlying random access file when this - * stream is closed. - */ - private boolean sympathyClose; - - /** - * Constructor. - * - * If using this constructor, caller created the RAF and therefore - * its assumed wants to control close of the RAF. The RAF.close - * is not called if this constructor is used on close of this stream. - * - * @param raf RandomAccessFile to wrap. - * @throws IOException - */ - public RandomAccessInputStream(RandomAccessFile raf) - throws IOException { - this(raf, false, 0); - } - - /** - * Constructor. - * - * @param file File to get RAFIS on. Creates an RAF from passed file. - * Closes the created RAF when this stream is closed. - * @throws IOException - */ - public RandomAccessInputStream(final File file) - throws IOException { - this(new RandomAccessFile(file, "r"), true, 0); - } - - /** - * Constructor. - * - * @param file File to get RAFIS on. Creates an RAF from passed file. - * Closes the created RAF when this stream is closed. - * @param offset - * @throws IOException - */ - public RandomAccessInputStream(final File file, final long offset) - throws IOException { - this(new RandomAccessFile(file, "r"), true, offset); - } - - /** - * @param raf RandomAccessFile to wrap. - * @param sympathyClose Set to true if we are to close the RAF - * file when this stream is closed. - * @param offset - * @throws IOException - */ - public RandomAccessInputStream(final RandomAccessFile raf, - final boolean sympathyClose, final long offset) - throws IOException { - super(); - this.sympathyClose = sympathyClose; - this.raf = raf; - if (offset > 0) { - this.raf.seek(offset); - } - } - - /* (non-Javadoc) - * @see java.io.InputStream#read() - */ - public int read() throws IOException { - return this.raf.read(); - } - - /* (non-Javadoc) - * @see java.io.InputStream#read(byte[], int, int) - */ - public int read(byte[] b, int off, int len) throws IOException { - return this.raf.read(b, off, len); - } - - /* (non-Javadoc) - * @see java.io.InputStream#read(byte[]) - */ - public int read(byte[] b) throws IOException { - return this.raf.read(b); - } - - /* (non-Javadoc) - * @see java.io.InputStream#skip(long) - */ - public long skip(long n) throws IOException { - this.raf.seek(this.raf.getFilePointer() + n); - return n; - } - - public long position() throws IOException { - return this.raf.getFilePointer(); - } - - public void position(long position) throws IOException { - this.raf.seek(position); - } - - public int available() throws IOException { - long amount = this.raf.length() - this.position(); - return (amount >= Integer.MAX_VALUE)? Integer.MAX_VALUE: (int)amount; - } - - public boolean markSupported() { - return true; - } - - public synchronized void mark(int readlimit) { - try { - this.markpos = position(); - } catch (IOException e) { - // Set markpos to -1. Will cause exception reset. - this.markpos = -1; - } - } - - public synchronized void reset() throws IOException { - if (this.markpos == -1) { - throw new IOException("Mark has not been set."); - } - position(this.markpos); - } - - public void close() throws IOException { - try { - super.close(); - } finally { - if (this.sympathyClose) { - this.raf.close(); - } - } - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/RandomAccessOutputStream.java b/commons/src/main/java/org/archive/io/RandomAccessOutputStream.java deleted file mode 100644 index 225f995f..00000000 --- a/commons/src/main/java/org/archive/io/RandomAccessOutputStream.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.RandomAccessFile; - - -/** - * Wraps a RandomAccessFile with OutputStream interface. - * - * @author gojomo - */ -public class RandomAccessOutputStream extends OutputStream { - protected RandomAccessFile raf; - - /** - * Wrap the given RandomAccessFile - */ - public RandomAccessOutputStream(RandomAccessFile raf) { - super(); - this.raf = raf; - } - - /* (non-Javadoc) - * @see java.io.OutputStream#write(int) - */ - public void write(int b) throws IOException { - raf.write(b); - } - - /* (non-Javadoc) - * @see java.io.OutputStream#close() - */ - public void close() throws IOException { - raf.close(); - } - - /* (non-Javadoc) - * @see java.io.OutputStream#write(byte[], int, int) - */ - public void write(byte[] b, int off, int len) throws IOException { - raf.write(b, off, len); - } - - /* (non-Javadoc) - * @see java.io.OutputStream#write(byte[]) - */ - public void write(byte[] b) throws IOException { - raf.write(b); - } -} diff --git a/commons/src/main/java/org/archive/io/ReadSource.java b/commons/src/main/java/org/archive/io/ReadSource.java deleted file mode 100644 index a3c29967..00000000 --- a/commons/src/main/java/org/archive/io/ReadSource.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.Reader; - -/** - * Interface for objects that can provide a Reader view of their - * contents. - * - */ -public interface ReadSource { - /** - * Obtain a Reader. Not named 'getReader' so that it is not - * considered a simple costless read-only property by - * bean-convention introspection tools. - * @return a Reader on this object - */ - Reader obtainReader(); -} diff --git a/commons/src/main/java/org/archive/io/RecorderIOException.java b/commons/src/main/java/org/archive/io/RecorderIOException.java deleted file mode 100644 index 07b30061..00000000 --- a/commons/src/main/java/org/archive/io/RecorderIOException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; - -/** - * - * @author Gordon Mohr - */ -public class RecorderIOException extends IOException { - - private static final long serialVersionUID = 5907470275350314277L; - - public RecorderIOException() { - super(); - } - - public RecorderIOException(String msg) { - super(msg); - } -} diff --git a/commons/src/main/java/org/archive/io/RecorderLengthExceededException.java b/commons/src/main/java/org/archive/io/RecorderLengthExceededException.java deleted file mode 100644 index 8c3e067d..00000000 --- a/commons/src/main/java/org/archive/io/RecorderLengthExceededException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -/** - * Indicates a length exception thrown by the Recorder. - * - * @author Gordon Mohr - */ -public class RecorderLengthExceededException -extends RecorderIOException { - - private static final long serialVersionUID = 6655419033414648444L; - - public RecorderLengthExceededException() { - super(); - } - - public RecorderLengthExceededException(String msg) { - super(msg); - } -} diff --git a/commons/src/main/java/org/archive/io/RecorderTimeoutException.java b/commons/src/main/java/org/archive/io/RecorderTimeoutException.java deleted file mode 100644 index 32be5b5d..00000000 --- a/commons/src/main/java/org/archive/io/RecorderTimeoutException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -/** - * Indicates a timeout thrown by the RecordingInputStream. - * - * @author Gordon Mohr - */ -public class RecorderTimeoutException extends RecorderIOException { - - private static final long serialVersionUID = 7433214063765078269L; - - public RecorderTimeoutException() { - super(); - } - - public RecorderTimeoutException(String msg) { - super(msg); - } -} diff --git a/commons/src/main/java/org/archive/io/RecorderTooMuchHeaderException.java b/commons/src/main/java/org/archive/io/RecorderTooMuchHeaderException.java deleted file mode 100644 index 23f5d264..00000000 --- a/commons/src/main/java/org/archive/io/RecorderTooMuchHeaderException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -/** - * Indicates a too much header material exception thrown by the Recorder - * (specificially the RecordingOutputStream) - * - * @author Gordon Mohr - */ -public class RecorderTooMuchHeaderException -extends RecorderIOException { - - private static final long serialVersionUID = 3528516034898129150L; - - public RecorderTooMuchHeaderException() { - super(); - } - - public RecorderTooMuchHeaderException(String msg) { - super(msg); - } -} diff --git a/commons/src/main/java/org/archive/io/RecordingInputStream.java b/commons/src/main/java/org/archive/io/RecordingInputStream.java deleted file mode 100644 index c654eb61..00000000 --- a/commons/src/main/java/org/archive/io/RecordingInputStream.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; -import java.io.InputStream; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.security.MessageDigest; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.apache.commons.io.IOUtils; - - -/** - * Stream which records all data read from it, which it acquires from a wrapped - * input stream. - * - * Makes use of a RecordingOutputStream for recording because of its being - * file backed so we can write massive amounts of data w/o worrying about - * overflowing memory. - * - * @author gojomo - * - */ -public class RecordingInputStream - extends InputStream { - - protected static Logger logger = - Logger.getLogger("org.archive.io.RecordingInputStream"); - - /** - * Where we are recording to. - */ - private RecordingOutputStream recordingOutputStream; - - /** - * Stream to record. - */ - private InputStream in = null; - - /** - * Reusable buffer to avoid reallocation on each readFullyUntil - */ - protected byte[] drainBuffer = new byte[16*1024]; - - /** - * Create a new RecordingInputStream. - * - * @param bufferSize Size of buffer to use. - * @param backingFilename Name of backing file. - */ - public RecordingInputStream(int bufferSize, String backingFilename) - { - this.recordingOutputStream = new RecordingOutputStream(bufferSize, - backingFilename); - } - - public void open(InputStream wrappedStream) throws IOException { - if (logger.isLoggable(Level.FINE)) { - logger.fine("wrapping " + wrappedStream + " in thread " - + Thread.currentThread().getName()); - } - if(isOpen()) { - // error; should not be opening/wrapping in an unclosed - // stream remains open - throw new IOException("RIS already open for " - +Thread.currentThread().getName()); - } - try { - this.in = wrappedStream; - this.recordingOutputStream.open(); - } catch (IOException ioe) { - close(); // ...and rethrow... - throw ioe; - } - } - - public int read() throws IOException { - if (!isOpen()) { - throw new IOException("Stream closed " + - Thread.currentThread().getName()); - } - int b = this.in.read(); - if (b != -1) { - assert this.recordingOutputStream != null: "ROS is null " + - Thread.currentThread().getName(); - this.recordingOutputStream.write(b); - } - return b; - } - - public int read(byte[] b, int off, int len) throws IOException { - if (!isOpen()) { - throw new IOException("Stream closed " + - Thread.currentThread().getName()); - } - int count = this.in.read(b,off,len); - if (count > 0) { - assert this.recordingOutputStream != null: "ROS is null " + - Thread.currentThread().getName(); - this.recordingOutputStream.write(b,off,count); - } - return count; - } - - public int read(byte[] b) throws IOException { - if (!isOpen()) { - throw new IOException("Stream closed " + - Thread.currentThread().getName()); - } - int count = this.in.read(b); - if (count > 0) { - assert this.recordingOutputStream != null: "ROS is null " + - Thread.currentThread().getName(); - this.recordingOutputStream.write(b,0,count); - } - return count; - } - - public void close() throws IOException { - if (logger.isLoggable(Level.FINE)) { - logger.fine("closing " + this.in + " in thread " - + Thread.currentThread().getName()); - } - IOUtils.closeQuietly(this.in); - this.in = null; - IOUtils.closeQuietly(this.recordingOutputStream); - } - - public ReplayInputStream getReplayInputStream() throws IOException { - return this.recordingOutputStream.getReplayInputStream(); - } - - public ReplayInputStream getMessageBodyReplayInputStream() throws IOException { - return this.recordingOutputStream.getMessageBodyReplayInputStream(); - } - - public long readFully() throws IOException { - while(read(drainBuffer) != -1) { - // Empty out stream. - continue; - } - return this.recordingOutputStream.getSize(); - } - - public void readToEndOfContent(long contentLength) - throws IOException, InterruptedException { - // Check we're open before proceeding. - if (!isOpen()) { - // TODO: should this be a noisier exception-raising error? - return; - } - - long totalBytes = recordingOutputStream.position - recordingOutputStream.getMessageBodyBegin(); - long bytesRead = -1L; - long maxToRead = -1; - while (contentLength <= 0 || totalBytes < contentLength) { - try { - // read no more than soft max - maxToRead = (contentLength <= 0) - ? drainBuffer.length - : Math.min(drainBuffer.length, contentLength - totalBytes); - // nor more than hard max - maxToRead = Math.min(maxToRead, recordingOutputStream.getRemainingLength()); - // but always at least 1 (to trigger hard max exception) XXX wtf is this? - maxToRead = Math.max(maxToRead, 1); - - bytesRead = read(drainBuffer,0,(int)maxToRead); - if (bytesRead == -1) { - break; - } - totalBytes += bytesRead; - - if (Thread.interrupted()) { - throw new InterruptedException("Interrupted during IO"); - } - } catch (SocketTimeoutException e) { - // A socket timeout is just a transient problem, meaning - // nothing was available in the configured timeout period, - // but something else might become available later. - // Take this opportunity to check the overall - // timeout (below). One reason for this timeout is - // servers that keep up the connection, 'keep-alive', even - // though we asked them to not keep the connection open. - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "socket timeout", e); - } - // check for interrupt - if (Thread.interrupted()) { - throw new InterruptedException("Interrupted during IO"); - } - // check for overall timeout - recordingOutputStream.checkLimits(); - } catch (SocketException se) { - throw se; - } catch (NullPointerException e) { - // [ 896757 ] NPEs in Andy's Th-Fri Crawl. - // A crawl was showing NPE's in this part of the code but can - // not reproduce. Adding this rethrowing catch block w/ - // diagnostics to help should we come across the problem in the - // future. - throw new NullPointerException("Stream " + this.in + ", " + - e.getMessage() + " " + Thread.currentThread().getName()); - } - } - } - - /** - * Read all of a stream (Or read until we timeout or have read to the max). - * @param softMaxLength Maximum length to read; if zero or < 0, then no - * limit. If met, return normally. - * @throws IOException failed read. - * @throws RecorderLengthExceededException - * @throws RecorderTimeoutException - * @throws InterruptedException - * @deprecated - */ - public void readFullyOrUntil(long softMaxLength) - throws IOException, RecorderLengthExceededException, - RecorderTimeoutException, InterruptedException { - // Check we're open before proceeding. - if (!isOpen()) { - // TODO: should this be a noisier exception-raising error? - return; - } - - long totalBytes = 0L; - long bytesRead = -1L; - long maxToRead = -1; - while (true) { - try { - // read no more than soft max - maxToRead = (softMaxLength <= 0) - ? drainBuffer.length - : Math.min(drainBuffer.length, softMaxLength - totalBytes); - // nor more than hard max - maxToRead = Math.min(maxToRead, recordingOutputStream.getRemainingLength()); - // but always at least 1 (to trigger hard max exception - maxToRead = Math.max(maxToRead, 1); - - bytesRead = read(drainBuffer,0,(int)maxToRead); - if (bytesRead == -1) { - break; - } - totalBytes += bytesRead; - - if (Thread.interrupted()) { - throw new InterruptedException("Interrupted during IO"); - } - } catch (SocketTimeoutException e) { - // A socket timeout is just a transient problem, meaning - // nothing was available in the configured timeout period, - // but something else might become available later. - // Take this opportunity to check the overall - // timeout (below). One reason for this timeout is - // servers that keep up the connection, 'keep-alive', even - // though we asked them to not keep the connection open. - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "socket timeout", e); - } - // check for interrupt - if (Thread.interrupted()) { - throw new InterruptedException("Interrupted during IO"); - } - // check for overall timeout - recordingOutputStream.checkLimits(); - } catch (SocketException se) { - throw se; - } catch (NullPointerException e) { - // [ 896757 ] NPEs in Andy's Th-Fri Crawl. - // A crawl was showing NPE's in this part of the code but can - // not reproduce. Adding this rethrowing catch block w/ - // diagnostics to help should we come across the problem in the - // future. - throw new NullPointerException("Stream " + this.in + ", " + - e.getMessage() + " " + Thread.currentThread().getName()); - } - - // if have read 'enough', just finish - if (softMaxLength > 0 && totalBytes >= softMaxLength) { - break; // return - } - } - } - - public long getSize() { - return this.recordingOutputStream.getSize(); - } - - public void markContentBegin() { - this.recordingOutputStream.markMessageBodyBegin(); - } - - public long getContentBegin() { - return this.recordingOutputStream.getMessageBodyBegin(); - } - - public void startDigest() { - this.recordingOutputStream.startDigest(); - } - - /** - * Convenience method for setting SHA1 digest. - */ - public void setSha1Digest() { - this.recordingOutputStream.setSha1Digest(); - } - - /** - * Sets a digest algorithm which may be applied to recorded data. - * As usually only a subset of the recorded data should - * be fed to the digest, you must also call startDigest() - * to begin digesting. - * - * @param algorithm - */ - public void setDigest(String algorithm) { - this.recordingOutputStream.setDigest(algorithm); - } - - /** - * Sets a digest function which may be applied to recorded data. - * As usually only a subset of the recorded data should - * be fed to the digest, you must also call startDigest() - * to begin digesting. - * - * @param md - */ - public void setDigest(MessageDigest md) { - this.recordingOutputStream.setDigest(md); - } - - /** - * Return the digest value for any recorded, digested data. Call - * only after all data has been recorded; otherwise, the running - * digest state is ruined. - * - * @return the digest final value - */ - public byte[] getDigestValue() { - return this.recordingOutputStream.getDigestValue(); - } - - public long getResponseContentLength() { - return this.recordingOutputStream.getResponseContentLength(); - } - - public void closeRecorder() throws IOException { - this.recordingOutputStream.closeRecorder(); - } - - /** - * @return True if we've been opened. - */ - public boolean isOpen() - { - return this.in != null; - } - - @Override - public synchronized void mark(int readlimit) { - this.in.mark(readlimit); - this.recordingOutputStream.mark(); - } - - @Override - public boolean markSupported() { - return this.in.markSupported(); - } - - @Override - public synchronized void reset() throws IOException { - this.in.reset(); - this.recordingOutputStream.reset(); - } - - /** - * Set limits to be enforced by internal recording-out - */ - public void setLimits(long hardMax, long timeoutMs, long maxRateKBps) { - recordingOutputStream.setLimits(hardMax, timeoutMs, maxRateKBps); - } - - /** - * Expose the amount of in-memory buffering used by the internal - * recording stream. - * @return int buffer size - */ - public int getRecordedBufferLength() { - return recordingOutputStream.getBufferLength(); - } - - /** - * See doc on {@link RecordingOutputStream#chopAtMessageBodyBegin()} - */ - public void chopAtMessageBodyBegin() { - recordingOutputStream.chopAtMessageBodyBegin(); - } -} diff --git a/commons/src/main/java/org/archive/io/RecordingOutputStream.java b/commons/src/main/java/org/archive/io/RecordingOutputStream.java deleted file mode 100644 index dfec4f33..00000000 --- a/commons/src/main/java/org/archive/io/RecordingOutputStream.java +++ /dev/null @@ -1,628 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import it.unimi.dsi.fastutil.io.FastBufferedOutputStream; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * An output stream that records all writes to wrapped output - * stream. - * - * A RecordingOutputStream can be wrapped around any other - * OutputStream to record all bytes written to it. You can - * then request a ReplayInputStream to read those bytes. - * - *

The RecordingOutputStream uses an in-memory buffer and - * backing disk file to allow it to record streams of - * arbitrary length limited only by available disk space. - * - *

As long as the stream recorded is smaller than the - * in-memory buffer, no disk access will occur. - * - *

Recorded content can be recovered as a ReplayInputStream - * (via getReplayInputStream() or, for only the content after - * the content-begin-mark is set, getContentReplayInputStream() ) - * or as a ReplayCharSequence (via getReplayCharSequence()). - * - *

This class is also used as a straight output stream - * by {@link RecordingInputStream} to which it records all reads. - * {@link RecordingInputStream} is exploiting the file backed buffer - * facility of this class passing null for the stream - * to wrap. TODO: Make a FileBackedOutputStream class that is - * subclassed by RecordingInputStream. - * - * @author gojomo - * - */ -public class RecordingOutputStream extends OutputStream { - protected static Logger logger = - Logger.getLogger(RecordingOutputStream.class.getName()); - - /** - * Size of recording. - * - * Later passed to ReplayInputStream on creation. It uses it to know when - * EOS. - */ - protected long size = 0; - - protected String backingFilename; - protected OutputStream diskStream = null; - - /** - * Buffer we write recordings to. - * - * We write all recordings here first till its full. Thereafter we - * write the backing file. - */ - private byte[] buffer; - - /** current virtual position in the recording */ - long position; - - /** flag to disable recording */ - private boolean recording; - - /** - * Reusable buffer for FastBufferedOutputStream - */ - protected byte[] bufStreamBuf = - new byte [ FastBufferedOutputStream.DEFAULT_BUFFER_SIZE ]; - - /** - * True if we're to digest content. - */ - private boolean shouldDigest = false; - - /** - * Digest instance. - */ - private MessageDigest digest = null; - - /** - * Define for SHA1 algarithm. - */ - private static final String SHA1 = "SHA1"; - - /** - * Maximum amount of header material to accept without the content - * body beginning -- if more, throw a RecorderTooMuchHeaderException. - * TODO: make configurable? make smaller? - */ - protected static final long MAX_HEADER_MATERIAL = 1024*1024; // 1MB - - // configurable max length, max time limits - /** maximum length of material to record before throwing exception */ - protected long maxLength = Long.MAX_VALUE; - /** maximum time to record before throwing exception */ - protected long timeoutMs = Long.MAX_VALUE; - /** maximum rate to record (adds delays to hit target rate) */ - protected long maxRateBytesPerMs = Long.MAX_VALUE; - /** time recording begins for timeout, rate calculations */ - protected long startTime = Long.MAX_VALUE; - - /** - * When recording HTTP, where the content-body starts. - */ - protected long messageBodyBeginMark; - - /** - * While messageBodyBeginMark is not set, the last two bytes seen. - * - *

- * This class does automatic detection of http message body begin (i.e. end - * of http headers). Unfortunately httpcomponents did not want to add - * functionality to help us with this, see - * https://issues.apache.org/jira/browse/HTTPCORE-325 - * - *

- * It works like this: while messageBodyBeginMark is not set, we remember - * the last two bytes seen, and look at each byte we write. If the - * lastTwoBytes+currentByte is "\n\r\n", or lastTwoBytes[1]+currentByte is - * "\n\n" then we call markMessageBodyBegin() at the position after - * currentByte. - * - *

- * An assumption here is that protocols other than http don't have headers, - * and for those protocols the user of this class will call - * markMessageBodyBegin() at position 0 before writing anything. - */ - protected int[] lastTwoBytes = new int[] {-1, -1}; - - /** - * Stream to record. - */ - private OutputStream out = null; - - // mark/reset support - /** furthest position reached before any reset()s */ - private long maxPosition = 0; - /** remembered position to reset() to */ - private long markPosition = 0; - - /** - * Create a new RecordingOutputStream. - * - * @param bufferSize Buffer size to use. - * @param backingFilename Name of backing file to use. - */ - public RecordingOutputStream(int bufferSize, String backingFilename) { - this.buffer = new byte[bufferSize]; - this.backingFilename = backingFilename; - recording = true; - } - - /** - * Wrap the given stream, both recording and passing along any data written - * to this RecordingOutputStream. - * - * @throws IOException If failed creation of backing file. - */ - public void open() throws IOException { - this.open(null); - } - - /** - * Wrap the given stream, both recording and passing along any data written - * to this RecordingOutputStream. - * - * @param wrappedStream Stream to wrap. May be null for case where we - * want to write to a file backed stream only. - * - * @throws IOException If failed creation of backing file. - */ - public void open(OutputStream wrappedStream) throws IOException { - if(isOpen()) { - // error; should not be opening/wrapping in an unclosed - // stream remains open - throw new IOException("ROS already open for " - +Thread.currentThread().getName()); - } - this.out = wrappedStream; - this.position = 0; - this.markPosition = 0; - this.maxPosition = 0; - this.size = 0; - this.messageBodyBeginMark = -1; - // ensure recording turned on - this.recording = true; - // Always begins false; must use startDigest() to begin - this.shouldDigest = false; - if (this.diskStream != null) { - closeDiskStream(); - } - if (this.diskStream == null) { - // TODO: Fix so we only make file when its actually needed. - FileOutputStream fis = new FileOutputStream(this.backingFilename); - - this.diskStream = new RecyclingFastBufferedOutputStream(fis, bufStreamBuf); - } - startTime = System.currentTimeMillis(); - } - - public void write(int b) throws IOException { - if(position 0) { - write(b[off]); - off++; - len--; - } - - if(recording) { - record(b, off, len); - } - if (this.out != null) { - this.out.write(b, off, len); - } - checkLimits(); - } - - /** - * Check any enforced limits. - */ - protected void checkLimits() throws RecorderIOException { - // too much material before finding end of headers? - if (messageBodyBeginMark<0) { - // no mark yet - if(position>MAX_HEADER_MATERIAL) { - throw new RecorderTooMuchHeaderException(); - } - } - // overlong? - if(position>maxLength) { - throw new RecorderLengthExceededException(); - } - // taking too long? - long duration = System.currentTimeMillis() - startTime; - duration = Math.max(duration,1); // !divzero - if(duration>timeoutMs) { - throw new RecorderTimeoutException(); - } - // need to throttle reading to hit max configured rate? - if(position/duration >= maxRateBytesPerMs) { - long desiredDuration = position / maxRateBytesPerMs; - try { - Thread.sleep(desiredDuration-duration); - } catch (InterruptedException e) { - logger.log(Level.WARNING, - "bandwidth throttling sleep interrupted", e); - } - } - } - - /** - * Record the given byte for later recovery - * - * @param b Int to record. - * - * @exception IOException Failed write to backing file. - */ - private void record(int b) throws IOException { - if (this.shouldDigest) { - this.digest.update((byte)b); - } - if (this.position >= this.buffer.length) { - // TODO: Its possible to call write w/o having first opened a - // stream. Protect ourselves against this. - assert this.diskStream != null: "Diskstream is null"; - this.diskStream.write(b); - } else { - this.buffer[(int) this.position] = (byte) b; - } - this.position++; - } - - /** - * Record the given byte-array range for recovery later - * - * @param b Buffer to record. - * @param off Offset into buffer at which to start recording. - * @param len Length of buffer to record. - * - * @exception IOException Failed write to backing file. - */ - private void record(byte[] b, int off, int len) throws IOException { - if(this.shouldDigest) { - assert this.digest != null: "Digest is null."; - this.digest.update(b, off, len); - } - tailRecord(b, off, len); - } - - /** - * Record without digesting. - * - * @param b Buffer to record. - * @param off Offset into buffer at which to start recording. - * @param len Length of buffer to record. - * - * @exception IOException Failed write to backing file. - */ - private void tailRecord(byte[] b, int off, int len) throws IOException { - if(this.position >= this.buffer.length){ - // TODO: Its possible to call write w/o having first opened a - // stream. Lets protect ourselves against this. - if (this.diskStream == null) { - throw new IOException("diskstream is null"); - } - this.diskStream.write(b, off, len); - this.position += len; - } else { - assert this.buffer != null: "Buffer is null"; - int toCopy = (int)Math.min(this.buffer.length - this.position, len); - assert b != null: "Passed buffer is null"; - System.arraycopy(b, off, this.buffer, (int)this.position, toCopy); - this.position += toCopy; - // TODO verify these are +1 -1 right - if (toCopy < len) { - tailRecord(b, off + toCopy, len - toCopy); - } - } - } - - public void close() throws IOException { - if(messageBodyBeginMark<0) { - // if unset, consider 0 posn as content-start - // (so that a -1 never survives to replay step) - messageBodyBeginMark = 0; - } - if (this.out != null) { - this.out.close(); - this.out = null; - } - closeRecorder(); - } - - protected synchronized void closeDiskStream() - throws IOException { - if (this.diskStream != null) { - this.diskStream.close(); - this.diskStream = null; - } - } - - public void closeRecorder() throws IOException { - recording = false; - closeDiskStream(); // if any - // This setting of size is important. Its passed to ReplayInputStream - // on creation. It uses it to know EOS. - if (this.size == 0) { - this.size = this.position; - } - } - - /* (non-Javadoc) - * @see java.io.OutputStream#flush() - */ - public void flush() throws IOException { - if (this.out != null) { - this.out.flush(); - } - if (this.diskStream != null) { - this.diskStream.flush(); - } - } - - public ReplayInputStream getReplayInputStream() throws IOException { - return getReplayInputStream(0); - } - - public ReplayInputStream getReplayInputStream(long skip) throws IOException { - // If this method is being called, then assumption must be that the - // stream is closed. If it ain't, then the stream gotten won't work - // -- the size will zero so any attempt at a read will get back EOF. - assert this.out == null: "Stream is still open."; - ReplayInputStream replay = new ReplayInputStream(this.buffer, - this.size, this.messageBodyBeginMark, this.backingFilename); - replay.skip(skip); - return replay; - } - - /** - * Return a replay stream, cued up to begining of content - * - * @throws IOException - * @return An RIS. - */ - public ReplayInputStream getMessageBodyReplayInputStream() throws IOException { - return getReplayInputStream(this.messageBodyBeginMark); - } - - public long getSize() { - return this.size; - } - - /** - * Remember the current position as the start of the "message - * body". Useful when recording HTTP traffic as a way to start - * replays after the headers. - */ - public void markMessageBodyBegin() { - this.messageBodyBeginMark = this.position; - startDigest(); - } - - /** - * Return stored message-body-begin-mark (which is also end-of-headers) - */ - public long getMessageBodyBegin() { - return this.messageBodyBeginMark; - } - - /** - * Starts digesting recorded data, if a MessageDigest has been - * set. - */ - public void startDigest() { - if (this.digest != null) { - this.digest.reset(); - this.shouldDigest = true; - } - } - - /** - * Convenience method for setting SHA1 digest. - * @see #setDigest(String) - */ - public void setSha1Digest() { - setDigest(SHA1); - } - - - /** - * Sets a digest function which may be applied to recorded data. - * The difference between calling this method and {@link #setDigest(MessageDigest)} - * is that this method tries to reuse MethodDigest instance if already allocated - * and of appropriate algorithm. - * @param algorithm Message digest algorithm to use. - * @see #setDigest(MessageDigest) - */ - public void setDigest(String algorithm) { - try { - // Reuse extant digest if its sha1 algorithm. - if (this.digest == null || - !this.digest.getAlgorithm().equals(algorithm)) { - setDigest(MessageDigest.getInstance(algorithm)); - } - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - } - - /** - * Sets a digest function which may be applied to recorded data. - * - * As usually only a subset of the recorded data should - * be fed to the digest, you must also call startDigest() - * to begin digesting. - * - * @param md Message digest function to use. - */ - public void setDigest(MessageDigest md) { - this.digest = md; - } - - /** - * Return the digest value for any recorded, digested data. Call - * only after all data has been recorded; otherwise, the running - * digest state is ruined. - * - * @return the digest final value - */ - public byte[] getDigestValue() { - if(this.digest == null) { - return null; - } - return this.digest.digest(); - } - - public long getResponseContentLength() { - return this.size - this.messageBodyBeginMark; - } - - /** - * @return True if this ROS is open. - */ - public boolean isOpen() { - return this.out != null; - } - - public int getBufferLength() { - return this.buffer.length; - } - - /** - * When used alongside a mark-supporting RecordingInputStream, remember - * a position reachable by a future reset(). - */ - public void mark() { - // remember this position for subsequent reset() - this.markPosition = position; - } - - /** - * When used alongside a mark-supporting RecordingInputStream, reset - * the position to that saved by previous mark(). Until the position - * again reached "new" material, none of the bytes pushed to this - * stream will be digested or recorded. - */ - public void reset() { - // take note of furthest-position-reached to avoid double-recording - maxPosition = Math.max(maxPosition, position); - // reset to previous position - position = markPosition; - } - - /** - * Set limits on length, time, and rate to enforce. - * - * @param length - * @param milliseconds - * @param rateKBps - */ - public void setLimits(long length, long milliseconds, long rateKBps) { - maxLength = (length>0) ? length : Long.MAX_VALUE; - timeoutMs = (milliseconds>0) ? milliseconds : Long.MAX_VALUE; - maxRateBytesPerMs = (rateKBps>0) ? rateKBps*1024/1000 : Long.MAX_VALUE; - } - - /** - * Reset limits to effectively-unlimited defaults - */ - public void resetLimits() { - maxLength = Long.MAX_VALUE; - timeoutMs = Long.MAX_VALUE; - maxRateBytesPerMs = Long.MAX_VALUE; - } - - /** - * Return number of bytes that could be recorded without hitting - * length limit - * - * @return long byte count - */ - public long getRemainingLength() { - return maxLength - position; - } - - /** - * Forget about anything past the point where the content-body starts. This - * is needed to support FetchHTTP's shouldFetchBody setting. See also the - * docs on {@link #lastTwoBytes} - */ - public void chopAtMessageBodyBegin() { - if (messageBodyBeginMark >= 0) { - this.size = messageBodyBeginMark; - this.position = messageBodyBeginMark; - } - } -} - diff --git a/commons/src/main/java/org/archive/io/RecoverableIOException.java b/commons/src/main/java/org/archive/io/RecoverableIOException.java deleted file mode 100644 index 5ce2251a..00000000 --- a/commons/src/main/java/org/archive/io/RecoverableIOException.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; - -/** - * A decorator on IOException for IOEs that are likely not fatal or at least - * merit retry. - * @author stack - * @version $Date$, $Revision$ - */ -public class RecoverableIOException extends IOException { - private static final long serialVersionUID = 6194776587381865451L; - private final IOException decoratedIOException; - - public RecoverableIOException(final String message) { - this(new IOException(message)); - } - - public RecoverableIOException(final IOException ioe) { - super(); - this.decoratedIOException = ioe; - } - - public Throwable getCause() { - return this.decoratedIOException.getCause(); - } - - public String getLocalizedMessage() { - return this.decoratedIOException.getLocalizedMessage(); - } - - public String getMessage() { - return this.decoratedIOException.getMessage(); - } - - public StackTraceElement[] getStackTrace() { - return this.decoratedIOException.getStackTrace(); - } - - public synchronized Throwable initCause(Throwable cause) { - return this.decoratedIOException.initCause(cause); - } - - public void printStackTrace() { - this.decoratedIOException.printStackTrace(); - } - - public void printStackTrace(PrintStream s) { - this.decoratedIOException.printStackTrace(s); - } - - public void printStackTrace(PrintWriter s) { - this.decoratedIOException.printStackTrace(s); - } - - public void setStackTrace(StackTraceElement[] stackTrace) { - this.decoratedIOException.setStackTrace(stackTrace); - } - - public String toString() { - return this.decoratedIOException.toString(); - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/RecyclingFastBufferedOutputStream.java b/commons/src/main/java/org/archive/io/RecyclingFastBufferedOutputStream.java deleted file mode 100644 index a3b76e46..00000000 --- a/commons/src/main/java/org/archive/io/RecyclingFastBufferedOutputStream.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import it.unimi.dsi.fastutil.io.FastBufferedOutputStream; - -import java.io.OutputStream; - -/** - * FastBufferedOutputStream that accepts a passed-in buffer (avoiding - * reallocation). - */ -public class RecyclingFastBufferedOutputStream extends FastBufferedOutputStream { - public RecyclingFastBufferedOutputStream( final OutputStream os, final byte[] buffer ) { - super(os); - this.buffer = buffer; - avail = buffer.length; - } -} - - diff --git a/commons/src/main/java/org/archive/io/ReplayCharSequence.java b/commons/src/main/java/org/archive/io/ReplayCharSequence.java deleted file mode 100644 index aa9b9587..00000000 --- a/commons/src/main/java/org/archive/io/ReplayCharSequence.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.Closeable; -import java.io.IOException; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; - -import com.google.common.base.Charsets; - - -/** - * CharSequence interface with addition of a {@link #close()} method. - * - * Users of implementations of this interface must call {@link #close()} so - * implementations get a chance at cleaning up after themselves. - * - * @author stack - * @version $Revision$, $Date$ - */ -public interface ReplayCharSequence extends CharSequence, Closeable { - - /** charset to use in replay when declared value - * is absent/illegal/unavailable */ - public Charset FALLBACK_CHARSET = Charsets.ISO_8859_1; // TODO: should this be UTF-8? - - /** - * Call this method when done so implementation has chance to clean up - * resources. - * - * @throws IOException Problem cleaning up file system resources. - */ - public void close() throws IOException; - - /** - * Report count of decoder errors silently eaten during ReplayCharSequence - * use. May be less than the number of individual decoding anomalies in - * underlying content (if decoding method doesn't allow counting individual - * errors). - */ - public long getDecodeExceptionCount(); - - /** - * Return the first coding-exception encountered, if the count > 0. - * @return CharacterCodingException - */ - public CharacterCodingException getCodingException(); - - /** - * @return false if {@link #close()} has been called - */ - public boolean isOpen(); - - /** - * Return the effective Charset used to create this CharSequence from - * (raw byte) source material. - */ - public Charset getCharset(); -} diff --git a/commons/src/main/java/org/archive/io/ReplayInputStream.java b/commons/src/main/java/org/archive/io/ReplayInputStream.java deleted file mode 100644 index 35ea8175..00000000 --- a/commons/src/main/java/org/archive/io/ReplayInputStream.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.commons.io.IOUtils; -import org.archive.util.ArchiveUtils; -import org.archive.util.FileUtils; - - -/** - * Replays the bytes recorded from a RecordingInputStream or - * RecordingOutputStream. - * - * This InputStream supports mark and reset. - * - * @author gojomo - */ -public class ReplayInputStream extends SeekInputStream -{ - private static final int DEFAULT_BUFFER_SIZE = 256*1024; // 256KiB - private BufferedSeekInputStream diskStream; - private byte[] buffer; - private long position; - - /** - * Total size of stream content. - * - * Size of data to replay. - */ - private long size = -1; - - /** - * Where the response body starts, if marked - */ - protected long responseBodyStart = -1; - - - /** - * Constructor. - * - * @param buffer Buffer to read from. - * @param size Size of data to replay. - * @param responseBodyStart Start of the response body. - * @param backingFilename Backing file that sits behind the buffer. If - * size > than buffer then we go to backing file to read - * data that is beyond buffer.length. - * - * @throws IOException If we fail to open an input stream on - * backing file. - */ - public ReplayInputStream(byte[] buffer, long size, long responseBodyStart, - String backingFilename) - throws IOException - { - this(buffer, size, backingFilename); - this.responseBodyStart = responseBodyStart; - } - - /** - * Constructor. - * - * @param buffer Buffer to read from. - * @param size Size of data to replay. - * @param backingFilename Backing file that sits behind the buffer. If - * size > than buffer then we go to backing file to read - * data that is beyond buffer.length. - * @throws IOException If we fail to open an input stream on - * backing file. - */ - public ReplayInputStream(byte[] buffer, long size, String backingFilename) - throws IOException - { - this.buffer = buffer; - this.size = size; - if (size > buffer.length) { - setupDiskStream(new File(backingFilename)); - } - } - - protected void setupDiskStream(File backingFile) throws IOException { - RandomAccessInputStream rais = new RandomAccessInputStream(backingFile); - diskStream = new BufferedSeekInputStream(rais, 4096); - } - - protected File backingFile; - - /** - * Create a ReplayInputStream from the given source stream. Requires - * reading the entire stream (and possibly overflowing to a temporary - * file). Primary reason for doing so would be to have a repositionable - * version of the original stream's contents. - * - * If created via this constructor, use the destroy() method to ensure - * prompt deletion of any associated tmp file when done. - * - * @param fillStream - * @throws IOException - */ - public ReplayInputStream(InputStream fillStream) throws IOException { - this.buffer = new byte[DEFAULT_BUFFER_SIZE]; - long count = ArchiveUtils.readFully(fillStream, buffer); - if(fillStream.available()>0) { - this.backingFile = File.createTempFile("tid"+Thread.currentThread().getId(), "ris"); - count += FileUtils.readFullyToFile(fillStream, backingFile); - setupDiskStream(backingFile); - } - this.size = count; - } - - /** - * Close & destroy any internally-generated temporary files. - */ - public void destroy() { - IOUtils.closeQuietly(this); - if(backingFile!=null) { - FileUtils.deleteSoonerOrLater(backingFile); - } - } - - public long setToResponseBodyStart() throws IOException { - position(responseBodyStart); - return this.position; - } - - - /* (non-Javadoc) - * @see java.io.InputStream#read() - */ - public int read() throws IOException { - if (position == size) { - return -1; // EOF - } - if (position < buffer.length) { - // Convert to unsigned int. - int c = buffer[(int) position] & 0xFF; - position++; - return c; - } - int c = diskStream.read(); - if (c >= 0) { - position++; - } - return c; - } - - /* - * (non-Javadoc) - * - * @see java.io.InputStream#read(byte[], int, int) - */ - public int read(byte[] b, int off, int len) throws IOException { - if (position == size) { - return -1; // EOF - } - if (position < buffer.length) { - int toCopy = (int)Math.min(size - position, - Math.min(len, buffer.length - position)); - System.arraycopy(buffer, (int)position, b, off, toCopy); - if (toCopy > 0) { - position += toCopy; - } - return toCopy; - } - // into disk zone - int read = diskStream.read(b,off,len); - if(read>0) { - position += read; - } - return read; - } - - public void readFullyTo(OutputStream os) throws IOException { - readFullyTo(this, os); - } - - public static void readFullyTo(InputStream in, OutputStream os) throws IOException { - byte[] buf = new byte[4096]; - int c = in.read(buf); - while (c != -1) { - os.write(buf,0,c); - c = in.read(buf); - } - } - - /* - * Like 'readFullyTo', but only reads the header-part. - * Starts from the beginning each time it is called. - */ - public void readHeaderTo(OutputStream os) throws IOException { - position = 0; - byte[] buf = new byte[(int)responseBodyStart]; - int c = read(buf,0,buf.length); - if(c != -1) { - os.write(buf,0,c); - } - } - - /* - * Like 'readFullyTo', but only reads the content-part. - */ - public void readContentTo(OutputStream os) throws IOException { - setToResponseBodyStart(); - readFullyTo(os); - } - - /** - * Convenience method to copy content out to target stream. - * @param os stream to write content to - * @param maxSize maximum count of bytes to copy - * @throws IOException - */ - public void readContentTo(OutputStream os, long maxSize) throws IOException { - setToResponseBodyStart(); - byte[] buf = new byte[4096]; - int c = read(buf); - long tot = 0; - while (c != -1 && tot < maxSize) { - os.write(buf,0,c); - c = read(buf); - tot += c; - } - } - - /* (non-Javadoc) - * @see java.io.InputStream#close() - */ - public void close() throws IOException { - super.close(); - if(diskStream != null) { - diskStream.close(); - } - } - - /** - * Total size of stream content. - * @return Returns the size. - */ - public long getSize() - { - return size; - } - - /** - * Total size of header. - * @return the size of the header. - */ - public long getHeaderSize() - { - return responseBodyStart; - } - - /** - * Total size of content. - * @return the size of the content. - */ - public long getContentSize() - { - return size - responseBodyStart; - } - - /** - * @return Amount THEORETICALLY remaining (TODO: Its not theoretical - * seemingly. The class implemetentation depends on it being exact). - */ - public long remaining() { - return size - position; - } - - - /** - * Reposition the stream. - * - * @param p the new position for this stream - * @throws IOException if an IO error occurs - */ - public void position(long p) throws IOException { - if (p < 0) { - throw new IOException("Negative seek offset."); - } - if (p > size) { - throw new IOException("Desired position exceeds size."); - } - if (p < buffer.length) { - // Only seek file if necessary - if (position > buffer.length) { - diskStream.position(0); - } - } else { - diskStream.position(p - buffer.length); - } - this.position = p; - } - - - public long position() throws IOException { - return position; - } - - protected byte[] getBuffer() { - return buffer; - } -} diff --git a/commons/src/main/java/org/archive/io/RepositionableInputStream.java b/commons/src/main/java/org/archive/io/RepositionableInputStream.java deleted file mode 100644 index 6f885130..00000000 --- a/commons/src/main/java/org/archive/io/RepositionableInputStream.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import it.unimi.dsi.fastutil.io.RepositionableStream; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * Wrapper around an {@link InputStream} to make a primitive Repositionable - * stream. Uses a {@link BufferedInputStream}. Calls mark on every read so - * we'll remember at least the last thing read (You can only backup on the - * last thing read -- not last 2 or 3 things read). Used by - * {@link GzippedInputStream} when reading streams over a network. Wraps a - * HTTP, etc., stream so we can back it up if needs be after the - * GZIP inflater has done a fill of its full buffer though it only needed - * the first few bytes to finish decompressing the current GZIP member. - * - *

TODO: More robust implementation. Tried to use the it.unimi.dsi.io - * FastBufferdInputStream but relies on FileChannel ByteBuffers and if not - * present -- as would be the case reading from a network stream, the main - * application for this instance -- then it expects the underlying stream - * implements RepositionableStream interface so chicken or egg problem. - * @author stack - */ -public class RepositionableInputStream extends BufferedInputStream implements - RepositionableStream { - private long position = 0; - private long markPosition = -1; - - public RepositionableInputStream(InputStream in) { - super(in); - } - - public RepositionableInputStream(InputStream in, int size) { - super(in, size); - } - - public int read(byte[] b) throws IOException { - int read = super.read(b); - if (read != -1) { - position += read; - } - return read; - } - - public synchronized int read(byte[] b, int offset, int ct) - throws IOException { - // Mark the underlying stream so that we'll remember what we are about - // to read unless a mark has been set in this RepositionableStream - // (We have two levels of mark). In this latter case we want the - // underlying stream to preserve its mark position so aligns with - // this RS when eset is called. - if (!isMarked()) { - super.mark((ct > offset)? ct - offset: ct); - } - int read = super.read(b, offset, ct); - if (read != -1) { - position += read; - } - return read; - } - - public int read() throws IOException { - // Mark the underlying stream so that we'll remember what we are about - // to read unless a mark has been set in this RepositionableStream - // (We have two levels of mark). In this latter case we want the - // underlying stream to preserve its mark position so aligns with - // this RS when eset is called. - if (!isMarked()) { - super.mark(1); - } - int c = super.read(); - if (c != -1) { - position++; - } - return c; - } - - public void position(final long offset) { - if (this.position == offset) { - return; - } - int diff = (int)(offset - this.position); - long lowerBound = this.position - this.pos; - long upperBound = lowerBound + this.count; - if (offset < lowerBound || offset >= upperBound) { - throw new IllegalAccessError("Offset goes outside " + - "current this.buf (TODO: Do buffer fills if positive)"); - } - this.position = offset; - this.pos += diff; - // Clear any mark. - this.markPosition = -1; - } - - public void mark(int readlimit) { - this.markPosition = this.position; - super.mark(readlimit); - } - - public void reset() throws IOException { - super.reset(); - this.position = this.markPosition; - this.markPosition = -1; - } - - protected boolean isMarked() { - return this.markPosition != -1; - } - - public long position() { - return this.position; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/SafeSeekInputStream.java b/commons/src/main/java/org/archive/io/SafeSeekInputStream.java deleted file mode 100644 index 0d8f83b1..00000000 --- a/commons/src/main/java/org/archive/io/SafeSeekInputStream.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import java.io.IOException; - - -/** - * Enables multiple concurrent streams based on the same underlying stream. - * - * @author pjack - */ -public class SafeSeekInputStream extends SeekInputStream { - - - /** - * The underlying stream. - */ - private SeekInputStream input; - - - /** - * The expected position of the underlying stream. - */ - private long expected; - - - /** - * Constructor. The given stream will be positioned to 0 so that an - * accurate position can be tracked. - * - * @param input the underlying input stream - * @throws IOException if an IO error occurs - */ - public SafeSeekInputStream(SeekInputStream input) throws IOException { - this.input = input; - this.expected = input.position(); - } - - - /** - * Ensures that the underlying stream's position is what we expect to be. - * - * @throws IOException if an IO error occurs - */ - private void ensure() throws IOException { - if (expected != input.position()) { - input.position(expected); - } - } - - - @Override - public int read() throws IOException { - ensure(); - int c = input.read(); - if (c >= 0) { - expected++; - } - return c; - } - - - @Override - public int read(byte[] buf, int ofs, int len) throws IOException { - ensure(); - int r = input.read(buf, ofs, len); - if (r > 0) { - expected += r; - } - return r; - } - - - @Override - public int read(byte[] buf) throws IOException { - ensure(); - int r = input.read(buf); - if (r > 0) { - expected += r; - } - return r; - } - - - @Override - public long skip(long c) throws IOException { - ensure(); - long r = input.skip(c); - if (r > 0) { - expected += r; - } - return r; - } - - - public void position(long p) throws IOException { - input.position(p); - expected = p; - } - - - public long position() throws IOException { - return expected; - } - -} diff --git a/commons/src/main/java/org/archive/io/SeekInputStream.java b/commons/src/main/java/org/archive/io/SeekInputStream.java deleted file mode 100644 index 177724ec..00000000 --- a/commons/src/main/java/org/archive/io/SeekInputStream.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import it.unimi.dsi.fastutil.io.RepositionableStream; - -import java.io.IOException; -import java.io.InputStream; - - -/** - * Base class for repositionable input streams. - * - * @author pjack - */ -public abstract class SeekInputStream extends InputStream -implements RepositionableStream { - - - /** - * The marked file position. A value less than zero - * indicates that no mark has been set. - */ - private long mark = -1; - - - /** - * Marks the current position of the stream. The limit parameter is - * ignored; the mark will remain valid until reset is called or the - * stream is closed. - * - * @param limit ignored - */ - public void mark(int limit) { - try { - this.mark = position(); - } catch (IOException e) { - mark = -1; - } - } - - - /** - * Resets this stream to its marked position. - * - * @throws IOException if there is no mark, or if an IO error occurs - */ - public void reset() throws IOException { - if (mark < 0) { - throw new IOException("No mark."); - } - position(mark); - } - - - /** - * Returns true, since SeekInputStreams support mark/reset by default. - * - * @return true - */ - public boolean markSupported() { - return true; - } -} diff --git a/commons/src/main/java/org/archive/io/SeekReader.java b/commons/src/main/java/org/archive/io/SeekReader.java deleted file mode 100644 index 4abf7847..00000000 --- a/commons/src/main/java/org/archive/io/SeekReader.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -import java.io.IOException; -import java.io.Reader; - -import it.unimi.dsi.fastutil.io.RepositionableStream; - - -/** - * Base class for repositionable readers. - * - * @author pjack - */ -public abstract class SeekReader extends Reader -implements RepositionableStream { - - - /** - * The marked file position. A value less than zero - * indicates that no mark has been set. - */ - private long mark = -1; - - - /** - * Marks the current position of the stream. The limit parameter is - * ignored; the mark will remain valid until reset is called or the - * stream is closed. - * - * @param limit ignored - */ - @Override - public void mark(int limit) { - try { - this.mark = position(); - } catch (IOException e) { - mark = -1; - } - } - - - /** - * Resets this stream to its marked position. - * - * @throws IOException if there is no mark, or if an IO error occurs - */ - @Override - public void reset() throws IOException { - if (mark < 0) { - throw new IOException("No mark."); - } - position(mark); - } - - - /** - * Returns true, since SeekInputStreams support mark/reset by default. - * - * @return true - */ - @Override - public boolean markSupported() { - return true; - } -} diff --git a/commons/src/main/java/org/archive/io/SeekReaderCharSequence.java b/commons/src/main/java/org/archive/io/SeekReaderCharSequence.java deleted file mode 100644 index a9b4880f..00000000 --- a/commons/src/main/java/org/archive/io/SeekReaderCharSequence.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.archive.io; - -import java.io.IOException; - -public class SeekReaderCharSequence implements CharSequence { - - - final private SeekReader reader; - final private int size; - - - public SeekReaderCharSequence(SeekReader reader, int size) { - this.reader = reader; - this.size = size; - } - - - public int length() { - return size; - } - - - public char charAt(int index) { - if ((index < 0) || (index >= length())) { - throw new IndexOutOfBoundsException(Integer.toString(index)); - } - try { - reader.position(index); - int r = reader.read(); - if (r < 0) { - throw new IllegalStateException("EOF"); - } - return (char)reader.read(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - - public CharSequence subSequence(int start, int end) { - return new CharSubSequence(this, start, end); - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - try { - reader.position(0); - for (int ch = reader.read(); ch >= 0; ch = reader.read()) { - sb.append((char)ch); - } - return sb.toString(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } -} diff --git a/commons/src/main/java/org/archive/io/SinkHandlerLogThread.java b/commons/src/main/java/org/archive/io/SinkHandlerLogThread.java deleted file mode 100644 index 0070785e..00000000 --- a/commons/src/main/java/org/archive/io/SinkHandlerLogThread.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - - -/** - * Implemented by threads that provide extra information. - * - * TODO: rename class, rename getCurrentProcessorName() - */ -public interface SinkHandlerLogThread { - - String getName(); - String getCurrentProcessorName(); - int getSerialNumber(); - -} diff --git a/commons/src/main/java/org/archive/io/UTF8Bytes.java b/commons/src/main/java/org/archive/io/UTF8Bytes.java deleted file mode 100644 index c280b08d..00000000 --- a/commons/src/main/java/org/archive/io/UTF8Bytes.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.UnsupportedEncodingException; - -/** - * Marker Interface for instances that can be serialized as UTF8 bytes. - * TODO: Do we need a UTF8Stream Marker Interface? - * @author stack - * @version $Date$ $Version$ - */ -public interface UTF8Bytes { - public static final String UTF8 = "UTF-8"; - - /** - * @return Instance as UTF-8 bytes. - * @throws UnsupportedEncodingException - */ - public byte [] getUTF8Bytes() throws UnsupportedEncodingException; -} diff --git a/commons/src/main/java/org/archive/io/WriterPool.java b/commons/src/main/java/org/archive/io/WriterPool.java deleted file mode 100644 index 11931516..00000000 --- a/commons/src/main/java/org/archive/io/WriterPool.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.IOException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Pool of Writers. - * - * Abstract. Override and pass in the Constructor a factory that creates - * {@link WriterPoolMember} implementations. - * - * @author stack - */ -public abstract class WriterPool { - private final Logger logger = Logger.getLogger(this.getClass().getName()); - - /** - * Used to generate unique filename sequences. - */ - final protected AtomicInteger serialNo; - - /** - * Default maximum active number of files in the pool. - */ - public static final int DEFAULT_MAX_ACTIVE = 1; - - /** Assumed largest possible value of maxActive; pool will have this - * maximum capacity, so dynamic changes beyond this number won't work. */ - protected static final int LARGEST_MAX_ACTIVE = 255; - - /** - * Maximum time to wait on a free file before considering - * making a new one (if not already at max) - */ - public static final int DEFAULT_MAX_WAIT_FOR_IDLE = 500; - - /** - * File settings. - * Keep in data structure rather than as individual values. - */ - protected final WriterPoolSettings settings; - - /** maximum number of writers to create at a time*/ - protected int maxActive; - /** maximum ms to wait before considering creation of a writer */ - protected int maxWait; - /** current count of active writers; only read/mutated in synchronized blocks */ - protected int currentActive = 0; - /** round-robin queue of available writers */ - protected BlockingQueue availableWriters; - - /** system time when writer was last wanted (because one was not ready in time) */ - protected long lastWriterNeededTime; - /** system time when writer was last 'rolled over' (imminent creation of new file) */ - protected long lastWriterRolloverTime; - - /** - * Constructor - * @param serial Used to generate unique filename sequences - * @param factory Factory that knows how to make a {@link WriterPoolMember}. - * @param settings Settings for this pool. - * @param poolMaximumActive - * @param poolMaximumWait - */ - public WriterPool(final AtomicInteger serial, - final WriterPoolSettings settings, - final int poolMaximumActive, final int poolMaximumWait) { - logger.info("Initial configuration:" + - " prefix=" + settings.getPrefix() + - ", template=" + settings.getTemplate() + - ", compress=" + settings.getCompress() + - ", maxSize=" + settings.getMaxFileSizeBytes() + - ", maxActive=" + poolMaximumActive + - ", maxWait=" + poolMaximumWait); - this.settings = settings; - this.maxActive = poolMaximumActive; - this.maxWait = poolMaximumWait; - availableWriters = new ArrayBlockingQueue(LARGEST_MAX_ACTIVE, true); - this.serialNo = serial; - } - - /** - * Check out a {@link WriterPoolMember}. - * - * This method should be followed by a call to - * {@link #returnFile(WriterPoolMember)} or - * {@link #invalidateFile(WriterPoolMember)} else pool starts leaking. - * - * @return Writer checked out of a pool of files or created - * @throws IOException Problem getting Writer from pool (Converted - * from Exception to IOException so this pool can live as a good citizen - * down in depths of ARCSocketFactory). - */ - public WriterPoolMember borrowFile() - throws IOException { - WriterPoolMember writer = null; - while(writer == null) { - try { - writer = availableWriters.poll(maxWait,TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - // nothing to do but proceed - } - if(writer==null) { - writer = makeNewWriterIfAppropriate(); - } - } - return writer; - } - - /** - * Create a new writer instance, if still below maxActive count. - * Remember times to help make later decision when writer should - * be discarded. - * - * @return WriterPoolMember or null if already at max - */ - protected synchronized WriterPoolMember makeNewWriterIfAppropriate() { - long now = System.currentTimeMillis(); - lastWriterNeededTime = now; - if(currentActive < maxActive) { - currentActive++; - lastWriterRolloverTime = now; - return makeWriter(); - } - return null; - } - - /** - * @return new WriterPoolMember of appropriate type - */ - protected abstract WriterPoolMember makeWriter(); - - /** - * Discard a previously-used writer, cleanly closing it and leaving it out - * of the pool. - * @param writer - * @throws IOException - */ - public synchronized void destroyWriter(WriterPoolMember writer) throws IOException { - currentActive--; - writer.close(); - } - /** - * Return a writer, for likely reuse unless (1) writer's current file has - * reached its target size; and (2) there's been no demand for additional - * writers since the last time a new writer-file was rolled-over. In that - * case, the possibly-superfluous writer instance is discarded. - * @param writer Writer to return to the pool. - * @throws IOException Problem returning File to pool. - */ - public void returnFile(WriterPoolMember writer) - throws IOException { - synchronized(this) { - if(writer.isOversize()) { - // maybe retire writer rather than recycle - if(lastWriterNeededTime<=lastWriterRolloverTime) { - // no timeouts waiting for recycled writer since last writer rollover - destroyWriter(writer); - return; - } else { - // reuse writer instance, causing new file to be created - lastWriterRolloverTime = System.currentTimeMillis(); - } - } - } - if(!availableWriters.offer(writer)) { - logger.log(Level.WARNING, "writer unreturnable to available pool; closing early"); - destroyWriter(writer); - } - } - - /** - * Close and discard a writer that experienced a potentially-corrupting - * error. - * @param f writer with problem - * @throws IOException - */ - public synchronized void invalidateFile(WriterPoolMember f) - throws IOException { - try { - destroyWriter(f); - } catch (Exception e) { - // Convert exception. - throw new IOException(e.getMessage()); - } - // It'll have been closed. Rename with an '.invalid' suffix so it - // gets attention. - File file = f.getFile(); - file.renameTo(new File(file.getAbsoluteFile() + - WriterPoolMember.INVALID_SUFFIX)); - } - - /** - * @return Number of {@link WriterPoolMember}s checked out of pool. - * @throws java.lang.UnsupportedOperationException - */ - public synchronized int getNumActive() - throws UnsupportedOperationException { - return currentActive - getNumIdle(); - } - - /** - * @return Number of {@link WriterPoolMember} instances still in the pool. - * @throws java.lang.UnsupportedOperationException - */ - public int getNumIdle() - throws UnsupportedOperationException { - return availableWriters.size(); - } - - /** - * Close all {@link WriterPoolMember}s in pool. - */ - public void close() { - WriterPoolMember writer = availableWriters.poll(); - while (writer!=null) { - try { - destroyWriter(writer); - } catch (IOException e) { - logger.log(Level.WARNING,"problem closing writer",e); - } - writer = availableWriters.poll(); - } - } - - /** - * @return Returns settings. - */ - public WriterPoolSettings getSettings() { - return this.settings; - } - - /** - * @return State of the pool string - */ - protected String getPoolState() { - StringBuffer buffer = new StringBuffer("Active "); - buffer.append(getNumActive()); - buffer.append(" of max "); - buffer.append(maxActive); - buffer.append(", idle "); - buffer.append(getNumIdle()); - return buffer.toString(); - } - - /** - * Returns the atomic integer used to generate serial numbers - * for files. - * - * @return the serial number generator - */ - public AtomicInteger getSerialNo() { - return serialNo; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/WriterPoolMember.java b/commons/src/main/java/org/archive/io/WriterPoolMember.java deleted file mode 100644 index 6ea6b295..00000000 --- a/commons/src/main/java/org/archive/io/WriterPoolMember.java +++ /dev/null @@ -1,487 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Logger; -import java.util.zip.GZIPOutputStream; - -import org.archive.util.ArchiveUtils; -import org.archive.util.FileUtils; -import org.archive.util.PropertyUtils; - - - -/** - * Member of {@link WriterPool}. - * Implements rotating off files, file naming with some guarantee of - * uniqueness, and position in file. Subclass to pick up functionality for a - * particular Writer type. - * @author stack - * @version $Date$ $Revision$ - */ -public abstract class WriterPoolMember implements ArchiveFileConstants { - private final Logger logger = Logger.getLogger(this.getClass().getName()); - - public static final String UTF8 = "UTF-8"; - - /** - * Default archival-aggregate filename template. - * - * Under usual assumptions -- hostnames aren't shared among crawling hosts; - * processes have unique PIDs and admin ports; timestamps inside one process - * don't repeat (see UniqueTimestampService); clocks are generally - * accurate -- will generate a unique name. - * - * Stands for Internet Archive Heritrix. - */ - public static final String DEFAULT_TEMPLATE = - "${prefix}-${timestamp17}-${serialno}-${heritrix.pid}~${heritrix.hostname}~${heritrix.port}"; - - /** - * Default for file prefix. - */ - public static final String DEFAULT_PREFIX = "WEB"; - - /** - * Reference to file we're currently writing. - */ - protected File f = null; - - /** Output stream for file. */ - protected OutputStream out = null; - /** Counting stream for metering */ - protected MiserOutputStream countOut = null; - - /** reusable buffer for recycling scenarios */ - protected byte[] rebuf; - - protected WriterPoolSettings settings; - private final String extension; - - /** - * Creation date for the current file. - * Set by {@link #createFile()}. - */ - protected String currentTimestamp = "UNSET!!!"; - - protected String currentBasename; - - /** - * A running sequence used making unique file names. - */ - final private AtomicInteger serialNo; - - /** - * Directories round-robin index. - */ - protected static int roundRobinIndex = 0; - - /** - * NumberFormat instance for formatting serial number. - * - * Pads serial number with zeros. - */ - protected static NumberFormat serialNoFormatter = new DecimalFormat("00000"); - - - /** - * Buffer to reuse writing streams. - */ - protected final byte [] scratchbuffer = new byte[4 * 1024]; - - - /** - * Constructor. - * Takes a stream. Use with caution. There is no upperbound check on size. - * Will just keep writing. - * - * @param serialNo used to create unique filename sequences - * @param out Where to write. - * @param file File the out is connected to. - * @param cmprs Compress the content written. - * @param a14DigitDate If null, we'll write current time. - * @throws IOException - */ - protected WriterPoolMember(AtomicInteger serialNo, - final OutputStream out, final File file, - final WriterPoolSettings settings) - throws IOException { - this(serialNo, settings, null); - this.countOut = (out instanceof MiserOutputStream) - ? (MiserOutputStream)out - : new MiserOutputStream(out, settings.getFrequentFlushes()); - this.out = this.countOut; - this.f = file; - } - - /** - * Constructor. - * - * @param serialNo used to create unique filename sequences - * @param dirs Where to drop files. - * @param prefix File prefix to use. - * @param cmprs Compress the records written. - * @param maxSize Maximum size for ARC files written. - * @param template filenaming template to use - * @param extension Extension to give file. - */ - public WriterPoolMember(AtomicInteger serialNo, - final WriterPoolSettings settings, final String extension) { - this.settings = settings; - this.extension = extension; - this.serialNo = serialNo; - } - - /** - * Call this method just before/after any significant write. - * - * Call at the end of the writing of a record or just before we start - * writing a new record. Will close current file and open a new file - * if file size has passed out maxSize. - * - *

Creates and opens a file if none already open. One use of this method - * then is after construction, call this method to add the metadata, then - * call {@link #getPosition()} to find offset of first record. - * - * TODO: perhaps this should be called checkForNewOpen? because it also - * handles initial open, even when not rolling oversize - * - * @exception IOException - */ - public void checkSize() throws IOException { - if (this.out == null || isOversize()) { - createFile(); - } - } - - /** Check if underlying file has already reached its target size. - * @return boolean true if file has reached target size and due to be closed - */ - public boolean isOversize() { - return settings.getMaxFileSizeBytes() != -1 && (this.getPosition() > settings.getMaxFileSizeBytes()); - } - - /** - * Create a new file. - * Rotates off the current Writer and creates a new in its place - * to take subsequent writes. Usually called from {@link #checkSize()}. - * @return Name of file created. - * @throws IOException - */ - protected String createFile() throws IOException { - generateNewBasename(); - String name = currentBasename + '.' + this.extension + - ((settings.getCompress())? DOT_COMPRESSED_FILE_EXTENSION: "") + - OCCUPIED_SUFFIX; - File dir = getNextDirectory(settings.calcOutputDirs()); - return createFile(new File(dir, name)); - } - - protected String createFile(final File file) throws IOException { - close(); - this.f = file; - FileOutputStream fos = new FileOutputStream(this.f); - if(rebuf==null) { - rebuf = new byte[settings.getWriteBufferSize()]; - } - this.countOut = new MiserOutputStream(new RecyclingFastBufferedOutputStream(fos,rebuf),settings.getFrequentFlushes()); - this.out = this.countOut; - logger.fine("Opened " + this.f.getAbsolutePath()); - return this.f.getName(); - } - - /** - * @param dirs List of File objects that point at directories. - * @return Find next directory to write an arc too. If more - * than one, it tries to round-robin through each in turn. - * @throws IOException - */ - protected File getNextDirectory(List dirs) - throws IOException { - if (WriterPoolMember.roundRobinIndex >= dirs.size()) { - WriterPoolMember.roundRobinIndex = 0; - } - File d = null; - try { - d = checkWriteable((File)dirs. - get(WriterPoolMember.roundRobinIndex)); - } catch (IndexOutOfBoundsException e) { - // Dirs list might be altered underneath us. - // If so, we get this exception -- just keep on going. - } - if (d == null && dirs.size() > 1) { - for (Iterator i = dirs.iterator(); d == null && i.hasNext();) { - d = checkWriteable((File)i.next()); - } - } else { - WriterPoolMember.roundRobinIndex++; - } - if (d == null) { - throw new IOException("Directories unusable."); - } - return d; - } - - protected File checkWriteable(File d) { - if (d == null) { - return d; - } - - try { - FileUtils.ensureWriteableDirectory(d); - } catch(IOException e) { - logger.warning("Directory " + d.getPath() + " is not" + - " writeable or cannot be created: " + e.getMessage()); - d = null; - } - return d; - } - - /** - * Generate a new basename by interpolating values in the configured - * template. Values come from local state, other configured values, and - * global system properties. The recommended default template will - * generate a unique basename under reasonable assumptions. - */ - protected void generateNewBasename() { - Properties localProps = new Properties(); - localProps.setProperty("prefix", settings.getPrefix()); - synchronized(this.getClass()) { - // ensure that serialNo and timestamp are minted together (never inverted sort order) - String paddedSerialNumber = WriterPoolMember.serialNoFormatter.format(serialNo.getAndIncrement()); - String timestamp17 = ArchiveUtils.getUnique17DigitDate(); - String timestamp14 = ArchiveUtils.getUnique14DigitDate(); - currentTimestamp = timestamp17; - localProps.setProperty("serialno", paddedSerialNumber); - localProps.setProperty("timestamp17", timestamp17); - localProps.setProperty("timestamp14", timestamp14); - } - currentBasename = PropertyUtils.interpolateWithProperties(settings.getTemplate(), - localProps, System.getProperties()); - } - - - /** - * Get the file name - * - * @return the filename, as if uncompressed - */ - protected String getBaseFilename() { - String name = this.f.getName(); - if (settings.getCompress() && name.endsWith(DOT_COMPRESSED_FILE_EXTENSION)) { - return name.substring(0,name.length() - 3); - } else if(settings.getCompress() && - name.endsWith(DOT_COMPRESSED_FILE_EXTENSION + - OCCUPIED_SUFFIX)) { - return name.substring(0, name.length() - - (3 + OCCUPIED_SUFFIX.length())); - } else { - return name; - } - } - - /** - * Get this file. - * - * Used by junit test to test for creation and when {@link WriterPool} wants - * to invalidate a file. - * - * @return The current file. - */ - public File getFile() { - return this.f; - } - - /** - * Post write tasks. - * - * Has side effects. Will open new file if we're at the upper bound. - * If we're writing compressed files, it will wrap output stream with a - * GZIP writer with side effect that GZIP header is written out on the - * stream. - * - * @exception IOException - */ - protected void preWriteRecordTasks() - throws IOException { - if (this.out == null) { - createFile(); - } - if (settings.getCompress()) { - // Wrap stream in GZIP Writer. - // The below construction immediately writes the GZIP 'default' - // header out on the underlying stream. - this.out = new CompressedStream(this.out); - } - } - - /** - * Post file write tasks. - * If compressed, finishes up compression and flushes stream so any - * subsequent checks get good reading. - * - * @exception IOException - */ - protected void postWriteRecordTasks() - throws IOException { - if (settings.getCompress()) { - CompressedStream o = (CompressedStream)this.out; - o.finish(); - o.flush(); - o.end(); - this.out = o.getWrappedStream(); - } - } - - /** - * Position in raw output (typically, physical file). - * Used making accounting of bytes written. - * @return Position in final media (assuming all flushing completes) - * @throws IOException - */ - public long getPosition() { - return (countOut==null)? 0L : this.countOut.getCount(); - } - - public boolean isCompressed() { - return settings.getCompress(); - } - - protected void write(final byte [] b) throws IOException { - this.out.write(b); - } - - protected void flush() throws IOException { - this.out.flush(); - } - - protected void write(byte[] b, int off, int len) throws IOException { - this.out.write(b, off, len); - } - - protected void write(int b) throws IOException { - this.out.write(b); - } - - /** - * Copy bytes from the provided InputStream to the target file/stream being - * written. - * - * @return number of bytes written (normally equal to {@code enforceLength}) - * @param is - * InputStream to copy bytes from - * @param recordLength - * expected number of bytes to copy - * @param enforceLength - * whether to throw an exception if too many/too few bytes are - * available from stream - * @throws IOException - */ - protected long copyFrom(final InputStream is, final long recordLength, - boolean enforceLength) throws IOException { - int read = scratchbuffer.length; - long tot = 0; - while ((tot < recordLength) - && (read = is.read(scratchbuffer)) != -1) { - int write = read; - // never write more than enforced length - write = (int) Math.min(write, recordLength - tot); - tot += read; - write(scratchbuffer, 0, write); - } - if (enforceLength && tot != recordLength) { - // throw exception if desired for read vs. declared mismatches - throw new IOException("Read " + tot + " but expected " - + recordLength); - } - - return tot; - } - - public void close() throws IOException { - if (this.out == null) { - return; - } - this.out.close(); - this.out = null; - if (this.f != null && this.f.exists()) { - String path = this.f.getAbsolutePath(); - if (path.endsWith(OCCUPIED_SUFFIX)) { - File f = new File(path.substring(0, - path.length() - OCCUPIED_SUFFIX.length())); - if (f.exists() & !f.delete()) { - logger.warning("Failed delete of " + f); - } - if (!this.f.renameTo(f)) { - logger.warning("Failed rename of " + path); - } - this.f = f; - } - - logger.fine("Closed " + this.f.getAbsolutePath() + - ", size " + this.f.length()); - } - } - - protected OutputStream getOutputStream() { - return this.out; - } - - /** - * An override so we get access to underlying output stream. - * and offer an end() that does not accompany closing underlying - * stream. - * @author stack - */ - private class CompressedStream extends GZIPOutputStream { - public CompressedStream(OutputStream out) - throws IOException { - super(out); - } - - /** - * @return Reference to stream being compressed. - */ - OutputStream getWrappedStream() { - return this.out; - } - - /** - * Release the deflater's native process resources, - * which otherwise would not occur until either - * finalization or DeflaterOutputStream.close() - * (which would also close underlying stream). - */ - public void end() { - def.end(); - } - } -} diff --git a/commons/src/main/java/org/archive/io/WriterPoolSettings.java b/commons/src/main/java/org/archive/io/WriterPoolSettings.java deleted file mode 100644 index d0805cdc..00000000 --- a/commons/src/main/java/org/archive/io/WriterPoolSettings.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io; - -import java.io.File; -import java.util.List; - -/** - * Settings object for a {@link WriterPool}. - * Used creating {@link WriterPoolMember}s. - * @author stack - * @version $Date$, $Revision$ - */ -public interface WriterPoolSettings { - public long getMaxFileSizeBytes(); - public String getPrefix(); - public String getTemplate(); - public List calcOutputDirs(); - public boolean getCompress(); - public List getMetadata(); - public boolean getFrequentFlushes(); - public int getWriteBufferSize(); -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/arc/ARC2WCDX.java b/commons/src/main/java/org/archive/io/arc/ARC2WCDX.java deleted file mode 100644 index 19010131..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARC2WCDX.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Date; -import java.util.Iterator; -import java.util.zip.GZIPOutputStream; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HeaderGroup; -import org.apache.commons.httpclient.util.DateParseException; -import org.apache.commons.httpclient.util.DateUtil; -import org.archive.io.ArchiveRecord; -import org.archive.util.ArchiveUtils; -import org.archive.util.SURT; - -/** - * Create a 'Wide' CDX from an ARC. Takes one argument, the path to the ARC. - * Writes .wcdx.gz in same directory. - * - * @author gojomo - */ -public class ARC2WCDX { - final public static String WCDX_VERSION="0.1"; - - public static void main(String[] args) throws IOException { - String arcFilename = args[0]; - createWcdx(arcFilename); - } - - public static Object[] createWcdx(String arcFilename) throws IOException { - ARCReader reader = ARCReaderFactory.get(arcFilename); - Object[] retVal = createWcdx(reader); - reader.close(); - return retVal; - } - - public static Object[] createWcdx(ARCReader reader) { - reader.setDigest(true); - - String wcdxPath = reader.getReaderIdentifier().replaceAll("\\.arc(\\.gz)?$",".wcdx.gz"); - File wcdxFile = new File(wcdxPath+".open"); - PrintStream writer = null; - long count = 0; - try { - writer = new PrintStream(new GZIPOutputStream(new FileOutputStream(wcdxFile))); - - // write header: legend + timestamp - StringBuilder legend = new StringBuilder(); - appendField(legend,"CDX"); - appendField(legend,"surt-uri"); - appendField(legend,"b"); // ARC timestamp - appendField(legend,"http-date"); - appendField(legend,"s"); // status code - appendField(legend,"m"); // media type - appendField(legend,"sha1"); // content sha1 - appendField(legend,"g"); // ARC name - appendField(legend,"V"); // start offset - appendField(legend,"end-offset"); // TODO: implement - appendField(legend,"n"); // ARC record length TODO: verify - appendField(legend,"http-content-length"); - appendField(legend,"http-last-modified"); - appendField(legend,"http-expires"); - appendField(legend,"http-etag"); - appendField(legend,"http-location"); - appendField(legend,"e"); // IP - appendField(legend,"a"); // original URL - // WCDX version+creation time: crude version control - appendField(legend,WCDX_VERSION+"@"+ArchiveUtils.get14DigitDate()); - writer.println(legend.toString()); - - Iterator iter = reader.iterator(); - count = 0; - while(iter.hasNext()) { - ARCRecord record = (ARCRecord) iter.next(); - record.close(); - ARCRecordMetaData h = (ARCRecordMetaData) record.getHeader(); - Header[] httpHeaders = record.getHttpHeaders(); - if(httpHeaders==null) { - httpHeaders = new Header[0]; - } - HeaderGroup hg = new HeaderGroup(); - hg.setHeaders(httpHeaders); - StringBuilder builder = new StringBuilder(); - - // SURT-form URI - appendField(builder,SURT.fromURI(h.getUrl())); - // record timestamp ('b') - appendField(builder,h.getDate()); - // http header date - appendTimeField(builder,hg.getFirstHeader("Date")); - // response code ('s') - appendField(builder,h.getStatusCode()); - // media type ('m') - appendField(builder,h.getMimetype()); - // content checksum (like 'c', but here Base32 SHA1) - appendField(builder,record.getDigestStr()); - // arc name ('g') - appendField(builder,reader.getFileName()); - // compressed start offset ('V') - appendField(builder,h.getOffset()); - - // compressed end offset (?) -// appendField(builder, -// reader.getInputStream() instanceof RepositionableStream -// ? ((GzippedInputStream)reader.getInputStream()).vPosition() -// : "-"); - // TODO; leave unavail for now - appendField(builder, "-"); - - // uncompressed (declared in ARC headerline) record length - appendField(builder,h.getLength()); - // http header content-length - appendField(builder,hg.getFirstHeader("Content-Length")); - - // http header mod-date - appendTimeField(builder,hg.getFirstHeader("Last-Modified")); - // http header expires - appendTimeField(builder,hg.getFirstHeader("Expires")); - - // http header etag - appendField(builder,hg.getFirstHeader("ETag")); - // http header redirect ('Location' header?) - appendField(builder,hg.getFirstHeader("Location")); - // ip ('e') - appendField(builder,h.getIp()); - // original URI - appendField(builder,h.getUrl()); - // TODO MAYBE - a title from inside content? - - writer.println(builder.toString()); - count++; - } - wcdxFile.renameTo(new File(wcdxPath)); - } catch (IOException e) { - // soldier on: but leave '.open' wcdx file as indicator of error - if(!wcdxFile.exists()) { - try { - wcdxFile.createNewFile(); - } catch (IOException e1) { - // TODO Auto-generated catch block - throw new RuntimeException(e1); - } - } - } catch (RuntimeException e) { - // soldier on: but leave '.open' wcdx file as indicator of error - if(!wcdxFile.exists()) { - try { - wcdxFile.createNewFile(); - } catch (IOException e1) { - // TODO Auto-generated catch block - throw new RuntimeException(e1); - } - } - } finally { - if(writer!=null) { - writer.close(); - } - } - - return new Object[] {wcdxPath, count}; - } - - protected static void appendField(StringBuilder builder, Object obj) { - if(builder.length()>0) { - // prepend with delimiter - builder.append(' '); - } - if(obj instanceof Header) { - obj = ((Header)obj).getValue().trim(); - } - - builder.append((obj==null||obj.toString().length()==0)?"-":obj); - } - - protected static void appendTimeField(StringBuilder builder, Object obj) { - if(builder.length()>0) { - // prepend with delimiter - builder.append(' '); - } - if(obj==null) { - builder.append("-"); - return; - } - if(obj instanceof Header) { - String s = ((Header)obj).getValue().trim(); - try { - Date date = DateUtil.parseDate(s); - String d = ArchiveUtils.get14DigitDate(date); - if(d.startsWith("209")) { - d = "199"+d.substring(3); - } - obj = d; - } catch (DateParseException e) { - builder.append('e'); - return; - } - - } - builder.append(obj); - } -} - -//'wide' CDX -//a original url -//b timestamp -//s resp code -//m type -//? content md5 (full 'k'? 'c'? -//g arc name -//V compressed start offset -//? compressed length -//n? uncompressed length -//? mod date -//? expires -//? server 'date' hdr -//? etag -//r redirect ('Location'?) -//e ip -//MAYBE: -//? TITLE from HTML or other format? - - diff --git a/commons/src/main/java/org/archive/io/arc/ARCConstants.java b/commons/src/main/java/org/archive/io/arc/ARCConstants.java deleted file mode 100644 index 23407236..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCConstants.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.util.Arrays; -import java.util.List; -import java.util.zip.Deflater; -import java.util.zip.GZIPInputStream; - -import org.archive.io.ArchiveFileConstants; -import org.archive.util.zip.GzipHeader; - -/** - * Constants used by ARC files and in ARC file processing. - * - * @author stack - */ -public interface ARCConstants extends ArchiveFileConstants { - /** - * Default maximum ARC file size. - */ - public static final long DEFAULT_MAX_ARC_FILE_SIZE = 100000000; - - /** - * Maximum length for a metadata line. - */ - public static final int MAX_METADATA_LINE_LENGTH = (4 * 1024); - - /** - * ARC file extention. - */ - public static final String ARC_FILE_EXTENSION = "arc"; - - /** - * Dot ARC file extension. - */ - public static final String DOT_ARC_FILE_EXTENSION = - "." + ARC_FILE_EXTENSION; - - public static final String DOT_COMPRESSED_FILE_EXTENSION = - ArchiveFileConstants.DOT_COMPRESSED_FILE_EXTENSION; - - /** - * Compressed arc file extension. - */ - public static final String COMPRESSED_ARC_FILE_EXTENSION = - ARC_FILE_EXTENSION + DOT_COMPRESSED_FILE_EXTENSION; - - /** - * Compressed dot arc file extension. - */ - public static final String DOT_COMPRESSED_ARC_FILE_EXTENSION = - DOT_ARC_FILE_EXTENSION + DOT_COMPRESSED_FILE_EXTENSION; - - /** - * Encoding to use getting bytes from strings. - * - * Specify an encoding rather than leave it to chance: i.e whatever the - * JVMs encoding. Use an encoding that gets the stream as bytes, not chars. - */ - public static final String DEFAULT_ENCODING = "ISO-8859-1"; - - /** - * ARC file line seperator character. - * - * This is what the alexa c-code looks for delimiting lines. - */ - public static final char LINE_SEPARATOR = '\n'; - - /** - * ARC header field seperator character. - */ - public static final char HEADER_FIELD_SEPARATOR = ' '; - - /** - * ARC file *MAGIC NUMBER*. - * - * Every ARC file must begin w/ this. - */ - public static final String ARC_MAGIC_NUMBER = "filedesc://"; - - /** - * The FLG.FEXTRA field that is added to ARC files. (See RFC1952 to - * understand FLG.FEXTRA). - */ - public static final byte[] ARC_GZIP_EXTRA_FIELD = { 8, 0, 'L', 'X', 4, 0, - 0, 0, 0, 0 }; - - /** - * Key for the ARC Header IP field. - * - * Lowercased. - */ - public static final String IP_HEADER_FIELD_KEY = "ip-address"; - - /** - * Key for the ARC Header Result Code field. - * - * Lowercased. - */ - public static final String CODE_HEADER_FIELD_KEY = "result-code"; - - /** - * Key for the ARC Header Checksum field. - * - * Lowercased. - */ - public static final String CHECKSUM_HEADER_FIELD_KEY = "checksum"; - - /** - * Key for the ARC Header Location field. - * - * Lowercased. - */ - public static final String LOCATION_HEADER_FIELD_KEY = "location"; - - /** - * Key for the ARC Header Offset field. - * - * Lowercased. - */ - public static final String OFFSET_HEADER_FIELD_KEY = "offset"; - - /** - * Key for the ARC Header filename field. - * - * Lowercased. - */ - public static final String FILENAME_HEADER_FIELD_KEY = "filename"; - - /** - * Key for statuscode field. - */ - public static final String STATUSCODE_FIELD_KEY = "statuscode"; - - /** - * Key for offset field. - */ - public static final String OFFSET_FIELD_KEY = OFFSET_HEADER_FIELD_KEY; - - /** - * Key for filename field. - */ - public static final String FILENAME_FIELD_KEY = FILENAME_HEADER_FIELD_KEY; - - /** - * Key for checksum field. - */ - public static final String CHECKSUM_FIELD_KEY = CHECKSUM_HEADER_FIELD_KEY; - - /** - * Tokenized field prefix. - * - * Use this prefix for tokenized fields when naming fields in - * an index. - */ - public static final String TOKENIZED_PREFIX = "tokenized_"; - - /** - * Assumed maximum size of a record meta header line. - * - * This 100k which seems massive but its the same as the LINE_LENGTH from - * alexa/include/a_arcio.h: - *

-     * #define LINE_LENGTH     (100*1024)
-     * 
- */ - public static final int MAX_HEADER_LINE_LENGTH = 1024 * 100; - - /** - * Version 1 required metadata fields. - */ - public static List REQUIRED_VERSION_1_HEADER_FIELDS = Arrays - .asList(new String[] { URL_FIELD_KEY, IP_HEADER_FIELD_KEY, - DATE_FIELD_KEY, MIMETYPE_FIELD_KEY, - LENGTH_FIELD_KEY, VERSION_FIELD_KEY, - ABSOLUTE_OFFSET_KEY }); - - /** - * Minimum possible record length. - * - * This is a rough calc. When the header is data it will occupy less space. - */ - public static int MINIMUM_RECORD_LENGTH = 1 + "://".length() + 1 - + ARC_FILE_EXTENSION.length() + " ".length() + +1 + " ".length() - + 1 + " ".length() + 1 + "/".length() + 1 + " ".length() + 1; - - /** - * Start of a GZIP header that uses default deflater. - */ - public static final byte[] GZIP_HEADER_BEGIN = { - (byte) GZIPInputStream.GZIP_MAGIC, // Magic number (short) - (byte) (GZIPInputStream.GZIP_MAGIC >> 8), // Magic number (short) - Deflater.DEFLATED // Compression method (CM) - }; - - /** - * Length of minimual 'default GZIP header. - * - * See RFC1952 for explaination of value of 10. - */ - public static final int DEFAULT_GZIP_HEADER_LENGTH = - GzipHeader.MINIMAL_GZIP_HEADER_LENGTH; - - /** - * set of known errors encountered reading ARCs - */ - public enum ArcRecordErrors { - HTTP_HEADER_TRUNCATED, - HTTP_STATUS_LINE_INVALID, - HTTP_STATUS_LINE_EXCEPTION, - } - -} diff --git a/commons/src/main/java/org/archive/io/arc/ARCLocation.java b/commons/src/main/java/org/archive/io/arc/ARCLocation.java deleted file mode 100644 index c6c64437..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCLocation.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -/** - * Datastructure to hold ARC record location. - * Used by wayback machine. - * @author stack - */ -public interface ARCLocation { - /** - * @return Returns the ARC filename. Can be full path to ARC, URL to an - * ARC or just the portion of an ARC name that is unique to a collection. - */ - public String getName(); - - /** - * @return Returns the offset into the ARC. - */ - public long getOffset(); -} diff --git a/commons/src/main/java/org/archive/io/arc/ARCReader.java b/commons/src/main/java/org/archive/io/arc/ARCReader.java deleted file mode 100644 index 7f85cc2a..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCReader.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Logger; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; -import org.archive.io.ArchiveReader; -import org.archive.io.ArchiveRecord; -import org.archive.io.ArchiveRecordHeader; -import org.archive.io.RecoverableIOException; -import org.archive.io.WriterPoolMember; -import org.archive.util.ArchiveUtils; - - -/** - * Get an iterator on an ARC file or get a record by absolute position. - * - * ARC files are described here: - * Arc - * File Format. - * - *

This class knows how to parse an ARC file. Pass it a file path - * or an URL to an ARC. It can parse ARC Version 1 and 2. - * - *

Iterator returns ARCRecord - * though {@link Iterator#next()} is returning - * java.lang.Object. Cast the return. - * - *

Profiling java.io vs. memory-mapped ByteBufferInputStream shows the - * latter slightly slower -- but not by much. TODO: Test more. Just - * change {@link #getInputStream(File, long)}. - * - * @author stack - * @version $Date$ $Revision$ - */ -public abstract class ARCReader extends ArchiveReader -implements ARCConstants, Closeable { - private final Logger logger = Logger.getLogger(ARCReader.class.getName()); - - /** - * Set to true if we are aligned on first record of Archive file. - * We used depend on offset. If offset was zero, then we were - * aligned on first record. This is no longer necessarily the case when - * Reader is created at an offset into an Archive file: The offset is zero - * but its relative to where we started reading. - */ - private boolean alignedOnFirstRecord = true; - - private boolean parseHttpHeaders = true; - - protected ARCReader() { - super(); - } - - /** - * Skip over any trailing new lines at end of the record so we're lined up - * ready to read the next. - * @param record - * @throws IOException - */ - protected void gotoEOR(ArchiveRecord record) throws IOException { - if (getIn().available() <= 0) { - return; - } - - // Remove any trailing LINE_SEPARATOR - int c = -1; - while (getIn().available() > 0) { - if (getIn().markSupported()) { - getIn().mark(1); - } - c = getIn().read(); - if (c != -1) { - if (c == LINE_SEPARATOR) { - continue; - } - if (getIn().markSupported()) { - // We've overread. We're probably in next record. There is - // no way of telling for sure. It may be dross at end of - // current record. Backup. - getIn().reset(); - break; - } - ArchiveRecordHeader h = (getCurrentRecord() != null)? - record.getHeader(): null; - throw new IOException("Read " + (char)c + - " when only " + LINE_SEPARATOR + " expected. " + - getReaderIdentifier() + ((h != null)? - h.getHeaderFields().toString(): "")); - } - } - } - - /** - * Create new arc record. - * - * Encapsulate housekeeping that has to do w/ creating a new record. - * - *

Call this method at end of constructor to read in the - * arcfile header. Will be problems reading subsequent arc records - * if you don't since arcfile header has the list of metadata fields for - * all records that follow. - * - *

When parsing through ARCs writing out CDX info, we spend about - * 38% of CPU in here -- about 30% of which is in getTokenizedHeaderLine - * -- of which 16% is reading. - * - * @param is InputStream to use. - * @param offset Absolute offset into arc file. - * @return An arc record. - * @throws IOException - */ - protected ARCRecord createArchiveRecord(InputStream is, long offset) - throws IOException { - try { - String version = super.getVersion(); - ARCRecord record = new ARCRecord(is, getReaderIdentifier(), offset, - isDigest(), isStrict(), isParseHttpHeaders(), - isAlignedOnFirstRecord(), version); - if (version != null && super.getVersion() == null) - super.setVersion(version); - currentRecord(record); - } catch (IOException e) { - if (e instanceof RecoverableIOException) { - // Don't mess with RecoverableIOExceptions. Let them out. - throw e; - } - IOException newE = new IOException(e.getMessage() + " (Offset " + - offset + ")."); - newE.setStackTrace(e.getStackTrace()); - throw newE; - } - return (ARCRecord)getCurrentRecord(); - } - - /** - * Returns version of this ARC file. Usually read from first record of ARC. - * If we're reading without having first read the first record -- e.g. - * random access into middle of an ARC -- then version will not have been - * set. For now, we return a default, version 1.1. Later, if more than - * just one version of ARC, we could look at such as the meta line to see - * what version of ARC this is. - * @return Version of this ARC file. - */ - public String getVersion() { - return (super.getVersion() == null)? "1.1": super.getVersion(); - } - - protected boolean isAlignedOnFirstRecord() { - return alignedOnFirstRecord; - } - - protected void setAlignedOnFirstRecord(boolean alignedOnFirstRecord) { - this.alignedOnFirstRecord = alignedOnFirstRecord; - } - - /** - * @return Returns the parseHttpHeaders. - */ - public boolean isParseHttpHeaders() { - return this.parseHttpHeaders; - } - - /** - * @param parse The parseHttpHeaders to set. - */ - public void setParseHttpHeaders(boolean parse) { - this.parseHttpHeaders = parse; - } - - public String getFileExtension() { - return ARC_FILE_EXTENSION; - } - - public String getDotFileExtension() { - return DOT_ARC_FILE_EXTENSION; - } - - protected boolean output(final String format) - throws IOException, java.text.ParseException { - boolean result = super.output(format); - if(!result && (format.equals(NOHEAD) || format.equals(HEADER))) { - throw new IOException(format + - " format only supported for single Records"); - } - return result; - } - - public boolean outputRecord(final String format) throws IOException { - boolean result = super.outputRecord(format); - if (result) { - return result; - } - if (format.equals(NOHEAD)) { - // No point digesting if dumping content. - setDigest(false); - ARCRecord r = (ARCRecord) get(); - r.skipHttpHeader(); - r.dump(); - result = true; - } else if (format.equals(HEADER)) { - // No point digesting if dumping content. - setDigest(false); - ARCRecord r = (ARCRecord) get(); - r.dumpHttpHeader(); - result = true; - } - - return result; - } - - public void dump(final boolean compress) - throws IOException, java.text.ParseException { - // No point digesting if we're doing a dump. - setDigest(false); - boolean firstRecord = true; - ARCWriter writer = null; - for (Iterator ii = iterator(); ii.hasNext();) { - ARCRecord r = (ARCRecord)ii.next(); - // We're to dump the arc on stdout. - // Get the first record's data if any. - ARCRecordMetaData meta = r.getMetaData(); - if (firstRecord) { - firstRecord = false; - // Get an ARCWriter. - ByteArrayOutputStream baos = - new ByteArrayOutputStream(r.available()); - // This is slow but done only once at top of ARC. - while (r.available() > 0) { - baos.write(r.read()); - } - List listOfMetadata = new ArrayList(); - listOfMetadata.add(baos.toString(WriterPoolMember.UTF8)); - // Assume getArc returns full path to file. ARCWriter - // or new File will complain if it is otherwise. - List outDirs = new ArrayList(); - WriterPoolSettingsData settings = - new WriterPoolSettingsData("","",-1L,compress,outDirs,listOfMetadata); - writer = new ARCWriter(new AtomicInteger(), System.out, - new File(meta.getArc()), settings); - continue; - } - - writer.write(meta.getUrl(), meta.getMimetype(), meta.getIp(), - ArchiveUtils.parse14DigitDate(meta.getDate()).getTime(), - (int)meta.getLength(), r); - } - // System.out.println(System.currentTimeMillis() - start); - } - - /** - * @return an ArchiveReader that will delete a local file on close. Used - * when we bring Archive files local and need to clean up afterward. - */ - public ARCReader getDeleteFileOnCloseReader(final File f) { - final ARCReader d = this; - return new ARCReader() { - private final ARCReader delegate = d; - private File archiveFile = f; - - public void close() throws IOException { - this.delegate.close(); - if (this.archiveFile != null) { - if (archiveFile.exists()) { - archiveFile.delete(); - } - this.archiveFile = null; - } - } - - public ArchiveRecord get(long o) throws IOException { - return this.delegate.get(o); - } - - public boolean isDigest() { - return this.delegate.isDigest(); - } - - public boolean isStrict() { - return this.delegate.isStrict(); - } - - public Iterator iterator() { - return this.delegate.iterator(); - } - - public void setDigest(boolean d) { - this.delegate.setDigest(d); - } - - public void setStrict(boolean s) { - this.delegate.setStrict(s); - } - - public List validate() throws IOException { - return this.delegate.validate(); - } - - @Override - public ArchiveRecord get() throws IOException { - return this.delegate.get(); - } - - @Override - public String getVersion() { - return this.delegate.getVersion(); - } - - @Override - public List validate(int noRecords) throws IOException { - return this.delegate.validate(noRecords); - } - - @Override - protected ARCRecord createArchiveRecord(InputStream is, - long offset) - throws IOException { - return this.delegate.createArchiveRecord(is, offset); - } - - @Override - protected void gotoEOR(ArchiveRecord record) throws IOException { - this.delegate.gotoEOR(record); - } - - @Override - public void dump(boolean compress) - throws IOException, java.text.ParseException { - this.delegate.dump(compress); - } - - @Override - public String getDotFileExtension() { - return this.delegate.getDotFileExtension(); - } - - @Override - public String getFileExtension() { - return this.delegate.getFileExtension(); - } - }; - } - - // Static methods follow. - - /** - * - * @param formatter Help formatter instance. - * @param options Usage options. - * @param exitCode Exit code. - */ - private static void usage(HelpFormatter formatter, Options options, - int exitCode) { - formatter.printHelp("java org.archive.io.arc.ARCReader" + - " [--digest=true|false] \\\n" + - " [--format=cdx|cdxfile|dump|gzipdump|header|nohead]" + - " [--offset=#] \\\n[--strict] [--parse] ARC_FILE|ARC_URL", - options); - System.exit(exitCode); - } - - /** - * Write out the arcfile. - * - * @param reader - * @param format Format to use outputting. - * @throws IOException - * @throws java.text.ParseException - */ - protected static void output(ARCReader reader, String format) - throws IOException, java.text.ParseException { - if (!reader.output(format)) { - throw new IOException("Unsupported format: " + format); - } - } - - /** - * Generate a CDX index file for an ARC file. - * - * @param urlOrPath The ARC file to generate a CDX index for - * @throws IOException - * @throws java.text.ParseException - */ - public static void createCDXIndexFile(String urlOrPath) - throws IOException, java.text.ParseException { - ARCReader r = ARCReaderFactory.get(urlOrPath); - r.setStrict(false); - r.setParseHttpHeaders(true); - r.setDigest(true); - output(r, CDX_FILE); - } - - /** - * Command-line interface to ARCReader. - * - * Here is the command-line interface: - *

-     * usage: java org.archive.io.arc.ARCReader [--offset=#] ARCFILE
-     *  -h,--help      Prints this message and exits.
-     *  -o,--offset    Outputs record at this offset into arc file.
- * - *

See in $HERITRIX_HOME/bin/arcreader for a script that'll - * take care of classpaths and the calling of ARCReader. - * - *

Outputs using a pseudo-CDX format as described here: - * CDX - * Legent and here - * Example. - * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'. - * Hash is hard-coded straight SHA-1 hash of content. - * - * @param args Command-line arguments. - * @throws ParseException Failed parse of the command line. - * @throws IOException - * @throws java.text.ParseException - */ - @SuppressWarnings("unchecked") - public static void main(String [] args) - throws ParseException, IOException, java.text.ParseException { - Options options = getOptions(); - options.addOption(new Option("p","parse", false, "Parse headers.")); - PosixParser parser = new PosixParser(); - CommandLine cmdline = parser.parse(options, args, false); - List cmdlineArgs = cmdline.getArgList(); - Option [] cmdlineOptions = cmdline.getOptions(); - HelpFormatter formatter = new HelpFormatter(); - - // If no args, print help. - if (cmdlineArgs.size() <= 0) { - usage(formatter, options, 0); - } - - // Now look at options passed. - long offset = -1; - boolean digest = false; - boolean strict = false; - boolean parse = false; - String format = CDX; - for (int i = 0; i < cmdlineOptions.length; i++) { - switch(cmdlineOptions[i].getId()) { - case 'h': - usage(formatter, options, 0); - break; - - case 'o': - offset = - Long.parseLong(cmdlineOptions[i].getValue()); - break; - - case 's': - strict = true; - break; - - case 'p': - parse = true; - break; - - case 'd': - digest = getTrueOrFalse(cmdlineOptions[i].getValue()); - break; - - case 'f': - format = cmdlineOptions[i].getValue().toLowerCase(); - boolean match = false; - // List of supported formats. - final String [] supportedFormats = - {CDX, DUMP, GZIP_DUMP, HEADER, NOHEAD, CDX_FILE}; - for (int ii = 0; ii < supportedFormats.length; ii++) { - if (supportedFormats[ii].equals(format)) { - match = true; - break; - } - } - if (!match) { - usage(formatter, options, 1); - } - break; - - default: - throw new RuntimeException("Unexpected option: " + - + cmdlineOptions[i].getId()); - } - } - - if (offset >= 0) { - if (cmdlineArgs.size() != 1) { - System.out.println("Error: Pass one arcfile only."); - usage(formatter, options, 1); - } - ARCReader arc = ARCReaderFactory.get((String)cmdlineArgs.get(0), - offset); - arc.setStrict(strict); - // We must parse headers if we need to skip them. - if (format.equals(NOHEAD) || format.equals(HEADER)) { - parse = true; - } - arc.setParseHttpHeaders(parse); - outputRecord(arc, format); - } else { - for (String urlOrPath : cmdlineArgs) { - try { - ARCReader r = ARCReaderFactory.get(urlOrPath); - r.setStrict(strict); - r.setParseHttpHeaders(parse); - r.setDigest(digest); - output(r, format); - } catch (RuntimeException e) { - // Write out name of file we failed on to help with - // debugging. Then print stack trace and try to keep - // going. We do this for case where we're being fed - // a bunch of ARCs; just note the bad one and move - // on to the next. - System.err.println("Exception processing " + urlOrPath + - ": " + e.getMessage()); - e.printStackTrace(System.err); - System.exit(1); - } - } - } - } -} diff --git a/commons/src/main/java/org/archive/io/arc/ARCReaderFactory.java b/commons/src/main/java/org/archive/io/arc/ARCReaderFactory.java deleted file mode 100644 index e7dc1625..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCReaderFactory.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; -import java.util.logging.Level; - -import org.archive.io.ArchiveReader; -import org.archive.io.ArchiveReaderFactory; -import org.archive.io.ArchiveRecord; -import org.archive.io.ArchiveRecordHeader; -import org.archive.util.FileUtils; -import org.archive.util.zip.GZIPMembersInputStream; -import org.archive.util.zip.GzipHeader; -import org.archive.util.zip.NoGzipMagicException; - -import com.google.common.io.CountingInputStream; - - -/** - * Factory that returns an ARCReader. - * - * Can handle compressed and uncompressed ARCs. - * - * @author stack - */ -public class ARCReaderFactory extends ArchiveReaderFactory -implements ARCConstants { - /** - * This factory instance. - */ - private static final ARCReaderFactory factory = new ARCReaderFactory(); - - /** - * Shutdown any access to default constructor. - */ - protected ARCReaderFactory() { - super(); - } - - public static ARCReader get(String arcFileOrUrl) - throws MalformedURLException, IOException { - return (ARCReader)ARCReaderFactory.factory. - getArchiveReader(arcFileOrUrl); - } - - public static ARCReader get(String arcFileOrUrl, final long offset) - throws MalformedURLException, IOException { - return (ARCReader)ARCReaderFactory.factory. - getArchiveReader(arcFileOrUrl, offset); - } - - public static ARCReader get(final File f) throws IOException { - return (ARCReader)ARCReaderFactory.factory.getArchiveReader(f); - } - - public static ARCReader get(final File f, final long offset) - throws IOException { - return (ARCReader)ARCReaderFactory.factory.getArchiveReader(f, offset); - } - - protected ArchiveReader getArchiveReader(final File f, final long offset) - throws IOException { - return getArchiveReader(f, true, offset); - } - - /** - * @param f An arcfile to read. - * @param skipSuffixTest Set to true if want to test that ARC has proper - * suffix. Use this method and pass false to open ARCs - * with the .open or otherwise suffix. - * @param offset Have returned ARCReader set to start reading at passed - * offset. - * @return An ARCReader. - * @throws IOException - */ - public static ARCReader get(final File f, - final boolean skipSuffixTest, final long offset) - throws IOException { - return (ARCReader)ARCReaderFactory.factory.getArchiveReader(f, - skipSuffixTest, offset); - } - - protected ArchiveReader getArchiveReader(final File arcFile, - final boolean skipSuffixTest, final long offset) - throws IOException { - boolean compressed = testCompressedARCFile(arcFile, skipSuffixTest); - if (!compressed) { - if (!FileUtils.isReadableWithExtensionAndMagic(arcFile, - ARC_FILE_EXTENSION, ARC_MAGIC_NUMBER)) { - throw new IOException(arcFile.getAbsolutePath() + - " is not an Internet Archive ARC file."); - } - } - return compressed? - (ARCReader)ARCReaderFactory.factory. - new CompressedARCReader(arcFile, offset): - (ARCReader)ARCReaderFactory.factory. - new UncompressedARCReader(arcFile, offset); - } - - public static ArchiveReader get(final String s, final InputStream is, - final boolean atFirstRecord) - throws IOException { - return ARCReaderFactory.factory.getArchiveReader(s, is, - atFirstRecord); - } - - protected ArchiveReader getArchiveReader(final String arc, - final InputStream is, final boolean atFirstRecord) - throws IOException { - - // We do this mark() reset() stuff, wrapping in a BufferedInputStream if - // necessary to make it work, because testCompressedARCStream() consumes - // some bytes from the input stream - InputStream possiblyWrapped; - if (is.markSupported()) { - possiblyWrapped = is; - } else { - possiblyWrapped = new BufferedInputStream(is); - } - - possiblyWrapped.mark(100); - boolean compressed = testCompressedARCStream(possiblyWrapped); - possiblyWrapped.reset(); - - if (compressed) { - return new CompressedARCReader(arc, possiblyWrapped, atFirstRecord); - } else { - return new UncompressedARCReader(arc, possiblyWrapped); - } - } - - /** - * Get an ARCReader aligned at offset. This version of get - * will not bring the ARC local but will try to stream across the net making - * an HTTP 1.1 Range request on remote http server (RFC1435 Section 14.35). - * - * @param arcUrl HTTP URL for an ARC (All ARCs considered remote). - * @param offset Offset into ARC at which to start fetching. - * @return An ARCReader aligned at offset. - * @throws IOException - */ - public static ARCReader get(final URL arcUrl, final long offset) - throws IOException { - return (ARCReader)ARCReaderFactory.factory.getArchiveReader(arcUrl, - offset); - } - - /** - * Get an ARCReader. - * Pulls the ARC local into whereever the System Property - * java.io.tmpdir points. It then hands back an ARCReader that - * points at this local copy. A close on this ARCReader instance will - * remove the local copy. - * @param arcUrl An URL that points at an ARC. - * @return An ARCReader. - * @throws IOException - */ - public static ARCReader get(final URL arcUrl) - throws IOException { - return (ARCReader)ARCReaderFactory.factory.getArchiveReader(arcUrl); - } - - /** - * @param arcFile File to test. - * @return True if arcFile is compressed ARC. - * @throws IOException - */ - public boolean isCompressed(File arcFile) throws IOException { - return testCompressedARCFile(arcFile); - } - - /** - * Check file is compressed and in ARC GZIP format. - * - * @param arcFile File to test if its Internet Archive ARC file - * GZIP compressed. - * - * @return True if this is an Internet Archive GZIP'd ARC file (It begins - * w/ the Internet Archive GZIP header and has the - * COMPRESSED_ARC_FILE_EXTENSION suffix). - * - * @exception IOException If file does not exist or is not unreadable. - */ - public static boolean testCompressedARCFile(File arcFile) - throws IOException { - return testCompressedARCFile(arcFile, false); - } - - /** - * Check file is compressed and in ARC GZIP format. - * - * @param arcFile File to test if its Internet Archive ARC file - * GZIP compressed. - * @param skipSuffixCheck Set to true if we're not to test on the - * '.arc.gz' suffix. - * - * @return True if this is an Internet Archive GZIP'd ARC file (It begins - * w/ the Internet Archive GZIP header). - * - * @exception IOException If file does not exist or is not unreadable. - */ - public static boolean testCompressedARCFile(File arcFile, - boolean skipSuffixCheck) - throws IOException { - boolean compressedARCFile = false; - FileUtils.assertReadable(arcFile); - if(!skipSuffixCheck && !arcFile.getName().toLowerCase() - .endsWith(COMPRESSED_ARC_FILE_EXTENSION)) { - return compressedARCFile; - } - - final InputStream is = new FileInputStream(arcFile); - try { - compressedARCFile = testCompressedARCStream(is); - } finally { - is.close(); - } - return compressedARCFile; - } - - public static boolean isARCSuffix(final String arcName) { - return (arcName == null)? - false: - (arcName.toLowerCase().endsWith(DOT_COMPRESSED_ARC_FILE_EXTENSION))? - true: - (arcName.toLowerCase().endsWith(DOT_ARC_FILE_EXTENSION))? - true: false; - } - - /** - * Tests passed stream is gzip stream by reading in the HEAD. - * Does not reposition the stream. That is left up to the caller. - * @param is An InputStream. - * @return True if compressed stream. - * @throws IOException - */ - public static boolean testCompressedARCStream(final InputStream is) - throws IOException { - boolean compressedARCFile = false; - GzipHeader gh = null; - try { - gh = new GzipHeader(is); - } catch (NoGzipMagicException e) { - return false; - } - - byte[] fextra = gh.getFextra(); - // Now make sure following bytes are IA GZIP comment. - // First check length. ARC_GZIP_EXTRA_FIELD includes length - // so subtract two and start compare to ARC_GZIP_EXTRA_FIELD - // at +2. - // some Alexa ARC files gzip extra fields have changed slightly - // after the first two bytes, so we'll just look for the 'LX' - // extension for valid IA ARC files. - if (fextra != null) { - if (fextra.length >= ARC_GZIP_EXTRA_FIELD.length - 2) { - if (fextra[0] == ARC_GZIP_EXTRA_FIELD[2] && - fextra[1] == ARC_GZIP_EXTRA_FIELD[3]) { - compressedARCFile = true; - } - } - } else { - // Some old arcs don't have an extra header at all, but they're still compressed - compressedARCFile = true; - } - - return compressedARCFile; - } - - /** - * Uncompressed arc file reader. - * @author stack - */ - public class UncompressedARCReader extends ARCReader { - /** - * Constructor. - * @param f Uncompressed arcfile to read. - * @throws IOException - */ - public UncompressedARCReader(final File f) - throws IOException { - this(f, 0); - } - - /** - * Constructor. - * - * @param f Uncompressed arcfile to read. - * @param offset Offset at which to position ARCReader. - * @throws IOException - */ - public UncompressedARCReader(final File f, final long offset) - throws IOException { - // Arc file has been tested for existence by time it has come - // to here. - setIn(new CountingInputStream(getInputStream(f, offset))); - getIn().skip(offset); - initialize(f.getAbsolutePath()); - } - - /** - * Constructor. - * - * @param f Uncompressed arc to read. - * @param is InputStream. - */ - public UncompressedARCReader(final String f, final InputStream is) { - // Arc file has been tested for existence by time it has come - // to here. - setIn(new CountingInputStream(is)); - initialize(f); - } - } - - /** - * Compressed arc file reader. - * - * @author stack - */ - public class CompressedARCReader extends ARCReader { - - /** - * Constructor. - * - * @param f - * Compressed arcfile to read. - * @throws IOException - */ - public CompressedARCReader(final File f) throws IOException { - this(f, 0); - } - - /** - * Constructor. - * - * @param f Compressed arcfile to read. - * @param offset Position at where to start reading file. - * @throws IOException - */ - public CompressedARCReader(final File f, final long offset) - throws IOException { - // Arc file has been tested for existence by time it has come - // to here. - setIn(new GZIPMembersInputStream(getInputStream(f, offset))); - ((GZIPMembersInputStream)getIn()).compressedSeek(offset); - setCompressed((offset == 0)); // TODO: does this make sense??? - initialize(f.getAbsolutePath()); - } - - /** - * Constructor. - * - * @param f Compressed arcfile. - * @param is InputStream to use. - * @throws IOException - */ - public CompressedARCReader(final String f, final InputStream is, - final boolean atFirstRecord) - throws IOException { - // Arc file has been tested for existence by time it has come - // to here. - setIn(new GZIPMembersInputStream(is)); - setCompressed(true); - setAlignedOnFirstRecord(atFirstRecord); - initialize(f); - } - - /** - * Get record at passed offset. - * - * @param offset - * Byte index into arcfile at which a record starts. - * @return An ARCRecord reference. - * @throws IOException - */ - public ARCRecord get(long offset) throws IOException { - cleanupCurrentRecord(); - ((GZIPMembersInputStream)getIn()).compressedSeek(offset); - return createArchiveRecord(getIn(), offset); - } - - public Iterator iterator() { - /** - * Override ARCRecordIterator so can base returned iterator on - * GzippedInputStream iterator. - */ - return new ArchiveRecordIterator() { - private GZIPMembersInputStream gis = - (GZIPMembersInputStream)getIn(); - - private Iterator gzipIterator = this.gis.memberIterator(); - - protected boolean innerHasNext() { - return this.gzipIterator.hasNext(); - } - - protected ArchiveRecord innerNext() throws IOException { - InputStream is = this.gzipIterator.next(); - return createArchiveRecord(is, Math.max(gis.getCurrentMemberStart(), gis.getCurrentMemberEnd())); - } - }; - } - - protected void gotoEOR(ArchiveRecord rec) throws IOException { - int c; - while ((c = getIn().read())==LINE_SEPARATOR); - if(c==-1) { - return; - } - long skipped = 1; - while (getIn().read()>-1) { - skipped++; - } - // Report on system error the number of unexpected characters - // at the end of this record. - ArchiveRecordHeader meta = (getCurrentRecord() != null)? - rec.getHeader(): null; - String message = "Record STARTING at " + - ((GZIPMembersInputStream)getIn()).getCurrentMemberStart() + - " has " + skipped + " trailing byte(s): " + - ((meta != null)? meta.toString(): ""); - if (isStrict()) { - throw new IOException(message); - } - logStdErr(Level.WARNING, message); - } - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/arc/ARCRecord.java b/commons/src/main/java/org/archive/io/arc/ARCRecord.java deleted file mode 100644 index 21bea07c..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCRecord.java +++ /dev/null @@ -1,835 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.StatusLine; -import org.apache.commons.httpclient.util.EncodingUtil; -import org.apache.commons.lang.StringUtils; -import org.archive.io.ArchiveRecord; -import org.archive.io.ArchiveRecordHeader; -import org.archive.io.RecoverableIOException; -import org.archive.util.InetAddressUtil; -import org.archive.util.LaxHttpParser; -import org.archive.util.TextUtils; - -/** - * An ARC file record. - * Does not compass the ARCRecord metadata line, just the record content. - * @author stack - */ -public class ARCRecord extends ArchiveRecord implements ARCConstants { - /** - * Http status line object. - * - * May be null if record is not http. - */ - private StatusLine httpStatus = null; - - /** - * Http header bytes. - * - * If non-null and bytes available, give out its contents before we - * go back to the underlying stream. - */ - private InputStream httpHeaderStream = null; - - /** - * Http headers. - * - * Only populated after reading of headers. - */ - private Header [] httpHeaders = null; - - /** - * Array of field names. - * - * Used to initialize headerFieldNameKeys. - */ - private final String [] headerFieldNameKeysArray = { - URL_FIELD_KEY, - IP_HEADER_FIELD_KEY, - DATE_FIELD_KEY, - MIMETYPE_FIELD_KEY, - LENGTH_FIELD_KEY - }; - - /** - * An array of the header field names found in the ARC file header on - * the 3rd line. - * - * We used to read these in from the arc file first record 3rd line but - * now we hardcode them for sake of improved performance. - */ - private final List headerFieldNameKeys = - Arrays.asList(this.headerFieldNameKeysArray); - - /** - * Http header bytes read while trying to read http header - */ - public long httpHeaderBytesRead = -1; - - /** - * record length from metadata line - */ - public long recordDeclaredLength; - - /** - * null if source was not compressed - */ - public long compressedBytes; - - /** - * actual payload data (not including trailing newline), - * should match record-declared-length - */ - public long uncompressedBytes; - - /** - * content-length header, iff HTTP and present, null otherwise - */ - public long httpPayloadDeclaredLength; - - /** - * actual http payload length, should match http-payload-declared-length - */ - public long httpPayloadActualLength; - - /** - * errors encountered reading record - */ - public List errors = new ArrayList(); - - /** - * verbatim ARC record header string - */ - private String headerString; - public String getHeaderString() { - return this.headerString; - } - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the record this instance - * is to represent. - * @param metaData Meta data. - * @throws IOException - */ - public ARCRecord(InputStream in, ArchiveRecordHeader metaData) - throws IOException { - this(in, metaData, 0, true, false, true); - } - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the record this instance - * is to represent. - * @param metaData Meta data. - * @param bodyOffset Offset into the body. Usually 0. - * @param digest True if we're to calculate digest for this record. Not - * digesting saves about ~15% of cpu during an ARC parse. - * @param strict Be strict parsing (Parsing stops if ARC inproperly - * formatted). - * @param parseHttpHeaders True if we are to parse HTTP headers. Costs - * about ~20% of CPU during an ARC parse. - * @throws IOException - */ - public ARCRecord(InputStream in, ArchiveRecordHeader metaData, - int bodyOffset, boolean digest, boolean strict, - final boolean parseHttpHeaders) - throws IOException { - super(in, metaData, bodyOffset, digest, strict); - if (parseHttpHeaders) { - this.httpHeaderStream = readHttpHeader(); - } - } - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the records metadata - * this instance is to represent. - * @param identifier Identifier for this the hosting Reader. - * @param offset Current offset into in (Used to keep - * position properly aligned). Usually 0. - * @param digest True if we're to calculate digest for this record. Not - * digesting saves about ~15% of cpu during an ARC parse. - * @param strict Be strict parsing (Parsing stops if ARC inproperly - * formatted). - * @param parseHttpHeaders True if we are to parse HTTP headers. Costs - * about ~20% of CPU during an ARC parse. - * @param isAllignedOnFirstRecord True if this is the first record to be - * read from an archive - * @param String version Version information to be returned to the - * ARCReader constructing this record - * - * @throws IOException - */ - public ARCRecord(InputStream in, final String identifier, - final long offset, boolean digest, boolean strict, - final boolean parseHttpHeaders, - final boolean isAlignedOnFirstRecord, String version) - throws IOException { - super(in, null, 0, digest, strict); - setHeader(parseHeaders(in, identifier, offset, strict, isAlignedOnFirstRecord, version)); - if (parseHttpHeaders) { - this.httpHeaderStream = readHttpHeader(); - } - } - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the records metadata - * this instance is to represent. - * @param identifier Identifier for this the hosting Reader. - * @param offset Current offset into in (Used to keep - * position properly aligned). Usually 0. - * @param digest True if we're to calculate digest for this record. Not - * digesting saves about ~15% of cpu during an ARC parse. - * @param strict Be strict parsing (Parsing stops if ARC inproperly - * formatted). - * @param parseHttpHeaders True if we are to parse HTTP headers. Costs - * about ~20% of CPU during an ARC parse. - * - * @throws IOException - */ - public ARCRecord(InputStream in, final String identifier, - final long offset, boolean digest, boolean strict, - final boolean parseHttpHeaders) - throws IOException { - this(in, identifier, offset, digest, strict, parseHttpHeaders, - false, null); - } - - private ArchiveRecordHeader parseHeaders(final InputStream in, - final String identifier, final long offset, final boolean strict, - final boolean isAlignedOnFirstRecord, String version) - throws IOException { - - ArrayList firstLineValues = new ArrayList(20); - getTokenizedHeaderLine(in, firstLineValues); - - int bodyOffset = 0; - if (offset == 0 && isAlignedOnFirstRecord) { - // If offset is zero and we were aligned at first record on - // creation (See #alignedOnFirstRecord for more on this), then no - // records have been read yet and we're reading our first one, the - // record of ARC file meta info. Its special. In ARC versions - // 1.x, first record has three lines of meta info. We've just read - // the first line. There are two more. The second line has misc. - // info. We're only interested in the first field, the version - // number. The third line is the list of field names. Here's what - // ARC file version 1.x meta content looks like: - // - // filedesc://testIsBoundary-JunitIAH200401070157520.arc 0.0.0.0 \\ - // 20040107015752 text/plain 77 - // 1 0 InternetArchive - // URL IP-address Archive-date Content-type Archive-length - // - ArrayList secondLineValues = new ArrayList(20); - bodyOffset += getTokenizedHeaderLine(in, secondLineValues); - version = ((String)secondLineValues.get(0) + - "." + (String)secondLineValues.get(1)); - // Just read over the 3rd line. We used to parse it and use - // values found here but now we just hardcode them to avoid - // having to read this 3rd line even for random arc file accesses. - bodyOffset += getTokenizedHeaderLine(in, null); - // this.position = bodyOffset; - } - setBodyOffset(bodyOffset); - - return computeMetaData(this.headerFieldNameKeys, firstLineValues, version, offset, identifier); - } - - /** - * Get a record header line as list of tokens. - * - * We keep reading till we find a LINE_SEPARATOR or we reach the end - * of file w/o finding a LINE_SEPARATOR or the line length is crazy. - * - * @param stream InputStream to read from. - * @param list Empty list that gets filled w/ string tokens. - * @return Count of characters read. - * @exception IOException If problem reading stream or no line separator - * found or EOF before EOL or we didn't get minimum header fields. - */ - private int getTokenizedHeaderLine(final InputStream stream, - List list) throws IOException { - // Preallocate usual line size. - StringBuilder buffer = new StringBuilder(2048 + 20); - int read = 0; - int previous = -1; - for (int c = -1; true;) { - previous = c; - c = stream.read(); - if (c == -1) { - throw new RecoverableIOException("Hit EOF before header EOL."); - } - c &= 0xff; - read++; - if (read > MAX_HEADER_LINE_LENGTH) { - throw new IOException("Header line longer than max allowed " + - " -- " + String.valueOf(MAX_HEADER_LINE_LENGTH) + - " -- or passed buffer doesn't contain a line (Read: " + - buffer.length() + "). Here's" + - " some of what was read: " + - buffer.substring(0, Math.min(buffer.length(), 256))); - } - - if (c == LINE_SEPARATOR) { - if (buffer.length() == 0) { - // Empty line at start of buffer. Skip it and try again. - continue; - } - - if (list != null) { - list.add(buffer.toString()); - } - // LOOP TERMINATION. - break; - } else if (c == HEADER_FIELD_SEPARATOR) { - if (!isStrict() && previous == HEADER_FIELD_SEPARATOR) { - // Early ARCs sometimes had multiple spaces between fields. - continue; - } - if (list != null) { - list.add(buffer.toString()); - } - // reset to empty - buffer.setLength(0); - } else { - buffer.append((char)c); - } - } - - // List must have at least 3 elements in it and no more than 10. If - // it has other than this, then bogus parse. - if (list != null && (list.size() < 3 || list.size() > 100)) { - throw new IOException("Unparseable header line: " + list); - } - - // save verbatim header String - this.headerString = StringUtils.join(list," "); - - return read; - } - - /** - * Compute metadata fields. - * - * Here we check the meta field has right number of items in it. - * - * @param keys Keys to use composing headerFields map. - * @param values Values to set into the headerFields map. - * @param v The version of this ARC file. - * @param offset Offset into arc file. - * - * @return Metadata structure for this record. - * - * @exception IOException If no. of keys doesn't match no. of values. - */ - private ARCRecordMetaData computeMetaData(List keys, - List values, String v, long offset, final String identifier) - throws IOException { - if (keys.size() != values.size()) { - List originalValues = values; - if (!isStrict()) { - values = fixSpaceInURL(values, keys.size()); - // If values still doesn't match key size, try and do - // further repair. - if (keys.size() != values.size()) { - // Early ARCs had a space in mimetype. - if (values.size() == (keys.size() + 1) && - values.get(4).toLowerCase().startsWith("charset=")) { - List nuvalues = - new ArrayList(keys.size()); - nuvalues.add(0, values.get(0)); - nuvalues.add(1, values.get(1)); - nuvalues.add(2, values.get(2)); - nuvalues.add(3, values.get(3) + values.get(4)); - nuvalues.add(4, values.get(5)); - values = nuvalues; - } else if((values.size() + 1) == keys.size() && - isLegitimateIPValue(values.get(1)) && - isDate(values.get(2)) && isNumber(values.get(3))) { - // Mimetype is empty. - List nuvalues = - new ArrayList(keys.size()); - nuvalues.add(0, values.get(0)); - nuvalues.add(1, values.get(1)); - nuvalues.add(2, values.get(2)); - nuvalues.add(3, "-"); - nuvalues.add(4, values.get(3)); - values = nuvalues; - } - } - } - if (keys.size() != values.size()) { - throw new IOException("Size of field name keys does" + - " not match count of field values: " + values); - } - // Note that field was fixed on stderr. - System.err.println(Level.WARNING.toString() + "Fixed spaces in metadata line at " + - "offset " + offset + - " Original: " + originalValues + ", New: " + values); - } - - Map headerFields = - new HashMap(keys.size() + 2); - for (int i = 0; i < keys.size(); i++) { - headerFields.put(keys.get(i), values.get(i)); - } - - // Add a check for tabs in URLs. If any, replace with '%09'. - // See https://sourceforge.net/tracker/?group_id=73833&atid=539099&func=detail&aid=1010966, - // [ 1010966 ] crawl.log has URIs with spaces in them. - String url = (String)headerFields.get(URL_FIELD_KEY); - if (url != null && url.indexOf('\t') >= 0) { - headerFields.put(URL_FIELD_KEY, - TextUtils.replaceAll("\t", url, "%09")); - } - - headerFields.put(VERSION_FIELD_KEY, v); - headerFields.put(ABSOLUTE_OFFSET_KEY, new Long(offset)); - - return new ARCRecordMetaData(identifier, headerFields); - } - - /** - * Fix space in URLs. - * The ARCWriter used to write into the ARC URLs with spaces in them. - * See [ 1010966 ] - * crawl.log has URIs with spaces in them. - * This method does fix up on such headers converting all spaces found - * to '%20'. - * @param values List of metadata values. - * @param requiredSize Expected size of resultant values list. - * @return New list if we successfully fixed up values or original if - * fixup failed. - */ - private List fixSpaceInURL(List values, int requiredSize) { - // Do validity check. 3rd from last is a date of 14 numeric - // characters. The 4th from last is IP, all before the IP - // should be concatenated together with a '%20' joiner. - // In the below, '4' is 4th field from end which has the IP. - if (!(values.size() > requiredSize) || values.size() < 4) { - return values; - } - // Test 3rd field is valid date. - if (!isDate((String) values.get(values.size() - 3))) { - return values; - } - - // Test 4th field is valid IP. - if (!isLegitimateIPValue((String) values.get(values.size() - 4))) { - return values; - } - - List newValues = new ArrayList(requiredSize); - StringBuffer url = new StringBuffer(); - for (int i = 0; i < (values.size() - 4); i++) { - if (i > 0) { - url.append("%20"); - } - url.append(values.get(i)); - } - newValues.add(url.toString()); - for (int i = values.size() - 4; i < values.size(); i++) { - newValues.add(values.get(i)); - } - return newValues; - } - - private boolean isDate(final String date) { - if (date.length() != 14) { - return false; - } - return isNumber(date); - } - - private boolean isNumber(final String n) { - for (int i = 0; i < n.length(); i++) { - if (!Character.isDigit(n.charAt(i))) { - return false; - } - } - return true; - } - - private boolean isLegitimateIPValue(final String ip) { - if ("-".equals(ip)) { - return true; - } - Matcher m = InetAddressUtil.IPV4_QUADS.matcher(ip); - return m != null && m.matches(); - } - - /** - * Skip over the the http header if one present. - * - * Subsequent reads will get the body. - * - *

Calling this method in the midst of reading the header - * will make for strange results. Otherwise, safe to call - * at any time though before reading any of the arc record - * content is only time that it makes sense. - * - *

After calling this method, you can call - * {@link #getHttpHeaders()} to get the read http header. - * - * @throws IOException - */ - public void skipHttpHeader() throws IOException { - if (this.httpHeaderStream != null) { - // Empty the httpHeaderStream - for (int available = this.httpHeaderStream.available(); - this.httpHeaderStream != null && - (available = this.httpHeaderStream.available()) > 0;) { - // We should be in this loop once only we should only do this - // buffer allocation once. - byte [] buffer = new byte[available]; - // The read nulls out httpHeaderStream when done with it so - // need check for null in the loop control line. - read(buffer, 0, available); - } - } - } - - public void dumpHttpHeader() throws IOException { - if (this.httpHeaderStream == null) { - return; - } - // Dump the httpHeaderStream to STDOUT - for (int available = this.httpHeaderStream.available(); - this.httpHeaderStream != null - && (available = this.httpHeaderStream.available()) > 0;) { - // We should be in this loop only once and should do this - // buffer allocation once. - byte[] buffer = new byte[available]; - // The read nulls out httpHeaderStream when done with it so - // need check for null in the loop control line. - int read = read(buffer, 0, available); - System.out.write(buffer, 0, read); - } - } - - /** - * Read http header if present. Technique borrowed from HttpClient HttpParse - * class. set errors when found. - * - * @return ByteArrayInputStream with the http header in it or null if no - * http header. - * @throws IOException - */ - private InputStream readHttpHeader() throws IOException { - - // this can be helpful when simply iterating over records, - // looking for problems. - Logger logger = Logger.getLogger(this.getClass().getName()); - ArchiveRecordHeader h = this.getHeader(); - - // If judged a record that doesn't have an http header, return - // immediately. - String url = getHeader().getUrl(); - if(!url.startsWith("http") || - getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) { - return null; - } - - String statusLine; - byte[] statusBytes; - int eolCharCount = 0; - int errOffset = 0; - - // Read status line, skipping any errant http headers found before it - // This allows a larger number of 'corrupt' arcs -- where headers were accidentally - // inserted before the status line to be readable - while (true) { - statusBytes = LaxHttpParser.readRawLine(getIn()); - eolCharCount = getEolCharsCount(statusBytes); - if (eolCharCount <= 0) { - throw new RecoverableIOException( - "Failed to read http status where one was expected: " - + ((statusBytes == null) ? "" : new String(statusBytes))); - } - - statusLine = EncodingUtil.getString(statusBytes, 0, - statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING); - - // If a null or DELETED break immediately - if ((statusLine == null) || statusLine.startsWith("DELETED")) { - break; - } - - // If it's actually the status line, break, otherwise continue skipping any - // previous header values - if (!statusLine.contains(":") && StatusLine.startsWithHTTP(statusLine)) { - break; - } - - // Add bytes read to error "offset" to add to position - errOffset += statusBytes.length; - } - - if (errOffset > 0) { - this.incrementPosition(errOffset); - } - - if ((statusLine == null) || - !StatusLine.startsWithHTTP(statusLine)) { - if (statusLine.startsWith("DELETED")) { - // Some old ARCs have deleted records like following: - // http://vireo.gatech.edu:80/ebt-bin/nph-dweb/dynaweb/SGI_Developer/SGITCL_PG/@Generic__BookTocView/11108%3Btd%3D2 130.207.168.42 19991010131803 text/html 29202 - // DELETED_TIME=20000425001133_DELETER=Kurt_REASON=alexalist - // (follows ~29K spaces) - // For now, throw a RecoverableIOException so if iterating over - // records, we keep going. TODO: Later make a legitimate - // ARCRecord from the deleted record rather than throw - // exception. - throw new DeletedARCRecordIOException(statusLine); - } else { - this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_INVALID); - } - } - - try { - this.httpStatus = new StatusLine(statusLine); - } catch(IOException e) { - logger.warning(e.getMessage() + " at offset: " + h.getOffset()); - this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_EXCEPTION); - } - - // Save off all bytes read. Keep them as bytes rather than - // convert to strings so we don't have to worry about encodings - // though this should never be a problem doing http headers since - // its all supposed to be ascii. - ByteArrayOutputStream baos = - new ByteArrayOutputStream(statusBytes.length + 4 * 1024); - baos.write(statusBytes); - - // Now read rest of the header lines looking for the separation - // between header and body. - for (byte [] lineBytes = null; true;) { - lineBytes = LaxHttpParser.readRawLine(getIn()); - eolCharCount = getEolCharsCount(lineBytes); - if (eolCharCount <= 0) { - if (getIn().available() == 0) { - httpHeaderBytesRead += statusBytes.length; - logger.warning("HTTP header truncated at offset: " + h.getOffset()); - this.errors.add(ArcRecordErrors.HTTP_HEADER_TRUNCATED); - this.setEor(true); - break; - } else { - throw new IOException("Failed reading http headers: " + - ((lineBytes != null)? new String(lineBytes): null)); - } - } else { - httpHeaderBytesRead += lineBytes.length; - } - // Save the bytes read. - baos.write(lineBytes); - if ((lineBytes.length - eolCharCount) <= 0) { - // We've finished reading the http header. - break; - } - } - - byte [] headerBytes = baos.toByteArray(); - // Save off where body starts. - this.getMetaData().setContentBegin(headerBytes.length); - ByteArrayInputStream bais = - new ByteArrayInputStream(headerBytes); - if (!bais.markSupported()) { - throw new IOException("ByteArrayInputStream does not support mark"); - } - bais.mark(headerBytes.length); - // Read the status line. Don't let it into the parseHeaders function. - // It doesn't know what to do with it. - bais.read(statusBytes, 0, statusBytes.length); - this.httpHeaders = LaxHttpParser.parseHeaders(bais, - ARCConstants.DEFAULT_ENCODING); - this.getMetaData().setStatusCode(Integer.toString(getStatusCode())); - bais.reset(); - return bais; - } - - private static class DeletedARCRecordIOException - extends RecoverableIOException { - private static final long serialVersionUID = 1L; - - public DeletedARCRecordIOException(final String reason) { - super(reason); - } - } - - /** - * Return status code for this record. - * - * This method will return -1 until the http header has been read. - * @return Status code. - */ - public int getStatusCode() { - return (this.httpStatus == null)? -1: this.httpStatus.getStatusCode(); - } - - /** - * @param bytes Array of bytes to examine for an EOL. - * @return Count of end-of-line characters or zero if none. - */ - private int getEolCharsCount(byte [] bytes) { - int count = 0; - if (bytes != null && bytes.length >=1 && - bytes[bytes.length - 1] == '\n') { - count++; - if (bytes.length >=2 && bytes[bytes.length -2] == '\r') { - count++; - } - } - return count; - } - - /** - * @return Meta data for this record. - */ - public ARCRecordMetaData getMetaData() { - return (ARCRecordMetaData)getHeader(); - } - - /** - * @return http headers (Only available after header has been read). - */ - public Header [] getHttpHeaders() { - return this.httpHeaders; - } - - /** - * @return ArcRecordErrors encountered when reading - */ - public List getErrors() { - return this.errors; - } - - /** - * @return true if ARC record errors found - */ - public boolean hasErrors() { - return !this.errors.isEmpty(); - } - - /** - * @return Next character in this ARCRecord's content else -1 if at end of - * this record. - * @throws IOException - */ - public int read() throws IOException { - int c = -1; - if (this.httpHeaderStream != null && - (this.httpHeaderStream.available() > 0)) { - // If http header, return bytes from it before we go to underlying - // stream. - c = this.httpHeaderStream.read(); - // If done with the header stream, null it out. - if (this.httpHeaderStream.available() <= 0) { - this.httpHeaderStream = null; - } - incrementPosition(); - } else { - c = super.read(); - } - return c; - } - - public int read(byte [] b, int offset, int length) throws IOException { - int read = -1; - if (this.httpHeaderStream != null && - (this.httpHeaderStream.available() > 0)) { - // If http header, return bytes from it before we go to underlying - // stream. - read = Math.min(length, this.httpHeaderStream.available()); - if (read == 0) { - read = -1; - } else { - read = this.httpHeaderStream.read(b, offset, read); - } - // If done with the header stream, null it out. - if (this.httpHeaderStream.available() <= 0) { - this.httpHeaderStream = null; - } - incrementPosition(read); - } else { - read = super.read(b, offset, length); - } - return read; - } - - /** - * @return Offset at which the body begins (Only known after - * header has been read) or -1 if none or if we haven't read - * headers yet. Usually length of HTTP headers (does not include ARC - * metadata line length). - */ - public int getBodyOffset() { - return this.getMetaData().getContentBegin(); - } - - @Override - protected String getIp4Cdx(ArchiveRecordHeader h) { - String result = null; - if (h instanceof ARCRecordMetaData) { - result = ((ARCRecordMetaData)h).getIp(); - } - return (result != null)? result: super.getIp4Cdx(h); - } - - @Override - protected String getStatusCode4Cdx(ArchiveRecordHeader h) { - String result = null; - if (h instanceof ARCRecordMetaData) { - result = ((ARCRecordMetaData) h).getStatusCode(); - } - return (result != null) ? result: super.getStatusCode4Cdx(h); - } - - @Override - protected String getDigest4Cdx(ArchiveRecordHeader h) { - String result = null; - if (h instanceof ARCRecordMetaData) { - result = ((ARCRecordMetaData) h).getDigest(); - } - return (result != null) ? result: super.getDigest4Cdx(h); - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/arc/ARCRecordMetaData.java b/commons/src/main/java/org/archive/io/arc/ARCRecordMetaData.java deleted file mode 100644 index 3f617041..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCRecordMetaData.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.io.File; -import java.io.IOException; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.archive.io.ArchiveRecordHeader; - - -/** - * An immutable class to hold an ARC record meta data. - * - * @author stack - */ -public class ARCRecordMetaData implements ArchiveRecordHeader, ARCConstants { - /** - * Map of record header fields. - * - * We store all in a hashmap. This way we can hold version 1 or - * version 2 record meta data. - * - *

Keys are lowercase. - */ - protected Map headerFields = null; - - /** - * Digest for the record. - * - * Only available after the record has been read in totality. - */ - private String digest = null; - - /** - * Status for this request. - * - * There may be no status. - */ - private String statusCode = null; - - /** - * The arc this metadata came out. - * Descriptive String, either path or URL. - */ - private String arc = null; - - private int contentBegin = 0; - - /** - * Shut down the default constructor. - */ - protected ARCRecordMetaData() { - super(); - } - - /** - * Constructor. - * - * @param arc The arc file this metadata came out of. - * @param headerFields Hash of meta fields. - * - * @throws IOException - */ - public ARCRecordMetaData(final String arc, Map headerFields) - throws IOException { - // Make sure the minimum required fields are present, - for (Iterator i = REQUIRED_VERSION_1_HEADER_FIELDS.iterator(); - i.hasNext(); ) { - testRequiredField(headerFields, (String)i.next()); - } - this.headerFields = headerFields; - this.arc = arc; - } - - /** - * Test required field is present in hash. - * - * @param fields Map of fields. - * @param requiredField Field to test for. - * - * @exception IOException If required field is not present. - */ - protected void testRequiredField(Map fields, String requiredField) - throws IOException { - if (!fields.containsKey(requiredField)) { - throw new IOException("Required field " + requiredField + - " not in meta data."); - } - } - - /** - * Get the time when the record was harvested. - *

- * Returns the date in Heritrix 14 digit time format (UTC). See the - * {@link org.archive.util.ArchiveUtils} class for converting to Java - * dates. - * - * @return Header date in Heritrix 14 digit format. - * @see org.archive.util.ArchiveUtils#parse14DigitDate(String) - */ - public String getDate() { - return (String) this.headerFields.get(DATE_FIELD_KEY); - } - - /** - * @return Return length of the record. - */ - public long getLength() { - return Long.parseLong((String)this.headerFields. - get(LENGTH_FIELD_KEY)); - } - - /** - * @return Return Content-Length of the contents of the record - * Same as record length for arcs? TODO - */ - public long getContentLength() { - return getLength(); - } - - /** - * @return Header url. - */ - public String getUrl() { - return (String)this.headerFields.get(URL_FIELD_KEY); - } - - /** - * @return IP. - */ - public String getIp() - { - return (String)this.headerFields.get(IP_HEADER_FIELD_KEY); - } - - /** - * @return mimetype The mimetype that is in the ARC metaline -- NOT the http - * content-type content. - */ - public String getMimetype() { - return (String)this.headerFields.get(MIMETYPE_FIELD_KEY); - } - - /** - * @return Arcfile version. - */ - public String getVersion() { - return (String)this.headerFields.get(VERSION_FIELD_KEY); - } - - /** - * @return Offset into arcfile at which this record begins. - */ - public long getOffset() { - return ((Long)this.headerFields.get(ABSOLUTE_OFFSET_KEY)).longValue(); - } - - /** - * @param key Key to use looking up field value. - * @return value for passed key of null if no such entry. - */ - public Object getHeaderValue(String key) { - return this.headerFields.get(key); - } - - /** - * @return Header field name keys. - */ - public Set getHeaderFieldKeys() - { - return this.headerFields.keySet(); - } - - /** - * @return Map of header fields. - */ - public Map getHeaderFields() { - return this.headerFields; - } - - /** - * @return Returns identifier for ARC. - */ - public String getArc() { - return this.arc; - } - - /** - * @return Convenience method that does a - * return new File(this.arc) (Be aware this.arc is not always - * full path to an ARC file -- may be an URL). Test - * returned file for existence. - */ - public File getArcFile() { - return new File(this.arc); - } - - /** - * @return Returns the digest. - */ - public String getDigest() { - return this.digest; - } - - /** - * @param d The digest to set. - */ - public void setDigest(String d) { - this.digest = d; - } - - /** - * @return Returns the statusCode. May be null. - */ - public String getStatusCode() { - return this.statusCode; - } - - /** - * @param statusCode The statusCode to set. - */ - public void setStatusCode(String statusCode) { - this.statusCode = statusCode; - } - - public String toString() { - return ((this.arc != null)? this.arc: "") + - ": " + - ((this.headerFields != null)? this.headerFields.toString(): ""); - } - - public String getReaderIdentifier() { - return this.getArc(); - } - - public String getRecordIdentifier() { - return getDate() + "/" + getUrl(); - } - - public int getContentBegin() { - return this.contentBegin; - } - - protected void setContentBegin(final int offset) { - this.contentBegin = offset; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/arc/ARCUtils.java b/commons/src/main/java/org/archive/io/arc/ARCUtils.java deleted file mode 100644 index 88e0e3a1..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCUtils.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import it.unimi.dsi.fastutil.io.RepositionableStream; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; - -import org.archive.net.UURI; -import org.archive.util.zip.GzipHeader; -import org.archive.util.zip.NoGzipMagicException; - -public class ARCUtils implements ARCConstants { - /** - * @param pathOrUri Path or URI to extract arc filename from. - * @return Extracted arc file name. - * @throws URISyntaxException - */ - public static String parseArcFilename(final String pathOrUri) - throws URISyntaxException { - String path = pathOrUri; - if (UURI.hasScheme(pathOrUri)) { - URI url = new URI(pathOrUri); - path = url.getPath(); - } - return (new File(path)).getName(); - } - - /** - * @param arcFile File to test. - * @return True if arcFile is compressed ARC. - * @throws IOException - */ - public static boolean isCompressed(File arcFile) throws IOException { - return testCompressedARCFile(arcFile); - } - - /** - * Check file is compressed and in ARC GZIP format. - * - * @param arcFile File to test if its Internet Archive ARC file - * GZIP compressed. - * - * @return True if this is an Internet Archive GZIP'd ARC file (It begins - * w/ the Internet Archive GZIP header and has the - * COMPRESSED_ARC_FILE_EXTENSION suffix). - * - * @exception IOException If file does not exist or is not unreadable. - */ - public static boolean testCompressedARCFile(File arcFile) - throws IOException { - return testCompressedARCFile(arcFile, false); - } - - /** - * Check file is compressed and in ARC GZIP format. - * - * @param arcFile File to test if its Internet Archive ARC file - * GZIP compressed. - * @param skipSuffixCheck Set to true if we're not to test on the - * '.arc.gz' suffix. - * - * @return True if this is an Internet Archive GZIP'd ARC file (It begins - * w/ the Internet Archive GZIP header). - * - * @exception IOException If file does not exist or is not unreadable. - */ - public static boolean testCompressedARCFile(File arcFile, - boolean skipSuffixCheck) - throws IOException { - boolean compressedARCFile = false; - isReadable(arcFile); - if(!skipSuffixCheck && !arcFile.getName().toLowerCase() - .endsWith(COMPRESSED_ARC_FILE_EXTENSION)) { - return compressedARCFile; - } - - final InputStream is = new FileInputStream(arcFile); - try { - compressedARCFile = testCompressedARCStream(is); - } finally { - is.close(); - } - return compressedARCFile; - } - - /** - * Tests passed stream is gzip stream by reading in the HEAD. - * Does not reposition the stream. That is left up to the caller. - * @param is An InputStream. - * @return True if compressed stream. - * @throws IOException - */ - public static boolean testCompressedARCStream(final InputStream is) - throws IOException { - boolean compressedARCFile = false; - GzipHeader gh = null; - try { - gh = new GzipHeader(is); - } catch (NoGzipMagicException e ) { - return compressedARCFile; - } - - byte[] fextra = gh.getFextra(); - // Now make sure following bytes are IA GZIP comment. - // First check length. ARC_GZIP_EXTRA_FIELD includes length - // so subtract two and start compare to ARC_GZIP_EXTRA_FIELD - // at +2. - if (fextra != null && - ARC_GZIP_EXTRA_FIELD.length - 2 == fextra.length) { - compressedARCFile = true; - for (int i = 0; i < fextra.length; i++) { - if (fextra[i] != ARC_GZIP_EXTRA_FIELD[i + 2]) { - compressedARCFile = false; - break; - } - } - } - return compressedARCFile; - } - - /** - * Tests passed stream is gzip stream by reading in the HEAD. - * Does reposition of stream when done. - * @param rs An InputStream that is Repositionable. - * @return True if compressed stream. - * @throws IOException - */ - public static boolean testCompressedRepositionalStream( - final RepositionableStream rs) - throws IOException { - boolean compressedARCFile = false; - long p = rs.position(); - try { - compressedARCFile = testCompressedStream((InputStream)rs); - } finally { - rs.position(p); - } - return compressedARCFile; - } - - /** - * Tests passed stream is gzip stream by reading in the HEAD. - * Does reposition of stream when done. - * @param is An InputStream. - * @return True if compressed stream. - * @throws IOException - */ - public static boolean testCompressedStream(final InputStream is) - throws IOException { - boolean compressedARCFile = false; - try { - new GzipHeader(is); - compressedARCFile = true; - } catch (NoGzipMagicException e) { - return compressedARCFile; - } - return compressedARCFile; - } - - /** - * Check file is uncompressed ARC file. - * - * @param arcFile - * File to test if its Internet Archive ARC file uncompressed. - * - * @return True if this is an Internet Archive ARC file. - * - * @exception IOException - * If file does not exist or is not unreadable. - */ - public static boolean testUncompressedARCFile(File arcFile) - throws IOException { - boolean uncompressedARCFile = false; - isReadable(arcFile); - if(arcFile.getName().toLowerCase().endsWith(ARC_FILE_EXTENSION)) { - FileInputStream fis = new FileInputStream(arcFile); - try { - byte [] b = new byte[ARC_MAGIC_NUMBER.length()]; - int read = fis.read(b, 0, ARC_MAGIC_NUMBER.length()); - fis.close(); - if (read == ARC_MAGIC_NUMBER.length()) { - StringBuffer beginStr - = new StringBuffer(ARC_MAGIC_NUMBER.length()); - for (int i = 0; i < ARC_MAGIC_NUMBER.length(); i++) { - beginStr.append((char)b[i]); - } - - if (beginStr.toString(). - equalsIgnoreCase(ARC_MAGIC_NUMBER)) { - uncompressedARCFile = true; - } - } - } finally { - fis.close(); - } - } - - return uncompressedARCFile; - } - - - /** - * @param arcFile File to test. - * @exception IOException If file does not exist or is not unreadable. - */ - private static void isReadable(File arcFile) throws IOException { - if (!arcFile.exists()) { - throw new FileNotFoundException(arcFile.getAbsolutePath() + - " does not exist."); - } - - if (!arcFile.canRead()) { - throw new FileNotFoundException(arcFile.getAbsolutePath() + - " is not readable."); - } - } -} diff --git a/commons/src/main/java/org/archive/io/arc/ARCWriter.java b/commons/src/main/java/org/archive/io/arc/ARCWriter.java deleted file mode 100644 index b5825d50..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCWriter.java +++ /dev/null @@ -1,459 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.util.Iterator; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.archive.io.ReplayInputStream; -import org.archive.io.WriterPoolMember; -import org.archive.io.WriterPoolSettings; -import org.archive.util.ArchiveUtils; -import org.archive.util.DevUtils; -import org.archive.util.MimetypeUtils; - - -/** - * Write ARC files. - * - * Assumption is that the caller is managing access to this ARCWriter ensuring - * only one thread of control accessing this ARC file instance at any one time. - * - *

ARC files are described here: - * Arc - * File Format. This class does version 1 of the ARC file format. It also - * writes version 1.1 which is version 1 with data stuffed into the body of the - * first arc record in the file, the arc file meta record itself. - * - *

An ARC file is three lines of meta data followed by an optional 'body' and - * then a couple of '\n' and then: record, '\n', record, '\n', record, etc. - * If we are writing compressed ARC files, then each of the ARC file records is - * individually gzipped and concatenated together to make up a single ARC file. - * In GZIP terms, each ARC record is a GZIP member of a total gzip'd - * file. - * - *

The GZIPping of the ARC file meta data is exceptional. It is GZIPped - * w/ an extra GZIP header, a special Internet Archive (IA) extra header field - * (e.g. FEXTRA is set in the GZIP header FLG field and an extra field is - * appended to the GZIP header). The extra field has little in it but its - * presence denotes this GZIP as an Internet Archive gzipped ARC. See RFC1952 - * to learn about the GZIP header structure. - * - *

This class then does its GZIPping in the following fashion. Each GZIP - * member is written w/ a new instance of GZIPOutputStream -- actually - * ARCWriterGZIPOututStream so we can get access to the underlying stream. - * The underlying stream stays open across GZIPoutputStream instantiations. - * For the 'special' GZIPing of the ARC file meta data, we cheat by catching the - * GZIPOutputStream output into a byte array, manipulating it adding the - * IA GZIP header, before writing to the stream. - * - *

I tried writing a resettable GZIPOutputStream and could make it work w/ - * the SUN JDK but the IBM JDK threw NPE inside in the deflate.reset -- its zlib - * native call doesn't seem to like the notion of resetting -- so I gave up on - * it. - * - *

Because of such as the above and troubles with GZIPInputStream, we should - * write our own GZIP*Streams, ones that resettable and consious of gzip - * members. - * - *

This class will write until we hit >= maxSize. The check is done at - * record boundary. Records do not span ARC files. We will then close current - * file and open another and then continue writing. - * - *

TESTING: Here is how to test that produced ARC files are good - * using the - * alexa - * ARC c-tools: - *

- * % av_procarc hx20040109230030-0.arc.gz | av_ziparc > \
- *     /tmp/hx20040109230030-0.dat.gz
- * % av_ripdat /tmp/hx20040109230030-0.dat.gz > /tmp/hx20040109230030-0.cdx
- * 
- * Examine the produced cdx file to make sure it makes sense. Search - * for 'no-type 0'. If found, then we're opening a gzip record w/o data to - * write. This is bad. - * - *

You can also do gzip -t FILENAME and it will tell you if the - * ARC makes sense to GZIP. - * - *

While being written, ARCs have a '.open' suffix appended. - * - * @author stack - */ -public class ARCWriter extends WriterPoolMember implements ARCConstants, Closeable { - private static final Logger logger = - Logger.getLogger(ARCWriter.class.getName()); - - /** - * Metadata line pattern. - */ - private static final Pattern METADATA_LINE_PATTERN = - Pattern.compile("^\\S+ \\S+ \\S+ \\S+ \\S+(" + LINE_SEPARATOR + "?)$"); - - - /** - * Constructor. - * Takes a stream. Use with caution. There is no upperbound check on size. - * Will just keep writing. - * - * @param serialNo used to generate unique file name sequences - * @param out Where to write. - * @param arc File the out is connected to. - * @param cmprs Compress the content written. - * @param metadata File meta data. Can be null. Is list of File and/or - * String objects. - * @param a14DigitDate If null, we'll write current time. - * @throws IOException - */ - public ARCWriter(final AtomicInteger serialNo, final PrintStream out, - final File arc, final WriterPoolSettings settings) - throws IOException { - super(serialNo, out, arc, settings); - writeFirstRecord(ArchiveUtils.get14DigitDate()); - } - - /** - * Constructor. - * - * @param serialNo used to generate unique file name sequences - * @param settings all creation parameters - */ - public ARCWriter(final AtomicInteger serialNo, final WriterPoolSettings settings) { - super(serialNo, settings, ARC_FILE_EXTENSION); - - } - - protected String createFile() - throws IOException { - String name = super.createFile(); - writeFirstRecord(currentTimestamp); - return name; - } - - private void writeFirstRecord(final String ts) - throws IOException { - write(generateARCFileMetaData(ts)); - } - - /** - * Write out the ARCMetaData. - * - *

Generate ARC file meta data. Currently we only do version 1 of the - * ARC file formats or version 1.1 when metadata has been supplied (We - * write it into the body of the first record in the arc file). - * - *

Version 1 metadata looks roughly like this: - * - *

filedesc://testWriteRecord-JunitIAH20040110013326-2.arc 0.0.0.0 \\
-     *  20040110013326 text/plain 77
-     * 1 0 InternetArchive
-     * URL IP-address Archive-date Content-type Archive-length
-     * 
- * - *

If compress is set, then we generate a header that has been gzipped - * in the Internet Archive manner. Such a gzipping enables the FEXTRA - * flag in the FLG field of the gzip header. It then appends an extra - * header field: '8', '0', 'L', 'X', '0', '0', '0', '0'. The first two - * bytes are the length of the field and the last 6 bytes the Internet - * Archive header. To learn about GZIP format, see RFC1952. To learn - * about the Internet Archive extra header field, read the source for - * av_ziparc which can be found at - * alexa/vista/alexa-tools-1.2/src/av_ziparc.cc. - * - *

We do things in this roundabout manner because the java - * GZIPOutputStream does not give access to GZIP header fields. - * - * @param date Date to put into the ARC metadata; if 17-digit will be - * truncated to traditional 14-digits - * - * @return Byte array filled w/ the arc header. - * @throws IOException - */ - private byte [] generateARCFileMetaData(String date) - throws IOException { - if(date!=null && date.length()>14) { - date = date.substring(0,14); - } - int metadataBodyLength = getMetadataLength(); - // If metadata body, then the minor part of the version is '1' rather - // than '0'. - String metadataHeaderLinesTwoAndThree = - getMetadataHeaderLinesTwoAndThree("1 " + - ((metadataBodyLength > 0)? "1": "0")); - int recordLength = metadataBodyLength + - metadataHeaderLinesTwoAndThree.getBytes(DEFAULT_ENCODING).length; - String metadataHeaderStr = ARC_MAGIC_NUMBER + getBaseFilename() + - " 0.0.0.0 " + date + " text/plain " + recordLength + - metadataHeaderLinesTwoAndThree; - ByteArrayOutputStream metabaos = - new ByteArrayOutputStream(recordLength); - // Write the metadata header. - metabaos.write(metadataHeaderStr.getBytes(DEFAULT_ENCODING)); - // Write the metadata body, if anything to write. - if (metadataBodyLength > 0) { - writeMetaData(metabaos); - } - - // Write out a LINE_SEPARATORs to end this record. - metabaos.write(LINE_SEPARATOR); - - // Now get bytes of all just written and compress if flag set. - byte [] bytes = metabaos.toByteArray(); - - if(isCompressed()) { - // GZIP the header but catch the gzipping into a byte array so we - // can add the special IA GZIP header to the product. After - // manipulations, write to the output stream (The JAVA GZIP - // implementation does not give access to GZIP header. It - // produces a 'default' header only). We can get away w/ these - // maniupulations because the GZIP 'default' header doesn't - // do the 'optional' CRC'ing of the header. - byte [] gzippedMetaData = ArchiveUtils.gzip(bytes); - if (gzippedMetaData[3] != 0) { - throw new IOException("The GZIP FLG header is unexpectedly " + - " non-zero. Need to add smarter code that can deal " + - " when already extant extra GZIP header fields."); - } - // Set the GZIP FLG header to '4' which says that the GZIP header - // has extra fields. Then insert the alex {'L', 'X', '0', '0', '0, - // '0'} 'extra' field. The IA GZIP header will also set byte - // 9 (zero-based), the OS byte, to 3 (Unix). We'll do the same. - gzippedMetaData[3] = 4; - gzippedMetaData[9] = 3; - byte [] assemblyBuffer = new byte[gzippedMetaData.length + - ARC_GZIP_EXTRA_FIELD.length]; - // '10' in the below is a pointer past the following bytes of the - // GZIP header: ID1 ID2 CM FLG + MTIME(4-bytes) XFL OS. See - // RFC1952 for explaination of the abbreviations just used. - System.arraycopy(gzippedMetaData, 0, assemblyBuffer, 0, 10); - System.arraycopy(ARC_GZIP_EXTRA_FIELD, 0, assemblyBuffer, 10, - ARC_GZIP_EXTRA_FIELD.length); - System.arraycopy(gzippedMetaData, 10, assemblyBuffer, - 10 + ARC_GZIP_EXTRA_FIELD.length, gzippedMetaData.length - 10); - bytes = assemblyBuffer; - } - return bytes; - } - - public String getMetadataHeaderLinesTwoAndThree(String version) { - StringBuffer buffer = new StringBuffer(); - buffer.append(LINE_SEPARATOR); - buffer.append(version); - buffer.append(" InternetArchive"); - buffer.append(LINE_SEPARATOR); - buffer.append("URL IP-address Archive-date Content-type Archive-length"); - buffer.append(LINE_SEPARATOR); - return buffer.toString(); - } - - /** - * Write all metadata to passed baos. - * - * @param baos Byte array to write to. - * @throws UnsupportedEncodingException - * @throws IOException - */ - private void writeMetaData(ByteArrayOutputStream baos) - throws UnsupportedEncodingException, IOException { - if (settings.getMetadata() == null) { - return; - } - - for (Iterator i = settings.getMetadata().iterator(); - i.hasNext();) { - Object obj = i.next(); - if (obj instanceof String) { - baos.write(((String)obj).getBytes(DEFAULT_ENCODING)); - } else if (obj instanceof File) { - InputStream is = null; - try { - is = new BufferedInputStream( - new FileInputStream((File)obj)); - byte [] buffer = new byte[4096]; - for (int read = -1; (read = is.read(buffer)) != -1;) { - baos.write(buffer, 0, read); - } - } finally { - if (is != null) { - is.close(); - } - } - } else if (obj != null) { - logger.severe("Unsupported metadata type: " + obj); - } - } - return; - } - - /** - * @return Total length of metadata. - * @throws UnsupportedEncodingException - */ - private int getMetadataLength() - throws UnsupportedEncodingException { - int result = -1; - if (settings.getMetadata() == null) { - result = 0; - } else { - for (Iterator i = settings.getMetadata().iterator(); - i.hasNext();) { - Object obj = i.next(); - if (obj instanceof String) { - result += ((String)obj).getBytes(DEFAULT_ENCODING).length; - } else if (obj instanceof File) { - result += ((File)obj).length(); - } else { - logger.severe("Unsupported metadata type: " + obj); - } - } - } - return result; - } - - /** - * @deprecated use input-stream version directly instead - */ - public void write(String uri, String contentType, String hostIP, - long fetchBeginTimeStamp, long recordLength, - ByteArrayOutputStream baos) - throws IOException { - write(uri, contentType, hostIP, fetchBeginTimeStamp, recordLength, - new ByteArrayInputStream(baos.toByteArray()), false); - } - - public void write(String uri, String contentType, String hostIP, - long fetchBeginTimeStamp, long recordLength, InputStream in) - throws IOException { - write(uri,contentType,hostIP,fetchBeginTimeStamp,recordLength,in,true); - } - - /** - * Write a record with the given metadata/content. - * - * @param uri - * URI for metadata-line - * @param contentType - * MIME content-type for metadata-line - * @param hostIP - * IP for metadata-line - * @param fetchBeginTimeStamp - * timestamp for metadata-line - * @param recordLength - * length for metadata-line; also may be enforced - * @param in - * source InputStream for record content - * @param enforceLength - * whether to enforce the declared length; should be true - * unless intentionally writing bad records for testing - * @throws IOException - */ - public void write(String uri, String contentType, String hostIP, - long fetchBeginTimeStamp, long recordLength, InputStream in, - boolean enforceLength) throws IOException { - preWriteRecordTasks(); - try { - write(getMetaLine(uri, contentType, hostIP, fetchBeginTimeStamp, - recordLength).getBytes(UTF8)); - copyFrom(in, recordLength, enforceLength); - if (in instanceof ReplayInputStream) { - // check for consumption of entire recorded material - long remaining = ((ReplayInputStream) in).remaining(); - // Should be zero at this stage. If not, something is - // wrong. - if (remaining != 0) { - String message = "Gap between expected and actual: " - + remaining + LINE_SEPARATOR + DevUtils.extraInfo() - + " writing arc " - + this.getFile().getAbsolutePath(); - DevUtils.warnHandle(new Throwable(message), message); - throw new IOException(message); - } - } - write(LINE_SEPARATOR); - } finally { - postWriteRecordTasks(); - } - } - - /** - * @param uri - * @param contentType - * @param hostIP - * @param fetchBeginTimeStamp - * @param recordLength - * @return Metadata line for an ARCRecord made of passed components. - * @exception IOException - */ - protected String getMetaLine(String uri, String contentType, String hostIP, - long fetchBeginTimeStamp, long recordLength) - throws IOException { - if (fetchBeginTimeStamp <= 0) { - throw new IOException("Bogus fetchBeginTimestamp: " + - Long.toString(fetchBeginTimeStamp)); - } - - return validateMetaLine(createMetaline(uri, hostIP, - ArchiveUtils.get14DigitDate(fetchBeginTimeStamp), - MimetypeUtils.truncate(contentType), - Long.toString(recordLength))); - } - - public String createMetaline(String uri, String hostIP, - String timeStamp, String mimetype, String recordLength) { - return uri + HEADER_FIELD_SEPARATOR + hostIP + - HEADER_FIELD_SEPARATOR + timeStamp + - HEADER_FIELD_SEPARATOR + mimetype + - HEADER_FIELD_SEPARATOR + recordLength + LINE_SEPARATOR; - } - - /** - * Test that the metadata line is valid before writing. - * @param metaLineStr - * @throws IOException - * @return The passed in metaline. - */ - protected String validateMetaLine(String metaLineStr) - throws IOException { - if (metaLineStr.length() > MAX_METADATA_LINE_LENGTH) { - throw new IOException("Metadata line too long (" - + metaLineStr.length() + ">" + MAX_METADATA_LINE_LENGTH - + "): " + metaLineStr); - } - Matcher m = METADATA_LINE_PATTERN.matcher(metaLineStr); - if (!m.matches()) { - throw new IOException("Metadata line doesn't match expected" + - " pattern: " + metaLineStr); - } - return metaLineStr; - } -} diff --git a/commons/src/main/java/org/archive/io/arc/ARCWriterPool.java b/commons/src/main/java/org/archive/io/arc/ARCWriterPool.java deleted file mode 100644 index b55b3ed4..00000000 --- a/commons/src/main/java/org/archive/io/arc/ARCWriterPool.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.util.concurrent.atomic.AtomicInteger; - -import org.archive.io.WriterPool; -import org.archive.io.WriterPoolMember; -import org.archive.io.WriterPoolSettings; - - -/** - * A pool of ARCWriters. - * - * @author stack - */ -public class ARCWriterPool extends WriterPool { - /** - * Constructor - * - * @param settings Settings for this pool. - * @param poolMaximumActive - * @param poolMaximumWait - */ - public ARCWriterPool(final WriterPoolSettings settings, - final int poolMaximumActive, final int poolMaximumWait) { - this(new AtomicInteger(), settings, poolMaximumActive, poolMaximumWait); - } - - /** - * Constructor - * - * @param serial Used to generate unique filename sequences - * @param settings Settings for this pool. - * @param poolMaximumActive - * @param poolMaximumWait - */ - public ARCWriterPool(final AtomicInteger serial, - final WriterPoolSettings settings, - final int poolMaximumActive, final int poolMaximumWait) { - super(serial, settings, poolMaximumActive, poolMaximumWait); - } - - /* (non-Javadoc) - * @see org.archive.io.WriterPool#makeWriter() - */ - protected WriterPoolMember makeWriter() { - return new ARCWriter(serialNo, settings); - } - - - -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/arc/WriterPoolSettingsData.java b/commons/src/main/java/org/archive/io/arc/WriterPoolSettingsData.java deleted file mode 100644 index 7396f2d8..00000000 --- a/commons/src/main/java/org/archive/io/arc/WriterPoolSettingsData.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.arc; - -import java.io.File; -import java.util.List; - -import org.archive.io.WriterPoolSettings; - -public class WriterPoolSettingsData implements WriterPoolSettings { - protected long maxFileSizeBytes; - protected String prefix; - protected String template; - protected List outputDirs; - protected boolean compress; - protected List metadata; - protected boolean frequentFlushes = true; - protected int writeBufferSize = 16*1024; - - public WriterPoolSettingsData(String prefix, String template, - long maxFileSizeBytes, boolean compress, List outputDirs, - List metadata) { - super(); - this.maxFileSizeBytes = maxFileSizeBytes; - this.prefix = prefix; - this.template = template; - this.outputDirs = outputDirs; - this.compress = compress; - this.metadata = metadata; - } - - @Override - public boolean getCompress() { - return compress; - } - @Override - public long getMaxFileSizeBytes() { - return maxFileSizeBytes; - } - @Override - public List getMetadata() { - return metadata; - } - @Override - public List calcOutputDirs() { - return outputDirs; - } - @Override - public String getPrefix() { - return prefix; - } - @Override - public String getTemplate() { - return template; - } - @Override - public boolean getFrequentFlushes() { - return frequentFlushes; - } - @Override - public int getWriteBufferSize() { - return writeBufferSize; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/arc/package.html b/commons/src/main/java/org/archive/io/arc/package.html deleted file mode 100644 index d1798b80..00000000 --- a/commons/src/main/java/org/archive/io/arc/package.html +++ /dev/null @@ -1,9 +0,0 @@ - - - -org.archive.io.arc package - - -ARC file reading and writing. - - diff --git a/commons/src/main/java/org/archive/io/warc/WARCConstants.java b/commons/src/main/java/org/archive/io/warc/WARCConstants.java deleted file mode 100644 index 83cc8a6d..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCConstants.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -@Deprecated -public interface WARCConstants extends org.archive.format.warc.WARCConstants { -} diff --git a/commons/src/main/java/org/archive/io/warc/WARCReader.java b/commons/src/main/java/org/archive/io/warc/WARCReader.java deleted file mode 100644 index a34854ef..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCReader.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; -import org.apache.commons.lang.NotImplementedException; -import org.archive.io.ArchiveReader; -import org.archive.io.ArchiveRecord; - -/** - * WARCReader. - * Go via {@link WARCReaderFactory} to get instance. - * @author stack - * @version $Date: 2006-11-27 18:03:03 -0800 (Mon, 27 Nov 2006) $ $Version$ - */ -public class WARCReader extends ArchiveReader implements WARCConstants { - protected WARCReader() { - super(); - } - - @Override - protected void initialize(String i) { - super.initialize(i); - setVersion(WARC_VERSION); - } - - /** - * Skip over any trailing new lines at end of the record so we're lined up - * ready to read the next. - * @param record - * @throws IOException - */ - protected void gotoEOR(ArchiveRecord record) throws IOException { - if (record.available() != 0) { - throw new IOException("Record should be exhausted before coming " + - "in here"); - } - - // Records end in 2*CRLF. Suck it up. - readExpectedChar(getIn(), CRLF.charAt(0)); - readExpectedChar(getIn(), CRLF.charAt(1)); - readExpectedChar(getIn(), CRLF.charAt(0)); - readExpectedChar(getIn(), CRLF.charAt(1)); - } - - protected void readExpectedChar(final InputStream is, final int expected) - throws IOException { - int c = is.read(); - if (c != expected) { - throw new IOException("Unexpected character " + - Integer.toHexString(c) + "(Expecting " + - Integer.toHexString(expected) + ")"); - } - } - - /** - * Create new WARC record. - * Encapsulate housekeeping that has to do w/ creating new Record. - * @param is InputStream to use. - * @param offset Absolute offset into WARC file. - * @return A WARCRecord. - * @throws IOException - */ - protected WARCRecord createArchiveRecord(InputStream is, long offset) - throws IOException { - return (WARCRecord)currentRecord(new WARCRecord(is, - getReaderIdentifier(), offset, isDigest(), isStrict())); - } - - @Override - public void dump(boolean compress) - throws IOException, java.text.ParseException { - for (final Iterator i = iterator(); i.hasNext();) { - ArchiveRecord r = i.next(); - System.out.println(r.getHeader().toString()); - r.dump(); - System.out.println(); - } - } - - - @Override - public ArchiveReader getDeleteFileOnCloseReader(final File f) { - throw new NotImplementedException("TODO"); - } - - @Override - public String getDotFileExtension() { - return DOT_WARC_FILE_EXTENSION; - } - - @Override - public String getFileExtension() { - return WARC_FILE_EXTENSION; - } - - // Static methods follow. Mostly for command-line processing. - - /** - * - * @param formatter Help formatter instance. - * @param options Usage options. - * @param exitCode Exit code. - */ - private static void usage(HelpFormatter formatter, Options options, - int exitCode) { - formatter.printHelp("java org.archive.io.arc.WARCReader" + - " [--digest=true|false] \\\n" + - " [--format=cdx|cdxfile|dump|gzipdump]" + - " [--offset=#] \\\n[--strict] [--parse] WARC_FILE|WARC_URL", - options); - System.exit(exitCode); - } - - /** - * Write out the arcfile. - * - * @param reader - * @param format Format to use outputting. - * @throws IOException - * @throws java.text.ParseException - */ - protected static void output(WARCReader reader, String format) - throws IOException, java.text.ParseException { - if (!reader.output(format)) { - throw new IOException("Unsupported format: " + format); - } - } - - /** - * Generate a CDX index file for an ARC file. - * - * @param urlOrPath The ARC file to generate a CDX index for - * @throws IOException - * @throws java.text.ParseException - */ - public static void createCDXIndexFile(String urlOrPath) - throws IOException, java.text.ParseException { - WARCReader r = WARCReaderFactory.get(urlOrPath); - r.setStrict(false); - r.setDigest(true); - output(r, CDX_FILE); - } - - /** - * Command-line interface to WARCReader. - * - * Here is the command-line interface: - *

-     * usage: java org.archive.io.arc.WARCReader [--offset=#] ARCFILE
-     *  -h,--help      Prints this message and exits.
-     *  -o,--offset    Outputs record at this offset into arc file.
- * - *

Outputs using a pseudo-CDX format as described here: - * CDX - * Legent and here - * Example. - * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'. - * Hash is hard-coded straight SHA-1 hash of content. - * - * @param args Command-line arguments. - * @throws ParseException Failed parse of the command line. - * @throws IOException - * @throws java.text.ParseException - */ - public static void main(String [] args) - throws ParseException, IOException, java.text.ParseException { - Options options = getOptions(); - PosixParser parser = new PosixParser(); - CommandLine cmdline = parser.parse(options, args, false); - @SuppressWarnings("unchecked") - List cmdlineArgs = cmdline.getArgList(); - Option [] cmdlineOptions = cmdline.getOptions(); - HelpFormatter formatter = new HelpFormatter(); - - // If no args, print help. - if (cmdlineArgs.size() <= 0) { - usage(formatter, options, 0); - } - - // Now look at options passed. - long offset = -1; - boolean digest = false; - boolean strict = false; - String format = CDX; - for (int i = 0; i < cmdlineOptions.length; i++) { - switch(cmdlineOptions[i].getId()) { - case 'h': - usage(formatter, options, 0); - break; - - case 'o': - offset = - Long.parseLong(cmdlineOptions[i].getValue()); - break; - - case 's': - strict = true; - break; - - case 'd': - digest = getTrueOrFalse(cmdlineOptions[i].getValue()); - break; - - case 'f': - format = cmdlineOptions[i].getValue().toLowerCase(); - boolean match = false; - // List of supported formats. - final String [] supportedFormats = - {CDX, DUMP, GZIP_DUMP, CDX_FILE}; - for (int ii = 0; ii < supportedFormats.length; ii++) { - if (supportedFormats[ii].equals(format)) { - match = true; - break; - } - } - if (!match) { - usage(formatter, options, 1); - } - break; - - default: - throw new RuntimeException("Unexpected option: " + - + cmdlineOptions[i].getId()); - } - } - - if (offset >= 0) { - if (cmdlineArgs.size() != 1) { - System.out.println("Error: Pass one arcfile only."); - usage(formatter, options, 1); - } - WARCReader r = WARCReaderFactory.get( - new File((String)cmdlineArgs.get(0)), offset); - r.setStrict(strict); - outputRecord(r, format); - } else { - for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) { - String urlOrPath = (String)i.next(); - try { - WARCReader r = WARCReaderFactory.get(urlOrPath); - r.setStrict(strict); - r.setDigest(digest); - output(r, format); - } catch (RuntimeException e) { - // Write out name of file we failed on to help with - // debugging. Then print stack trace and try to keep - // going. We do this for case where we're being fed - // a bunch of ARCs; just note the bad one and move - // on to the next. - System.err.println("Exception processing " + urlOrPath + - ": " + e.getMessage()); - e.printStackTrace(System.err); - System.exit(1); - } - } - } - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/warc/WARCReaderFactory.java b/commons/src/main/java/org/archive/io/warc/WARCReaderFactory.java deleted file mode 100644 index 9c6c7e77..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCReaderFactory.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; - -import org.archive.io.ArchiveReader; -import org.archive.io.ArchiveReaderFactory; -import org.archive.io.ArchiveRecord; -import org.archive.io.warc.WARCConstants; -import org.archive.util.ArchiveUtils; -import org.archive.util.FileUtils; -import org.archive.util.zip.GZIPMembersInputStream; - -import com.google.common.io.CountingInputStream; - -/** - * Factory for WARC Readers. - * Figures whether to give out a compressed file Reader or an uncompressed - * Reader. - * @author stack - * @version $Date: 2006-08-23 17:59:04 -0700 (Wed, 23 Aug 2006) $ $Version$ - */ -public class WARCReaderFactory extends ArchiveReaderFactory -implements WARCConstants { - private static final WARCReaderFactory factory = new WARCReaderFactory(); - - /** - * Shutdown any access to default constructor. - * This factory is Singleton. - */ - private WARCReaderFactory() { - super(); - } - - public static WARCReader get(String arcFileOrUrl) - throws MalformedURLException, IOException { - return (WARCReader)WARCReaderFactory.factory. - getArchiveReader(arcFileOrUrl); - } - - public static WARCReader get(final File f) throws IOException { - return (WARCReader)WARCReaderFactory.factory.getArchiveReader(f); - } - - /** - * @param f An arcfile to read. - * @param offset Have returned Reader set to start reading at this offset. - * @return A WARCReader. - * @throws IOException - */ - public static WARCReader get(final File f, final long offset) - throws IOException { - return (WARCReader)WARCReaderFactory.factory. - getArchiveReader(f, offset); - } - - protected ArchiveReader getArchiveReader(final File f, final long offset) - throws IOException { - boolean compressed = testCompressedWARCFile(f); - if (!compressed) { - if (!FileUtils.isReadableWithExtensionAndMagic(f, - DOT_WARC_FILE_EXTENSION, WARC_MAGIC)) { - throw new IOException(f.getAbsolutePath() - + " is not a WARC file."); - } - } - return (WARCReader)(compressed? - WARCReaderFactory.factory.new CompressedWARCReader(f, offset): - WARCReaderFactory.factory.new UncompressedWARCReader(f, offset)); - } - - public static ArchiveReader get(final String s, final InputStream is, - final boolean atFirstRecord) - throws IOException { - return WARCReaderFactory.factory.getArchiveReader(s, is, - atFirstRecord); - } - - protected ArchiveReader getArchiveReader(final String f, - final InputStream is, final boolean atFirstRecord) - throws IOException { - // For now, assume stream is compressed. Later add test of input - // stream or handle exception thrown when figure not compressed stream. - return new CompressedWARCReader(f, is, atFirstRecord); - } - - public static WARCReader get(final URL arcUrl, final long offset) - throws IOException { - return (WARCReader)WARCReaderFactory.factory.getArchiveReader(arcUrl, - offset); - } - - /** - * Get an ARCReader. - * Pulls the ARC local into whereever the System Property - * java.io.tmpdir points. It then hands back an ARCReader that - * points at this local copy. A close on this ARCReader instance will - * remove the local copy. - * @param arcUrl An URL that points at an ARC. - * @return An ARCReader. - * @throws IOException - */ - public static WARCReader get(final URL arcUrl) - throws IOException { - return (WARCReader)WARCReaderFactory.factory.getArchiveReader(arcUrl); - } - - /** - * Check file is compressed WARC. - * - * @param f File to test. - * - * @return True if this is compressed WARC (TODO: Just tests if file is - * GZIP'd file (It begins w/ GZIP MAGIC)). - * - * @exception IOException If file does not exist or is not unreadable. - */ - public static boolean testCompressedWARCFile(final File f) - throws IOException { - FileUtils.assertReadable(f); - boolean compressed = false; - final InputStream is = new FileInputStream(f); - try { - compressed = ArchiveUtils.isGzipped(is); - } finally { - is.close(); - } - return compressed; - } - - /** - * Uncompressed WARC file reader. - * @author stack - */ - public class UncompressedWARCReader extends WARCReader { - /** - * Constructor. - * @param f Uncompressed arcfile to read. - * @throws IOException - */ - public UncompressedWARCReader(final File f) - throws IOException { - this(f, 0); - } - - /** - * Constructor. - * - * @param f Uncompressed file to read. - * @param offset Offset at which to position Reader. - * @throws IOException - */ - public UncompressedWARCReader(final File f, final long offset) - throws IOException { - // File has been tested for existence by time it has come to here. - setIn(new CountingInputStream(getInputStream(f, offset))); - getIn().skip(offset); - initialize(f.getAbsolutePath()); - } - - /** - * Constructor. - * - * @param f Uncompressed file to read. - * @param is InputStream. - */ - public UncompressedWARCReader(final String f, final InputStream is) { - // Arc file has been tested for existence by time it has come - // to here. - setIn(new CountingInputStream(is)); - initialize(f); - } - } - - /** - * Compressed WARC file reader. - * - * @author stack - */ - public class CompressedWARCReader extends WARCReader { - /** - * Constructor. - * - * @param f Compressed file to read. - * @throws IOException - */ - public CompressedWARCReader(final File f) throws IOException { - this(f, 0); - } - - /** - * Constructor. - * - * @param f Compressed arcfile to read. - * @param offset Position at where to start reading file. - * @throws IOException - */ - public CompressedWARCReader(final File f, final long offset) - throws IOException { - // File has been tested for existence by time it has come to here. - setIn(new GZIPMembersInputStream(getInputStream(f, offset))); - ((GZIPMembersInputStream)getIn()).compressedSeek(offset); - setCompressed((offset == 0)); // TODO: does this make sense?!?! - initialize(f.getAbsolutePath()); - } - - /** - * Constructor. - * - * @param f Compressed arcfile. - * @param is InputStream to use. - * @param atFirstRecord - * @throws IOException - */ - public CompressedWARCReader(final String f, final InputStream is, - final boolean atFirstRecord) - throws IOException { - // Arc file has been tested for existence by time it has come - // to here. - setIn(new GZIPMembersInputStream(is)); - setCompressed(true); - initialize(f); - // TODO: Ignore atFirstRecord. Probably doesn't apply in WARC world. - } - - /** - * Get record at passed offset. - * - * @param offset Byte index into file at which a record starts. - * @return A WARCRecord reference. - * @throws IOException - */ - public WARCRecord get(long offset) throws IOException { - cleanupCurrentRecord(); - ((GZIPMembersInputStream)getIn()).compressedSeek(offset); - return (WARCRecord) createArchiveRecord(getIn(), offset); - } - - public Iterator iterator() { - /** - * Override ArchiveRecordIterator so can base returned iterator on - * GzippedInputStream iterator. - */ - return new ArchiveRecordIterator() { - private GZIPMembersInputStream gis = - (GZIPMembersInputStream)getIn(); - - private Iterator gzipIterator = this.gis.memberIterator(); - - protected boolean innerHasNext() { - return this.gzipIterator.hasNext(); - } - - protected ArchiveRecord innerNext() throws IOException { - // Get the position before gzipIterator.next moves - // it on past the gzip header. - InputStream is = (InputStream) this.gzipIterator.next(); - return createArchiveRecord(is, Math.max(gis.getCurrentMemberStart(), gis.getCurrentMemberEnd())); - } - }; - } - - protected void gotoEOR(ArchiveRecord rec) throws IOException { - long skipped = 0; - while (getIn().read()>-1) { - skipped++; - } - if(skipped>4) { - System.err.println("unexpected extra data after record "+rec); - } - return; - } - } - - public static boolean isWARCSuffix(final String f) { - return (f == null)? - false: - (f.toLowerCase().endsWith(DOT_COMPRESSED_WARC_FILE_EXTENSION))? - true: - (f.toLowerCase().endsWith(DOT_WARC_FILE_EXTENSION))? - true: false; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/warc/WARCRecord.java b/commons/src/main/java/org/archive/io/warc/WARCRecord.java deleted file mode 100644 index 635d1c3b..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCRecord.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import it.unimi.dsi.fastutil.io.RepositionableStream; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpParser; -import org.archive.io.ArchiveRecord; -import org.archive.io.ArchiveRecordHeader; -import org.archive.util.LaxHttpParser; - - -/** - * A WARC file Record. - * - * @author stack - */ -public class WARCRecord extends ArchiveRecord implements WARCConstants { - private Pattern WHITESPACE = Pattern.compile("\\s"); - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the record this instance - * is to represent. - * @throws IOException - */ - public WARCRecord(InputStream in, final String identifier, - final long offset) - throws IOException { - this(in, identifier, offset, true, false); - } - - /** - * Constructor. - * @param in Stream cue'd up just past Header Line and Named Fields. - * @param headers Header Line and ANVL Named fields. - * @throws IOException - */ - public WARCRecord(InputStream in, ArchiveRecordHeader headers) - throws IOException { - super(in, headers, 0, true, false); - } - - /** - * Constructor. - * - * @param in Stream cue'd up to be at the start of the record this instance - * is to represent or, if headers is not null, just past the - * Header Line and Named Fields. - * @param identifier Identifier for this the hosting Reader. - * @param offset Current offset into in (Used to keep - * position properly aligned). Usually 0. - * @param digest True if we're to calculate digest for this record. Not - * digesting saves about ~15% of cpu during parse. - * @param strict Be strict parsing (Parsing stops if file inproperly - * formatted). - * @throws IOException - */ - public WARCRecord(final InputStream in, final String identifier, - final long offset, boolean digest, boolean strict) - throws IOException { - super(in, null, 0, digest, strict); - setHeader(parseHeaders(in, identifier, offset, strict)); - } - - /** - * Parse WARC Header Line and Named Fields. - * @param in Stream to read. - * @param identifier Identifier for the hosting Reader. - * @param offset Absolute offset into Reader. - * @param strict Whether to be loose parsing or not. - * @return An ArchiveRecordHeader. - * @throws IOException - */ - protected ArchiveRecordHeader parseHeaders(final InputStream in, - final String identifier, final long offset, final boolean strict) - throws IOException { - final Map m = new HashMap(); - m.put(ABSOLUTE_OFFSET_KEY, new Long(offset)); - m.put(READER_IDENTIFIER_FIELD_KEY, identifier); - - long startPosition = -1; - if (in instanceof RepositionableStream) { - startPosition = ((RepositionableStream)in).position(); - } - String firstLine = - new String(LaxHttpParser.readLine(in, WARC_HEADER_ENCODING)); - if (firstLine == null || firstLine.length() <=0) { - throw new IOException("Failed to read WARC_MAGIC"); - } - if (!firstLine.startsWith(WARC_MAGIC)) { - throw new IOException("Failed to find WARC MAGIC: " + firstLine); - } - // Here we start reading off the inputstream but we're reading the - // stream direct rather than going via WARCRecord#read. The latter will - // keep count of bytes read, digest and fail properly if EOR too soon... - // We don't want digesting while reading Headers. - // - Header [] h = LaxHttpParser.parseHeaders(in, WARC_HEADER_ENCODING); - for (int i = 0; i < h.length; i++) { - m.put(h[i].getName(), h[i].getValue()); - } - int headerLength = -1; - if (in instanceof RepositionableStream) { - headerLength = - (int)(((RepositionableStream)in).position() - startPosition); - } - final int contentOffset = headerLength; - incrementPosition(contentOffset); - - return new ArchiveRecordHeader() { - private Map headers = m; - private int contentBegin = contentOffset; - - public String getDate() { - return (String)this.headers.get(HEADER_KEY_DATE); - } - - public String getDigest() { - return null; - // TODO: perhaps return block-digest? - // superclass def implies this is calculated ("only after - // read in totality"), not pulled from header, so - // below prior implementation was misleading -// return (String)this.headers.get(HEADER_KEY_CHECKSUM); - } - - public String getReaderIdentifier() { - return (String)this.headers.get(READER_IDENTIFIER_FIELD_KEY); - } - - public Set getHeaderFieldKeys() { - return this.headers.keySet(); - } - - public Map getHeaderFields() { - return this.headers; - } - - public Object getHeaderValue(String key) { - return this.headers.get(key); - } - - // Returns just the Content-Length of the warc record - public long getContentLength() { - Object o = this.headers.get(CONTENT_LENGTH); - if (o == null) { - return -1; - } - long contentLength = (o instanceof Long)? - ((Long)o).longValue(): Long.parseLong((String)o); - return contentLength; - } - - // Returns the full record length - public long getLength() - { - return getContentLength() + contentOffset; - } - - public String getMimetype() { - return (String)this.headers.get(CONTENT_TYPE); - } - - public long getOffset() { - Object o = this.headers.get(ABSOLUTE_OFFSET_KEY); - if (o == null) { - return -1; - } - return (o instanceof Long)? - ((Long)o).longValue(): Long.parseLong((String)o); - } - - public String getRecordIdentifier() { - return (String)this.headers.get(RECORD_IDENTIFIER_FIELD_KEY); - } - - public String getUrl() { - return (String)this.headers.get(HEADER_KEY_URI); - } - - public String getVersion() { - return (String)this.headers.get(VERSION_FIELD_KEY); - } - - public int getContentBegin() { - return this.contentBegin; - } - - @Override - public String toString() { - return this.headers.toString(); - } - }; - } - - @Override - protected String getMimetype4Cdx(ArchiveRecordHeader h) { - final String m = super.getMimetype4Cdx(h); - // Mimetypes can have spaces in WARCs. Emitting for CDX, just - // squash them for now. Later, quote them since squashing spaces won't - // work for params that have quoted-string values. - Matcher matcher = WHITESPACE.matcher(m); - return matcher.replaceAll(""); - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/warc/WARCRecordInfo.java b/commons/src/main/java/org/archive/io/warc/WARCRecordInfo.java deleted file mode 100644 index a6198c44..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCRecordInfo.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import java.io.InputStream; -import java.net.URI; - -import org.archive.format.warc.WARCConstants.WARCRecordType; -import org.archive.util.anvl.ANVLRecord; - -public class WARCRecordInfo { - - protected WARCRecordType type; - protected String url; - protected String create14DigitDate; - protected String mimetype; - protected URI recordId; - protected ANVLRecord extraHeaders; - protected InputStream contentStream; - protected long contentLength; - protected boolean enforceLength; - protected String warcFilename; - protected Long warcFileOffset; - - public void setType(WARCRecordType type) { - this.type = type; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getCreate14DigitDate() { - return create14DigitDate; - } - - public void setCreate14DigitDate(String create14DigitDate) { - this.create14DigitDate = create14DigitDate; - } - - public String getMimetype() { - return mimetype; - } - - public void setMimetype(String mimetype) { - this.mimetype = mimetype; - } - - public URI getRecordId() { - return recordId; - } - - public void setRecordId(URI recordId) { - this.recordId = recordId; - } - - public ANVLRecord getExtraHeaders() { - return extraHeaders; - } - - public void setExtraHeaders(ANVLRecord extraHeaders) { - this.extraHeaders = extraHeaders; - } - - public InputStream getContentStream() { - return contentStream; - } - - public void setContentStream(InputStream contentStream) { - this.contentStream = contentStream; - } - - public long getContentLength() { - return contentLength; - } - - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - public boolean isEnforceLength() { - return enforceLength; - } - - public boolean getEnforceLength() { - return enforceLength; - } - - public void setEnforceLength(boolean enforceLength) { - this.enforceLength = enforceLength; - } - - public WARCRecordType getType() { - return type; - } - - public String getUrl() { - return url; - } - - public void addExtraHeader(String label, String value) { - if (extraHeaders == null) { - extraHeaders = new ANVLRecord(); - } - extraHeaders.addLabelValue(label, value); - } - - public void setWARCFilename(String warcFilenameWithoutOccupiedSuffix) { - this.warcFilename = warcFilenameWithoutOccupiedSuffix; - } - - public String getWARCFilename() { - return warcFilename; - } - - public void setWARCFileOffset(Long startPosition) { - this.warcFileOffset = startPosition; - } - - public Long getWARCFileOffset() { - return warcFileOffset; - } -} diff --git a/commons/src/main/java/org/archive/io/warc/WARCWriter.java b/commons/src/main/java/org/archive/io/warc/WARCWriter.java deleted file mode 100644 index b9558263..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCWriter.java +++ /dev/null @@ -1,436 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URI; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.apache.commons.lang.StringUtils; -import org.archive.io.ArchiveFileConstants; -import org.archive.io.UTF8Bytes; -import org.archive.io.WriterPoolMember; -import org.archive.util.ArchiveUtils; -import org.archive.util.anvl.Element; - - -/** - * WARC implementation. - * - *

Assumption is that the caller is managing access to this - * WARCWriter ensuring only one thread accessing this WARC instance - * at any one time. - * - *

While being written, WARCs have a '.open' suffix appended. - * - * @contributor stack - * @version $Revision: 4604 $ $Date: 2006-09-05 22:38:18 -0700 (Tue, 05 Sep 2006) $ - */ -public class WARCWriter extends WriterPoolMember -implements WARCConstants { - public static final String TOTALS = "totals"; - public static final String SIZE_ON_DISK = "sizeOnDisk"; - public static final String TOTAL_BYTES = "totalBytes"; - public static final String CONTENT_BYTES = "contentBytes"; - public static final String NUM_RECORDS = "numRecords"; - - private static final Logger logger = - Logger.getLogger(WARCWriter.class.getName()); - - /** - * NEWLINE as bytes. - */ - public static byte [] CRLF_BYTES; - static { - try { - CRLF_BYTES = CRLF.getBytes(DEFAULT_ENCODING); - } catch(Exception e) { - e.printStackTrace(); - } - }; - - /** - * Temporarily accumulates stats managed externally by - * {@link WARCWriterProcessor}. WARCWriterProcessor will call - * {@link #resetTmpStats()}, write some records, then add - * {@link #getTmpStats()} into its long-term running totals. - */ - private Map> tmpStats; - - /** Temporarily accumulates info on written warc records for use externally. */ - private LinkedList tmpRecordLog = new LinkedList(); - - /** - * Constructor. - * Takes a stream. Use with caution. There is no upperbound check on size. - * Will just keep writing. Only pass Streams that are bounded. - * @param serialNo used to generate unique file name sequences - * @param out Where to write. - * @param f File the out is connected to. - * @param cmprs Compress the content written. - * @param a14DigitDate If null, we'll write current time. - * @throws IOException - */ - public WARCWriter(final AtomicInteger serialNo, - final OutputStream out, final File f, - final WARCWriterPoolSettings settings) - throws IOException { - super(serialNo, out, f, settings); - } - - /** - * Constructor. - * - * @param dirs Where to drop files. - * @param prefix File prefix to use. - * @param cmprs Compress the records written. - * @param maxSize Maximum size for ARC files written. - * @param suffix File tail to use. If null, unused. - * @param warcinfoData File metadata for warcinfo record. - */ - public WARCWriter(final AtomicInteger serialNo, - final WARCWriterPoolSettings settings) { - super(serialNo, settings, WARC_FILE_EXTENSION); - } - - @Override - protected String createFile(File file) throws IOException { - String filename = super.createFile(file); - writeWarcinfoRecord(filename); - return filename; - } - - protected void baseCharacterCheck(final char c, final String parameter) - throws IllegalArgumentException { - // TODO: Too strict? UNICODE control characters? - if (Character.isISOControl(c) || !Character.isValidCodePoint(c)) { - throw new IllegalArgumentException("Contains illegal character 0x" + - Integer.toHexString(c) + ": " + parameter); - } - } - - protected String checkHeaderValue(final String value) - throws IllegalArgumentException { - for (int i = 0; i < value.length(); i++) { - final char c = value.charAt(i); - baseCharacterCheck(c, value); - if (Character.isWhitespace(c)) { - throw new IllegalArgumentException("Contains disallowed white space 0x" + - Integer.toHexString(c) + ": " + value); - } - } - return value; - } - - protected String checkHeaderLineMimetypeParameter(final String parameter) - throws IllegalArgumentException { - StringBuilder sb = new StringBuilder(parameter.length()); - boolean wasWhitespace = false; - for (int i = 0; i < parameter.length(); i++) { - char c = parameter.charAt(i); - if (Character.isWhitespace(c)) { - // Map all to ' ' and collapse multiples into one. - // TODO: Make sure white space occurs in legal location -- - // before parameter or inside quoted-string. - if (wasWhitespace) { - continue; - } - wasWhitespace = true; - c = ' '; - } else { - wasWhitespace = false; - baseCharacterCheck(c, parameter); - } - sb.append(c); - } - - return sb.toString(); - } - -// protected String createRecordHeader(final String type, -// final String url, final String create14DigitDate, -// final String mimetype, final URI recordId, -// final ANVLRecord xtraHeaders, final long contentLength) - protected String createRecordHeader(WARCRecordInfo metaRecord) - throws IllegalArgumentException { - final StringBuilder sb = - new StringBuilder(2048/*A SWAG: TODO: Do analysis.*/); - sb.append(WARC_ID).append(CRLF); - sb.append(HEADER_KEY_TYPE).append(COLON_SPACE).append(metaRecord.getType()). - append(CRLF); - // Do not write a subject-uri if not one present. - if (!StringUtils.isEmpty(metaRecord.getUrl())) { - sb.append(HEADER_KEY_URI).append(COLON_SPACE). - append(checkHeaderValue(metaRecord.getUrl())).append(CRLF); - } - sb.append(HEADER_KEY_DATE).append(COLON_SPACE). - append(metaRecord.getCreate14DigitDate()).append(CRLF); - if (metaRecord.getExtraHeaders() != null) { - for (final Iterator i = metaRecord.getExtraHeaders().iterator(); i.hasNext();) { - sb.append(i.next()).append(CRLF); - } - } - - sb.append(HEADER_KEY_ID).append(COLON_SPACE).append('<'). - append(metaRecord.getRecordId().toString()).append('>').append(CRLF); - if (metaRecord.getContentLength() > 0) { - sb.append(CONTENT_TYPE).append(COLON_SPACE).append( - checkHeaderLineMimetypeParameter(metaRecord.getMimetype())).append(CRLF); - } - sb.append(CONTENT_LENGTH).append(COLON_SPACE). - append(Long.toString(metaRecord.getContentLength())).append(CRLF); - - return sb.toString(); - } - - public void writeRecord(WARCRecordInfo recordInfo) - throws IOException { - - if (recordInfo.getContentLength() == 0 && - (recordInfo.getExtraHeaders() == null || recordInfo.getExtraHeaders().size() <= 0)) { - throw new IllegalArgumentException("Cannot write record " + - "of content-length zero and base headers only."); - } - - String header; - try { - header = createRecordHeader(recordInfo); - - } catch (IllegalArgumentException e) { - logger.log(Level.SEVERE,"could not write record type: " + recordInfo.getType() - + "for URL: " + recordInfo.getUrl(), e); - return; - } - - long contentBytes = 0; - long totalBytes = 0; - long startPosition; - - try { - startPosition = getPosition(); - preWriteRecordTasks(); - - // TODO: Revisit encoding of header. - byte[] bytes = header.getBytes(WARC_HEADER_ENCODING); - write(bytes); - totalBytes += bytes.length; - - if (recordInfo.getContentStream() != null && recordInfo.getContentLength() > 0) { - // Write out the header/body separator. - write(CRLF_BYTES); // TODO: should this be written even for zero-length? - totalBytes += CRLF_BYTES.length; - contentBytes += copyFrom(recordInfo.getContentStream(), - recordInfo.getContentLength(), - recordInfo.getEnforceLength()); - totalBytes += contentBytes; - } - - // Write out the two blank lines at end of all records. - write(CRLF_BYTES); - write(CRLF_BYTES); - totalBytes += 2 * CRLF_BYTES.length; - - tally(recordInfo.getType(), contentBytes, totalBytes, getPosition() - startPosition); - - recordInfo.setWARCFilename(getFilenameWithoutOccupiedSuffix()); - recordInfo.setWARCFileOffset(startPosition); - tmpRecordLog.add(recordInfo); - } finally { - postWriteRecordTasks(); - } - } - - public String getFilenameWithoutOccupiedSuffix() { - String name = getFile().getName(); - if (name.endsWith(ArchiveFileConstants.OCCUPIED_SUFFIX)) { - name = name.substring(0, name.length() - ArchiveFileConstants.OCCUPIED_SUFFIX.length()); - } - return name; - } - - // if compression is enabled, sizeOnDisk means compressed bytes; if not, it - // should be the same as totalBytes (right?) - protected void tally(WARCRecordType warcRecordType, long contentBytes, long totalBytes, long sizeOnDisk) { - if (tmpStats == null) { - tmpStats = new HashMap>(); - } - - // add to stats for this record type - Map substats = tmpStats.get(warcRecordType.toString()); - if (substats == null) { - substats = new HashMap(); - tmpStats.put(warcRecordType.toString(), substats); - } - subtally(substats, contentBytes, totalBytes, sizeOnDisk); - - // add to totals - substats = tmpStats.get(TOTALS); - if (substats == null) { - substats = new HashMap(); - tmpStats.put(TOTALS, substats); - } - subtally(substats, contentBytes, totalBytes, sizeOnDisk); - } - - protected void subtally(Map substats, long contentBytes, - long totalBytes, long sizeOnDisk) { - - if (substats.get(NUM_RECORDS) == null) { - substats.put(NUM_RECORDS, 1l); - } else { - substats.put(NUM_RECORDS, substats.get(NUM_RECORDS) + 1); - } - - if (substats.get(CONTENT_BYTES) == null) { - substats.put(CONTENT_BYTES, contentBytes); - } else { - substats.put(CONTENT_BYTES, substats.get(CONTENT_BYTES) + contentBytes); - } - - if (substats.get(TOTAL_BYTES) == null) { - substats.put(TOTAL_BYTES, totalBytes); - } else { - substats.put(TOTAL_BYTES, substats.get(TOTAL_BYTES) + totalBytes); - } - - if (substats.get(SIZE_ON_DISK) == null) { - substats.put(SIZE_ON_DISK, sizeOnDisk); - } else { - substats.put(SIZE_ON_DISK, substats.get(SIZE_ON_DISK) + sizeOnDisk); - } - } - - protected URI generateRecordId(final Map qualifiers) - throws IOException { - return ((WARCWriterPoolSettings)settings).getRecordIDGenerator().getQualifiedRecordID(qualifiers); - } - - protected URI generateRecordId(final String key, final String value) - throws IOException { - return ((WARCWriterPoolSettings)settings).getRecordIDGenerator().getQualifiedRecordID(key, value); - } - - public URI writeWarcinfoRecord(String filename) - throws IOException { - return writeWarcinfoRecord(filename, null); - } - - public URI writeWarcinfoRecord(String filename, final String description) - throws IOException { - WARCRecordInfo recordInfo = new WARCRecordInfo(); - recordInfo.setType(WARCRecordType.warcinfo); - recordInfo.setCreate14DigitDate(ArchiveUtils.getLog14Date()); - recordInfo.setMimetype("application/warc-fields"); - - // Strip .open suffix if present. - if (filename.endsWith(WriterPoolMember.OCCUPIED_SUFFIX)) { - filename = filename.substring(0, - filename.length() - WriterPoolMember.OCCUPIED_SUFFIX.length()); - } - recordInfo.addExtraHeader(HEADER_KEY_FILENAME, filename); - if (description != null && description.length() > 0) { - recordInfo.addExtraHeader(CONTENT_DESCRIPTION, description); - } - - // Add warcinfo body. - byte [] warcinfoBody = null; - if (settings.getMetadata() == null) { - // TODO: What to write into a warcinfo? What to associate? - warcinfoBody = "TODO: Unimplemented".getBytes(); - } else { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - for (final Iterator i = settings.getMetadata().iterator(); - i.hasNext();) { - baos.write(i.next().toString().getBytes(UTF8Bytes.UTF8)); - } - warcinfoBody = baos.toByteArray(); - } - recordInfo.setContentStream(new ByteArrayInputStream(warcinfoBody)); - recordInfo.setContentLength((long) warcinfoBody.length); - recordInfo.setEnforceLength(true); - - recordInfo.setRecordId(generateRecordId(TYPE, WARCRecordType.warcinfo.toString())); - - writeRecord(recordInfo); - - // TODO: If at start of file, and we're writing compressed, - // write out our distinctive GZIP extensions. - return recordInfo.getRecordId(); - } - - /** - * @see WARCWriter#tmpStats for usage model - */ - public void resetTmpStats() { - if (tmpStats != null) { - for (Map substats : tmpStats.values()) { - for (Entry entry : substats.entrySet()) { - entry.setValue(0l); - } - } - } - } - - public Map> getTmpStats() { - return tmpStats; - } - - public static long getStat(Map> map, String key, - String subkey) { - if (map != null && map.get(key) != null - && map.get(key).get(subkey) != null) { - return map.get(key).get(subkey); - } else { - return 0l; - } - } - - public static long getStat( - ConcurrentMap> map, - String key, String subkey) { - if (map != null && map.get(key) != null - && map.get(key).get(subkey) != null) { - return map.get(key).get(subkey).get(); - } else { - return 0l; - } - } - - public void resetTmpRecordLog() { - tmpRecordLog.clear(); - } - - public Iterable getTmpRecordLog() { - return tmpRecordLog; - } -} diff --git a/commons/src/main/java/org/archive/io/warc/WARCWriterPool.java b/commons/src/main/java/org/archive/io/warc/WARCWriterPool.java deleted file mode 100644 index fdc97162..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCWriterPool.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import java.util.concurrent.atomic.AtomicInteger; - -import org.archive.io.WriterPool; -import org.archive.io.WriterPoolMember; - - -/** - * A pool of WARCWriters. - * @contributor stack - * @contributor gojomo - * @version $Revision: 4566 $ $Date: 2006-08-31 09:51:41 -0700 (Thu, 31 Aug 2006) $ - */ -public class WARCWriterPool extends WriterPool { - /** - * Constructor - * @param settings Settings for this pool. - * @param poolMaximumActive - * @param poolMaximumWait - */ - public WARCWriterPool(final WARCWriterPoolSettings settings, - final int poolMaximumActive, final int poolMaximumWait) { - this(new AtomicInteger(), settings, poolMaximumActive, poolMaximumWait); - } - - /** - * Constructor - * @param serial Used to generate unique filename sequences - * @param settings Settings for this pool. - * @param poolMaximumActive - * @param poolMaximumWait - */ - public WARCWriterPool(final AtomicInteger serial, - final WARCWriterPoolSettings settings, - final int poolMaximumActive, final int poolMaximumWait) { - super(serial, settings, poolMaximumActive, poolMaximumWait); - } - - /* (non-Javadoc) - * @see org.archive.io.WriterPool#makeWriter() - */ - protected WriterPoolMember makeWriter() { - return new WARCWriter(serialNo, (WARCWriterPoolSettings)settings); - } -} diff --git a/commons/src/main/java/org/archive/io/warc/WARCWriterPoolSettings.java b/commons/src/main/java/org/archive/io/warc/WARCWriterPoolSettings.java deleted file mode 100644 index b028a8b7..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCWriterPoolSettings.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import org.archive.io.WriterPoolSettings; -import org.archive.uid.RecordIDGenerator; - -/** - * Settings object for a {@link WARCWriterPool}. - * Used creating {@link WARCWriter}s. - * - * @version $Date: 2010-08-19 17:21:43 -0700 (Thu, 19 Aug 2010) $, $Revision: 6927 $ - */ -public interface WARCWriterPoolSettings extends WriterPoolSettings { - public RecordIDGenerator getRecordIDGenerator(); -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/warc/WARCWriterPoolSettingsData.java b/commons/src/main/java/org/archive/io/warc/WARCWriterPoolSettingsData.java deleted file mode 100644 index d56c9971..00000000 --- a/commons/src/main/java/org/archive/io/warc/WARCWriterPoolSettingsData.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.io.warc; - -import java.io.File; -import java.util.List; - -import org.archive.io.arc.WriterPoolSettingsData; -import org.archive.uid.RecordIDGenerator; - -public class WARCWriterPoolSettingsData extends WriterPoolSettingsData implements WARCWriterPoolSettings { - RecordIDGenerator generator; - - public WARCWriterPoolSettingsData(String prefix, String template, - long maxFileSizeBytes, boolean compress, List outputDirs, - List metadata, RecordIDGenerator generator) { - super(prefix,template,maxFileSizeBytes,compress,outputDirs,metadata); - this.generator = generator; - } - @Override - public RecordIDGenerator getRecordIDGenerator() { - return generator; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/io/warc/package.html b/commons/src/main/java/org/archive/io/warc/package.html deleted file mode 100644 index f52aa95b..00000000 --- a/commons/src/main/java/org/archive/io/warc/package.html +++ /dev/null @@ -1,38 +0,0 @@ - - - -org.archive.io.warc package - - -Experimental WARC Writer and Readers. Code and specification subject to change -with no guarantees of backward compatibility: i.e. newer readers -may not be able to parse WARCs written with older writers. This package -contains prototyping code for revision 0.12 of the WARC specification. -See latest revision -for current state (Version 0.10 code and its documentation has been moved into the -v10 subpackage). - - -

Implementation Notes

-

Tools

-

Initial implementations of Arc2Warc and Warc2Arc -tools can be found in the package above this one, at -{@link org.archive.io.Arc2Warc} and {@link org.archive.io.Warc2Arc} -respectively. Pass --help to learn how to use each tool. -

- -

TODO

-
    -
  • Is MIME-Version header needed? MIME Parsers seem fine without (python email -lib and java mail).
  • -
  • Should we write out a Content-Transfer-Encoding -header (Currently we do not). Need section in spec. explicit about our -interpretation of MIME and deviations (e.g. content-transfer-encoding should -be assumed binary in case of WARCs, multipart is not disallowed but not -encouraged, etc.)
  • -
  • Minor: Do WARC-Version: 0.12 like MIME-Version: 1.0 rather than -WARC/0.12 for lead in to an ARCRecord?
  • -
- - - diff --git a/commons/src/main/java/org/archive/net/DownloadURLConnection.java b/commons/src/main/java/org/archive/net/DownloadURLConnection.java deleted file mode 100644 index fbcee421..00000000 --- a/commons/src/main/java/org/archive/net/DownloadURLConnection.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.util.Arrays; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.archive.util.ProcessUtils; -import org.archive.util.ProcessUtils.ProcessResult; - -/** - * An URL Connection that pre-downloads URL reference before passing back a - * Stream reference. When closed, it removes the local download file. - * @author stack - * @version $Date$, $Revision$ - */ -public abstract class DownloadURLConnection extends URLConnection { - private final String CLASSNAME = DownloadURLConnection.class.getName(); - private final Logger LOGGER = Logger.getLogger(CLASSNAME); - private static final File TMPDIR = - new File(System.getProperty("java.io.tmpdir", "/tmp")); - private File downloadFile = null; - - protected DownloadURLConnection(URL u) { - super(u); - } - - protected String getScript() { - return System.getProperty(this.getClass().getName() + ".path", - "UNDEFINED"); - } - - protected String [] getCommand(final URL thisUrl, - final File downloadFile) { - return new String[] {getScript(), thisUrl.getPath(), - downloadFile.getAbsolutePath()}; - } - - /** - * Do script copy to local file. - * File is available via {@link #getFile()}. - * @throws IOException - */ - public void connect() throws IOException { - if (this.connected) { - return; - } - - this.downloadFile = File.createTempFile(CLASSNAME, null, TMPDIR); - try { - String [] cmd = getCommand(this.url, this.downloadFile); - if (LOGGER.isLoggable(Level.FINE)) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < cmd.length; i++) { - if (i > 0) { - buffer.append(" "); - } - buffer.append(cmd[i]); - } - LOGGER.fine("Command: " + buffer.toString()); - } - ProcessResult pr = ProcessUtils.exec(cmd); - if (pr.getResult() != 0) { - LOGGER.info(Arrays.toString(cmd) + " returned non-null " + pr.getResult()); - } - // Assume download went smoothly. - this.connected = true; - } catch (IOException ioe) { - // Clean up my tmp file. - this.downloadFile.delete(); - this.downloadFile = null; - // Rethrow. - throw ioe; - } - } - - public File getFile() { - return this.downloadFile; - } - - protected void setFile(final File f) { - this.downloadFile = f; - } - - public InputStream getInputStream() throws IOException { - if (!this.connected) { - connect(); - } - - // Return BufferedInputStream so 'delegation' is done for me, so - // I don't have to implement all IS methods and pass to my - // 'delegate' instance. - final DownloadURLConnection connection = this; - return new BufferedInputStream(new FileInputStream(this.downloadFile)) { - private DownloadURLConnection ruc = connection; - - public void close() throws IOException { - super.close(); - if (this.ruc != null && this.ruc.getFile()!= null && - this.ruc.getFile().exists()) { - this.ruc.getFile().delete(); - this.ruc.setFile(null); - } - } - }; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/net/FTPException.java b/commons/src/main/java/org/archive/net/FTPException.java deleted file mode 100644 index 2d104390..00000000 --- a/commons/src/main/java/org/archive/net/FTPException.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net; - -import java.io.IOException; - -/** - * Indicates that a FTP operation failed due to a protocol violation. - * For instance, if authentication fails. - * - * @author pjack - */ -public class FTPException extends IOException { - private static final long serialVersionUID = 1L; - - /** - * The reply code from the FTP server. - */ - private int code; - - /** - * Constructs a new FTPException. - * - * @param code the error code from the FTP server - */ - public FTPException(int code) { - super("FTP error code: " + code); - this.code = code; - } - - - /** - * Returns the error code from the FTP server. - * - * @return the error code from the FTP server - */ - public int getReplyCode() { - return code; - } -} diff --git a/commons/src/main/java/org/archive/net/PublicSuffixes.java b/commons/src/main/java/org/archive/net/PublicSuffixes.java deleted file mode 100644 index eab8081a..00000000 --- a/commons/src/main/java/org/archive/net/PublicSuffixes.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.io.IOUtils; -import org.archive.util.TextUtils; - -/** - * Utility class for making use of the information about 'public suffixes' at - * http://publicsuffix.org. - * - * The public suffix list (once known as 'effective TLDs') was motivated by the - * need to decide on which broader domains a subdomain was allowed to set - * cookies. For example, a server at 'www.example.com' can set cookies for - * 'www.example.com' or 'example.com' but not 'com'. 'www.example.co.uk' can set - * cookies for 'www.example.co.uk' or 'example.co.uk' but not 'co.uk' or 'uk'. - * The number of rules for all top-level-domains and 2nd- or 3rd- level domains - * has become quite long; essentially the broadest domain a subdomain may assign - * to is the one that was sold/registered to a specific name registrant. - * - * This concept should be useful in other contexts, too. Grouping URIs (or - * queues of URIs to crawl) together with others sharing the same registered - * suffix may be useful for applying the same rules to all, such as assigning - * them to the same queue or crawler in a multi- machine setup. - * - * As of Heritrix3, we prefer the term 'Assignment Level Domain' (ALD) - * for such domains, by analogy to 'Top Level Domain' (TLD) or '2nd Level - * Domain' (2LD), etc. - * - * @author Gojomo - * - * this version of PublicSuffixes uses suffix-tree data structure for generating less - * redundant regular expression. It may be even possible to write a light-weight, - * thread-safe matcher based on this class. - * @author Kenji Nagahashi - */ -public class PublicSuffixes { - protected static Pattern topmostAssignedSurtPrefixPattern; - protected static String topmostAssignedSurtPrefixRegex; - - /** - * prefix tree node. each Node represents sequence of letters (prefix) - * and alternative sequences following it (list of Node's). Nodes in - * {@code branches} are sorted for skip list like lookup and for generating - * effective regular expression (see {@link #compareTo(Node)} and {@link #compareTo(char).) - * - * as is intended for internal use only, there's no access methods. procedures for updating - * prefix tree with new input are defined within this class ({@link #addBranch(CharSequence)}). - * - * terminal node could be represented in two different form: 1) Node with zero branches, - * or 2) Node with zero-length {@code cs}. So, root node must be initialized with empty (not null) - * {@code branches} unless empty string matches the overall pattern. - * {@code cs} must not be null except for root node. - */ - public static class Node implements Comparable { - protected CharSequence cs; - protected List branches; - public Node() { - this("", null); - } - protected Node(CharSequence cs) { - this(cs, null); - } - protected Node(CharSequence cs, List branches) { - this.cs = cs; - this.branches = branches; - } - public void addBranch(CharSequence s) { - if (branches == null) { - branches = new ArrayList(); - branches.add(new Node("", null)); - } - for (int i = 0; i < branches.size(); i++) { - Node alt = branches.get(i); - if (alt.add(s)) return; - if (alt.compareTo(s.charAt(0)) > 0) { - Node alt1 = new Node(s, null); - branches.add(i, alt1); - return; - } - } - Node alt2 = new Node(s, null); - branches.add(alt2); - } - public boolean add(CharSequence s) { - int l = Math.min(s.length(), cs.length()); - int i = 0; - while (i < l && s.charAt(i) == cs.charAt(i)) - i++; - // zero-length match holds only when both cs and s are empty. - if (i == 0) return cs.length() == 0 && s.length() == 0; - if (i < cs.length()) { - CharSequence cs0 = cs.subSequence(0, i); - CharSequence cs1 = cs.subSequence(i, cs.length()); - CharSequence cs2 = s.subSequence(i, s.length()); - cs = cs0; - Node alt1 = new Node(cs1, branches); - (branches = new ArrayList()).add(alt1); - addBranch(cs2); - } else { - assert i == cs.length(); - addBranch(s.subSequence(i, s.length())); - } - return true; - } - public int compareTo(Node other) { - if (other.cs == null || other.cs.length() == 0) - return (cs == null || cs.length() == 0) ? 0 : -1; - return compareTo(other.cs.charAt(0)); - } - public int compareTo(char oc) { - if (cs == null || cs.length() == 0) return 1; - // '!' and '*' must come after ordinary letters, in this order, for regexp - // to work as intended. - char c = cs.charAt(0); - if (c == oc) return 0; - if (c == '!') return oc == '*' ? -1 : 1; - if (c == '*') return 1; - if (oc == '*' || oc == '!') return -1; - return Character.valueOf(c).compareTo(oc); - // for generating the same regexp as previous version. - //return Character.valueOf(oc).compareTo(c); - } - } - - /** - * Utility method for dumping a regex String, based on a published public - * suffix list, which matches any SURT-form hostname up through the broadest - * 'private' (assigned/sold) domain-segment. That is, for any of the - * SURT-form hostnames... - * - * com,example, com,example,www, com,example,california,www - * - * ...the regex will match 'com,example,'. - * - * @param args - * @throws IOException - */ - public static void main(String args[]) throws IOException { - InputStream is; - if (args.length == 0 || "=".equals(args[0])) { - // use bundled list - is = PublicSuffixes.class.getClassLoader().getResourceAsStream( - "effective_tld_names.dat"); - } else { - is = new FileInputStream(args[0]); - } - BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); - String regex = getTopmostAssignedSurtPrefixRegex(reader); - IOUtils.closeQuietly(is); - - boolean needsClose = false; - BufferedWriter writer; - if (args.length >= 2) { - // write to specified file - writer = new BufferedWriter(new FileWriter(args[1])); - needsClose = true; - } else { - // write to stdout - writer = new BufferedWriter(new OutputStreamWriter(System.out)); - } - writer.append(regex); - writer.flush(); - if (needsClose) { - writer.close(); - } - } - /** - * Reads a file of the format promulgated by publicsuffix.org, ignoring - * comments and '!' exceptions/notations, converting domain segments to - * SURT-ordering. Leaves glob-style '*' wildcarding in place. Returns root - * node of SURT-ordered prefix tree. - * - * @param reader - * @return root of prefix tree node. - * @throws IOException - */ - protected static Node readPublishedFileToSurtTrie(BufferedReader reader) throws IOException { - // initializing with empty Alt list prevents empty pattern from being - // created for the first addBranch() - Node alt = new Node(null, new ArrayList()); - String line; - while ((line = reader.readLine()) != null) { - // discard whitespace, empty lines, comments, exceptions - line = line.trim(); - if (line.length() == 0 || line.startsWith("//")) continue; - // discard utf8 notation after entry - line = line.split("\\s+")[0]; - // TODO: maybe we don't need to create lower-cased String - line = line.toLowerCase(); - // SURT-order domain segments - String[] segs = line.split("\\."); - StringBuilder sb = new StringBuilder(); - for (int i = segs.length - 1; i >= 0; i--) { - if (segs[i].length() == 0) continue; - sb.append(segs[i]).append(','); - } - alt.addBranch(sb.toString()); - } - return alt; - } - /** - * utility function for dumping prefix tree structure. intended for debug use. - * @param alt root of prefix tree. - * @param lv indent level. 0 for root (no indent). - * @param out writer to send output to. - */ - public static void dump(Node alt, int lv, PrintWriter out) { - for (int i = 0; i < lv; i++) - out.print(" "); - out.println(alt.cs != null ? ('"'+alt.cs.toString()+'"') : "(null)"); - if (alt.branches != null) { - for (Node br : alt.branches) { - dump(br, lv + 1, out); - } - } - } - /** - * bulids regular expression from prefix-tree {@code alt} into buffer {@code sb}. - * @param alt prefix tree root. - * @param sb StringBuffer to store regular expression. - */ - protected static void buildRegex(Node alt, StringBuilder sb) { - String close = null; - if (alt.cs != null) { - // actually '!' always be the first character, because it is - // always used along with '*'. - for (int i = 0; i < alt.cs.length(); i++) { - char c = alt.cs.charAt(i); - if (c == '!') { - if (close != null) - throw new RuntimeException("more than one '!'"); - sb.append("(?="); - close = ")"; - } else if (c == '*') { - sb.append("[-\\w]+"); - } else { - sb.append(c); - } - } - } - if (alt.branches != null) { - // alt.branches.size() should always be > 1 - if (alt.branches.size() > 1) { - sb.append("(?:"); - } - String sep = ""; - for (Node alt1 : alt.branches) { - sb.append(sep); sep = "|"; - buildRegex(alt1, sb); - } - if (alt.branches.size() > 1) { - sb.append(")"); - } - } - if (close != null) - sb.append(close); - } - - /** - * Converts SURT-ordered list of public prefixes into a Java regex which - * matches the public-portion "plus one" segment, giving the domain on which - * cookies can be set or other policy grouping should occur. Also adds to - * regex a fallback matcher that for any new/unknown TLDs assumes the - * second-level domain is assignable. (Eg: 'zzz,example,'). - * - * @param list - * @return - */ - private static String surtPrefixRegexFromTrie(Node trie) { - StringBuilder regex = new StringBuilder(); - regex.append("(?ix)^\n"); - trie.addBranch("*,"); // for new/unknown TLDs - buildRegex(trie, regex); - regex.append("\n([-\\w]+,)"); - return regex.toString(); - } - - public static synchronized Pattern getTopmostAssignedSurtPrefixPattern() { - if (topmostAssignedSurtPrefixPattern == null) { - topmostAssignedSurtPrefixPattern = Pattern - .compile(getTopmostAssignedSurtPrefixRegex()); - } - return topmostAssignedSurtPrefixPattern; - } - - public static synchronized String getTopmostAssignedSurtPrefixRegex() { - if (topmostAssignedSurtPrefixRegex == null) { - // use bundled list - try { - BufferedReader reader = new BufferedReader(new InputStreamReader( - PublicSuffixes.class.getClassLoader().getResourceAsStream( - "effective_tld_names.dat"), "UTF-8")); - topmostAssignedSurtPrefixRegex = getTopmostAssignedSurtPrefixRegex(reader); - IOUtils.closeQuietly(reader); - } catch (UnsupportedEncodingException ex) { - // should never happen - throw new RuntimeException(ex); - } - } - return topmostAssignedSurtPrefixRegex; - } - - public static String getTopmostAssignedSurtPrefixRegex(BufferedReader reader) { - try { - Node trie = readPublishedFileToSurtTrie(reader); - return surtPrefixRegexFromTrie(trie); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Truncate SURT to its topmost assigned domain segment; that is, - * the public suffix plus one segment, but as a SURT-ordered prefix. - * - * if the pattern doesn't match, the passed-in SURT is returned. - * - * @param surt SURT to truncate - * @return truncated-to-topmost-assigned SURT prefix - */ - public static String reduceSurtToAssignmentLevel(String surt) { - Matcher matcher = TextUtils.getMatcher( - getTopmostAssignedSurtPrefixRegex(), surt); - if (matcher.find()) { - surt = matcher.group(); - } - TextUtils.recycleMatcher(matcher); - return surt; - } -} diff --git a/commons/src/main/java/org/archive/net/md5/Handler.java b/commons/src/main/java/org/archive/net/md5/Handler.java deleted file mode 100644 index 8afcdebb..00000000 --- a/commons/src/main/java/org/archive/net/md5/Handler.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net.md5; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; - -/** - * A protocol handler for an 'md5' URI scheme. - * Md5 URLs look like this: md5:deadbeefdeadbeefdeadbeefdeadbeef - * When this handler is invoked against an md5 URL, it passes the raw md5 to - * the configured script as an argument. The configured script then does the - * work to bring the item pointed to by the md5 local so we can open a Stream - * on the local copy. Local file is deleted when we finish. Do - * {@link org.archive.net.DownloadURLConnection#getFile()} to get name of - * temporary file. - * - *

You need to define the system property - * -Djava.protocol.handler.pkgs=org.archive.net to add this handler - * to the java.net.URL set. Also define system properties - * -Dorg.archive.net.md5.Md5URLConnection.path=PATH_TO_SCRIPT to - * pass path of script to run as well as - * -Dorg.archive.net.md5.Md5URLConnection.options=OPTIONS for - * any options you'd like to include. The pointed-to PATH_TO_SCRIPT - * will be invoked as follows: PATH_TO_SCRIPT OPTIONS MD5 - * LOCAL_TMP_FILE. The LOCAL_TMP_FILE file is made in - * java.io.tmpdir using java tmp name code. - * @author stack - */ -public class Handler extends URLStreamHandler { - protected URLConnection openConnection(URL u) { - return new Md5URLConnection(u); - } - - /** - * Main dumps rsync file to STDOUT. - * @param args - * @throws IOException - */ - public static void main(String[] args) - throws IOException { - if (args.length != 1) { - System.out.println("Usage: java java " + - "-Djava.protocol.handler.pkgs=org.archive.net " + - "org.archive.net.md5.Handler " + - "md5:deadbeefdeadbeefdeadbeefdeadbeef"); - System.exit(1); - } - System.setProperty("org.archive.net.md5.Md5URLConnection.path", - "/tmp/manifest"); - System.setProperty("java.protocol.handler.pkgs", "org.archive.net"); - URL u = new URL(args[0]); - URLConnection connect = u.openConnection(); - // Write download to stdout. - final int bufferlength = 4096; - byte [] buffer = new byte [bufferlength]; - InputStream is = connect.getInputStream(); - try { - for (int count = is.read(buffer, 0, bufferlength); - (count = is.read(buffer, 0, bufferlength)) != -1;) { - System.out.write(buffer, 0, count); - } - System.out.flush(); - } finally { - is.close(); - } - } -} diff --git a/commons/src/main/java/org/archive/net/md5/Md5URLConnection.java b/commons/src/main/java/org/archive/net/md5/Md5URLConnection.java deleted file mode 100644 index e4fe98e3..00000000 --- a/commons/src/main/java/org/archive/net/md5/Md5URLConnection.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net.md5; - -import java.net.URL; - -import org.archive.net.DownloadURLConnection; - -/** - * Md5 URL connection. - * @author stack - * @version $Date$, $Revision$ - */ -public class Md5URLConnection extends DownloadURLConnection { - protected Md5URLConnection(URL u) { - super(u); - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/net/rsync/Handler.java b/commons/src/main/java/org/archive/net/rsync/Handler.java deleted file mode 100644 index 9eb35f5d..00000000 --- a/commons/src/main/java/org/archive/net/rsync/Handler.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net.rsync; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; - -/** - * A protocol handler that uses native rsync client to do copy. - * You need to define the system property - * -Djava.protocol.handler.pkgs=org.archive.net to add this handler - * to the java.net.URL set. Assumes rsync is in path. Define - * system property - * -Dorg.archive.net.rsync.RsyncUrlConnection.path=PATH_TO_RSYNC to - * pass path to rsync. Downloads to java.io.tmpdir. - * @author stack - */ -public class Handler extends URLStreamHandler { - protected URLConnection openConnection(URL u) { - return new RsyncURLConnection(u); - } - - /** - * Main dumps rsync file to STDOUT. - * @param args - * @throws IOException - */ - public static void main(String[] args) - throws IOException { - if (args.length != 1) { - System.out.println("Usage: java java " + - "-Djava.protocol.handler.pkgs=org.archive.net " + - "org.archive.net.rsync.Handler RSYNC_URL"); - System.exit(1); - } - URL u = new URL(args[0]); - URLConnection connect = u.openConnection(); - // Write download to stdout. - final int bufferlength = 4096; - byte [] buffer = new byte [bufferlength]; - InputStream is = connect.getInputStream(); - try { - for (int count = is.read(buffer, 0, bufferlength); - (count = is.read(buffer, 0, bufferlength)) != -1;) { - System.out.write(buffer, 0, count); - } - System.out.flush(); - } finally { - is.close(); - } - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/net/rsync/RsyncURLConnection.java b/commons/src/main/java/org/archive/net/rsync/RsyncURLConnection.java deleted file mode 100644 index c6097e96..00000000 --- a/commons/src/main/java/org/archive/net/rsync/RsyncURLConnection.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net.rsync; - -import java.io.File; -import java.net.URL; - -import org.archive.net.DownloadURLConnection; - -/** - * Rsync URL connection. - * @author stack - * @version $Date$, $Revision$ - */ -public class RsyncURLConnection extends DownloadURLConnection { - private final String RSYNC_TIMEOUT = - System.getProperty(RsyncURLConnection.class.getName() + ".timeout", - "300"); - - protected RsyncURLConnection(URL u) { - super(u); - } - - protected String getScript() { - return System.getProperty(this.getClass().getName() + ".path", - "rsync"); - } - - @Override - protected String[] getCommand(final URL thisUrl, - final File downloadFile) { - return new String[] {getScript(), "--timeout=" + RSYNC_TIMEOUT, - this.url.getPath(), downloadFile.getAbsolutePath()}; - } -} diff --git a/commons/src/main/java/org/archive/uid/RecordIDGenerator.java b/commons/src/main/java/org/archive/uid/RecordIDGenerator.java deleted file mode 100644 index 97f1a022..00000000 --- a/commons/src/main/java/org/archive/uid/RecordIDGenerator.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.uid; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; - -/** - * A record-id generator. - * - * @contributor stack - * @contributor gojomo - * @version $Revision$ $Date$ - */ -public interface RecordIDGenerator { - /** - * @return A URI that can serve as a record-id. - * @throws URISyntaxException - */ - public URI getRecordID(); - - /** - * @param qualifiers Qualifiers to add. - * @return A URI qualified with passed qualifiers that can - * serve as a record-id, or, a new, unique record-id without qualifiers - * (if qualifiers not easily implemented using passed URI scheme). - */ - public URI getQualifiedRecordID(final Map qualifiers); - - /** - * @param key Name of qualifier - * @param value Value of qualifier - * @return A URI qualified with passed qualifiers that can - * serve as a record-id, or, a new, unique record-id without qualifiers - * (if qualifiers not easily implemented using passed URI scheme). - */ - public URI getQualifiedRecordID(final String key, final String value); - - /** - * Append (or if already present, update) qualifiers to passed - * recordId. Use with caution. Guard against turning up a - * result that already exists. Use when writing a group of records inside - * a single transaction. - * - * How qualifiers are appended/updated varies with URI scheme. Its allowed - * that an invocation of this method does nought but call - * {@link #getRecordID()}, returning a new URI unrelated to the passed - * recordId and passed qualifier. - * @param recordId URI to append qualifier to. - * @param qualifiers Map of qualifier values keyed by qualifier name. - * @return New URI based off passed uri and passed qualifier. - */ - public URI qualifyRecordID(final URI recordId, - final Map qualifiers); -} diff --git a/commons/src/main/java/org/archive/uid/UUIDGenerator.java b/commons/src/main/java/org/archive/uid/UUIDGenerator.java deleted file mode 100644 index 26d29e60..00000000 --- a/commons/src/main/java/org/archive/uid/UUIDGenerator.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.uid; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.UUID; - -/** - * Generates UUIDs, using - * {@link java.util.UUID java.util.UUID}, formatted as URNs from the UUID - * namespace [See RFC4122]. - * Here is an examples of the type of ID it makes: - * urn:uuid:0161811f-5da6-4c6e-9808-a2fab97114cf. Always makes a - * new identifier even when passed qualifiers. - * - * @author stack - * @version $Revision$ $Date$ - * @see RFC4122 - */ -public class UUIDGenerator implements RecordIDGenerator { - private static final String SCHEME = "urn:uuid"; - private static final String SCHEME_COLON = SCHEME + ":"; - - public UUIDGenerator() { - super(); - } - - public URI qualifyRecordID(URI recordId, - final Map qualifiers) { - return getRecordID(); - } - - private String getUUID() { - return UUID.randomUUID().toString(); - } - - public URI getRecordID() { - try { - return new URI(SCHEME_COLON + getUUID()); - } catch (URISyntaxException e) { - // should be impossible - throw new RuntimeException(e); - } - } - - public URI getQualifiedRecordID( - final String key, final String value){ - return getRecordID(); - } - - public URI getQualifiedRecordID(Map qualifiers){ - return getRecordID(); - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/uid/package.html b/commons/src/main/java/org/archive/uid/package.html deleted file mode 100644 index dc49f07b..00000000 --- a/commons/src/main/java/org/archive/uid/package.html +++ /dev/null @@ -1,28 +0,0 @@ - - - -org.archive.uid package - - -A unique ID generator. -Default is {@link org.archive.uid.UUIDGenerator}. -To use another ID Generator, set the System Property -org.archive.uid.GeneratorFactory.generator to point -at an alternate implementation of {@link org.archive.uid.Generator}. - -

TODO

-
    -
  • MIME boundaries have upper-bound of 70 characters total including - 'blank line' (CRLFCRLF) and two leading hyphens. Add to - {@link org.archive.uid.Generator} - interface an upper-bound on generated ID length.
  • -
  • Add example of an actionable uid generator: -e.g. http://archive.org/UID-SCHEME/ID -where scheme might be UUID and an ID might be -f9472055-fbb6-4810-90e8-68fd39e145a6;type=metadata or, -using ARK: -http://archive.org/ark:/13030/f9472055-fbb6-4810-90e8-68fd39e145a6;type=metadata. -
  • -
- - diff --git a/commons/src/main/java/org/archive/util/DevUtils.java b/commons/src/main/java/org/archive/util/DevUtils.java deleted file mode 100644 index d630a0b1..00000000 --- a/commons/src/main/java/org/archive/util/DevUtils.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.logging.Logger; - - -/** - * Write a message and stack trace to the 'org.archive.util.DevUtils' logger. - * - * @author gojomo - * @version $Revision$ $Date$ - */ -public class DevUtils { - public static Logger logger = - Logger.getLogger(DevUtils.class.getName()); - - /** - * Log a warning message to the logger 'org.archive.util.DevUtils' made of - * the passed 'note' and a stack trace based off passed exception. - * - * @param ex Exception we print a stacktrace on. - * @param note Message to print ahead of the stacktrace. - */ - public static void warnHandle(Throwable ex, String note) { - logger.warning(TextUtils.exceptionToString(note, ex)); - } - - /** - * @return Extra information gotten from current Thread. May not - * always be available in which case we return empty string. - */ - public static String extraInfo() { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - final Thread current = Thread.currentThread(); - if (current instanceof Reporter) { - Reporter tt = (Reporter)current; - try { - tt.reportTo(pw); - } catch (IOException e) { - // Not really possible w/ a StringWriter - e.printStackTrace(); - } - } - if (current instanceof ProgressStatisticsReporter) { - ProgressStatisticsReporter tt = (ProgressStatisticsReporter)current; - try { - tt.progressStatisticsLegend(pw); - tt.progressStatisticsLine(pw); - } catch (IOException e) { - // Not really possible w/ a StringWriter - e.printStackTrace(); - } - } - pw.flush(); - return sw.toString(); - } - - /** - * Nothing to see here, move along. - * @deprecated This method was never used. - */ - @Deprecated - public static void betterPrintStack(RuntimeException re) { - re.printStackTrace(System.err); - } - - /** - * Send this JVM process a SIGQUIT; giving a thread dump and possibly - * a heap histogram (if using -XX:+PrintClassHistogram). - * - * Used to automatically dump info, for example when a serious error - * is encountered. Would use 'jmap'/'jstack', but have seen JVM - * lockups -- perhaps due to lost thread wake signals -- when using - * those against Sun 1.5.0+03 64bit JVM. - */ - public static void sigquitSelf() { - try { - Process p = Runtime.getRuntime().exec( - new String[] {"perl", "-e", "print getppid(). \"\n\";"}); - BufferedReader br = - new BufferedReader(new InputStreamReader(p.getInputStream())); - String ppid = br.readLine(); - Runtime.getRuntime().exec( - new String[] {"sh", "-c", "kill -3 "+ppid}).waitFor(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } -} diff --git a/commons/src/main/java/org/archive/util/FileUtils.java b/commons/src/main/java/org/archive/util/FileUtils.java deleted file mode 100644 index 3b5b93ad..00000000 --- a/commons/src/main/java/org/archive/util/FileUtils.java +++ /dev/null @@ -1,699 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.channels.ClosedByInterruptException; -import java.nio.channels.FileChannel; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.filefilter.IOFileFilter; -import org.apache.commons.lang.math.LongRange; - - -/** Utility methods for manipulating files and directories. - * - * @contributor John Erik Halse - * @contributor gojomo - */ -public class FileUtils { - private static final Logger LOGGER = - Logger.getLogger(FileUtils.class.getName()); - - /** - * Constructor made private because all methods of this class are static. - */ - private FileUtils() { - super(); - } - - /** - * Copy the src file to the destination. Deletes any preexisting - * file at destination. - * - * @param src - * @param dest - * @return True if the extent was greater than actual bytes copied. - * @throws FileNotFoundException - * @throws IOException - */ - public static boolean copyFile(final File src, final File dest) - throws FileNotFoundException, IOException { - return copyFile(src, dest, -1, true); - } - - /** - * Copy up to extent bytes of the source file to the destination. - * Deletes any preexisting file at destination. - * - * @param src - * @param dest - * @param extent Maximum number of bytes to copy - * @return True if the extent was greater than actual bytes copied. - * @throws FileNotFoundException - * @throws IOException - */ - public static boolean copyFile(final File src, final File dest, - long extent) - throws FileNotFoundException, IOException { - return copyFile(src, dest, extent, true); - } - - /** - * Copy up to extent bytes of the source file to the destination - * - * @param src - * @param dest - * @param extent Maximum number of bytes to copy - * @param overwrite If target file already exits, and this parameter is - * true, overwrite target file (We do this by first deleting the target - * file before we begin the copy). - * @return True if the extent was greater than actual bytes copied. - * @throws FileNotFoundException - * @throws IOException - */ - public static boolean copyFile(final File src, final File dest, - long extent, final boolean overwrite) - throws FileNotFoundException, IOException { - boolean result = false; - if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.fine("Copying file " + src + " to " + dest + " extent " + - extent + " exists " + dest.exists()); - } - if (dest.exists()) { - if (overwrite) { - dest.delete(); - LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); - } else { - // Already in place and we're not to overwrite. Return. - return result; - } - } - FileInputStream fis = null; - FileOutputStream fos = null; - FileChannel fcin = null; - FileChannel fcout = null; - try { - // Get channels - fis = new FileInputStream(src); - fos = new FileOutputStream(dest); - fcin = fis.getChannel(); - fcout = fos.getChannel(); - if (extent < 0) { - extent = fcin.size(); - } - - // Do the file copy - long trans = fcin.transferTo(0, extent, fcout); - if (trans < extent) { - result = false; - } - result = true; - } catch (IOException e) { - // Add more info to the exception. Preserve old stacktrace. - // We get 'Invalid argument' on some file copies. See - // http://intellij.net/forums/thread.jsp?forum=13&thread=63027&message=853123 - // for related issue. - String message = "Copying " + src.getAbsolutePath() + " to " + - dest.getAbsolutePath() + " with extent " + extent + - " got IOE: " + e.getMessage(); - if ((e instanceof ClosedByInterruptException) || - ((e.getMessage()!=null) - &&e.getMessage().equals("Invalid argument"))) { - LOGGER.severe("Failed copy, trying workaround: " + message); - workaroundCopyFile(src, dest); - } else { - IOException newE = new IOException(message); - newE.initCause(e); - throw newE; - } - } finally { - // finish up - if (fcin != null) { - fcin.close(); - } - if (fcout != null) { - fcout.close(); - } - if (fis != null) { - fis.close(); - } - if (fos != null) { - fos.close(); - } - } - return result; - } - - protected static void workaroundCopyFile(final File src, - final File dest) - throws IOException { - FileInputStream from = null; - FileOutputStream to = null; - try { - from = new FileInputStream(src); - to = new FileOutputStream(dest); - byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = from.read(buffer)) != -1) { - to.write(buffer, 0, bytesRead); - } - } finally { - if (from != null) { - try { - from.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if (to != null) { - try { - to.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - /** - * Get a list of all files in directory that have passed prefix. - * - * @param dir Dir to look in. - * @param prefix Basename of files to look for. Compare is case insensitive. - * - * @return List of files in dir that start w/ passed basename. - */ - public static File [] getFilesWithPrefix(File dir, final String prefix) { - FileFilter prefixFilter = new FileFilter() { - public boolean accept(File pathname) - { - return pathname.getName().toLowerCase(). - startsWith(prefix.toLowerCase()); - } - }; - return dir.listFiles(prefixFilter); - } - - /** Get a @link java.io.FileFilter that filters files based on a regular - * expression. - * - * @param regex the regular expression the files must match. - * @return the newly created filter. - */ - public static IOFileFilter getRegexFileFilter(String regex) { - // Inner class defining the RegexFileFilter - class RegexFileFilter implements IOFileFilter { - Pattern pattern; - - protected RegexFileFilter(String re) { - pattern = Pattern.compile(re); - } - - public boolean accept(File pathname) { - return pattern.matcher(pathname.getName()).matches(); - } - - public boolean accept(File dir, String name) { - return accept(new File(dir,name)); - } - } - - return new RegexFileFilter(regex); - } - - /** - * Test file exists and is readable. - * @param f File to test. - * @exception FileNotFoundException If file does not exist or is not unreadable. - */ - public static File assertReadable(final File f) throws FileNotFoundException { - if (!f.exists()) { - throw new FileNotFoundException(f.getAbsolutePath() + - " does not exist."); - } - - if (!f.canRead()) { - throw new FileNotFoundException(f.getAbsolutePath() + - " is not readable."); - } - - return f; - } - - /** - * @param f File to test. - * @return True if file is readable, has uncompressed extension, - * and magic string at file start. - * @exception IOException If file not readable or other problem. - */ - public static boolean isReadableWithExtensionAndMagic(final File f, - final String uncompressedExtension, final String magic) - throws IOException { - boolean result = false; - FileUtils.assertReadable(f); - if(f.getName().toLowerCase().endsWith(uncompressedExtension)) { - FileInputStream fis = new FileInputStream(f); - try { - byte [] b = new byte[magic.length()]; - int read = fis.read(b, 0, magic.length()); - fis.close(); - if (read == magic.length()) { - StringBuffer beginStr - = new StringBuffer(magic.length()); - for (int i = 0; i < magic.length(); i++) { - beginStr.append((char)b[i]); - } - - if (beginStr.toString(). - equalsIgnoreCase(magic)) { - result = true; - } - } - } finally { - fis.close(); - } - } - - return result; - } - - /** - * Turn path into a File, relative to context (which may be ignored - * if path is absolute). - * - * @param context File context if path is relative - * @param path String path to make into a File - * @return File created - */ - public static File maybeRelative(File context, String path) { - File f = new File(path); - if(f.isAbsolute()) { - return f; - } - return new File(context, path); - } - - /** - * Load Properties instance from a File - * - * @param file - * @return Properties - * @throws IOException - */ - public static Properties loadProperties(File file) throws IOException { - FileInputStream finp = new FileInputStream(file); - try { - Properties p = new Properties(); - p.load(finp); - return p; - } finally { - ArchiveUtils.closeQuietly(finp); - } - } - - /** - * Store Properties instance to a File - * @param p - * @param file destination File - * @throws IOException - */ - public static void storeProperties(Properties p, File file) throws IOException { - FileOutputStream fos = new FileOutputStream(file); - try { - p.store(fos,""); - } finally { - ArchiveUtils.closeQuietly(fos); - } - } - - // TODO: comment - public static boolean moveAsideIfExists(File file) throws IOException { - if(!file.exists()) { - return true; - } - String newName = - file.getCanonicalPath() + "." - + ArchiveUtils.get14DigitDate(file.lastModified()); - boolean retVal = file.renameTo(new File(newName)); - if(!retVal) { - LOGGER.warning("unable to move aside: "+file+" to "+newName); - } - return retVal; - - } - - /** - * Retrieve a number of lines from the file around the given - * position, as when paging forward or backward through a file. - * - * @param file File to retrieve lines - * @param position offset to anchor lines - * @param signedDesiredLineCount lines requested; if negative, - * want this number of lines ending with a line containing - * the position; if positive, want this number of lines, - * all starting at or after position. - * @param lines List to insert found lines - * @param lineEstimate int estimate of line size, 0 means use default - * of 128 - * @return LongRange indicating the file offsets corresponding to - * the beginning of the first line returned, and the point - * after the end of the last line returned - * @throws IOException - */ - @SuppressWarnings("unchecked") - public static LongRange pagedLines(File file, long position, - int signedDesiredLineCount, List lines, int lineEstimate) - throws IOException { - // consider negative positions as from end of file; -1 = last byte - if (position < 0) { - position = file.length() + position; - } - - // calculate a reasonably sized chunk likely to have all desired lines - if(lineEstimate == 0) { - lineEstimate = 128; - } - int desiredLineCount = Math.abs(signedDesiredLineCount); - long startPosition; - long fileEnd = file.length(); - int bufferSize = (desiredLineCount + 5) * lineEstimate; - if(signedDesiredLineCount>0) { - // reading forward; include previous char in case line-end - startPosition = position - 1; - } else { - // reading backward - startPosition = position - bufferSize + (2 * lineEstimate); - } - if(startPosition<0) { - startPosition = 0; - } - if(startPosition+bufferSize > fileEnd) { - bufferSize = (int)(fileEnd - startPosition); - } - - // read that reasonable chunk - FileInputStream fis = new FileInputStream(file); - fis.getChannel().position(startPosition); - byte[] buf = new byte[bufferSize]; - ArchiveUtils.readFully(fis, buf); - IOUtils.closeQuietly(fis); - - // find all line starts fully in buffer - // (positions after a line-end, per line-end definition in - // BufferedReader.readLine) - LinkedList lineStarts = new LinkedList(); - if(startPosition==0) { - lineStarts.add(0); - } - boolean atLineEnd = false; - boolean eatLF = false; - int i; - for(i = 0; i < bufferSize; i++) { - if ((char) buf[i] == '\n' && eatLF) { - eatLF = false; - continue; - } - if(atLineEnd) { - atLineEnd = false; - lineStarts.add(i); - if(signedDesiredLineCount<0 && startPosition+i > position) { - // reached next line past position, read no more - break; - } - } - if ((char) buf[i] == '\r') { - atLineEnd = true; - eatLF = true; - continue; - } - if ((char) buf[i] == '\n') { - atLineEnd = true; - } - } - if(startPosition+i == fileEnd) { - // add phantom lineStart after end - lineStarts.add(bufferSize); - } - int foundFullLines = lineStarts.size()-1; - - // if found no lines - if(foundFullLines<1) { - if(signedDesiredLineCount>0) { - if(startPosition+bufferSize == fileEnd) { - // nothing more to read: return nothing - return new LongRange(fileEnd,fileEnd); - } else { - // retry with larger lineEstimate - return pagedLines(file, position, signedDesiredLineCount, lines, Math.max(bufferSize,lineEstimate)); - } - - } else { - // try again with much larger line estimate - // TODO: fail gracefully before growing to multi-MB buffers - return pagedLines(file, position, signedDesiredLineCount, lines, bufferSize); - } - } - - // trim unneeded lines - while(signedDesiredLineCount>0 && startPosition+lineStarts.getFirst()desiredLineCount+1) { - if (signedDesiredLineCount < 0 && (startPosition+lineStarts.get(1) <= position) ) { - // discard from front until reach line containing target position - lineStarts.removeFirst(); - } else { - lineStarts.removeLast(); - } - } - int firstLine = lineStarts.getFirst(); - int partialLine = lineStarts.getLast(); - LongRange range = new LongRange(startPosition + firstLine, startPosition + partialLine); - List foundLines = - IOUtils.readLines(new ByteArrayInputStream(buf,firstLine,partialLine-firstLine)); - - if(foundFullLines 0) { - // if needed and reading backward, read more lines from earlier - range = expandRange( - range, - pagedLines(file, - range.getMinimumLong()-1, - signedDesiredLineCount+foundFullLines, - lines, - bufferSize/foundFullLines)); - - } - - lines.addAll(foundLines); - - if(signedDesiredLineCount < 0 && range.getMaximumLong() < position) { - // did not get line containining start position - range = expandRange( - range, - pagedLines(file, - partialLine, - 1, - lines, - bufferSize/foundFullLines)); - } - - if(signedDesiredLineCount > 0 && foundFullLines < desiredLineCount && range.getMaximumLong() < fileEnd) { - // need more forward lines - range = expandRange( - range, - pagedLines(file, - range.getMaximumLong(), - desiredLineCount - foundFullLines, - lines, - bufferSize/foundFullLines)); - } - - return range; - } - - public static LongRange expandRange(LongRange range1, LongRange range2) { - return new LongRange(Math.min(range1.getMinimumLong(), range2.getMinimumLong()), - Math.max(range1.getMaximumLong(), range2.getMaximumLong())); - - } - - public static LongRange pagedLines(File file, long position, int signedDesiredLongCount, List lines) throws IOException { - return pagedLines(file, position, signedDesiredLongCount, lines, 0); - } - - /** - * Delete the file now -- but in the event of failure, keep trying - * in the future. - * - * VERY IMPORTANT: Do not use with any file whose name/path may be - * reused, because the lagged delete could then wind up deleting the - * newer file. Essentially, only to be used with uniquely-named temp - * files. - * - * Necessary because some platforms (looking at you, - * JVM-on-Windows) will have deletes fail because of things like - * file-mapped buffers remaining, and there's no explicit way to - * unmap a buffer. (See 6-year-old Sun-stumping Java bug - * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038 ) - * We just have to wait and retry. - * - * (Why not just File.deleteOnExit? There could be an arbitrary, - * unbounded number of files in such a situation, that are only - * deletable a few seconds or minutes after our first attempt. - * Waiting for JVM exist could mean disk exhaustion. It's also - * unclear if the native FS class implementations of deleteOnExit - * use RAM per pending file.) - * - * @param fileToDelete - */ - public static synchronized void deleteSoonerOrLater(File fileToDelete) { - pendingDeletes.add(fileToDelete); - // if things are getting out of hand, force gc/finalization - if(pendingDeletes.size()>50) { - LOGGER.warning(">50 pending Files to delete; forcing gc/finalization"); - System.gc(); - System.runFinalization(); - } - // try all pendingDeletes - Iterator iter = pendingDeletes.listIterator(); - while(iter.hasNext()) { - File pending = iter.next(); - if(pending.delete()) { - iter.remove(); - } - } - // if things are still out of hand, complain loudly - if(pendingDeletes.size()>50) { - LOGGER.severe(">50 pending Files to delete even after gc/finalization"); - } - } - protected static LinkedList pendingDeletes = new LinkedList(); - - /** - * Read the entire stream to EOF into the passed file. - * Closes is when done or if an exception. - * @param is Stream to read. - * @param toFile File to write to. - * @throws IOException - */ - public static long readFullyToFile(InputStream is, File toFile) - throws IOException { - OutputStream os = org.apache.commons.io.FileUtils.openOutputStream(toFile); - try { - return IOUtils.copyLarge(is, os); - } finally { - IOUtils.closeQuietly(os); - IOUtils.closeQuietly(is); - } - } - - /** - * Ensure writeable directory. - * - * If doesn't exist, we attempt creation. - * - * @param dir Directory to test for exitence and is writeable. - * - * @return The passed dir. - * - * @exception IOException If passed directory does not exist and is not - * createable, or directory is not writeable or is not a directory. - */ - public static File ensureWriteableDirectory(String dir) - throws IOException { - return FileUtils.ensureWriteableDirectory(new File(dir)); - } - - /** - * Ensure writeable directories. - * - * If doesn't exist, we attempt creation. - * - * @param dirs List of Files to test. - * - * @return The passed dirs. - * - * @exception IOException If passed directory does not exist and is not - * createable, or directory is not writeable or is not a directory. - */ - public static List ensureWriteableDirectory(List dirs) - throws IOException { - for (Iterator i = dirs.iterator(); i.hasNext();) { - FileUtils.ensureWriteableDirectory(i.next()); - } - return dirs; - } - - /** - * Ensure writeable directory. - * - * If doesn't exist, we attempt creation. - * - * @param dir Directory to test for exitence and is writeable. - * - * @return The passed dir. - * - * @exception IOException If passed directory does not exist and is not - * createable, or directory is not writeable or is not a directory. - */ - public static File ensureWriteableDirectory(File dir) - throws IOException { - if (!dir.exists()) { - boolean success = dir.mkdirs(); - if (!success) { - throw new IOException("Failed to create directory: " + dir); - } - } else { - if (!dir.canWrite()) { - throw new IOException("Dir " + dir.getAbsolutePath() + - " not writeable."); - } else if (!dir.isDirectory()) { - throw new IOException("Dir " + dir.getAbsolutePath() + - " is not a directory."); - } - } - - return dir; - } - - public static File tryToCanonicalize(File file) { - try { - return file.getCanonicalFile(); - } catch (IOException e) { - return file; - } - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/util/FilesystemLinkMaker.java b/commons/src/main/java/org/archive/util/FilesystemLinkMaker.java index 9899a29c..c489d04d 100644 --- a/commons/src/main/java/org/archive/util/FilesystemLinkMaker.java +++ b/commons/src/main/java/org/archive/util/FilesystemLinkMaker.java @@ -20,6 +20,7 @@ package org.archive.util; import java.io.File; import java.io.IOException; +import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.Platform; @@ -34,6 +35,8 @@ import com.sun.jna.win32.StdCallLibrary; */ public class FilesystemLinkMaker { + private static final Logger logger = Logger.getLogger(FilesystemLinkMaker.class.getName()); + // see https://github.com/twall/jna/blob/master/www/GettingStarted.md public interface Kernel32Library extends StdCallLibrary { Kernel32Library INSTANCE = (Kernel32Library) (Platform.isWindows() @@ -75,26 +78,38 @@ public class FilesystemLinkMaker { */ // XXX could handle errors better (examine errno, throw exception...) public static boolean makeHardLink(String existingPath, String newPath) { - if (Platform.isWindows()) { - return Kernel32Library.INSTANCE.CreateHardLinkA(newPath, existingPath, null); - } else { - int status = CLibrary.INSTANCE.link(existingPath, newPath); - return status == 0; + try { + if (Platform.isWindows()) { + return Kernel32Library.INSTANCE.CreateHardLinkA(newPath, existingPath, null); + } else { + int status = CLibrary.INSTANCE.link(existingPath, newPath); + return status == 0; + } + } catch (UnsatisfiedLinkError e) { + // see https://webarchive.jira.com/browse/HER-1979 + logger.warning("hard links not supported on this platform - " + e); + return false; } } /** - * Wrapper over platform-dependent system calls to create a symboic link. + * Wrapper over platform-dependent system calls to create a symbolic link. * * @return true on success */ // XXX could handle errors better (examine errno, throw exception...) public static boolean makeSymbolicLink(String existingPath, String newPath) { - if (Platform.isWindows()) { - return Kernel32Library.INSTANCE.CreateSymbolicLinkA(newPath, existingPath, null); - } else { - int status = CLibrary.INSTANCE.symlink(existingPath, newPath); - return status == 0; + try { + if (Platform.isWindows()) { + return Kernel32Library.INSTANCE.CreateSymbolicLinkA(newPath, existingPath, null); + } else { + int status = CLibrary.INSTANCE.symlink(existingPath, newPath); + return status == 0; + } + } catch (UnsatisfiedLinkError e) { + // see https://webarchive.jira.com/browse/HER-1979 + logger.warning("symbolic links not supported on this platform - " + e); + return false; } } diff --git a/commons/src/main/java/org/archive/util/InetAddressUtil.java b/commons/src/main/java/org/archive/util/InetAddressUtil.java deleted file mode 100644 index 585ba772..00000000 --- a/commons/src/main/java/org/archive/util/InetAddressUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * InetAddress utility. - * @author stack - * @version $Date$, $Revision$ - */ -public class InetAddressUtil { - private static Logger logger = - Logger.getLogger(InetAddressUtil.class.getName()); - - /** - * ipv4 address. - */ - public static Pattern IPV4_QUADS = Pattern.compile( - "([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})"); - - private InetAddressUtil () { - super(); - } - - /** - * Returns InetAddress for passed host IF its in - * IPV4 quads format (e.g. 128.128.128.128). - *

TODO: Move to an AddressParsingUtil class. - * @param host Host name to examine. - * @return InetAddress IF the passed name was an IP address, else null. - */ - public static InetAddress getIPHostAddress(String host) { - InetAddress result = null; - Matcher matcher = IPV4_QUADS.matcher(host); - if (matcher == null || !matcher.matches()) { - return result; - } - try { - // Doing an Inet.getByAddress() avoids a lookup. - result = InetAddress.getByAddress(host, - new byte[] { - (byte)(new Integer(matcher.group(1)).intValue()), - (byte)(new Integer(matcher.group(2)).intValue()), - (byte)(new Integer(matcher.group(3)).intValue()), - (byte)(new Integer(matcher.group(4)).intValue())}); - } catch (NumberFormatException e) { - logger.warning(e.getMessage()); - } catch (UnknownHostException e) { - logger.warning(e.getMessage()); - } - return result; - } - - /** - * @return All known local names for this host or null if none found. - */ - public static List getAllLocalHostNames() { - List localNames = new ArrayList(); - Enumeration e = null; - try { - e = NetworkInterface.getNetworkInterfaces(); - } catch(SocketException exception) { - throw new RuntimeException(exception); - } - for (; e.hasMoreElements();) { - for (Enumeration ee = e.nextElement().getInetAddresses(); - ee.hasMoreElements();) { - InetAddress ia = ee.nextElement(); - if (ia != null) { - if (ia.getHostName() != null) { - localNames.add(ia.getCanonicalHostName()); - } - if (ia.getHostAddress() != null) { - localNames.add(ia.getHostAddress()); - } - } - } - } - final String localhost = "localhost"; - if (!localNames.contains(localhost)) { - localNames.add(localhost); - } - final String localhostLocaldomain = "localhost.localdomain"; - if (!localNames.contains(localhostLocaldomain)) { - localNames.add(localhostLocaldomain); - } - return localNames; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/util/IterableLineIterator.java b/commons/src/main/java/org/archive/util/IterableLineIterator.java deleted file mode 100644 index 6e0d9dc8..00000000 --- a/commons/src/main/java/org/archive/util/IterableLineIterator.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.archive.util; - -import java.io.Reader; -import java.util.Iterator; - -import org.apache.commons.io.LineIterator; - -/** - * A LineIterator that also implements Iterable, so that it can be used with - * the java enhanced for-each loop syntax. - * - * @contributor nlevitt - */ -public class IterableLineIterator extends LineIterator - implements Iterable { - - public IterableLineIterator(final Reader reader) - throws IllegalArgumentException { - super(reader); - } - - @SuppressWarnings("unchecked") - public Iterator iterator() { - return this; - } -} diff --git a/commons/src/main/java/org/archive/util/LaxHttpParser.java b/commons/src/main/java/org/archive/util/LaxHttpParser.java deleted file mode 100644 index c1f768f0..00000000 --- a/commons/src/main/java/org/archive/util/LaxHttpParser.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/LaxHttpParser.java,v 1.13 2005/01/11 13:57:06 oglueck Exp $ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * Copyright 1999-2004 The Apache Software Foundation - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -/* - * - */ - -package org.archive.util; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.util.EncodingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * A Modified version of HttpParser which doesn't throw exceptions on bad header lines - * - * A utility class for parsing http header values according to - * RFC-2616 Section 4 and 19.3. - * - * @author Michael Becke - * @author Oleg Kalnichevski - * - * @since 2.0beta1 - */ -public class LaxHttpParser { - - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(LaxHttpParser.class); - - /** - * Constructor for LaxHttpParser. - */ - protected LaxHttpParser() { } - - /** - * Return byte array from an (unchunked) input stream. - * Stop reading when "\n" terminator encountered - * If the stream ends before the line terminator is found, - * the last part of the string will still be returned. - * If no input data available, null is returned. - * - * @param inputStream the stream to read from - * - * @throws IOException if an I/O problem occurs - * @return a byte array from the stream - */ - public static byte[] readRawLine(InputStream inputStream) throws IOException { - LOG.trace("enter LaxHttpParser.readRawLine()"); - - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - int ch; - while ((ch = inputStream.read()) >= 0) { - buf.write(ch); - if (ch == '\n') { // be tolerant (RFC-2616 Section 19.3) - break; - } - } - if (buf.size() == 0) { - return null; - } - return buf.toByteArray(); - } - - /** - * Read up to "\n" from an (unchunked) input stream. - * If the stream ends before the line terminator is found, - * the last part of the string will still be returned. - * If no input data available, null is returned. - * - * @param inputStream the stream to read from - * @param charset charset of HTTP protocol elements - * - * @throws IOException if an I/O problem occurs - * @return a line from the stream - * - * @since 3.0 - */ - public static String readLine(InputStream inputStream, String charset) throws IOException { - LOG.trace("enter LaxHttpParser.readLine(InputStream, String)"); - byte[] rawdata = readRawLine(inputStream); - if (rawdata == null) { - return null; - } - // strip CR and LF from the end - int len = rawdata.length; - int offset = 0; - if (len > 0) { - if (rawdata[len - 1] == '\n') { - offset++; - if (len > 1) { - if (rawdata[len - 2] == '\r') { - offset++; - } - } - } - } - return EncodingUtil.getString(rawdata, 0, len - offset, charset); - } - - /** - * Read up to "\n" from an (unchunked) input stream. - * If the stream ends before the line terminator is found, - * the last part of the string will still be returned. - * If no input data available, null is returned - * - * @param inputStream the stream to read from - * - * @throws IOException if an I/O problem occurs - * @return a line from the stream - * - * @deprecated use #readLine(InputStream, String) - */ - - public static String readLine(InputStream inputStream) throws IOException { - LOG.trace("enter LaxHttpParser.readLine(InputStream)"); - return readLine(inputStream, "US-ASCII"); - } - - /** - * Parses headers from the given stream. Headers with the same name are not - * combined. - * - * @param is the stream to read headers from - * @param charset the charset to use for reading the data - * - * @return an array of headers in the order in which they were parsed - * - * @throws IOException if an IO error occurs while reading from the stream - * @throws HttpException if there is an error parsing a header value - * - * @since 3.0 - */ - public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException { - LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)"); - - ArrayList

headers = new ArrayList
(); - String name = null; - StringBuffer value = null; - for (; ;) { - String line = LaxHttpParser.readLine(is, charset); - if ((line == null) || (line.trim().length() < 1)) { - break; - } - - // Parse the header name and value - // Check for folded headers first - // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 - // discussion on folded headers - if ((line.charAt(0) == ' ') || (line.charAt(0) == '\t')) { - // we have continuation folded header - // so append value - if (value != null) { - value.append(' '); - value.append(line.trim()); - } - } else { - // make sure we save the previous name,value pair if present - if (name != null) { - headers.add(new Header(name, value.toString())); - } - - // Otherwise we should have normal HTTP header line - // Parse the header name and value - int colon = line.indexOf(":"); - - // START IA/HERITRIX change - // Don't throw an exception if can't parse. We want to keep - // going even though header is bad. Rather, create - // pseudo-header. - if (colon < 0) { - // throw new ProtocolException("Unable to parse header: " + - // line); - name = "HttpClient-Bad-Header-Line-Failed-Parse"; - value = new StringBuffer(line); - - } else { - name = line.substring(0, colon).trim(); - value = new StringBuffer(line.substring(colon + 1).trim()); - } - // END IA/HERITRIX change - } - - } - - // make sure we save the last name,value pair if present - if (name != null) { - headers.add(new Header(name, value.toString())); - } - - return (Header[]) headers.toArray(new Header[headers.size()]); - } - - /** - * Parses headers from the given stream. Headers with the same name are not - * combined. - * - * @param is the stream to read headers from - * - * @return an array of headers in the order in which they were parsed - * - * @throws IOException if an IO error occurs while reading from the stream - * @throws HttpException if there is an error parsing a header value - * - * @deprecated use #parseHeaders(InputStream, String) - */ - public static Header[] parseHeaders(InputStream is) throws IOException, HttpException { - LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)"); - return parseHeaders(is, "US-ASCII"); - } -} diff --git a/commons/src/main/java/org/archive/util/MimetypeUtils.java b/commons/src/main/java/org/archive/util/MimetypeUtils.java deleted file mode 100644 index adfa1a0f..00000000 --- a/commons/src/main/java/org/archive/util/MimetypeUtils.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Class of mimetype utilities. - * @author stack - */ -public class MimetypeUtils { - /** - * The 'no-type' content-type. - * - * Defined in the ARC file spec at - * http://www.archive.org/web/researcher/ArcFileFormat.php. - */ - public static final String NO_TYPE_MIMETYPE = "no-type"; - - /** - * Truncation regex. - */ - protected final static Pattern TRUNCATION_REGEX = Pattern.compile("^([^\\s;,]+).*"); - - - /** - * Truncate passed mimetype. - * - * Ensure no spaces. Strip encoding. Truncation required by - * ARC files. - * - *

Truncate at delimiters [;, ]. - * Truncate multi-part content type header at ';'. - * Apache httpclient collapses values of multiple instances of the - * header into one comma-separated value,therefore truncated at ','. - * Current ia_tools that work with arc files expect 5-column - * space-separated meta-lines, therefore truncate at ' '. - * - * @param contentType Raw content-type. - * - * @return Computed content-type made from passed content-type after - * running it through a set of rules. - */ - public static String truncate(String contentType) { - if (contentType == null) { - contentType = NO_TYPE_MIMETYPE; - } else { - Matcher matcher = TRUNCATION_REGEX.matcher(contentType); - if (matcher.matches()) { - contentType = matcher.group(1); - } else { - contentType = NO_TYPE_MIMETYPE; - } - } - - return contentType; - } -} diff --git a/commons/src/main/java/org/archive/util/ProcessUtils.java b/commons/src/main/java/org/archive/util/ProcessUtils.java deleted file mode 100644 index af792981..00000000 --- a/commons/src/main/java/org/archive/util/ProcessUtils.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Arrays; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Class to run an external process. - * @author stack - * @version $Date$ $Revision$ - */ -public class ProcessUtils { - private static final Logger LOGGER = - Logger.getLogger(ProcessUtils.class.getName()); - - protected ProcessUtils() { - super(); - } - - /** - * Thread to gobble up an output stream. - * See http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html - */ - protected class StreamGobbler extends Thread { - private final InputStream is; - private final StringBuffer sink = new StringBuffer(); - - protected StreamGobbler(InputStream is, String name) { - this.is = is; - setName(name); - } - - public void run() { - try { - BufferedReader br = - new BufferedReader(new InputStreamReader(this.is)); - for (String line = null; (line = br.readLine()) != null;) { - this.sink.append(line); - } - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - public String getSink() { - return this.sink.toString(); - } - } - - /** - * Data structure to hold result of a process exec. - * @author stack - * @version $Date$ $Revision$ - */ - public class ProcessResult { - private final String [] args; - private final int result; - private final String stdout; - private final String stderr; - - protected ProcessResult(String [] args, int result, String stdout, - String stderr) { - this.args = args; - this.result = result; - this.stderr = stderr; - this.stdout = stdout; - } - - public int getResult() { - return this.result; - } - - public String getStdout() { - return this.stdout; - } - - public String getStderr() { - return this.stderr; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < this.args.length; i++) { - sb.append(this.args[i]); - sb.append(", "); - } - return sb.toString() + " exit code: " + this.result + - ((this.stderr != null && this.stderr.length() > 0)? - "\nSTDERR: " + this.stderr: "") + - ((this.stdout != null && this.stdout.length() > 0)? - "\nSTDOUT: " + this.stdout: ""); - } - } - - /** - * Runs process. - * @param args List of process args. - * @return A ProcessResult data structure. - * @throws IOException If interrupted, we throw an IOException. If non-zero - * exit code, we throw an IOException (This may need to change). - */ - public static ProcessUtils.ProcessResult exec(String [] args) - throws IOException { - Process p = Runtime.getRuntime().exec(args); - ProcessUtils pu = new ProcessUtils(); - // Gobble up any output. - StreamGobbler err = pu.new StreamGobbler(p.getErrorStream(), "stderr"); - err.setDaemon(true); - err.start(); - StreamGobbler out = pu.new StreamGobbler(p.getInputStream(), "stdout"); - out.setDaemon(true); - out.start(); - int exitVal; - try { - exitVal = p.waitFor(); - } catch (InterruptedException e) { - throw new IOException("Wait on process " + Arrays.toString(args) + " interrupted: " - + e.getMessage()); - } - ProcessUtils.ProcessResult result = - pu.new ProcessResult(args, exitVal, out.getSink(), err.getSink()); - if (exitVal != 0) { - throw new IOException(result.toString()); - } else if (LOGGER.isLoggable(Level.INFO)) { - LOGGER.info(result.toString()); - } - return result; - } -} diff --git a/commons/src/main/java/org/archive/util/ProgressStatisticsReporter.java b/commons/src/main/java/org/archive/util/ProgressStatisticsReporter.java deleted file mode 100644 index dc1e51f7..00000000 --- a/commons/src/main/java/org/archive/util/ProgressStatisticsReporter.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.io.IOException; -import java.io.PrintWriter; - -public interface ProgressStatisticsReporter { - /** - * @param writer Where to write statistics. - * @throws IOException - */ - public void progressStatisticsLine(PrintWriter writer) throws IOException; - - /** - * @param writer Where to write statistics legend. - * @throws IOException - */ - public void progressStatisticsLegend(PrintWriter writer) throws IOException; -} diff --git a/commons/src/main/java/org/archive/util/PropertyUtils.java b/commons/src/main/java/org/archive/util/PropertyUtils.java deleted file mode 100644 index 083615f6..00000000 --- a/commons/src/main/java/org/archive/util/PropertyUtils.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.util.Properties; -import java.util.regex.Matcher; - -import org.apache.commons.lang.StringUtils; - -/** - * Utilities for dealing with Java Properties (incl. System Properties) - * - * @contributor stack - * @contributor gojomo - * @version $Date$ $Revision$ - */ -public class PropertyUtils { - /*** - * @param key Property key. - * @return Named property or null if the property is null or empty. - */ - public static String getPropertyOrNull(final String key) { - String value = System.getProperty(key); - return (value == null || value.length() <= 0)? null: value; - } - - /*** - * @param key Property key. - * @return Boolean value or false if null or unreadable. - */ - public static boolean getBooleanProperty(final String key) { - return (getPropertyOrNull(key) == null)? - false: Boolean.valueOf(getPropertyOrNull(key)).booleanValue(); - } - - /** - * @param key Key to use looking up system property. - * @param fallback If no value found for passed key, return - * fallback. - * @return Value of property or fallback. - */ - public static int getIntProperty(final String key, final int fallback) { - return getPropertyOrNull(key) == null? - fallback: Integer.parseInt(getPropertyOrNull(key)); - } - - /** - * Given a string which may contain expressions of the form - * ${key}, replace each expression with the value corresponding to the - * given key in System Properties. If no value is present, - * the expression is replaced with the empty-string. - * - * @param original String - * @param properties Properties to try in order; first value found (if any) is used - * @return modified String - */ - public static String interpolateWithProperties(String original) { - return interpolateWithProperties(original,System.getProperties()); - } - - protected static String propRefPattern = "\\$\\{([^{}]+)\\}"; - - /** - * Given a string which may contain expressions of the form - * ${key}, replace each expression with the value corresponding to the - * given key in the supplied Properties instance. If no value is present, - * the expression is replaced with the empty-string. - * - * @param original String - * @param props Properties to try in order; first value found (if any) is used - * @return modified String - */ - public static String interpolateWithProperties(String original, - Properties... props) { - String result = original; - // cap number of interpolations as guard against unending loop - inter: for(int i =0; i < original.length()*2; i++) { - Matcher m = TextUtils.getMatcher(propRefPattern, result); - while(m.find()) { - String key = m.group(1); - String value = ""; - for(Properties properties : props) { - value = properties.getProperty(key, ""); - if(StringUtils.isNotEmpty(value)) { - break; - } - } - result = result.substring(0,m.start()) - + value - + result.substring(m.end()); - continue inter; - } - // we only hit here if there were no interpolations last while loop - break; - } - return result; - } -} diff --git a/commons/src/main/java/org/archive/util/Recorder.java b/commons/src/main/java/org/archive/util/Recorder.java deleted file mode 100644 index 298481ea..00000000 --- a/commons/src/main/java/org/archive/util/Recorder.java +++ /dev/null @@ -1,581 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.DeflaterInputStream; -import java.util.zip.GZIPInputStream; - -import org.apache.commons.httpclient.ChunkedInputStream; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.archive.io.GenericReplayCharSequence; -import org.archive.io.RecordingInputStream; -import org.archive.io.RecordingOutputStream; -import org.archive.io.ReplayCharSequence; -import org.archive.io.ReplayInputStream; - -import com.google.common.base.Charsets; - - -/** - * Pairs together a RecordingInputStream and RecordingOutputStream - * to capture exactly a single HTTP transaction. - * - * Initially only supports HTTP/1.0 (one request, one response per stream) - * - * Call {@link #markContentBegin()} to demarc the transition between HTTP - * header and body. - * - * @author gojomo - */ -public class Recorder { - protected static Logger logger = - Logger.getLogger("org.archive.util.HttpRecorder"); - - private static final int DEFAULT_OUTPUT_BUFFER_SIZE = 16384; - private static final int DEFAULT_INPUT_BUFFER_SIZE = 524288; - - private RecordingInputStream ris = null; - private RecordingOutputStream ros = null; - - /** - * Backing file basename. - * - * Keep it around so can clean up backing files left on disk. - */ - private String backingFileBasename = null; - - /** - * Backing file output stream suffix. - */ - private static final String RECORDING_OUTPUT_STREAM_SUFFIX = ".ros"; - - /** - * Backing file input stream suffix. - */ - private static final String RECORDING_INPUT_STREAM_SUFFIX = ".ris"; - - /** - * recording-input (ris) content character encoding. - */ - protected String characterEncoding = null; - - /** - * Charset to use for CharSequence provision. Will be UTF-8 if no - * encoding ever requested; a Charset matching above characterEncoding - * if possible; ISO_8859 if above characterEncoding is unsatisfiable. - * TODO: unify to UTF-8 for unspecified and bad-specified cases? - * (current behavior is for consistency with our prior but perhaps not - * optimal behavior) - */ - protected Charset charset = Charsets.UTF_8; - - /** whether recording-input (ris) message-body is chunked */ - protected boolean inputIsChunked = false; - - /** recording-input (ris) entity content-encoding (eg gzip, deflate), if any */ - protected String contentEncoding = null; - - private ReplayCharSequence replayCharSequence; - - - /** - * Create an HttpRecorder. - * - * @param tempDir Directory into which we drop backing files for - * recorded input and output. - * @param backingFilenameBase Backing filename base to which we'll append - * suffices ris for recorded input stream and - * ros for recorded output stream. - * @param outBufferSize Size of output buffer to use. - * @param inBufferSize Size of input buffer to use. - */ - public Recorder(File tempDir, String backingFilenameBase, - int outBufferSize, int inBufferSize) { - this(new File(ensure(tempDir), backingFilenameBase), - outBufferSize, inBufferSize); - } - - - private static File ensure(File tempDir) { - try { - org.archive.util.FileUtils.ensureWriteableDirectory(tempDir); - } catch (IOException e) { - throw new IllegalStateException(e); - } - - return tempDir; - } - - public Recorder(File file, int outBufferSize, int inBufferSize) { - super(); - this.backingFileBasename = file.getAbsolutePath(); - this.ris = new RecordingInputStream(inBufferSize, - this.backingFileBasename + RECORDING_INPUT_STREAM_SUFFIX); - this.ros = new RecordingOutputStream(outBufferSize, - this.backingFileBasename + RECORDING_OUTPUT_STREAM_SUFFIX); - } - - /** - * Create an HttpRecorder. - * - * @param tempDir - * Directory into which we drop backing files for recorded input - * and output. - * @param backingFilenameBase - * Backing filename base to which we'll append suffices - * ris for recorded input stream and - * ros for recorded output stream. - */ - public Recorder(File tempDir, String backingFilenameBase) { - this(tempDir, backingFilenameBase, DEFAULT_INPUT_BUFFER_SIZE, - DEFAULT_OUTPUT_BUFFER_SIZE); - } - - - /** - * Wrap the provided stream with the internal RecordingInputStream - * - * open() throws an exception if RecordingInputStream is already open. - * - * @param is InputStream to wrap. - * - * @return The input stream wrapper which itself is an input stream. - * Pass this in place of the passed stream so input can be recorded. - * - * @throws IOException - */ - public InputStream inputWrap(InputStream is) - throws IOException { - logger.fine(Thread.currentThread().getName() + " wrapping input"); - - // discard any state from previously-recorded input - this.characterEncoding = null; - this.inputIsChunked = false; - this.contentEncoding = null; - - this.ris.open(is); - return this.ris; - } - - /** - * Wrap the provided stream with the internal RecordingOutputStream - * - * open() throws an exception if RecordingOutputStream is already open. - * - * @param os The output stream to wrap. - * - * @return The output stream wrapper which is itself an output stream. - * Pass this in place of the passed stream so output can be recorded. - * - * @throws IOException - */ - public OutputStream outputWrap(OutputStream os) - throws IOException { - this.ros.open(os); - return this.ros; - } - - /** - * Close all streams. - */ - public void close() { - logger.fine(Thread.currentThread().getName() + " closing"); - try { - this.ris.close(); - } catch (IOException e) { - // TODO: Can we not let the exception out of here and report it - // higher up in the caller? - DevUtils.logger.log(Level.SEVERE, "close() ris" + - DevUtils.extraInfo(), e); - } - try { - this.ros.close(); - } catch (IOException e) { - DevUtils.logger.log(Level.SEVERE, "close() ros" + - DevUtils.extraInfo(), e); - } - } - - /** - * Return the internal RecordingInputStream - * - * @return A RIS. - */ - public RecordingInputStream getRecordedInput() { - return this.ris; - } - - /** - * @return The RecordingOutputStream. - */ - public RecordingOutputStream getRecordedOutput() { - return this.ros; - } - - /** - * Mark current position as the point where the HTTP headers end. - */ - public void markContentBegin() { - this.ris.markContentBegin(); - } - - public long getResponseContentLength() { - return this.ris.getResponseContentLength(); - } - - /** - * Close both input and output recorders. - * - * Recorders are the output streams to which we are recording. - * {@link #close()} closes the stream that is being recorded and the - * recorder. This method explicitly closes the recorder only. - */ - public void closeRecorders() { - try { - this.ris.closeRecorder(); - this.ros.closeRecorder(); - } catch (IOException e) { - DevUtils.warnHandle(e, "Convert to runtime exception?"); - } - } - - /** - * Cleanup backing files. - * - * Call when completely done w/ recorder. Removes any backing files that - * may have been dropped. - */ - public void cleanup() { - this.close(); - this.delete(this.backingFileBasename + RECORDING_OUTPUT_STREAM_SUFFIX); - this.delete(this.backingFileBasename + RECORDING_INPUT_STREAM_SUFFIX); - } - - /** - * Delete file if exists. - * - * @param name Filename to delete. - */ - private void delete(String name) { - File f = new File(name); - if (f.exists()) { - f.delete(); - } - } - - - protected static ThreadLocal currentRecorder = new ThreadLocal(); - - public static void setHttpRecorder(Recorder httpRecorder) { - currentRecorder.set(httpRecorder); - } - - /** - * Get the current threads' HttpRecorder. - * - * @return This threads' HttpRecorder. Returns null if can't find a - * HttpRecorder in current instance. - */ - public static Recorder getHttpRecorder() { - return currentRecorder.get(); - } - - /** - * @param characterEncoding Character encoding of input recording. - * @return actual charset in use after attempt to set - */ - public void setCharset(Charset cs) { - this.charset = cs; - } - - /** - * @return effective Charset of input recording - */ - public Charset getCharset() { - return this.charset; - } - - /** - * @param characterEncoding Character encoding of input recording. - */ - public void setInputIsChunked(boolean chunked) { - this.inputIsChunked = chunked; - } - - protected static Set SUPPORTED_ENCODINGS = new HashSet(); - static { - SUPPORTED_ENCODINGS.add("gzip"); - SUPPORTED_ENCODINGS.add("x-gzip"); - SUPPORTED_ENCODINGS.add("deflate"); - SUPPORTED_ENCODINGS.add("identity"); - SUPPORTED_ENCODINGS.add("none"); // unofficial but common - } - /** - * @param contentEncoding declared content-encoding of input recording. - */ - public void setContentEncoding(String contentEncoding) { - String lowerCoding = contentEncoding.toLowerCase(); - if(!SUPPORTED_ENCODINGS.contains(contentEncoding.toLowerCase())) { - throw new IllegalArgumentException("contentEncoding unsupported: "+contentEncoding); - } - this.contentEncoding = lowerCoding; - } - - /** - * @return Returns the characterEncoding. - */ - public String getContentEncoding() { - return this.contentEncoding; - } - - - /** - * @return - * @throws IOException - * @deprecated use getContentReplayCharSequence - */ - public ReplayCharSequence getReplayCharSequence() throws IOException { - return getContentReplayCharSequence(); - } - - /** - * @return A ReplayCharSequence. Caller may call - * {@link ReplayCharSequence#close()} when finished. However, in - * heritrix, the ReplayCharSequence is closed automatically when url - * processing has finished; in that context it's preferable not - * to close, so that processors can reuse the same instance. - * @throws IOException - * @see {@link #endReplays()} - */ - public ReplayCharSequence getContentReplayCharSequence() throws IOException { - if (replayCharSequence == null || !replayCharSequence.isOpen() - || !replayCharSequence.getCharset().equals(charset)) { - if(replayCharSequence!=null && replayCharSequence.isOpen()) { - // existing sequence must not have matched now-configured Charset; close - replayCharSequence.close(); - } - replayCharSequence = getContentReplayCharSequence(this.charset); - } - return replayCharSequence; - } - - - /** - * @param characterEncoding Encoding of recorded stream. - * @return A ReplayCharSequence Will return null if an IOException. Call - * close on returned RCS when done. - * @throws IOException - */ - public ReplayCharSequence getContentReplayCharSequence(Charset requestedCharset) throws IOException { - // raw data overflows to disk; use temp file - InputStream ris = getContentReplayInputStream(); - ReplayCharSequence rcs = new GenericReplayCharSequence( - ris, - calcRecommendedCharBufferSize(this.getRecordedInput()), - this.backingFileBasename + RECORDING_OUTPUT_STREAM_SUFFIX, - requestedCharset); - ris.close(); - return rcs; - } - - /** - * Calculate a recommended size for an in-memory decoded-character buffer - * of this content. We seek a size that is itself no larger (in 2-byte chars) - * than the memory already used by the RecordingInputStream's internal raw - * byte buffer, and also no larger than likely necessary. So, we take the - * minimum of the actual recorded byte size and the RecordingInputStream's - * max buffer size. - * - * @param inStream - * @return int length for in-memory decoded-character buffer - */ - static protected int calcRecommendedCharBufferSize(RecordingInputStream inStream) { - return (int) Math.min(inStream.getRecordedBufferLength()/2, inStream.getSize()); - } - - /** - * Get a raw replay of all recorded data (including, for example, HTTP - * protocol headers) - * - * @return A replay input stream. - * @throws IOException - */ - public ReplayInputStream getReplayInputStream() throws IOException { - return getRecordedInput().getReplayInputStream(); - } - - /** - * Get a raw replay of the 'message-body'. For the common case of - * HTTP, this is the raw, possibly chunked-transfer-encoded message - * contents not including the leading headers. - * - * @return A replay input stream. - * @throws IOException - */ - public ReplayInputStream getMessageBodyReplayInputStream() throws IOException { - return getRecordedInput().getMessageBodyReplayInputStream(); - } - - /** - * Get a raw replay of the 'entity'. For the common case of - * HTTP, this is the message-body after any (usually-unnecessary) - * transfer-decoding but before any content-encoding (eg gzip) decoding - * - * @return A replay input stream. - * @throws IOException - */ - public InputStream getEntityReplayInputStream() throws IOException { - if(inputIsChunked) { - return new ChunkedInputStream(getRecordedInput().getMessageBodyReplayInputStream()); - } else { - return getRecordedInput().getMessageBodyReplayInputStream(); - } - } - - /** - * Get a replay cued up for the 'content' (after all leading headers) - * - * @return A replay input stream. - * @throws IOException - */ - public InputStream getContentReplayInputStream() throws IOException { - InputStream entityStream = getEntityReplayInputStream(); - if(StringUtils.isEmpty(contentEncoding)) { - return entityStream; - } else if ("gzip".equalsIgnoreCase(contentEncoding) || "x-gzip".equalsIgnoreCase(contentEncoding)) { - try { - return new GZIPInputStream(entityStream); - } catch (IOException ioe) { - logger.log(Level.WARNING,"gzip problem; using raw entity instead",ioe); - IOUtils.closeQuietly(entityStream); // close partially-read stream - return getEntityReplayInputStream(); - } - } else if ("deflate".equalsIgnoreCase(contentEncoding)) { - return new DeflaterInputStream(entityStream); - } else if ("identity".equalsIgnoreCase(contentEncoding) || "none".equalsIgnoreCase(contentEncoding)) { - return entityStream; - } else { - // shouldn't be reached given check on setContentEncoding - logger.log(Level.INFO,"Unknown content-encoding '"+contentEncoding+"' declared; using raw entity instead"); - return entityStream; - } - } - - /** - * Return a short prefix of the presumed-textual content as a String. - * - * @param size max length of String to return - * @return String prefix, or empty String (with logged exception) on any error - */ - public String getContentReplayPrefixString(int size) { - return getContentReplayPrefixString(size, this.charset); - } - - /** - * Return a short prefix of the presumed-textual content as a String. - * - * @param size max length of String to return - * @return String prefix, or empty String (with logged exception) on any error - */ - public String getContentReplayPrefixString(int size, Charset cs) { - try { - InputStreamReader isr = new InputStreamReader(getContentReplayInputStream(), cs); - char[] chars = new char[size]; - int count = isr.read(chars); - isr.close(); - if (count > 0) { - return new String(chars,0,count); - } else { - return ""; - } - } catch (IOException e) { - logger.log(Level.SEVERE,"unable to get replay prefix string", e); - return ""; - } - } - - /** - * @param tempFile - * @throws IOException - */ - public void copyContentBodyTo(File tempFile) throws IOException { - InputStream inStream = null; - OutputStream outStream = null; - try { - inStream = getContentReplayInputStream(); - outStream = FileUtils.openOutputStream(tempFile); - IOUtils.copy(inStream, outStream); - } finally { - IOUtils.closeQuietly(inStream); - IOUtils.closeQuietly(outStream); - } - } - - /** - * Record the input stream for later playback by an extractor, etc. - * This is convenience method used to setup an artificial HttpRecorder - * scenario used in unit tests, etc. - * @param dir Directory to write backing file to. - * @param basename of what we're recording. - * @param in Stream to read. - * @param encoding Stream encoding. - * @throws IOException - * @return An {@link org.archive.util.Recorder}. - */ - public static Recorder wrapInputStreamWithHttpRecord(File dir, - String basename, InputStream in, String encoding) - throws IOException { - Recorder rec = new Recorder(dir, basename); - if (encoding != null && encoding.length() > 0) { - rec.setCharset(Charset.forName(encoding)); - } - // Do not use FastBufferedInputStream here. It does not - // support mark. - InputStream is = rec.inputWrap(new BufferedInputStream(in)); - final int BUFFER_SIZE = 1024 * 4; - byte [] buffer = new byte[BUFFER_SIZE]; - while(true) { - // Just read it all down. - int x = is.read(buffer); - if (x == -1) { - break; - } - } - is.close(); - return rec; - } - - public void endReplays() { - ArchiveUtils.closeQuietly(replayCharSequence); - replayCharSequence = null; - } -} diff --git a/commons/src/main/java/org/archive/util/Reporter.java b/commons/src/main/java/org/archive/util/Reporter.java deleted file mode 100644 index 2fcb8cd8..00000000 --- a/commons/src/main/java/org/archive/util/Reporter.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Map; - -public interface Reporter { - /** - * Make a default report to the passed-in Writer. Should - * be equivalent to reportTo(null, writer) - * - * @param writer to receive report - */ - public void reportTo(PrintWriter writer) throws IOException; - - /** - * Write a short single-line summary report - * - * @param writer to receive report - */ - @Deprecated - public void shortReportLineTo(PrintWriter pw) throws IOException; - - - /** - * @return Same data that's in the single line report, as key-value pairs - */ - public Map shortReportMap(); - - - /** - * Return a legend for the single-line summary report as a String. - * - * @return String single-line summary legend - */ - public String shortReportLegend(); -} diff --git a/commons/src/main/java/org/archive/util/TestUtils.java b/commons/src/main/java/org/archive/util/TestUtils.java index eb2e5a9f..889492a1 100644 --- a/commons/src/main/java/org/archive/util/TestUtils.java +++ b/commons/src/main/java/org/archive/util/TestUtils.java @@ -75,7 +75,7 @@ public class TestUtils { } - private static byte[] serialize(Object o) throws Exception { + public static byte[] serialize(Object o) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(o); diff --git a/commons/src/main/java/org/archive/util/anvl/ANVLRecord.java b/commons/src/main/java/org/archive/util/anvl/ANVLRecord.java deleted file mode 100644 index de2d3101..00000000 --- a/commons/src/main/java/org/archive/util/anvl/ANVLRecord.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util.anvl; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.archive.io.UTF8Bytes; - -/** - * An ordered {@link List} with 'data' {@link Element} values. - * ANVLRecords end with a blank line. - * - * @see A Name-Value - * Language (ANVL) - * @author stack - */ -public class ANVLRecord extends LinkedList implements UTF8Bytes { - private static final Logger logger = - Logger.getLogger(ANVLRecord.class.getName()); - - public static final String MIMETYPE = "application/warc-fields"; - - public static final ANVLRecord EMPTY_ANVL_RECORD = new ANVLRecord(); - - /** - * Arbitrary upper bound on maximum size of ANVL Record. - * Will throw an IOException if exceed this size. - */ - public static final long MAXIMUM_SIZE = 1024 * 10; - - /** - * An ANVL 'newline'. - * @see http://en.wikipedia.org/wiki/CRLF - */ - protected static final String CRLF = "\r\n"; - - protected static final String FOLD_PREFIX = CRLF + ' '; - - public ANVLRecord() { - super(); - } - - public ANVLRecord(Collection c) { - super(c); - } - - /** @deprecated */ - public ANVLRecord(int initialCapacity) { - super(); - } - - public boolean addLabel(final String l) { - return super.add(new Element(new Label(l))); - } - - public boolean addLabelValue(final String l, final String v) { - try { - return super.add(new Element(new Label(l), new Value(v))); - } catch (IllegalArgumentException e) { - logger.log(Level.WARNING, "bad label " + l + " or value " + v, e); - return false; - } - } - - @Override - public String toString() { - // TODO: What to emit for empty ANVLRecord? - StringBuilder sb = new StringBuilder(); - for (final Iterator i = iterator(); i.hasNext();) { - sb.append(i.next()); - sb.append(CRLF); - } - // 'ANVL Records end in a blank line'. - sb.append(CRLF); - return sb.toString(); - } - - public Map asMap() { - Map m = new HashMap(size()); - for (final Iterator i = iterator(); i.hasNext();) { - Element e = i.next(); - m.put(e.getLabel().toString(), - e.isValue()? e.getValue().toString(): (String)null); - } - return m; - } - - @Override - public ANVLRecord clone() { - return (ANVLRecord) super.clone(); - } - - /** - * @return This ANVLRecord as UTF8 bytes. - */ - public byte [] getUTF8Bytes() - throws UnsupportedEncodingException { - return toString().getBytes(UTF8); - } - - /** - * Parses a single ANVLRecord from passed InputStream. - * Read as a single-byte stream until we get to a CRLFCRLF which - * signifies End-of-ANVLRecord. Then parse all read as a UTF-8 Stream. - * Doing it this way, while requiring a double-scan, it makes it so do not - * need to be passed a RepositionableStream or a Stream that supports - * marking. Also no danger of over-reading which can happen when we - * wrap passed Stream with an InputStreamReader for doing UTF-8 - * character conversion (See the ISR class comment). - * @param is InputStream - * @return An ANVLRecord instance. - * @throws IOException - */ - public static ANVLRecord load(final InputStream is) - throws IOException { - // It doesn't look like a CRLF sequence is possible in UTF-8 without - // it signifying CRLF: The top bits are set in multibyte characters. - // Was thinking of recording CRLF as I was running through this first - // parse but the offsets would then be incorrect if any multibyte - // characters in the intervening gaps between CRLF. - boolean isCRLF = false; - boolean recordStart = false; - ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); - boolean done = false; - int read = 0; - for (int c = -1, previousCharacter; !done;) { - if (read++ >= MAXIMUM_SIZE) { - throw new IOException("Read " + MAXIMUM_SIZE + - " bytes without finding \\r\\n\\r\\n " + - "End-Of-ANVLRecord"); - } - previousCharacter = c; - c = is.read(); - if (c == -1) { - throw new IOException("End-Of-Stream before \\r\\n\\r\\n " + - "End-Of-ANVLRecord:\n" + - new String(baos.toByteArray(), UTF8)); - } - if (isLF((char)c) && isCR((char)previousCharacter)) { - if (isCRLF) { - // If we just had a CRLF, then its two CRLFs and its end of - // record. We're done. - done = true; - } else { - isCRLF = true; - } - } else if (!recordStart && Character.isWhitespace(c)) { - // Skip any whitespace at start of ANVLRecord. - continue; - } else { - // Clear isCRLF flag if this character is NOT a '\r'. - if (isCRLF && !isCR((char)c)) { - isCRLF = false; - } - // Not whitespace so start record if we haven't already. - if (!recordStart) { - recordStart = true; - } - } - baos.write(c); - } - return load(new String(baos.toByteArray(), UTF8)); - } - - /** - * Parse passed String for an ANVL Record. - * Looked at writing javacc grammer but preprocessing is required to - * handle folding: See - * https://javacc.dev.java.net/servlets/BrowseList?list=users&by=thread&from=56173. - * Looked at Terence Parr's ANTLR. More capable. Can set lookahead count. - * A value of 3 would help with folding. But its a pain defining UNICODE - * grammers -- needed by ANVL -- and support seems incomplete - * anyways: http://www.doc.ic.ac.uk/lab/secondyear/Antlr/lexer.html#unicode. - * For now, go with the below hand-rolled parser. - * @param s String with an ANVLRecord. - * @return ANVLRecord parsed from passed String. - * @throws IOException - */ - public static ANVLRecord load(final String s) - throws IOException { - ANVLRecord record = new ANVLRecord(); - boolean inValue = false, inLabel = false, inComment = false, - inNewLine = false; - String label = null; - StringBuilder sb = new StringBuilder(s.length()); - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - - // Assert I can do look-ahead. - if ((i + 1) > s.length()) { - throw new IOException("Premature End-of-ANVLRecord:\n" + - s.substring(i)); - } - - // If at LF of a CRLF, just go around again. Eat up the LF. - if (inNewLine && isLF(c)) { - continue; - } - - // If we're at a CRLF and we were just on one, exit. Found Record. - if (inNewLine && isCR(c) && isLF(s.charAt(i + 1))) { - break; - } - - // Check if we're on a fold inside a Value. Skip multiple white - // space after CRLF. - if (inNewLine && inValue && Character.isWhitespace(c)) { - continue; - } - - // Else set flag if we're at a CRLF. - inNewLine = isCR(c) && isLF(s.charAt(i + 1)); - - if (inNewLine) { - if (inComment) { - inComment = false; - } else if (label != null && !inValue) { - // Label only 'data element'. - record.addLabel(label); - label = null; - sb.setLength(0); - } else if (inValue) { - // Assert I can do look-ahead past current CRLF. - if ((i + 3) > s.length()) { - throw new IOException("Premature End-of-ANVLRecord " - + "(2):\n" + s.substring(i)); - } - if (!isCR(s.charAt(i + 2)) && !isLF(s.charAt(i + 3)) - && Character.isWhitespace(s.charAt(i + 2))) { - // Its a fold. Let it go around. But add in a CRLF and - // space and do it here. We don't let CRLF fall through - // to the sb.append on the end of this loop. - sb.append(CRLF); - sb.append(' '); - } else { - // Next line is a new SubElement, a new Comment or - // Label. - record.addLabelValue(label, sb.toString()); - sb.setLength(0); - label = null; - inValue = false; - } - } else { - // We're whitespace between label and value or whitespace - // before we've figured whether label or comment. - } - // Don't let the '\r' or CRLF through. - continue; - } - - if (inComment) { - continue; - } else if (inLabel) { - if (c == Label.COLON) { - label = sb.toString(); - sb.setLength(0); - inLabel = false; - continue; - } - } else { - if (!inLabel && !inValue && !inComment) { - // We have no state. Figure one. - if (Character.isWhitespace(c)) { - // If no state, and whitespace, skip. Don't record. - continue; - } else if (label == null && c == '#') { - inComment = true; - // Don't record comments. - continue; - } else if (label == null) { - inLabel = true; - } else { - inValue = true; - } - } - } - sb.append(c); - } - return record; - } - - /** - * @return Count of ANVLRecord bytes. Be careful, an empty ANVLRecord is - * CRLFCRLF so is of size 4. Also, expensive, since it makes String of - * the record so it can count bytes. - */ - public synchronized int getLength() { - int length = -1; - try { - length = getUTF8Bytes().length; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - return length; - } - - public static boolean isCROrLF(final char c) { - return isCR(c) || isLF(c); - } - - public static boolean isCR(final char c) { - return c == ANVLRecord.CRLF.charAt(0); - } - - public static boolean isLF(final char c) { - return c == ANVLRecord.CRLF.charAt(1); - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/util/anvl/Element.java b/commons/src/main/java/org/archive/util/anvl/Element.java deleted file mode 100644 index 5881fa9b..00000000 --- a/commons/src/main/java/org/archive/util/anvl/Element.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util.anvl; - - -/** - * ANVL 'data element'. - * Made of a lone {@link Label}, or a {@link Label} plus {@link Value}. - * - * @author stack - * @see A Name-Value - * Language (ANVL) - */ -public class Element { - private final SubElement [] subElements; - - public Element(final Label l) { - this.subElements = new SubElement [] {l}; - } - - public Element(final Label l, final Value v) { - this.subElements = new SubElement [] {l, v}; - } - - public boolean isValue() { - return this.subElements.length > 1; - } - - public Label getLabel() { - return (Label)this.subElements[0]; - } - - public Value getValue() { - if (!isValue()) { - return null; - } - return (Value)this.subElements[1]; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < subElements.length; i++) { - sb.append(subElements[i].toString()); - if (i == 0) { - // Add colon after Label. - sb.append(':'); - if (isValue()) { - // Add space to intro the value. - sb.append(' '); - } - } - } - return sb.toString(); - } -} diff --git a/commons/src/main/java/org/archive/util/anvl/Label.java b/commons/src/main/java/org/archive/util/anvl/Label.java deleted file mode 100644 index fdadb735..00000000 --- a/commons/src/main/java/org/archive/util/anvl/Label.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util.anvl; - -class Label extends SubElement { - public static final char COLON = ':'; - - @SuppressWarnings("unused") - private Label() { - this(null); - } - - public Label(final String s) { - super(s); - } - - @Override - protected void checkCharacter(char c, String srcStr, int index) { - super.checkCharacter(c, srcStr, index); - if (c == COLON) { - throw new IllegalArgumentException("Label cannot contain " + COLON); - } - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/util/anvl/SubElement.java b/commons/src/main/java/org/archive/util/anvl/SubElement.java deleted file mode 100644 index 33b9e9bb..00000000 --- a/commons/src/main/java/org/archive/util/anvl/SubElement.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util.anvl; - -/** - * Abstract ANVL 'data element' sub-part. - * Subclass to make a Comment, a Label, or a Value. - * @author stack - */ -abstract class SubElement { - private final String e; - - protected SubElement() { - this(null); - } - - public SubElement(final String s) { - this.e = baseCheck(s); - } - - protected String baseCheck(final String s) { - // Check for null. - if (s == null) { - throw new IllegalArgumentException("Can't be null"); - } - // Check for CRLF. - for (int i = 0; i < s.length(); i++) { - checkCharacter(s.charAt(i), s, i); - } - return s; - } - - protected void checkCharacter(final char c, final String srcStr, - final int index) { - checkControlCharacter(c, srcStr, index); - checkCRLF(c, srcStr, index); - } - - protected void checkControlCharacter(final char c, final String srcStr, - final int index) { - if (Character.isISOControl(c) && !Character.isWhitespace(c) || - !Character.isValidCodePoint(c)) { - throw new IllegalArgumentException(srcStr + - " contains a control character(s) or invalid code point: 0x" + - Integer.toHexString(c)); - } - } - - protected void checkCRLF(final char c, final String srcStr, - final int index) { - if (ANVLRecord.isCROrLF(c)) { - throw new IllegalArgumentException(srcStr + - " contains disallowed CRLF control character(s): 0x" + - Integer.toHexString(c)); - } - } - - @Override - public String toString() { - return e; - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/util/anvl/Value.java b/commons/src/main/java/org/archive/util/anvl/Value.java deleted file mode 100644 index 2a650ba2..00000000 --- a/commons/src/main/java/org/archive/util/anvl/Value.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.util.anvl; - -/** - * TODO: Now values 'fold' but should but perhaps they shouldn't be stored - * folded. Only when we serialize should we fold (But how to know where - * to fold?). - * @author stack - * @version $Date$ $Version$ - */ -class Value extends SubElement { - - private StringBuilder sb; - private boolean folding = false; - - @SuppressWarnings("unused") - private Value() { - this(null); - } - - public Value(final String s) { - super(s); - } - - protected String baseCheck(String s) { - this.sb = new StringBuilder(s.length() * 2); - super.baseCheck(s); - return sb.toString(); - } - - @Override - protected void checkCharacter(char c, String srcStr, int index) { - checkControlCharacter(c, srcStr, index); - // Now, rewrite the value String with folding (If CR or LF or CRLF - // present. - if (ANVLRecord.isCR(c)) { - this.folding = true; - this.sb.append(ANVLRecord.FOLD_PREFIX); - } else if (ANVLRecord.isLF(c)) { - if (!this.folding) { - this.folding = true; - this.sb.append(ANVLRecord.FOLD_PREFIX); - } else { - // Previous character was a CR. Fold prefix has been added. - } - } else if (this.folding && Character.isWhitespace(c)) { - // Only write out one whitespace character. Skip. - } else { - this.folding = false; - this.sb.append(c); - } - } -} \ No newline at end of file diff --git a/commons/src/main/java/org/archive/util/anvl/package.html b/commons/src/main/java/org/archive/util/anvl/package.html deleted file mode 100644 index 4a2a8963..00000000 --- a/commons/src/main/java/org/archive/util/anvl/package.html +++ /dev/null @@ -1,42 +0,0 @@ - - - -org.archive.util.anvl package - - -Parsers and Writers for the (expired) Internet-Draft A Name-Value -Language (ANVL). Use {@link org.archive.util.anvl.ANVLRecord} -to create new instances of ANVL Records and for parsing. - -

Implementation Details

-

The ANVL Internet-Draft of 14 February, 2005 is inspecific as to the -definition of 'blank line' and 'newline'. This parser implementation -assumes CRNL. -

-

Says "An element consists of a label, a colon, and an optional value". -Should that be: "An element consists of a label and an optional value, or a -comment."

- -

Specification is unclear regards CR or NL in label or -comment (This implementation disallows CR or NL in labels but lets -them pass in comments).

- -

A grammar would help. Here is RFC822: -

-     field       =  field-name ":" [ field-body ] CRLF
-     
-     field-name  =  1*<any CHAR, excluding CTLs, SPACE, and ":">
-     
-     field-body  =  field-body-contents
-                    [CRLF LWSP-char field-body]
-     
-     field-body-contents =
-                   <the ASCII characters making up the field-body, as
-                    defined in the following sections, and consisting
-                    of combinations of atom, quoted-string, and
-                    specials tokens, or else consisting of texts>
-
-

- - diff --git a/commons/src/main/resources/effective_tld_names.dat b/commons/src/main/resources/effective_tld_names.dat deleted file mode 100644 index 0df8800d..00000000 --- a/commons/src/main/resources/effective_tld_names.dat +++ /dev/null @@ -1,5229 +0,0 @@ -// ***** BEGIN LICENSE BLOCK ***** -// Version: MPL 1.1/GPL 2.0/LGPL 2.1 -// -// The contents of this file are subject to the Mozilla Public License Version -// 1.1 (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.mozilla.org/MPL/ -// -// Software distributed under the License is distributed on an "AS IS" basis, -// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License -// for the specific language governing rights and limitations under the -// License. -// -// The Original Code is the Public Suffix List. -// -// The Initial Developer of the Original Code is -// Jo Hermans . -// Portions created by the Initial Developer are Copyright (C) 2007 -// the Initial Developer. All Rights Reserved. -// -// Contributor(s): -// Ruben Arakelyan -// Gervase Markham -// Pamela Greene -// David Triendl -// Jothan Frakes -// The kind representatives of many TLD registries -// -// Alternatively, the contents of this file may be used under the terms of -// either the GNU General Public License Version 2 or later (the "GPL"), or -// the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), -// in which case the provisions of the GPL or the LGPL are applicable instead -// of those above. If you wish to allow use of your version of this file only -// under the terms of either the GPL or the LGPL, and not to allow others to -// use your version of this file under the terms of the MPL, indicate your -// decision by deleting the provisions above and replace them with the notice -// and other provisions required by the GPL or the LGPL. If you do not delete -// the provisions above, a recipient may use your version of this file under -// the terms of any one of the MPL, the GPL or the LGPL. -// -// ***** END LICENSE BLOCK ***** - -// ===BEGIN ICANN DOMAINS=== - -// ac : http://en.wikipedia.org/wiki/.ac -ac -com.ac -edu.ac -gov.ac -net.ac -mil.ac -org.ac - -// ad : http://en.wikipedia.org/wiki/.ad -ad -nom.ad - -// ae : http://en.wikipedia.org/wiki/.ae -// see also: "Domain Name Eligibility Policy" at http://www.aeda.ae/eng/aepolicy.php -ae -co.ae -net.ae -org.ae -sch.ae -ac.ae -gov.ae -mil.ae - -// aero : see http://www.information.aero/index.php?id=66 -aero -accident-investigation.aero -accident-prevention.aero -aerobatic.aero -aeroclub.aero -aerodrome.aero -agents.aero -aircraft.aero -airline.aero -airport.aero -air-surveillance.aero -airtraffic.aero -air-traffic-control.aero -ambulance.aero -amusement.aero -association.aero -author.aero -ballooning.aero -broker.aero -caa.aero -cargo.aero -catering.aero -certification.aero -championship.aero -charter.aero -civilaviation.aero -club.aero -conference.aero -consultant.aero -consulting.aero -control.aero -council.aero -crew.aero -design.aero -dgca.aero -educator.aero -emergency.aero -engine.aero -engineer.aero -entertainment.aero -equipment.aero -exchange.aero -express.aero -federation.aero -flight.aero -freight.aero -fuel.aero -gliding.aero -government.aero -groundhandling.aero -group.aero -hanggliding.aero -homebuilt.aero -insurance.aero -journal.aero -journalist.aero -leasing.aero -logistics.aero -magazine.aero -maintenance.aero -marketplace.aero -media.aero -microlight.aero -modelling.aero -navigation.aero -parachuting.aero -paragliding.aero -passenger-association.aero -pilot.aero -press.aero -production.aero -recreation.aero -repbody.aero -res.aero -research.aero -rotorcraft.aero -safety.aero -scientist.aero -services.aero -show.aero -skydiving.aero -software.aero -student.aero -taxi.aero -trader.aero -trading.aero -trainer.aero -union.aero -workinggroup.aero -works.aero - -// af : http://www.nic.af/help.jsp -af -gov.af -com.af -org.af -net.af -edu.af - -// ag : http://www.nic.ag/prices.htm -ag -com.ag -org.ag -net.ag -co.ag -nom.ag - -// ai : http://nic.com.ai/ -ai -off.ai -com.ai -net.ai -org.ai - -// al : http://www.ert.gov.al/ert_alb/faq_det.html?Id=31 -al -com.al -edu.al -gov.al -mil.al -net.al -org.al - -// am : http://en.wikipedia.org/wiki/.am -am - -// an : http://www.una.an/an_domreg/default.asp -an -com.an -net.an -org.an -edu.an - -// ao : http://en.wikipedia.org/wiki/.ao -// http://www.dns.ao/REGISTR.DOC -ao -ed.ao -gv.ao -og.ao -co.ao -pb.ao -it.ao - -// aq : http://en.wikipedia.org/wiki/.aq -aq - -// ar : http://en.wikipedia.org/wiki/.ar -*.ar -!congresodelalengua3.ar -!educ.ar -!gobiernoelectronico.ar -!mecon.ar -!nacion.ar -!nic.ar -!promocion.ar -!retina.ar -!uba.ar - -// arpa : http://en.wikipedia.org/wiki/.arpa -// Confirmed by registry 2008-06-18 -e164.arpa -in-addr.arpa -ip6.arpa -iris.arpa -uri.arpa -urn.arpa - -// as : http://en.wikipedia.org/wiki/.as -as -gov.as - -// asia : http://en.wikipedia.org/wiki/.asia -asia - -// at : http://en.wikipedia.org/wiki/.at -// Confirmed by registry 2008-06-17 -at -ac.at -co.at -gv.at -or.at - -// au : http://en.wikipedia.org/wiki/.au -// http://www.auda.org.au/ -// 2LDs -com.au -net.au -org.au -edu.au -gov.au -csiro.au -asn.au -id.au -// Historic 2LDs (closed to new registration, but sites still exist) -info.au -conf.au -oz.au -// CGDNs - http://www.cgdn.org.au/ -act.au -nsw.au -nt.au -qld.au -sa.au -tas.au -vic.au -wa.au -// 3LDs -act.edu.au -nsw.edu.au -nt.edu.au -qld.edu.au -sa.edu.au -tas.edu.au -vic.edu.au -wa.edu.au -act.gov.au -// Removed at request of Shae.Donelan@services.nsw.gov.au, 2010-03-04 -// nsw.gov.au -nt.gov.au -qld.gov.au -sa.gov.au -tas.gov.au -vic.gov.au -wa.gov.au - -// aw : http://en.wikipedia.org/wiki/.aw -aw -com.aw - -// ax : http://en.wikipedia.org/wiki/.ax -ax - -// az : http://en.wikipedia.org/wiki/.az -az -com.az -net.az -int.az -gov.az -org.az -edu.az -info.az -pp.az -mil.az -name.az -pro.az -biz.az - -// ba : http://en.wikipedia.org/wiki/.ba -ba -org.ba -net.ba -edu.ba -gov.ba -mil.ba -unsa.ba -unbi.ba -co.ba -com.ba -rs.ba - -// bb : http://en.wikipedia.org/wiki/.bb -bb -biz.bb -com.bb -edu.bb -gov.bb -info.bb -net.bb -org.bb -store.bb - -// bd : http://en.wikipedia.org/wiki/.bd -*.bd - -// be : http://en.wikipedia.org/wiki/.be -// Confirmed by registry 2008-06-08 -be -ac.be - -// bf : http://en.wikipedia.org/wiki/.bf -bf -gov.bf - -// bg : http://en.wikipedia.org/wiki/.bg -// https://www.register.bg/user/static/rules/en/index.html -bg -a.bg -b.bg -c.bg -d.bg -e.bg -f.bg -g.bg -h.bg -i.bg -j.bg -k.bg -l.bg -m.bg -n.bg -o.bg -p.bg -q.bg -r.bg -s.bg -t.bg -u.bg -v.bg -w.bg -x.bg -y.bg -z.bg -0.bg -1.bg -2.bg -3.bg -4.bg -5.bg -6.bg -7.bg -8.bg -9.bg - -// bh : http://en.wikipedia.org/wiki/.bh -bh -com.bh -edu.bh -net.bh -org.bh -gov.bh - -// bi : http://en.wikipedia.org/wiki/.bi -// http://whois.nic.bi/ -bi -co.bi -com.bi -edu.bi -or.bi -org.bi - -// biz : http://en.wikipedia.org/wiki/.biz -biz - -// bj : http://en.wikipedia.org/wiki/.bj -bj -asso.bj -barreau.bj -gouv.bj - -// bm : http://www.bermudanic.bm/dnr-text.txt -bm -com.bm -edu.bm -gov.bm -net.bm -org.bm - -// bn : http://en.wikipedia.org/wiki/.bn -*.bn - -// bo : http://www.nic.bo/ -bo -com.bo -edu.bo -gov.bo -gob.bo -int.bo -org.bo -net.bo -mil.bo -tv.bo - -// br : http://registro.br/dominio/dpn.html -// Updated by registry 2011-03-01 -br -adm.br -adv.br -agr.br -am.br -arq.br -art.br -ato.br -b.br -bio.br -blog.br -bmd.br -can.br -cim.br -cng.br -cnt.br -com.br -coop.br -ecn.br -edu.br -emp.br -eng.br -esp.br -etc.br -eti.br -far.br -flog.br -fm.br -fnd.br -fot.br -fst.br -g12.br -ggf.br -gov.br -imb.br -ind.br -inf.br -jor.br -jus.br -lel.br -mat.br -med.br -mil.br -mus.br -net.br -nom.br -not.br -ntr.br -odo.br -org.br -ppg.br -pro.br -psc.br -psi.br -qsl.br -radio.br -rec.br -slg.br -srv.br -taxi.br -teo.br -tmp.br -trd.br -tur.br -tv.br -vet.br -vlog.br -wiki.br -zlg.br - -// bs : http://www.nic.bs/rules.html -bs -com.bs -net.bs -org.bs -edu.bs -gov.bs - -// bt : http://en.wikipedia.org/wiki/.bt -bt -com.bt -edu.bt -gov.bt -net.bt -org.bt - -// bv : No registrations at this time. -// Submitted by registry 2006-06-16 - -// bw : http://en.wikipedia.org/wiki/.bw -// http://www.gobin.info/domainname/bw.doc -// list of other 2nd level tlds ? -bw -co.bw -org.bw - -// by : http://en.wikipedia.org/wiki/.by -// http://tld.by/rules_2006_en.html -// list of other 2nd level tlds ? -by -gov.by -mil.by -// Official information does not indicate that com.by is a reserved -// second-level domain, but it's being used as one (see www.google.com.by and -// www.yahoo.com.by, for example), so we list it here for safety's sake. -com.by - -// http://hoster.by/ -of.by - -// bz : http://en.wikipedia.org/wiki/.bz -// http://www.belizenic.bz/ -bz -com.bz -net.bz -org.bz -edu.bz -gov.bz - -// ca : http://en.wikipedia.org/wiki/.ca -ca -// ca geographical names -ab.ca -bc.ca -mb.ca -nb.ca -nf.ca -nl.ca -ns.ca -nt.ca -nu.ca -on.ca -pe.ca -qc.ca -sk.ca -yk.ca -// gc.ca: http://en.wikipedia.org/wiki/.gc.ca -// see also: http://registry.gc.ca/en/SubdomainFAQ -gc.ca - -// cat : http://en.wikipedia.org/wiki/.cat -cat - -// cc : http://en.wikipedia.org/wiki/.cc -cc - -// cd : http://en.wikipedia.org/wiki/.cd -// see also: https://www.nic.cd/domain/insertDomain_2.jsp?act=1 -cd -gov.cd - -// cf : http://en.wikipedia.org/wiki/.cf -cf - -// cg : http://en.wikipedia.org/wiki/.cg -cg - -// ch : http://en.wikipedia.org/wiki/.ch -ch - -// ci : http://en.wikipedia.org/wiki/.ci -// http://www.nic.ci/index.php?page=charte -ci -org.ci -or.ci -com.ci -co.ci -edu.ci -ed.ci -ac.ci -net.ci -go.ci -asso.ci -aéroport.ci -int.ci -presse.ci -md.ci -gouv.ci - -// ck : http://en.wikipedia.org/wiki/.ck -*.ck -!www.ck - -// cl : http://en.wikipedia.org/wiki/.cl -cl -gov.cl -gob.cl -co.cl -mil.cl - -// cm : http://en.wikipedia.org/wiki/.cm -cm -gov.cm - -// cn : http://en.wikipedia.org/wiki/.cn -// Submitted by registry 2008-06-11 -cn -ac.cn -com.cn -edu.cn -gov.cn -net.cn -org.cn -mil.cn -公司.cn -网络.cn -網絡.cn -// cn geographic names -ah.cn -bj.cn -cq.cn -fj.cn -gd.cn -gs.cn -gz.cn -gx.cn -ha.cn -hb.cn -he.cn -hi.cn -hl.cn -hn.cn -jl.cn -js.cn -jx.cn -ln.cn -nm.cn -nx.cn -qh.cn -sc.cn -sd.cn -sh.cn -sn.cn -sx.cn -tj.cn -xj.cn -xz.cn -yn.cn -zj.cn -hk.cn -mo.cn -tw.cn - -// co : http://en.wikipedia.org/wiki/.co -// Submitted by registry 2008-06-11 -co -arts.co -com.co -edu.co -firm.co -gov.co -info.co -int.co -mil.co -net.co -nom.co -org.co -rec.co -web.co - -// com : http://en.wikipedia.org/wiki/.com -com - -// coop : http://en.wikipedia.org/wiki/.coop -coop - -// cr : http://www.nic.cr/niccr_publico/showRegistroDominiosScreen.do -cr -ac.cr -co.cr -ed.cr -fi.cr -go.cr -or.cr -sa.cr - -// cu : http://en.wikipedia.org/wiki/.cu -cu -com.cu -edu.cu -org.cu -net.cu -gov.cu -inf.cu - -// cv : http://en.wikipedia.org/wiki/.cv -cv - -// cx : http://en.wikipedia.org/wiki/.cx -// list of other 2nd level tlds ? -cx -gov.cx - -// cy : http://en.wikipedia.org/wiki/.cy -*.cy - -// cz : http://en.wikipedia.org/wiki/.cz -cz - -// de : http://en.wikipedia.org/wiki/.de -// Confirmed by registry (with technical -// reservations) 2008-07-01 -de - -// dj : http://en.wikipedia.org/wiki/.dj -dj - -// dk : http://en.wikipedia.org/wiki/.dk -// Confirmed by registry 2008-06-17 -dk - -// dm : http://en.wikipedia.org/wiki/.dm -dm -com.dm -net.dm -org.dm -edu.dm -gov.dm - -// do : http://en.wikipedia.org/wiki/.do -do -art.do -com.do -edu.do -gob.do -gov.do -mil.do -net.do -org.do -sld.do -web.do - -// dz : http://en.wikipedia.org/wiki/.dz -dz -com.dz -org.dz -net.dz -gov.dz -edu.dz -asso.dz -pol.dz -art.dz - -// ec : http://www.nic.ec/reg/paso1.asp -// Submitted by registry 2008-07-04 -ec -com.ec -info.ec -net.ec -fin.ec -k12.ec -med.ec -pro.ec -org.ec -edu.ec -gov.ec -gob.ec -mil.ec - -// edu : http://en.wikipedia.org/wiki/.edu -edu - -// ee : http://www.eenet.ee/EENet/dom_reeglid.html#lisa_B -ee -edu.ee -gov.ee -riik.ee -lib.ee -med.ee -com.ee -pri.ee -aip.ee -org.ee -fie.ee - -// eg : http://en.wikipedia.org/wiki/.eg -eg -com.eg -edu.eg -eun.eg -gov.eg -mil.eg -name.eg -net.eg -org.eg -sci.eg - -// er : http://en.wikipedia.org/wiki/.er -*.er - -// es : https://www.nic.es/site_ingles/ingles/dominios/index.html -es -com.es -nom.es -org.es -gob.es -edu.es - -// et : http://en.wikipedia.org/wiki/.et -*.et - -// eu : http://en.wikipedia.org/wiki/.eu -eu - -// fi : http://en.wikipedia.org/wiki/.fi -fi -// aland.fi : http://en.wikipedia.org/wiki/.ax -// This domain is being phased out in favor of .ax. As there are still many -// domains under aland.fi, we still keep it on the list until aland.fi is -// completely removed. -// TODO: Check for updates (expected to be phased out around Q1/2009) -aland.fi - -// fj : http://en.wikipedia.org/wiki/.fj -*.fj - -// fk : http://en.wikipedia.org/wiki/.fk -*.fk - -// fm : http://en.wikipedia.org/wiki/.fm -fm - -// fo : http://en.wikipedia.org/wiki/.fo -fo - -// fr : http://www.afnic.fr/ -// domaines descriptifs : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-descriptifs -fr -com.fr -asso.fr -nom.fr -prd.fr -presse.fr -tm.fr -// domaines sectoriels : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-sectoriels -aeroport.fr -assedic.fr -avocat.fr -avoues.fr -cci.fr -chambagri.fr -chirurgiens-dentistes.fr -experts-comptables.fr -geometre-expert.fr -gouv.fr -greta.fr -huissier-justice.fr -medecin.fr -notaires.fr -pharmacien.fr -port.fr -veterinaire.fr - -// ga : http://en.wikipedia.org/wiki/.ga -ga - -// gb : This registry is effectively dormant -// Submitted by registry 2008-06-12 - -// gd : http://en.wikipedia.org/wiki/.gd -gd - -// ge : http://www.nic.net.ge/policy_en.pdf -ge -com.ge -edu.ge -gov.ge -org.ge -mil.ge -net.ge -pvt.ge - -// gf : http://en.wikipedia.org/wiki/.gf -gf - -// gg : http://www.channelisles.net/applic/avextn.shtml -gg -co.gg -org.gg -net.gg -sch.gg -gov.gg - -// gh : http://en.wikipedia.org/wiki/.gh -// see also: http://www.nic.gh/reg_now.php -// Although domains directly at second level are not possible at the moment, -// they have been possible for some time and may come back. -gh -com.gh -edu.gh -gov.gh -org.gh -mil.gh - -// gi : http://www.nic.gi/rules.html -gi -com.gi -ltd.gi -gov.gi -mod.gi -edu.gi -org.gi - -// gl : http://en.wikipedia.org/wiki/.gl -// http://nic.gl -gl - -// gm : http://www.nic.gm/htmlpages%5Cgm-policy.htm -gm - -// gn : http://psg.com/dns/gn/gn.txt -// Submitted by registry 2008-06-17 -ac.gn -com.gn -edu.gn -gov.gn -org.gn -net.gn - -// gov : http://en.wikipedia.org/wiki/.gov -gov - -// gp : http://www.nic.gp/index.php?lang=en -gp -com.gp -net.gp -mobi.gp -edu.gp -org.gp -asso.gp - -// gq : http://en.wikipedia.org/wiki/.gq -gq - -// gr : https://grweb.ics.forth.gr/english/1617-B-2005.html -// Submitted by registry 2008-06-09 -gr -com.gr -edu.gr -net.gr -org.gr -gov.gr - -// gs : http://en.wikipedia.org/wiki/.gs -gs - -// gt : http://www.gt/politicas.html -*.gt -!www.gt - -// gu : http://gadao.gov.gu/registration.txt -*.gu - -// gw : http://en.wikipedia.org/wiki/.gw -gw - -// gy : http://en.wikipedia.org/wiki/.gy -// http://registry.gy/ -gy -co.gy -com.gy -net.gy - -// hk : https://www.hkdnr.hk -// Submitted by registry 2008-06-11 -hk -com.hk -edu.hk -gov.hk -idv.hk -net.hk -org.hk -公司.hk -教育.hk -敎育.hk -政府.hk -個人.hk -个人.hk -箇人.hk -網络.hk -网络.hk -组織.hk -網絡.hk -网絡.hk -组织.hk -組織.hk -組织.hk - -// hm : http://en.wikipedia.org/wiki/.hm -hm - -// hn : http://www.nic.hn/politicas/ps02,,05.html -hn -com.hn -edu.hn -org.hn -net.hn -mil.hn -gob.hn - -// hr : http://www.dns.hr/documents/pdf/HRTLD-regulations.pdf -hr -iz.hr -from.hr -name.hr -com.hr - -// ht : http://www.nic.ht/info/charte.cfm -ht -com.ht -shop.ht -firm.ht -info.ht -adult.ht -net.ht -pro.ht -org.ht -med.ht -art.ht -coop.ht -pol.ht -asso.ht -edu.ht -rel.ht -gouv.ht -perso.ht - -// hu : http://www.domain.hu/domain/English/sld.html -// Confirmed by registry 2008-06-12 -hu -co.hu -info.hu -org.hu -priv.hu -sport.hu -tm.hu -2000.hu -agrar.hu -bolt.hu -casino.hu -city.hu -erotica.hu -erotika.hu -film.hu -forum.hu -games.hu -hotel.hu -ingatlan.hu -jogasz.hu -konyvelo.hu -lakas.hu -media.hu -news.hu -reklam.hu -sex.hu -shop.hu -suli.hu -szex.hu -tozsde.hu -utazas.hu -video.hu - -// id : http://en.wikipedia.org/wiki/.id -// see also: https://register.pandi.or.id/ -id -ac.id -co.id -go.id -mil.id -net.id -or.id -sch.id -web.id - -// ie : http://en.wikipedia.org/wiki/.ie -ie -gov.ie - -// il : http://en.wikipedia.org/wiki/.il -*.il - -// im : https://www.nic.im/pdfs/imfaqs.pdf -im -co.im -ltd.co.im -plc.co.im -net.im -gov.im -org.im -nic.im -ac.im - -// in : http://en.wikipedia.org/wiki/.in -// see also: http://www.inregistry.in/policies/ -// Please note, that nic.in is not an offical eTLD, but used by most -// government institutions. -in -co.in -firm.in -net.in -org.in -gen.in -ind.in -nic.in -ac.in -edu.in -res.in -gov.in -mil.in - -// info : http://en.wikipedia.org/wiki/.info -info - -// int : http://en.wikipedia.org/wiki/.int -// Confirmed by registry 2008-06-18 -int -eu.int - -// io : http://www.nic.io/rules.html -// list of other 2nd level tlds ? -io -com.io - -// iq : http://www.cmc.iq/english/iq/iqregister1.htm -iq -gov.iq -edu.iq -mil.iq -com.iq -org.iq -net.iq - -// ir : http://www.nic.ir/Terms_and_Conditions_ir,_Appendix_1_Domain_Rules -// Also see http://www.nic.ir/Internationalized_Domain_Names -// Two .ir entries added at request of , 2010-04-16 -ir -ac.ir -co.ir -gov.ir -id.ir -net.ir -org.ir -sch.ir -// xn--mgba3a4f16a.ir (.ir, Persian YEH) -ایران.ir -// xn--mgba3a4fra.ir (.ir, Arabic YEH) -ايران.ir - -// is : http://www.isnic.is/domain/rules.php -// Confirmed by registry 2008-12-06 -is -net.is -com.is -edu.is -gov.is -org.is -int.is - -// it : http://en.wikipedia.org/wiki/.it -it -gov.it -edu.it -// list of reserved geo-names : -// http://www.nic.it/documenti/regolamenti-e-linee-guida/regolamento-assegnazione-versione-6.0.pdf -// (There is also a list of reserved geo-names corresponding to Italian -// municipalities : http://www.nic.it/documenti/appendice-c.pdf , but it is -// not included here.) -agrigento.it -ag.it -alessandria.it -al.it -ancona.it -an.it -aosta.it -aoste.it -ao.it -arezzo.it -ar.it -ascoli-piceno.it -ascolipiceno.it -ap.it -asti.it -at.it -avellino.it -av.it -bari.it -ba.it -andria-barletta-trani.it -andriabarlettatrani.it -trani-barletta-andria.it -tranibarlettaandria.it -barletta-trani-andria.it -barlettatraniandria.it -andria-trani-barletta.it -andriatranibarletta.it -trani-andria-barletta.it -traniandriabarletta.it -bt.it -belluno.it -bl.it -benevento.it -bn.it -bergamo.it -bg.it -biella.it -bi.it -bologna.it -bo.it -bolzano.it -bozen.it -balsan.it -alto-adige.it -altoadige.it -suedtirol.it -bz.it -brescia.it -bs.it -brindisi.it -br.it -cagliari.it -ca.it -caltanissetta.it -cl.it -campobasso.it -cb.it -carboniaiglesias.it -carbonia-iglesias.it -iglesias-carbonia.it -iglesiascarbonia.it -ci.it -caserta.it -ce.it -catania.it -ct.it -catanzaro.it -cz.it -chieti.it -ch.it -como.it -co.it -cosenza.it -cs.it -cremona.it -cr.it -crotone.it -kr.it -cuneo.it -cn.it -dell-ogliastra.it -dellogliastra.it -ogliastra.it -og.it -enna.it -en.it -ferrara.it -fe.it -fermo.it -fm.it -firenze.it -florence.it -fi.it -foggia.it -fg.it -forli-cesena.it -forlicesena.it -cesena-forli.it -cesenaforli.it -fc.it -frosinone.it -fr.it -genova.it -genoa.it -ge.it -gorizia.it -go.it -grosseto.it -gr.it -imperia.it -im.it -isernia.it -is.it -laquila.it -aquila.it -aq.it -la-spezia.it -laspezia.it -sp.it -latina.it -lt.it -lecce.it -le.it -lecco.it -lc.it -livorno.it -li.it -lodi.it -lo.it -lucca.it -lu.it -macerata.it -mc.it -mantova.it -mn.it -massa-carrara.it -massacarrara.it -carrara-massa.it -carraramassa.it -ms.it -matera.it -mt.it -medio-campidano.it -mediocampidano.it -campidano-medio.it -campidanomedio.it -vs.it -messina.it -me.it -milano.it -milan.it -mi.it -modena.it -mo.it -monza.it -monza-brianza.it -monzabrianza.it -monzaebrianza.it -monzaedellabrianza.it -monza-e-della-brianza.it -mb.it -napoli.it -naples.it -na.it -novara.it -no.it -nuoro.it -nu.it -oristano.it -or.it -padova.it -padua.it -pd.it -palermo.it -pa.it -parma.it -pr.it -pavia.it -pv.it -perugia.it -pg.it -pescara.it -pe.it -pesaro-urbino.it -pesarourbino.it -urbino-pesaro.it -urbinopesaro.it -pu.it -piacenza.it -pc.it -pisa.it -pi.it -pistoia.it -pt.it -pordenone.it -pn.it -potenza.it -pz.it -prato.it -po.it -ragusa.it -rg.it -ravenna.it -ra.it -reggio-calabria.it -reggiocalabria.it -rc.it -reggio-emilia.it -reggioemilia.it -re.it -rieti.it -ri.it -rimini.it -rn.it -roma.it -rome.it -rm.it -rovigo.it -ro.it -salerno.it -sa.it -sassari.it -ss.it -savona.it -sv.it -siena.it -si.it -siracusa.it -sr.it -sondrio.it -so.it -taranto.it -ta.it -tempio-olbia.it -tempioolbia.it -olbia-tempio.it -olbiatempio.it -ot.it -teramo.it -te.it -terni.it -tr.it -torino.it -turin.it -to.it -trapani.it -tp.it -trento.it -trentino.it -tn.it -treviso.it -tv.it -trieste.it -ts.it -udine.it -ud.it -varese.it -va.it -venezia.it -venice.it -ve.it -verbania.it -vb.it -vercelli.it -vc.it -verona.it -vr.it -vibo-valentia.it -vibovalentia.it -vv.it -vicenza.it -vi.it -viterbo.it -vt.it - -// je : http://www.channelisles.net/applic/avextn.shtml -je -co.je -org.je -net.je -sch.je -gov.je - -// jm : http://www.com.jm/register.html -*.jm - -// jo : http://www.dns.jo/Registration_policy.aspx -jo -com.jo -org.jo -net.jo -edu.jo -sch.jo -gov.jo -mil.jo -name.jo - -// jobs : http://en.wikipedia.org/wiki/.jobs -jobs - -// jp : http://en.wikipedia.org/wiki/.jp -// http://jprs.co.jp/en/jpdomain.html -// Submitted by registry 2008-06-11 -// Updated by registry 2008-12-04 -jp -// jp organizational type names -ac.jp -ad.jp -co.jp -ed.jp -go.jp -gr.jp -lg.jp -ne.jp -or.jp -// jp geographic type names -// http://jprs.jp/doc/rule/saisoku-1.html -*.aichi.jp -*.akita.jp -*.aomori.jp -*.chiba.jp -*.ehime.jp -*.fukui.jp -*.fukuoka.jp -*.fukushima.jp -*.gifu.jp -*.gunma.jp -*.hiroshima.jp -*.hokkaido.jp -*.hyogo.jp -*.ibaraki.jp -*.ishikawa.jp -*.iwate.jp -*.kagawa.jp -*.kagoshima.jp -*.kanagawa.jp -*.kawasaki.jp -*.kitakyushu.jp -*.kobe.jp -*.kochi.jp -*.kumamoto.jp -*.kyoto.jp -*.mie.jp -*.miyagi.jp -*.miyazaki.jp -*.nagano.jp -*.nagasaki.jp -*.nagoya.jp -*.nara.jp -*.niigata.jp -*.oita.jp -*.okayama.jp -*.okinawa.jp -*.osaka.jp -*.saga.jp -*.saitama.jp -*.sapporo.jp -*.sendai.jp -*.shiga.jp -*.shimane.jp -*.shizuoka.jp -*.tochigi.jp -*.tokushima.jp -*.tokyo.jp -*.tottori.jp -*.toyama.jp -*.wakayama.jp -*.yamagata.jp -*.yamaguchi.jp -*.yamanashi.jp -*.yokohama.jp -!metro.tokyo.jp -!pref.aichi.jp -!pref.akita.jp -!pref.aomori.jp -!pref.chiba.jp -!pref.ehime.jp -!pref.fukui.jp -!pref.fukuoka.jp -!pref.fukushima.jp -!pref.gifu.jp -!pref.gunma.jp -!pref.hiroshima.jp -!pref.hokkaido.jp -!pref.hyogo.jp -!pref.ibaraki.jp -!pref.ishikawa.jp -!pref.iwate.jp -!pref.kagawa.jp -!pref.kagoshima.jp -!pref.kanagawa.jp -!pref.kochi.jp -!pref.kumamoto.jp -!pref.kyoto.jp -!pref.mie.jp -!pref.miyagi.jp -!pref.miyazaki.jp -!pref.nagano.jp -!pref.nagasaki.jp -!pref.nara.jp -!pref.niigata.jp -!pref.oita.jp -!pref.okayama.jp -!pref.okinawa.jp -!pref.osaka.jp -!pref.saga.jp -!pref.saitama.jp -!pref.shiga.jp -!pref.shimane.jp -!pref.shizuoka.jp -!pref.tochigi.jp -!pref.tokushima.jp -!pref.tottori.jp -!pref.toyama.jp -!pref.wakayama.jp -!pref.yamagata.jp -!pref.yamaguchi.jp -!pref.yamanashi.jp -!city.chiba.jp -!city.fukuoka.jp -!city.hiroshima.jp -!city.kawasaki.jp -!city.kitakyushu.jp -!city.kobe.jp -!city.kyoto.jp -!city.nagoya.jp -!city.niigata.jp -!city.okayama.jp -!city.osaka.jp -!city.saitama.jp -!city.sapporo.jp -!city.sendai.jp -!city.shizuoka.jp -!city.yokohama.jp - -// ke : http://www.kenic.or.ke/index.php?option=com_content&task=view&id=117&Itemid=145 -*.ke - -// kg : http://www.domain.kg/dmn_n.html -kg -org.kg -net.kg -com.kg -edu.kg -gov.kg -mil.kg - -// kh : http://www.mptc.gov.kh/dns_registration.htm -*.kh - -// ki : http://www.ki/dns/index.html -ki -edu.ki -biz.ki -net.ki -org.ki -gov.ki -info.ki -com.ki - -// km : http://en.wikipedia.org/wiki/.km -// http://www.domaine.km/documents/charte.doc -km -org.km -nom.km -gov.km -prd.km -tm.km -edu.km -mil.km -ass.km -com.km -// These are only mentioned as proposed suggestions at domaine.km, but -// http://en.wikipedia.org/wiki/.km says they're available for registration: -coop.km -asso.km -presse.km -medecin.km -notaires.km -pharmaciens.km -veterinaire.km -gouv.km - -// kn : http://en.wikipedia.org/wiki/.kn -// http://www.dot.kn/domainRules.html -kn -net.kn -org.kn -edu.kn -gov.kn - -// kp : http://www.kcce.kp/en_index.php -com.kp -edu.kp -gov.kp -org.kp -rep.kp -tra.kp - -// kr : http://en.wikipedia.org/wiki/.kr -// see also: http://domain.nida.or.kr/eng/registration.jsp -kr -ac.kr -co.kr -es.kr -go.kr -hs.kr -kg.kr -mil.kr -ms.kr -ne.kr -or.kr -pe.kr -re.kr -sc.kr -// kr geographical names -busan.kr -chungbuk.kr -chungnam.kr -daegu.kr -daejeon.kr -gangwon.kr -gwangju.kr -gyeongbuk.kr -gyeonggi.kr -gyeongnam.kr -incheon.kr -jeju.kr -jeonbuk.kr -jeonnam.kr -seoul.kr -ulsan.kr - -// kw : http://en.wikipedia.org/wiki/.kw -*.kw - -// ky : http://www.icta.ky/da_ky_reg_dom.php -// Confirmed by registry 2008-06-17 -ky -edu.ky -gov.ky -com.ky -org.ky -net.ky - -// kz : http://en.wikipedia.org/wiki/.kz -// see also: http://www.nic.kz/rules/index.jsp -kz -org.kz -edu.kz -net.kz -gov.kz -mil.kz -com.kz - -// la : http://en.wikipedia.org/wiki/.la -// Submitted by registry 2008-06-10 -la -int.la -net.la -info.la -edu.la -gov.la -per.la -com.la -org.la - -// lb : http://en.wikipedia.org/wiki/.lb -// Submitted by registry 2008-06-17 -com.lb -edu.lb -gov.lb -net.lb -org.lb - -// lc : http://en.wikipedia.org/wiki/.lc -// see also: http://www.nic.lc/rules.htm -lc -com.lc -net.lc -co.lc -org.lc -edu.lc -gov.lc - -// li : http://en.wikipedia.org/wiki/.li -li - -// lk : http://www.nic.lk/seclevpr.html -lk -gov.lk -sch.lk -net.lk -int.lk -com.lk -org.lk -edu.lk -ngo.lk -soc.lk -web.lk -ltd.lk -assn.lk -grp.lk -hotel.lk - -// lr : http://psg.com/dns/lr/lr.txt -// Submitted by registry 2008-06-17 -com.lr -edu.lr -gov.lr -org.lr -net.lr - -// ls : http://en.wikipedia.org/wiki/.ls -ls -co.ls -org.ls - -// lt : http://en.wikipedia.org/wiki/.lt -lt -// gov.lt : http://www.gov.lt/index_en.php -gov.lt - -// lu : http://www.dns.lu/en/ -lu - -// lv : http://www.nic.lv/DNS/En/generic.php -lv -com.lv -edu.lv -gov.lv -org.lv -mil.lv -id.lv -net.lv -asn.lv -conf.lv - -// ly : http://www.nic.ly/regulations.php -ly -com.ly -net.ly -gov.ly -plc.ly -edu.ly -sch.ly -med.ly -org.ly -id.ly - -// ma : http://en.wikipedia.org/wiki/.ma -// http://www.anrt.ma/fr/admin/download/upload/file_fr782.pdf -ma -co.ma -net.ma -gov.ma -org.ma -ac.ma -press.ma - -// mc : http://www.nic.mc/ -mc -tm.mc -asso.mc - -// md : http://en.wikipedia.org/wiki/.md -md - -// me : http://en.wikipedia.org/wiki/.me -me -co.me -net.me -org.me -edu.me -ac.me -gov.me -its.me -priv.me - -// mg : http://www.nic.mg/tarif.htm -mg -org.mg -nom.mg -gov.mg -prd.mg -tm.mg -edu.mg -mil.mg -com.mg - -// mh : http://en.wikipedia.org/wiki/.mh -mh - -// mil : http://en.wikipedia.org/wiki/.mil -mil - -// mk : http://en.wikipedia.org/wiki/.mk -// see also: http://dns.marnet.net.mk/postapka.php -mk -com.mk -org.mk -net.mk -edu.mk -gov.mk -inf.mk -name.mk - -// ml : http://www.gobin.info/domainname/ml-template.doc -// see also: http://en.wikipedia.org/wiki/.ml -ml -com.ml -edu.ml -gouv.ml -gov.ml -net.ml -org.ml -presse.ml - -// mm : http://en.wikipedia.org/wiki/.mm -*.mm - -// mn : http://en.wikipedia.org/wiki/.mn -mn -gov.mn -edu.mn -org.mn - -// mo : http://www.monic.net.mo/ -mo -com.mo -net.mo -org.mo -edu.mo -gov.mo - -// mobi : http://en.wikipedia.org/wiki/.mobi -mobi - -// mp : http://www.dot.mp/ -// Confirmed by registry 2008-06-17 -mp - -// mq : http://en.wikipedia.org/wiki/.mq -mq - -// mr : http://en.wikipedia.org/wiki/.mr -mr -gov.mr - -// ms : http://en.wikipedia.org/wiki/.ms -ms - -// mt : https://www.nic.org.mt/dotmt/ -*.mt - -// mu : http://en.wikipedia.org/wiki/.mu -mu -com.mu -net.mu -org.mu -gov.mu -ac.mu -co.mu -or.mu - -// museum : http://about.museum/naming/ -// http://index.museum/ -museum -academy.museum -agriculture.museum -air.museum -airguard.museum -alabama.museum -alaska.museum -amber.museum -ambulance.museum -american.museum -americana.museum -americanantiques.museum -americanart.museum -amsterdam.museum -and.museum -annefrank.museum -anthro.museum -anthropology.museum -antiques.museum -aquarium.museum -arboretum.museum -archaeological.museum -archaeology.museum -architecture.museum -art.museum -artanddesign.museum -artcenter.museum -artdeco.museum -arteducation.museum -artgallery.museum -arts.museum -artsandcrafts.museum -asmatart.museum -assassination.museum -assisi.museum -association.museum -astronomy.museum -atlanta.museum -austin.museum -australia.museum -automotive.museum -aviation.museum -axis.museum -badajoz.museum -baghdad.museum -bahn.museum -bale.museum -baltimore.museum -barcelona.museum -baseball.museum -basel.museum -baths.museum -bauern.museum -beauxarts.museum -beeldengeluid.museum -bellevue.museum -bergbau.museum -berkeley.museum -berlin.museum -bern.museum -bible.museum -bilbao.museum -bill.museum -birdart.museum -birthplace.museum -bonn.museum -boston.museum -botanical.museum -botanicalgarden.museum -botanicgarden.museum -botany.museum -brandywinevalley.museum -brasil.museum -bristol.museum -british.museum -britishcolumbia.museum -broadcast.museum -brunel.museum -brussel.museum -brussels.museum -bruxelles.museum -building.museum -burghof.museum -bus.museum -bushey.museum -cadaques.museum -california.museum -cambridge.museum -can.museum -canada.museum -capebreton.museum -carrier.museum -cartoonart.museum -casadelamoneda.museum -castle.museum -castres.museum -celtic.museum -center.museum -chattanooga.museum -cheltenham.museum -chesapeakebay.museum -chicago.museum -children.museum -childrens.museum -childrensgarden.museum -chiropractic.museum -chocolate.museum -christiansburg.museum -cincinnati.museum -cinema.museum -circus.museum -civilisation.museum -civilization.museum -civilwar.museum -clinton.museum -clock.museum -coal.museum -coastaldefence.museum -cody.museum -coldwar.museum -collection.museum -colonialwilliamsburg.museum -coloradoplateau.museum -columbia.museum -columbus.museum -communication.museum -communications.museum -community.museum -computer.museum -computerhistory.museum -comunicações.museum -contemporary.museum -contemporaryart.museum -convent.museum -copenhagen.museum -corporation.museum -correios-e-telecomunicações.museum -corvette.museum -costume.museum -countryestate.museum -county.museum -crafts.museum -cranbrook.museum -creation.museum -cultural.museum -culturalcenter.museum -culture.museum -cyber.museum -cymru.museum -dali.museum -dallas.museum -database.museum -ddr.museum -decorativearts.museum -delaware.museum -delmenhorst.museum -denmark.museum -depot.museum -design.museum -detroit.museum -dinosaur.museum -discovery.museum -dolls.museum -donostia.museum -durham.museum -eastafrica.museum -eastcoast.museum -education.museum -educational.museum -egyptian.museum -eisenbahn.museum -elburg.museum -elvendrell.museum -embroidery.museum -encyclopedic.museum -england.museum -entomology.museum -environment.museum -environmentalconservation.museum -epilepsy.museum -essex.museum -estate.museum -ethnology.museum -exeter.museum -exhibition.museum -family.museum -farm.museum -farmequipment.museum -farmers.museum -farmstead.museum -field.museum -figueres.museum -filatelia.museum -film.museum -fineart.museum -finearts.museum -finland.museum -flanders.museum -florida.museum -force.museum -fortmissoula.museum -fortworth.museum -foundation.museum -francaise.museum -frankfurt.museum -franziskaner.museum -freemasonry.museum -freiburg.museum -fribourg.museum -frog.museum -fundacio.museum -furniture.museum -gallery.museum -garden.museum -gateway.museum -geelvinck.museum -gemological.museum -geology.museum -georgia.museum -giessen.museum -glas.museum -glass.museum -gorge.museum -grandrapids.museum -graz.museum -guernsey.museum -halloffame.museum -hamburg.museum -handson.museum -harvestcelebration.museum -hawaii.museum -health.museum -heimatunduhren.museum -hellas.museum -helsinki.museum -hembygdsforbund.museum -heritage.museum -histoire.museum -historical.museum -historicalsociety.museum -historichouses.museum -historisch.museum -historisches.museum -history.museum -historyofscience.museum -horology.museum -house.museum -humanities.museum -illustration.museum -imageandsound.museum -indian.museum -indiana.museum -indianapolis.museum -indianmarket.museum -intelligence.museum -interactive.museum -iraq.museum -iron.museum -isleofman.museum -jamison.museum -jefferson.museum -jerusalem.museum -jewelry.museum -jewish.museum -jewishart.museum -jfk.museum -journalism.museum -judaica.museum -judygarland.museum -juedisches.museum -juif.museum -karate.museum -karikatur.museum -kids.museum -koebenhavn.museum -koeln.museum -kunst.museum -kunstsammlung.museum -kunstunddesign.museum -labor.museum -labour.museum -lajolla.museum -lancashire.museum -landes.museum -lans.museum -läns.museum -larsson.museum -lewismiller.museum -lincoln.museum -linz.museum -living.museum -livinghistory.museum -localhistory.museum -london.museum -losangeles.museum -louvre.museum -loyalist.museum -lucerne.museum -luxembourg.museum -luzern.museum -mad.museum -madrid.museum -mallorca.museum -manchester.museum -mansion.museum -mansions.museum -manx.museum -marburg.museum -maritime.museum -maritimo.museum -maryland.museum -marylhurst.museum -media.museum -medical.museum -medizinhistorisches.museum -meeres.museum -memorial.museum -mesaverde.museum -michigan.museum -midatlantic.museum -military.museum -mill.museum -miners.museum -mining.museum -minnesota.museum -missile.museum -missoula.museum -modern.museum -moma.museum -money.museum -monmouth.museum -monticello.museum -montreal.museum -moscow.museum -motorcycle.museum -muenchen.museum -muenster.museum -mulhouse.museum -muncie.museum -museet.museum -museumcenter.museum -museumvereniging.museum -music.museum -national.museum -nationalfirearms.museum -nationalheritage.museum -nativeamerican.museum -naturalhistory.museum -naturalhistorymuseum.museum -naturalsciences.museum -nature.museum -naturhistorisches.museum -natuurwetenschappen.museum -naumburg.museum -naval.museum -nebraska.museum -neues.museum -newhampshire.museum -newjersey.museum -newmexico.museum -newport.museum -newspaper.museum -newyork.museum -niepce.museum -norfolk.museum -north.museum -nrw.museum -nuernberg.museum -nuremberg.museum -nyc.museum -nyny.museum -oceanographic.museum -oceanographique.museum -omaha.museum -online.museum -ontario.museum -openair.museum -oregon.museum -oregontrail.museum -otago.museum -oxford.museum -pacific.museum -paderborn.museum -palace.museum -paleo.museum -palmsprings.museum -panama.museum -paris.museum -pasadena.museum -pharmacy.museum -philadelphia.museum -philadelphiaarea.museum -philately.museum -phoenix.museum -photography.museum -pilots.museum -pittsburgh.museum -planetarium.museum -plantation.museum -plants.museum -plaza.museum -portal.museum -portland.museum -portlligat.museum -posts-and-telecommunications.museum -preservation.museum -presidio.museum -press.museum -project.museum -public.museum -pubol.museum -quebec.museum -railroad.museum -railway.museum -research.museum -resistance.museum -riodejaneiro.museum -rochester.museum -rockart.museum -roma.museum -russia.museum -saintlouis.museum -salem.museum -salvadordali.museum -salzburg.museum -sandiego.museum -sanfrancisco.museum -santabarbara.museum -santacruz.museum -santafe.museum -saskatchewan.museum -satx.museum -savannahga.museum -schlesisches.museum -schoenbrunn.museum -schokoladen.museum -school.museum -schweiz.museum -science.museum -scienceandhistory.museum -scienceandindustry.museum -sciencecenter.museum -sciencecenters.museum -science-fiction.museum -sciencehistory.museum -sciences.museum -sciencesnaturelles.museum -scotland.museum -seaport.museum -settlement.museum -settlers.museum -shell.museum -sherbrooke.museum -sibenik.museum -silk.museum -ski.museum -skole.museum -society.museum -sologne.museum -soundandvision.museum -southcarolina.museum -southwest.museum -space.museum -spy.museum -square.museum -stadt.museum -stalbans.museum -starnberg.museum -state.museum -stateofdelaware.museum -station.museum -steam.museum -steiermark.museum -stjohn.museum -stockholm.museum -stpetersburg.museum -stuttgart.museum -suisse.museum -surgeonshall.museum -surrey.museum -svizzera.museum -sweden.museum -sydney.museum -tank.museum -tcm.museum -technology.museum -telekommunikation.museum -television.museum -texas.museum -textile.museum -theater.museum -time.museum -timekeeping.museum -topology.museum -torino.museum -touch.museum -town.museum -transport.museum -tree.museum -trolley.museum -trust.museum -trustee.museum -uhren.museum -ulm.museum -undersea.museum -university.museum -usa.museum -usantiques.museum -usarts.museum -uscountryestate.museum -usculture.museum -usdecorativearts.museum -usgarden.museum -ushistory.museum -ushuaia.museum -uslivinghistory.museum -utah.museum -uvic.museum -valley.museum -vantaa.museum -versailles.museum -viking.museum -village.museum -virginia.museum -virtual.museum -virtuel.museum -vlaanderen.museum -volkenkunde.museum -wales.museum -wallonie.museum -war.museum -washingtondc.museum -watchandclock.museum -watch-and-clock.museum -western.museum -westfalen.museum -whaling.museum -wildlife.museum -williamsburg.museum -windmill.museum -workshop.museum -york.museum -yorkshire.museum -yosemite.museum -youth.museum -zoological.museum -zoology.museum -ירושלים.museum -иком.museum - -// mv : http://en.wikipedia.org/wiki/.mv -// "mv" included because, contra Wikipedia, google.mv exists. -mv -aero.mv -biz.mv -com.mv -coop.mv -edu.mv -gov.mv -info.mv -int.mv -mil.mv -museum.mv -name.mv -net.mv -org.mv -pro.mv - -// mw : http://www.registrar.mw/ -mw -ac.mw -biz.mw -co.mw -com.mw -coop.mw -edu.mw -gov.mw -int.mw -museum.mw -net.mw -org.mw - -// mx : http://www.nic.mx/ -// Submitted by registry 2008-06-19 -mx -com.mx -org.mx -gob.mx -edu.mx -net.mx - -// my : http://www.mynic.net.my/ -my -com.my -net.my -org.my -gov.my -edu.my -mil.my -name.my - -// mz : http://www.gobin.info/domainname/mz-template.doc -*.mz - -// na : http://www.na-nic.com.na/ -// http://www.info.na/domain/ -na -info.na -pro.na -name.na -school.na -or.na -dr.na -us.na -mx.na -ca.na -in.na -cc.na -tv.na -ws.na -mobi.na -co.na -com.na -org.na - -// name : has 2nd-level tlds, but there's no list of them -name - -// nc : http://www.cctld.nc/ -nc -asso.nc - -// ne : http://en.wikipedia.org/wiki/.ne -ne - -// net : http://en.wikipedia.org/wiki/.net -net - -// nf : http://en.wikipedia.org/wiki/.nf -nf -com.nf -net.nf -per.nf -rec.nf -web.nf -arts.nf -firm.nf -info.nf -other.nf -store.nf - -// ng : http://psg.com/dns/ng/ -// Submitted by registry 2008-06-17 -ac.ng -com.ng -edu.ng -gov.ng -net.ng -org.ng - -// ni : http://www.nic.ni/dominios.htm -*.ni - -// nl : http://www.domain-registry.nl/ace.php/c,728,122,,,,Home.html -// Confirmed by registry (with technical -// reservations) 2008-06-08 -nl - -// BV.nl will be a registry for dutch BV's (besloten vennootschap) -bv.nl - -// no : http://www.norid.no/regelverk/index.en.html -// The Norwegian registry has declined to notify us of updates. The web pages -// referenced below are the official source of the data. There is also an -// announce mailing list: -// https://postlister.uninett.no/sympa/info/norid-diskusjon -no -// Norid generic domains : http://www.norid.no/regelverk/vedlegg-c.en.html -fhs.no -vgs.no -fylkesbibl.no -folkebibl.no -museum.no -idrett.no -priv.no -// Non-Norid generic domains : http://www.norid.no/regelverk/vedlegg-d.en.html -mil.no -stat.no -dep.no -kommune.no -herad.no -// no geographical names : http://www.norid.no/regelverk/vedlegg-b.en.html -// counties -aa.no -ah.no -bu.no -fm.no -hl.no -hm.no -jan-mayen.no -mr.no -nl.no -nt.no -of.no -ol.no -oslo.no -rl.no -sf.no -st.no -svalbard.no -tm.no -tr.no -va.no -vf.no -// primary and lower secondary schools per county -gs.aa.no -gs.ah.no -gs.bu.no -gs.fm.no -gs.hl.no -gs.hm.no -gs.jan-mayen.no -gs.mr.no -gs.nl.no -gs.nt.no -gs.of.no -gs.ol.no -gs.oslo.no -gs.rl.no -gs.sf.no -gs.st.no -gs.svalbard.no -gs.tm.no -gs.tr.no -gs.va.no -gs.vf.no -// cities -akrehamn.no -åkrehamn.no -algard.no -ålgård.no -arna.no -brumunddal.no -bryne.no -bronnoysund.no -brønnøysund.no -drobak.no -drøbak.no -egersund.no -fetsund.no -floro.no -florø.no -fredrikstad.no -hokksund.no -honefoss.no -hønefoss.no -jessheim.no -jorpeland.no -jørpeland.no -kirkenes.no -kopervik.no -krokstadelva.no -langevag.no -langevåg.no -leirvik.no -mjondalen.no -mjøndalen.no -mo-i-rana.no -mosjoen.no -mosjøen.no -nesoddtangen.no -orkanger.no -osoyro.no -osøyro.no -raholt.no -råholt.no -sandnessjoen.no -sandnessjøen.no -skedsmokorset.no -slattum.no -spjelkavik.no -stathelle.no -stavern.no -stjordalshalsen.no -stjørdalshalsen.no -tananger.no -tranby.no -vossevangen.no -// communities -afjord.no -åfjord.no -agdenes.no -al.no -ål.no -alesund.no -ålesund.no -alstahaug.no -alta.no -áltá.no -alaheadju.no -álaheadju.no -alvdal.no -amli.no -åmli.no -amot.no -åmot.no -andebu.no -andoy.no -andøy.no -andasuolo.no -ardal.no -årdal.no -aremark.no -arendal.no -ås.no -aseral.no -åseral.no -asker.no -askim.no -askvoll.no -askoy.no -askøy.no -asnes.no -åsnes.no -audnedaln.no -aukra.no -aure.no -aurland.no -aurskog-holand.no -aurskog-høland.no -austevoll.no -austrheim.no -averoy.no -averøy.no -balestrand.no -ballangen.no -balat.no -bálát.no -balsfjord.no -bahccavuotna.no -báhccavuotna.no -bamble.no -bardu.no -beardu.no -beiarn.no -bajddar.no -bájddar.no -baidar.no -báidár.no -berg.no -bergen.no -berlevag.no -berlevåg.no -bearalvahki.no -bearalváhki.no -bindal.no -birkenes.no -bjarkoy.no -bjarkøy.no -bjerkreim.no -bjugn.no -bodo.no -bodø.no -badaddja.no -bådåddjå.no -budejju.no -bokn.no -bremanger.no -bronnoy.no -brønnøy.no -bygland.no -bykle.no -barum.no -bærum.no -bo.telemark.no -bø.telemark.no -bo.nordland.no -bø.nordland.no -bievat.no -bievát.no -bomlo.no -bømlo.no -batsfjord.no -båtsfjord.no -bahcavuotna.no -báhcavuotna.no -dovre.no -drammen.no -drangedal.no -dyroy.no -dyrøy.no -donna.no -dønna.no -eid.no -eidfjord.no -eidsberg.no -eidskog.no -eidsvoll.no -eigersund.no -elverum.no -enebakk.no -engerdal.no -etne.no -etnedal.no -evenes.no -evenassi.no -evenášši.no -evje-og-hornnes.no -farsund.no -fauske.no -fuossko.no -fuoisku.no -fedje.no -fet.no -finnoy.no -finnøy.no -fitjar.no -fjaler.no -fjell.no -flakstad.no -flatanger.no -flekkefjord.no -flesberg.no -flora.no -fla.no -flå.no -folldal.no -forsand.no -fosnes.no -frei.no -frogn.no -froland.no -frosta.no -frana.no -fræna.no -froya.no -frøya.no -fusa.no -fyresdal.no -forde.no -førde.no -gamvik.no -gangaviika.no -gáŋgaviika.no -gaular.no -gausdal.no -gildeskal.no -gildeskål.no -giske.no -gjemnes.no -gjerdrum.no -gjerstad.no -gjesdal.no -gjovik.no -gjøvik.no -gloppen.no -gol.no -gran.no -grane.no -granvin.no -gratangen.no -grimstad.no -grong.no -kraanghke.no -kråanghke.no -grue.no -gulen.no -hadsel.no -halden.no -halsa.no -hamar.no -hamaroy.no -habmer.no -hábmer.no -hapmir.no -hápmir.no -hammerfest.no -hammarfeasta.no -hámmárfeasta.no -haram.no -hareid.no -harstad.no -hasvik.no -aknoluokta.no -ákŋoluokta.no -hattfjelldal.no -aarborte.no -haugesund.no -hemne.no -hemnes.no -hemsedal.no -heroy.more-og-romsdal.no -herøy.møre-og-romsdal.no -heroy.nordland.no -herøy.nordland.no -hitra.no -hjartdal.no -hjelmeland.no -hobol.no -hobøl.no -hof.no -hol.no -hole.no -holmestrand.no -holtalen.no -holtålen.no -hornindal.no -horten.no -hurdal.no -hurum.no -hvaler.no -hyllestad.no -hagebostad.no -hægebostad.no -hoyanger.no -høyanger.no -hoylandet.no -høylandet.no -ha.no -hå.no -ibestad.no -inderoy.no -inderøy.no -iveland.no -jevnaker.no -jondal.no -jolster.no -jølster.no -karasjok.no -karasjohka.no -kárášjohka.no -karlsoy.no -galsa.no -gálsá.no -karmoy.no -karmøy.no -kautokeino.no -guovdageaidnu.no -klepp.no -klabu.no -klæbu.no -kongsberg.no -kongsvinger.no -kragero.no -kragerø.no -kristiansand.no -kristiansund.no -krodsherad.no -krødsherad.no -kvalsund.no -rahkkeravju.no -ráhkkerávju.no -kvam.no -kvinesdal.no -kvinnherad.no -kviteseid.no -kvitsoy.no -kvitsøy.no -kvafjord.no -kvæfjord.no -giehtavuoatna.no -kvanangen.no -kvænangen.no -navuotna.no -návuotna.no -kafjord.no -kåfjord.no -gaivuotna.no -gáivuotna.no -larvik.no -lavangen.no -lavagis.no -loabat.no -loabát.no -lebesby.no -davvesiida.no -leikanger.no -leirfjord.no -leka.no -leksvik.no -lenvik.no -leangaviika.no -leaŋgaviika.no -lesja.no -levanger.no -lier.no -lierne.no -lillehammer.no -lillesand.no -lindesnes.no -lindas.no -lindås.no -lom.no -loppa.no -lahppi.no -láhppi.no -lund.no -lunner.no -luroy.no -lurøy.no -luster.no -lyngdal.no -lyngen.no -ivgu.no -lardal.no -lerdal.no -lærdal.no -lodingen.no -lødingen.no -lorenskog.no -lørenskog.no -loten.no -løten.no -malvik.no -masoy.no -måsøy.no -muosat.no -muosát.no -mandal.no -marker.no -marnardal.no -masfjorden.no -meland.no -meldal.no -melhus.no -meloy.no -meløy.no -meraker.no -meråker.no -moareke.no -moåreke.no -midsund.no -midtre-gauldal.no -modalen.no -modum.no -molde.no -moskenes.no -moss.no -mosvik.no -malselv.no -målselv.no -malatvuopmi.no -málatvuopmi.no -namdalseid.no -aejrie.no -namsos.no -namsskogan.no -naamesjevuemie.no -nååmesjevuemie.no -laakesvuemie.no -nannestad.no -narvik.no -narviika.no -naustdal.no -nedre-eiker.no -nes.akershus.no -nes.buskerud.no -nesna.no -nesodden.no -nesseby.no -unjarga.no -unjárga.no -nesset.no -nissedal.no -nittedal.no -nord-aurdal.no -nord-fron.no -nord-odal.no -norddal.no -nordkapp.no -davvenjarga.no -davvenjárga.no -nordre-land.no -nordreisa.no -raisa.no -ráisa.no -nore-og-uvdal.no -notodden.no -naroy.no -nærøy.no -notteroy.no -nøtterøy.no -odda.no -oksnes.no -øksnes.no -oppdal.no -oppegard.no -oppegård.no -orkdal.no -orland.no -ørland.no -orskog.no -ørskog.no -orsta.no -ørsta.no -os.hedmark.no -os.hordaland.no -osen.no -osteroy.no -osterøy.no -ostre-toten.no -østre-toten.no -overhalla.no -ovre-eiker.no -øvre-eiker.no -oyer.no -øyer.no -oygarden.no -øygarden.no -oystre-slidre.no -øystre-slidre.no -porsanger.no -porsangu.no -porsáŋgu.no -porsgrunn.no -radoy.no -radøy.no -rakkestad.no -rana.no -ruovat.no -randaberg.no -rauma.no -rendalen.no -rennebu.no -rennesoy.no -rennesøy.no -rindal.no -ringebu.no -ringerike.no -ringsaker.no -rissa.no -risor.no -risør.no -roan.no -rollag.no -rygge.no -ralingen.no -rælingen.no -rodoy.no -rødøy.no -romskog.no -rømskog.no -roros.no -røros.no -rost.no -røst.no -royken.no -røyken.no -royrvik.no -røyrvik.no -rade.no -råde.no -salangen.no -siellak.no -saltdal.no -salat.no -sálát.no -sálat.no -samnanger.no -sande.more-og-romsdal.no -sande.møre-og-romsdal.no -sande.vestfold.no -sandefjord.no -sandnes.no -sandoy.no -sandøy.no -sarpsborg.no -sauda.no -sauherad.no -sel.no -selbu.no -selje.no -seljord.no -sigdal.no -siljan.no -sirdal.no -skaun.no -skedsmo.no -ski.no -skien.no -skiptvet.no -skjervoy.no -skjervøy.no -skierva.no -skiervá.no -skjak.no -skjåk.no -skodje.no -skanland.no -skånland.no -skanit.no -skánit.no -smola.no -smøla.no -snillfjord.no -snasa.no -snåsa.no -snoasa.no -snaase.no -snåase.no -sogndal.no -sokndal.no -sola.no -solund.no -songdalen.no -sortland.no -spydeberg.no -stange.no -stavanger.no -steigen.no -steinkjer.no -stjordal.no -stjørdal.no -stokke.no -stor-elvdal.no -stord.no -stordal.no -storfjord.no -omasvuotna.no -strand.no -stranda.no -stryn.no -sula.no -suldal.no -sund.no -sunndal.no -surnadal.no -sveio.no -svelvik.no -sykkylven.no -sogne.no -søgne.no -somna.no -sømna.no -sondre-land.no -søndre-land.no -sor-aurdal.no -sør-aurdal.no -sor-fron.no -sør-fron.no -sor-odal.no -sør-odal.no -sor-varanger.no -sør-varanger.no -matta-varjjat.no -mátta-várjjat.no -sorfold.no -sørfold.no -sorreisa.no -sørreisa.no -sorum.no -sørum.no -tana.no -deatnu.no -time.no -tingvoll.no -tinn.no -tjeldsund.no -dielddanuorri.no -tjome.no -tjøme.no -tokke.no -tolga.no -torsken.no -tranoy.no -tranøy.no -tromso.no -tromsø.no -tromsa.no -romsa.no -trondheim.no -troandin.no -trysil.no -trana.no -træna.no -trogstad.no -trøgstad.no -tvedestrand.no -tydal.no -tynset.no -tysfjord.no -divtasvuodna.no -divttasvuotna.no -tysnes.no -tysvar.no -tysvær.no -tonsberg.no -tønsberg.no -ullensaker.no -ullensvang.no -ulvik.no -utsira.no -vadso.no -vadsø.no -cahcesuolo.no -čáhcesuolo.no -vaksdal.no -valle.no -vang.no -vanylven.no -vardo.no -vardø.no -varggat.no -várggát.no -vefsn.no -vaapste.no -vega.no -vegarshei.no -vegårshei.no -vennesla.no -verdal.no -verran.no -vestby.no -vestnes.no -vestre-slidre.no -vestre-toten.no -vestvagoy.no -vestvågøy.no -vevelstad.no -vik.no -vikna.no -vindafjord.no -volda.no -voss.no -varoy.no -værøy.no -vagan.no -vågan.no -voagat.no -vagsoy.no -vågsøy.no -vaga.no -vågå.no -valer.ostfold.no -våler.østfold.no -valer.hedmark.no -våler.hedmark.no - -// np : http://www.mos.com.np/register.html -*.np - -// nr : http://cenpac.net.nr/dns/index.html -// Confirmed by registry 2008-06-17 -nr -biz.nr -info.nr -gov.nr -edu.nr -org.nr -net.nr -com.nr - -// nu : http://en.wikipedia.org/wiki/.nu -nu - -// nz : http://en.wikipedia.org/wiki/.nz -*.nz - -// om : http://en.wikipedia.org/wiki/.om -*.om -!mediaphone.om -!nawrastelecom.om -!nawras.om -!omanmobile.om -!omanpost.om -!omantel.om -!rakpetroleum.om -!siemens.om -!songfest.om -!statecouncil.om - -// org : http://en.wikipedia.org/wiki/.org -org - -// pa : http://www.nic.pa/ -// Some additional second level "domains" resolve directly as hostnames, such as -// pannet.pa, so we add a rule for "pa". -pa -ac.pa -gob.pa -com.pa -org.pa -sld.pa -edu.pa -net.pa -ing.pa -abo.pa -med.pa -nom.pa - -// pe : https://www.nic.pe/InformeFinalComision.pdf -pe -edu.pe -gob.pe -nom.pe -mil.pe -org.pe -com.pe -net.pe - -// pf : http://www.gobin.info/domainname/formulaire-pf.pdf -pf -com.pf -org.pf -edu.pf - -// pg : http://en.wikipedia.org/wiki/.pg -*.pg - -// ph : http://www.domains.ph/FAQ2.asp -// Submitted by registry 2008-06-13 -ph -com.ph -net.ph -org.ph -gov.ph -edu.ph -ngo.ph -mil.ph -i.ph - -// pk : http://pk5.pknic.net.pk/pk5/msgNamepk.PK -pk -com.pk -net.pk -edu.pk -org.pk -fam.pk -biz.pk -web.pk -gov.pk -gob.pk -gok.pk -gon.pk -gop.pk -gos.pk -info.pk - -// pl : http://www.dns.pl/english/ -pl -// NASK functional domains (nask.pl / dns.pl) : http://www.dns.pl/english/dns-funk.html -aid.pl -agro.pl -atm.pl -auto.pl -biz.pl -com.pl -edu.pl -gmina.pl -gsm.pl -info.pl -mail.pl -miasta.pl -media.pl -mil.pl -net.pl -nieruchomosci.pl -nom.pl -org.pl -pc.pl -powiat.pl -priv.pl -realestate.pl -rel.pl -sex.pl -shop.pl -sklep.pl -sos.pl -szkola.pl -targi.pl -tm.pl -tourism.pl -travel.pl -turystyka.pl -// ICM functional domains (icm.edu.pl) -6bone.pl -art.pl -mbone.pl -// Government domains (administred by ippt.gov.pl) -gov.pl -uw.gov.pl -um.gov.pl -ug.gov.pl -upow.gov.pl -starostwo.gov.pl -so.gov.pl -sr.gov.pl -po.gov.pl -pa.gov.pl -// other functional domains -ngo.pl -irc.pl -usenet.pl -// NASK geographical domains : http://www.dns.pl/english/dns-regiony.html -augustow.pl -babia-gora.pl -bedzin.pl -beskidy.pl -bialowieza.pl -bialystok.pl -bielawa.pl -bieszczady.pl -boleslawiec.pl -bydgoszcz.pl -bytom.pl -cieszyn.pl -czeladz.pl -czest.pl -dlugoleka.pl -elblag.pl -elk.pl -glogow.pl -gniezno.pl -gorlice.pl -grajewo.pl -ilawa.pl -jaworzno.pl -jelenia-gora.pl -jgora.pl -kalisz.pl -kazimierz-dolny.pl -karpacz.pl -kartuzy.pl -kaszuby.pl -katowice.pl -kepno.pl -ketrzyn.pl -klodzko.pl -kobierzyce.pl -kolobrzeg.pl -konin.pl -konskowola.pl -kutno.pl -lapy.pl -lebork.pl -legnica.pl -lezajsk.pl -limanowa.pl -lomza.pl -lowicz.pl -lubin.pl -lukow.pl -malbork.pl -malopolska.pl -mazowsze.pl -mazury.pl -mielec.pl -mielno.pl -mragowo.pl -naklo.pl -nowaruda.pl -nysa.pl -olawa.pl -olecko.pl -olkusz.pl -olsztyn.pl -opoczno.pl -opole.pl -ostroda.pl -ostroleka.pl -ostrowiec.pl -ostrowwlkp.pl -pila.pl -pisz.pl -podhale.pl -podlasie.pl -polkowice.pl -pomorze.pl -pomorskie.pl -prochowice.pl -pruszkow.pl -przeworsk.pl -pulawy.pl -radom.pl -rawa-maz.pl -rybnik.pl -rzeszow.pl -sanok.pl -sejny.pl -siedlce.pl -slask.pl -slupsk.pl -sosnowiec.pl -stalowa-wola.pl -skoczow.pl -starachowice.pl -stargard.pl -suwalki.pl -swidnica.pl -swiebodzin.pl -swinoujscie.pl -szczecin.pl -szczytno.pl -tarnobrzeg.pl -tgory.pl -turek.pl -tychy.pl -ustka.pl -walbrzych.pl -warmia.pl -warszawa.pl -waw.pl -wegrow.pl -wielun.pl -wlocl.pl -wloclawek.pl -wodzislaw.pl -wolomin.pl -wroclaw.pl -zachpomor.pl -zagan.pl -zarow.pl -zgora.pl -zgorzelec.pl -// TASK geographical domains (www.task.gda.pl/uslugi/dns) -gda.pl -gdansk.pl -gdynia.pl -med.pl -sopot.pl -// other geographical domains -gliwice.pl -krakow.pl -poznan.pl -wroc.pl -zakopane.pl - -// pm : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf -pm - -// pn : http://www.government.pn/PnRegistry/policies.htm -pn -gov.pn -co.pn -org.pn -edu.pn -net.pn - -// pr : http://www.nic.pr/index.asp?f=1 -pr -com.pr -net.pr -org.pr -gov.pr -edu.pr -isla.pr -pro.pr -biz.pr -info.pr -name.pr -// these aren't mentioned on nic.pr, but on http://en.wikipedia.org/wiki/.pr -est.pr -prof.pr -ac.pr - -// pro : http://www.nic.pro/support_faq.htm -pro -aca.pro -bar.pro -cpa.pro -jur.pro -law.pro -med.pro -eng.pro - -// ps : http://en.wikipedia.org/wiki/.ps -// http://www.nic.ps/registration/policy.html#reg -ps -edu.ps -gov.ps -sec.ps -plo.ps -com.ps -org.ps -net.ps - -// pt : http://online.dns.pt/dns/start_dns -pt -net.pt -gov.pt -org.pt -edu.pt -int.pt -publ.pt -com.pt -nome.pt - -// pw : http://en.wikipedia.org/wiki/.pw -pw -co.pw -ne.pw -or.pw -ed.pw -go.pw -belau.pw - -// py : http://www.nic.py/faq_a.html#faq_b -*.py - -// qa : http://domains.qa/en/ -qa -com.qa -edu.qa -gov.qa -mil.qa -name.qa -net.qa -org.qa -sch.qa - -// re : http://www.afnic.re/obtenir/chartes/nommage-re/annexe-descriptifs -re -com.re -asso.re -nom.re - -// ro : http://www.rotld.ro/ -ro -com.ro -org.ro -tm.ro -nt.ro -nom.ro -info.ro -rec.ro -arts.ro -firm.ro -store.ro -www.ro - -// rs : http://en.wikipedia.org/wiki/.rs -rs -co.rs -org.rs -edu.rs -ac.rs -gov.rs -in.rs - -// ru : http://www.cctld.ru/ru/docs/aktiv_8.php -// Industry domains -ru -ac.ru -com.ru -edu.ru -int.ru -net.ru -org.ru -pp.ru -// Geographical domains -adygeya.ru -altai.ru -amur.ru -arkhangelsk.ru -astrakhan.ru -bashkiria.ru -belgorod.ru -bir.ru -bryansk.ru -buryatia.ru -cbg.ru -chel.ru -chelyabinsk.ru -chita.ru -chukotka.ru -chuvashia.ru -dagestan.ru -dudinka.ru -e-burg.ru -grozny.ru -irkutsk.ru -ivanovo.ru -izhevsk.ru -jar.ru -joshkar-ola.ru -kalmykia.ru -kaluga.ru -kamchatka.ru -karelia.ru -kazan.ru -kchr.ru -kemerovo.ru -khabarovsk.ru -khakassia.ru -khv.ru -kirov.ru -koenig.ru -komi.ru -kostroma.ru -krasnoyarsk.ru -kuban.ru -kurgan.ru -kursk.ru -lipetsk.ru -magadan.ru -mari.ru -mari-el.ru -marine.ru -mordovia.ru -mosreg.ru -msk.ru -murmansk.ru -nalchik.ru -nnov.ru -nov.ru -novosibirsk.ru -nsk.ru -omsk.ru -orenburg.ru -oryol.ru -palana.ru -penza.ru -perm.ru -pskov.ru -ptz.ru -rnd.ru -ryazan.ru -sakhalin.ru -samara.ru -saratov.ru -simbirsk.ru -smolensk.ru -spb.ru -stavropol.ru -stv.ru -surgut.ru -tambov.ru -tatarstan.ru -tom.ru -tomsk.ru -tsaritsyn.ru -tsk.ru -tula.ru -tuva.ru -tver.ru -tyumen.ru -udm.ru -udmurtia.ru -ulan-ude.ru -vladikavkaz.ru -vladimir.ru -vladivostok.ru -volgograd.ru -vologda.ru -voronezh.ru -vrn.ru -vyatka.ru -yakutia.ru -yamal.ru -yaroslavl.ru -yekaterinburg.ru -yuzhno-sakhalinsk.ru -// More geographical domains -amursk.ru -baikal.ru -cmw.ru -fareast.ru -jamal.ru -kms.ru -k-uralsk.ru -kustanai.ru -kuzbass.ru -magnitka.ru -mytis.ru -nakhodka.ru -nkz.ru -norilsk.ru -oskol.ru -pyatigorsk.ru -rubtsovsk.ru -snz.ru -syzran.ru -vdonsk.ru -zgrad.ru -// State domains -gov.ru -mil.ru -// Technical domains -test.ru - -// rw : http://www.nic.rw/cgi-bin/policy.pl -rw -gov.rw -net.rw -edu.rw -ac.rw -com.rw -co.rw -int.rw -mil.rw -gouv.rw - -// sa : http://www.nic.net.sa/ -sa -com.sa -net.sa -org.sa -gov.sa -med.sa -pub.sa -edu.sa -sch.sa - -// sb : http://www.sbnic.net.sb/ -// Submitted by registry 2008-06-08 -sb -com.sb -edu.sb -gov.sb -net.sb -org.sb - -// sc : http://www.nic.sc/ -sc -com.sc -gov.sc -net.sc -org.sc -edu.sc - -// sd : http://www.isoc.sd/sudanic.isoc.sd/billing_pricing.htm -// Submitted by registry 2008-06-17 -sd -com.sd -net.sd -org.sd -edu.sd -med.sd -gov.sd -info.sd - -// se : http://en.wikipedia.org/wiki/.se -// Submitted by registry 2008-06-24 -se -a.se -ac.se -b.se -bd.se -brand.se -c.se -d.se -e.se -f.se -fh.se -fhsk.se -fhv.se -g.se -h.se -i.se -k.se -komforb.se -kommunalforbund.se -komvux.se -l.se -lanbib.se -m.se -n.se -naturbruksgymn.se -o.se -org.se -p.se -parti.se -pp.se -press.se -r.se -s.se -sshn.se -t.se -tm.se -u.se -w.se -x.se -y.se -z.se - -// sg : http://www.nic.net.sg/sub_policies_agreement/2ld.html -sg -com.sg -net.sg -org.sg -gov.sg -edu.sg -per.sg - -// sh : http://www.nic.sh/rules.html -// list of 2nd level domains ? -sh - -// si : http://en.wikipedia.org/wiki/.si -si - -// sj : No registrations at this time. -// Submitted by registry 2008-06-16 - -// sk : http://en.wikipedia.org/wiki/.sk -// list of 2nd level domains ? -sk - -// sl : http://www.nic.sl -// Submitted by registry 2008-06-12 -sl -com.sl -net.sl -edu.sl -gov.sl -org.sl - -// sm : http://en.wikipedia.org/wiki/.sm -sm - -// sn : http://en.wikipedia.org/wiki/.sn -sn -art.sn -com.sn -edu.sn -gouv.sn -org.sn -perso.sn -univ.sn - -// so : http://www.soregistry.com/ -so -com.so -net.so -org.so - -// sr : http://en.wikipedia.org/wiki/.sr -sr - -// st : http://www.nic.st/html/policyrules/ -st -co.st -com.st -consulado.st -edu.st -embaixada.st -gov.st -mil.st -net.st -org.st -principe.st -saotome.st -store.st - -// su : http://en.wikipedia.org/wiki/.su -su - -// sv : http://www.svnet.org.sv/svpolicy.html -*.sv - -// sy : http://en.wikipedia.org/wiki/.sy -// see also: http://www.gobin.info/domainname/sy.doc -sy -edu.sy -gov.sy -net.sy -mil.sy -com.sy -org.sy - -// sz : http://en.wikipedia.org/wiki/.sz -// http://www.sispa.org.sz/ -sz -co.sz -ac.sz -org.sz - -// tc : http://en.wikipedia.org/wiki/.tc -tc - -// td : http://en.wikipedia.org/wiki/.td -td - -// tel: http://en.wikipedia.org/wiki/.tel -// http://www.telnic.org/ -tel - -// tf : http://en.wikipedia.org/wiki/.tf -tf - -// tg : http://en.wikipedia.org/wiki/.tg -// http://www.nic.tg/nictg/index.php implies no reserved 2nd-level domains, -// although this contradicts wikipedia. -tg - -// th : http://en.wikipedia.org/wiki/.th -// Submitted by registry 2008-06-17 -th -ac.th -co.th -go.th -in.th -mi.th -net.th -or.th - -// tj : http://www.nic.tj/policy.htm -tj -ac.tj -biz.tj -co.tj -com.tj -edu.tj -go.tj -gov.tj -int.tj -mil.tj -name.tj -net.tj -nic.tj -org.tj -test.tj -web.tj - -// tk : http://en.wikipedia.org/wiki/.tk -tk - -// tl : http://en.wikipedia.org/wiki/.tl -tl -gov.tl - -// tm : http://www.nic.tm/rules.html -// list of 2nd level tlds ? -tm - -// tn : http://en.wikipedia.org/wiki/.tn -// http://whois.ati.tn/ -tn -com.tn -ens.tn -fin.tn -gov.tn -ind.tn -intl.tn -nat.tn -net.tn -org.tn -info.tn -perso.tn -tourism.tn -edunet.tn -rnrt.tn -rns.tn -rnu.tn -mincom.tn -agrinet.tn -defense.tn -turen.tn - -// to : http://en.wikipedia.org/wiki/.to -// Submitted by registry 2008-06-17 -to -com.to -gov.to -net.to -org.to -edu.to -mil.to - -// tr : http://en.wikipedia.org/wiki/.tr -*.tr -!nic.tr -// Used by government in the TRNC -// http://en.wikipedia.org/wiki/.nc.tr -gov.nc.tr - -// travel : http://en.wikipedia.org/wiki/.travel -travel - -// tt : http://www.nic.tt/ -tt -co.tt -com.tt -org.tt -net.tt -biz.tt -info.tt -pro.tt -int.tt -coop.tt -jobs.tt -mobi.tt -travel.tt -museum.tt -aero.tt -name.tt -gov.tt -edu.tt - -// tv : http://en.wikipedia.org/wiki/.tv -// Not listing any 2LDs as reserved since none seem to exist in practice, -// Wikipedia notwithstanding. -tv - -// tw : http://en.wikipedia.org/wiki/.tw -tw -edu.tw -gov.tw -mil.tw -com.tw -net.tw -org.tw -idv.tw -game.tw -ebiz.tw -club.tw -網路.tw -組織.tw -商業.tw - -// tz : http://en.wikipedia.org/wiki/.tz -// Submitted by registry 2008-06-17 -// Updated from http://www.tznic.or.tz/index.php/domains.html 2010-10-25 -ac.tz -co.tz -go.tz -mil.tz -ne.tz -or.tz -sc.tz - -// ua : http://www.nic.net.ua/ -ua -com.ua -edu.ua -gov.ua -in.ua -net.ua -org.ua -// ua geo-names -cherkassy.ua -chernigov.ua -chernovtsy.ua -ck.ua -cn.ua -crimea.ua -cv.ua -dn.ua -dnepropetrovsk.ua -donetsk.ua -dp.ua -if.ua -ivano-frankivsk.ua -kh.ua -kharkov.ua -kherson.ua -khmelnitskiy.ua -kiev.ua -kirovograd.ua -km.ua -kr.ua -ks.ua -kv.ua -lg.ua -lugansk.ua -lutsk.ua -lviv.ua -mk.ua -nikolaev.ua -od.ua -odessa.ua -pl.ua -poltava.ua -rovno.ua -rv.ua -sebastopol.ua -sumy.ua -te.ua -ternopil.ua -uzhgorod.ua -vinnica.ua -vn.ua -zaporizhzhe.ua -zp.ua -zhitomir.ua -zt.ua - -// Private registries in .ua -co.ua -pp.ua - -// ug : http://www.registry.co.ug/ -ug -co.ug -ac.ug -sc.ug -go.ug -ne.ug -or.ug - -// uk : http://en.wikipedia.org/wiki/.uk -*.uk -*.sch.uk -!bl.uk -!british-library.uk -!icnet.uk -!jet.uk -!mod.uk -!nel.uk -!nhs.uk -!nic.uk -!nls.uk -!national-library-scotland.uk -!parliament.uk -!police.uk - -// us : http://en.wikipedia.org/wiki/.us -us -dni.us -fed.us -isa.us -kids.us -nsn.us -// us geographic names -ak.us -al.us -ar.us -as.us -az.us -ca.us -co.us -ct.us -dc.us -de.us -fl.us -ga.us -gu.us -hi.us -ia.us -id.us -il.us -in.us -ks.us -ky.us -la.us -ma.us -md.us -me.us -mi.us -mn.us -mo.us -ms.us -mt.us -nc.us -nd.us -ne.us -nh.us -nj.us -nm.us -nv.us -ny.us -oh.us -ok.us -or.us -pa.us -pr.us -ri.us -sc.us -sd.us -tn.us -tx.us -ut.us -vi.us -vt.us -va.us -wa.us -wi.us -wv.us -wy.us -// The registrar notes several more specific domains available in each state, -// such as state.*.us, dst.*.us, etc., but resolution of these is somewhat -// haphazard; in some states these domains resolve as addresses, while in others -// only subdomains are available, or even nothing at all. We include the -// most common ones where it's clear that different sites are different -// entities. -k12.ak.us -k12.al.us -k12.ar.us -k12.as.us -k12.az.us -k12.ca.us -k12.co.us -k12.ct.us -k12.dc.us -k12.de.us -k12.fl.us -k12.ga.us -k12.gu.us -// k12.hi.us Hawaii has a state-wide DOE login: bug 614565 -k12.ia.us -k12.id.us -k12.il.us -k12.in.us -k12.ks.us -k12.ky.us -k12.la.us -k12.ma.us -k12.md.us -k12.me.us -k12.mi.us -k12.mn.us -k12.mo.us -k12.ms.us -k12.mt.us -k12.nc.us -k12.nd.us -k12.ne.us -k12.nh.us -k12.nj.us -k12.nm.us -k12.nv.us -k12.ny.us -k12.oh.us -k12.ok.us -k12.or.us -k12.pa.us -k12.pr.us -k12.ri.us -k12.sc.us -k12.sd.us -k12.tn.us -k12.tx.us -k12.ut.us -k12.vi.us -k12.vt.us -k12.va.us -k12.wa.us -k12.wi.us -k12.wv.us -k12.wy.us - -cc.ak.us -cc.al.us -cc.ar.us -cc.as.us -cc.az.us -cc.ca.us -cc.co.us -cc.ct.us -cc.dc.us -cc.de.us -cc.fl.us -cc.ga.us -cc.gu.us -cc.hi.us -cc.ia.us -cc.id.us -cc.il.us -cc.in.us -cc.ks.us -cc.ky.us -cc.la.us -cc.ma.us -cc.md.us -cc.me.us -cc.mi.us -cc.mn.us -cc.mo.us -cc.ms.us -cc.mt.us -cc.nc.us -cc.nd.us -cc.ne.us -cc.nh.us -cc.nj.us -cc.nm.us -cc.nv.us -cc.ny.us -cc.oh.us -cc.ok.us -cc.or.us -cc.pa.us -cc.pr.us -cc.ri.us -cc.sc.us -cc.sd.us -cc.tn.us -cc.tx.us -cc.ut.us -cc.vi.us -cc.vt.us -cc.va.us -cc.wa.us -cc.wi.us -cc.wv.us -cc.wy.us - -lib.ak.us -lib.al.us -lib.ar.us -lib.as.us -lib.az.us -lib.ca.us -lib.co.us -lib.ct.us -lib.dc.us -lib.de.us -lib.fl.us -lib.ga.us -lib.gu.us -lib.hi.us -lib.ia.us -lib.id.us -lib.il.us -lib.in.us -lib.ks.us -lib.ky.us -lib.la.us -lib.ma.us -lib.md.us -lib.me.us -lib.mi.us -lib.mn.us -lib.mo.us -lib.ms.us -lib.mt.us -lib.nc.us -lib.nd.us -lib.ne.us -lib.nh.us -lib.nj.us -lib.nm.us -lib.nv.us -lib.ny.us -lib.oh.us -lib.ok.us -lib.or.us -lib.pa.us -lib.pr.us -lib.ri.us -lib.sc.us -lib.sd.us -lib.tn.us -lib.tx.us -lib.ut.us -lib.vi.us -lib.vt.us -lib.va.us -lib.wa.us -lib.wi.us -lib.wv.us -lib.wy.us - -// k12.ma.us contains school districts in Massachusetts. The 4LDs are -// managed indepedently except for private (PVT), charter (CHTR) and -// parochial (PAROCH) schools. Those are delegated dorectly to the -// 5LD operators. -pvt.k12.ma.us -chtr.k12.ma.us -paroch.k12.ma.us - -// uy : http://www.antel.com.uy/ -*.uy - -// uz : http://www.reg.uz/registerr.html -// are there other 2nd level tlds ? -uz -com.uz -co.uz - -// va : http://en.wikipedia.org/wiki/.va -va - -// vc : http://en.wikipedia.org/wiki/.vc -// Submitted by registry 2008-06-13 -vc -com.vc -net.vc -org.vc -gov.vc -mil.vc -edu.vc - -// ve : http://registro.nic.ve/nicve/registro/index.html -*.ve - -// vg : http://en.wikipedia.org/wiki/.vg -vg - -// vi : http://www.nic.vi/newdomainform.htm -// http://www.nic.vi/Domain_Rules/body_domain_rules.html indicates some other -// TLDs are "reserved", such as edu.vi and gov.vi, but doesn't actually say they -// are available for registration (which they do not seem to be). -vi -co.vi -com.vi -k12.vi -net.vi -org.vi - -// vn : https://www.dot.vn/vnnic/vnnic/domainregistration.jsp -vn -com.vn -net.vn -org.vn -edu.vn -gov.vn -int.vn -ac.vn -biz.vn -info.vn -name.vn -pro.vn -health.vn - -// vu : http://en.wikipedia.org/wiki/.vu -// list of 2nd level tlds ? -vu - -// wf : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf -wf - -// ws : http://en.wikipedia.org/wiki/.ws -// http://samoanic.ws/index.dhtml -ws -com.ws -net.ws -org.ws -gov.ws -edu.ws - -// yt : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf -yt - -// IDN ccTLDs -// Please sort by ISO 3166 ccTLD, then punicode string -// when submitting patches and follow this format: -// ("" ) : -// [optional sponsoring org] -// - -// xn--mgbaam7a8h ("Emerat" Arabic) : AE -//http://nic.ae/english/arabicdomain/rules.jsp -امارات - -// xn--54b7fta0cc ("Bangla" Bangla) : BD -বাংলা - -// xn--fiqs8s ("China" Chinese-Han-Simplified <.Zhonggou>) : CN -// CNNIC -// http://cnnic.cn/html/Dir/2005/10/11/3218.htm -中国 - -// xn--fiqz9s ("China" Chinese-Han-Traditional <.Zhonggou>) : CN -// CNNIC -// http://cnnic.cn/html/Dir/2005/10/11/3218.htm -中國 - -// xn--lgbbat1ad8j ("Algeria / Al Jazair" Arabic) : DZ -الجزائر - -// xn--wgbh1c ("Egypt" Arabic .masr) : EG -// http://www.dotmasr.eg/ -مصر - -// xn--node ("ge" Georgian (Mkhedruli)) : GE -გე - -// xn--j6w193g ("Hong Kong" Chinese-Han) : HK -// https://www2.hkirc.hk/register/rules.jsp -香港 - -// xn--h2brj9c ("Bharat" Devanagari) : IN -// India -भारत - -// xn--mgbbh1a71e ("Bharat" Arabic) : IN -// India -بھارت - -// xn--fpcrj9c3d ("Bharat" Telugu) : IN -// India -భారత్ - -// xn--gecrj9c ("Bharat" Gujarati) : IN -// India -ભારત - -// xn--s9brj9c ("Bharat" Gurmukhi) : IN -// India -ਭਾਰਤ - -// xn--45brj9c ("Bharat" Bengali) : IN -// India -ভারত - -// xn--xkc2dl3a5ee0h ("India" Tamil) : IN -// India -இந்தியா - -// xn--mgba3a4f16a ("Iran" Persian) : IR -ایران - -// xn--mgba3a4fra ("Iran" Arabic) : IR -ايران - -//xn--mgbayh7gpa ("al-Ordon" Arabic) JO -//National Information Technology Center (NITC) -//Royal Scientific Society, Al-Jubeiha -الاردن - -// xn--3e0b707e ("Republic of Korea" Hangul) : KR -한국 - -// xn--fzc2c9e2c ("Lanka" Sinhalese-Sinhala) : LK -// http://nic.lk -ලංකා - -// xn--xkc2al3hye2a ("Ilangai" Tamil) : LK -// http://nic.lk -இலங்கை - -// xn--mgbc0a9azcg ("Morocco / al-Maghrib" Arabic) : MA -المغرب - -// xn--mgb9awbf ("Oman" Arabic) : OM -عمان - -// xn--ygbi2ammx ("Falasteen" Arabic) : PS -// The Palestinian National Internet Naming Authority (PNINA) -// http://www.pnina.ps -فلسطين - -// xn--90a3ac ("srb" Cyrillic) : RS -срб - -// xn--p1ai ("rf" Russian-Cyrillic) : RU -// http://www.cctld.ru/en/docs/rulesrf.php -рф - -// xn--wgbl6a ("Qatar" Arabic) : QA -// http://www.ict.gov.qa/ -قطر - -// xn--mgberp4a5d4ar ("AlSaudiah" Arabic) : SA -// http://www.nic.net.sa/ -السعودية - -// xn--mgberp4a5d4a87g ("AlSaudiah" Arabic) variant : SA -السعودیة - -// xn--mgbqly7c0a67fbc ("AlSaudiah" Arabic) variant : SA -السعودیۃ - -// xn--mgbqly7cvafr ("AlSaudiah" Arabic) variant : SA -السعوديه - -// xn--ogbpf8fl ("Syria" Arabic) : SY -سورية - -// xn--mgbtf8fl ("Syria" Arabic) variant : SY -سوريا - -// xn--yfro4i67o Singapore ("Singapore" Chinese-Han) : SG -新加坡 - -// xn--clchc0ea0b2g2a9gcd ("Singapore" Tamil) : SG -சிங்கப்பூர் - -// xn--o3cw4h ("Thai" Thai) : TH -// http://www.thnic.co.th -ไทย - -// xn--pgbs0dh ("Tunis") : TN -// http://nic.tn -تونس - -// xn--kpry57d ("Taiwan" Chinese-Han-Traditional) : TW -// http://www.twnic.net/english/dn/dn_07a.htm -台灣 - -// xn--kprw13d ("Taiwan" Chinese-Han-Simplified) : TW -// http://www.twnic.net/english/dn/dn_07a.htm -台湾 - -// xn--nnx388a ("Taiwan") variant : TW -臺灣 - -// xn--j1amh ("ukr" Cyrillic) : UA -укр - -// xn--mgb2ddes ("AlYemen" Arabic) : YE -اليمن - -// xxx : http://icmregistry.com -xxx - -// ye : http://www.y.net.ye/services/domain_name.htm -*.ye - -// za : http://www.zadna.org.za/slds.html -*.za - -// zm : http://en.wikipedia.org/wiki/.zm -*.zm - -// zw : http://en.wikipedia.org/wiki/.zw -*.zw - -// ===END ICANN DOMAINS=== -// ===BEGIN PRIVATE DOMAINS=== - -// info.at : http://www.info.at/ -biz.at -info.at - -// priv.at : http://www.nic.priv.at/ -// Submitted by registry 2008-06-09 -priv.at - -// co.ca : http://registry.co.ca -co.ca - -// CentralNic : http://www.centralnic.com/names/domains -// Confirmed by registry 2008-06-09 -ar.com -br.com -cn.com -de.com -eu.com -gb.com -gr.com -hu.com -jpn.com -kr.com -no.com -qc.com -ru.com -sa.com -se.com -uk.com -us.com -uy.com -za.com -gb.net -jp.net -se.net -uk.net -ae.org -us.org -com.de - -// Opera Software, A.S.A. -// Requested by Yngve Pettersen 2009-11-26 -operaunite.com - -// Google, Inc. -// Requested by Eduardo Vela 2010-09-06 -appspot.com - -// iki.fi : Submitted by Hannu Aronsson 2009-11-05 -iki.fi - -// c.la : http://www.c.la/ -c.la - -// ZaNiC : http://www.za.net/ -// Confirmed by registry 2009-10-03 -za.net -za.org - -// CoDNS B.V. -// Added 2010-05-23. -co.nl -co.no - -// Mainseek Sp. z o.o. : http://www.co.pl/ -co.pl - -// DynDNS.com : http://www.dyndns.com/services/dns/dyndns/ -dyndns-at-home.com -dyndns-at-work.com -dyndns-blog.com -dyndns-free.com -dyndns-home.com -dyndns-ip.com -dyndns-mail.com -dyndns-office.com -dyndns-pics.com -dyndns-remote.com -dyndns-server.com -dyndns-web.com -dyndns-wiki.com -dyndns-work.com -dyndns.biz -dyndns.info -dyndns.org -dyndns.tv -at-band-camp.net -ath.cx -barrel-of-knowledge.info -barrell-of-knowledge.info -better-than.tv -blogdns.com -blogdns.net -blogdns.org -blogsite.org -boldlygoingnowhere.org -broke-it.net -buyshouses.net -cechire.com -dnsalias.com -dnsalias.net -dnsalias.org -dnsdojo.com -dnsdojo.net -dnsdojo.org -does-it.net -doesntexist.com -doesntexist.org -dontexist.com -dontexist.net -dontexist.org -doomdns.com -doomdns.org -dvrdns.org -dyn-o-saur.com -dynalias.com -dynalias.net -dynalias.org -dynathome.net -dyndns.ws -endofinternet.net -endofinternet.org -endoftheinternet.org -est-a-la-maison.com -est-a-la-masion.com -est-le-patron.com -est-mon-blogueur.com -for-better.biz -for-more.biz -for-our.info -for-some.biz -for-the.biz -forgot.her.name -forgot.his.name -from-ak.com -from-al.com -from-ar.com -from-az.net -from-ca.com -from-co.net -from-ct.com -from-dc.com -from-de.com -from-fl.com -from-ga.com -from-hi.com -from-ia.com -from-id.com -from-il.com -from-in.com -from-ks.com -from-ky.com -from-la.net -from-ma.com -from-md.com -from-me.org -from-mi.com -from-mn.com -from-mo.com -from-ms.com -from-mt.com -from-nc.com -from-nd.com -from-ne.com -from-nh.com -from-nj.com -from-nm.com -from-nv.com -from-ny.net -from-oh.com -from-ok.com -from-or.com -from-pa.com -from-pr.com -from-ri.com -from-sc.com -from-sd.com -from-tn.com -from-tx.com -from-ut.com -from-va.com -from-vt.com -from-wa.com -from-wi.com -from-wv.com -from-wy.com -ftpaccess.cc -fuettertdasnetz.de -game-host.org -game-server.cc -getmyip.com -gets-it.net -go.dyndns.org -gotdns.com -gotdns.org -groks-the.info -groks-this.info -ham-radio-op.net -here-for-more.info -hobby-site.com -hobby-site.org -home.dyndns.org -homedns.org -homeftp.net -homeftp.org -homeip.net -homelinux.com -homelinux.net -homelinux.org -homeunix.com -homeunix.net -homeunix.org -iamallama.com -in-the-band.net -is-a-anarchist.com -is-a-blogger.com -is-a-bookkeeper.com -is-a-bruinsfan.org -is-a-bulls-fan.com -is-a-candidate.org -is-a-caterer.com -is-a-celticsfan.org -is-a-chef.com -is-a-chef.net -is-a-chef.org -is-a-conservative.com -is-a-cpa.com -is-a-cubicle-slave.com -is-a-democrat.com -is-a-designer.com -is-a-doctor.com -is-a-financialadvisor.com -is-a-geek.com -is-a-geek.net -is-a-geek.org -is-a-green.com -is-a-guru.com -is-a-hard-worker.com -is-a-hunter.com -is-a-knight.org -is-a-landscaper.com -is-a-lawyer.com -is-a-liberal.com -is-a-libertarian.com -is-a-linux-user.org -is-a-llama.com -is-a-musician.com -is-a-nascarfan.com -is-a-nurse.com -is-a-painter.com -is-a-patsfan.org -is-a-personaltrainer.com -is-a-photographer.com -is-a-player.com -is-a-republican.com -is-a-rockstar.com -is-a-socialist.com -is-a-soxfan.org -is-a-student.com -is-a-teacher.com -is-a-techie.com -is-a-therapist.com -is-an-accountant.com -is-an-actor.com -is-an-actress.com -is-an-anarchist.com -is-an-artist.com -is-an-engineer.com -is-an-entertainer.com -is-by.us -is-certified.com -is-found.org -is-gone.com -is-into-anime.com -is-into-cars.com -is-into-cartoons.com -is-into-games.com -is-leet.com -is-lost.org -is-not-certified.com -is-saved.org -is-slick.com -is-uberleet.com -is-very-bad.org -is-very-evil.org -is-very-good.org -is-very-nice.org -is-very-sweet.org -is-with-theband.com -isa-geek.com -isa-geek.net -isa-geek.org -isa-hockeynut.com -issmarterthanyou.com -isteingeek.de -istmein.de -kicks-ass.net -kicks-ass.org -knowsitall.info -land-4-sale.us -lebtimnetz.de -leitungsen.de -likes-pie.com -likescandy.com -merseine.nu -mine.nu -misconfused.org -mypets.ws -myphotos.cc -neat-url.com -office-on-the.net -on-the-web.tv -podzone.net -podzone.org -readmyblog.org -saves-the-whales.com -scrapper-site.net -scrapping.cc -selfip.biz -selfip.com -selfip.info -selfip.net -selfip.org -sells-for-less.com -sells-for-u.com -sells-it.net -sellsyourhome.org -servebbs.com -servebbs.net -servebbs.org -serveftp.net -serveftp.org -servegame.org -shacknet.nu -simple-url.com -space-to-rent.com -stuff-4-sale.org -stuff-4-sale.us -teaches-yoga.com -thruhere.net -traeumtgerade.de -webhop.biz -webhop.info -webhop.net -webhop.org -worse-than.tv -writesthisblog.com - -// ===END PRIVATE DOMAINS=== diff --git a/commons/src/test/java/org/archive/net/PublicSuffixesTest.java b/commons/src/test/java/org/archive/net/PublicSuffixesTest.java deleted file mode 100644 index 2eac9c3b..00000000 --- a/commons/src/test/java/org/archive/net/PublicSuffixesTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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 org.archive.net; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.regex.Matcher; - -import junit.framework.TestCase; - -import org.archive.net.PublicSuffixes.Node; - -/** - * Test cases for PublicSuffixes utility. Confirm expected matches/nonmatches - * from constructed regex. - * - * @author gojomo - */ -public class PublicSuffixesTest extends TestCase { - // test of low level implementation - - public void testCompare() { - Node n = new Node("hoge"); - assertTrue(n.compareTo('a') > 0); - assertEquals(-1, n.compareTo('*')); - assertEquals(-1, n.compareTo('!')); - assertEquals(-1, n.compareTo(new Node("*,"))); - assertEquals(-1, n.compareTo(new Node("!muga,"))); - assertEquals(-1, n.compareTo(new Node(""))); - - n = new Node("*,"); - assertEquals(1, n.compareTo('a')); - assertEquals(0, n.compareTo('*')); - assertEquals(1, n.compareTo('!')); - assertEquals(0, n.compareTo(new Node("*,"))); - assertEquals(1, n.compareTo(new Node("!muga,"))); - assertEquals(-1, n.compareTo(new Node(""))); - - n = new Node("!hoge"); - assertEquals(1, n.compareTo('a')); - assertEquals(-1, n.compareTo('*')); - assertEquals(0, n.compareTo('!')); - assertEquals(-1, n.compareTo(new Node("*,"))); - assertEquals(0, n.compareTo(new Node("!muga,"))); - assertEquals(-1, n.compareTo(new Node(""))); - - n = new Node(""); - assertEquals(1, n.compareTo('a')); - assertEquals(1, n.compareTo('*')); - assertEquals(1, n.compareTo('!')); - assertEquals(0, n.compareTo(new Node(""))); - } - - protected String dump(Node alt) { - StringWriter w = new StringWriter(); - PublicSuffixes.dump(alt, 0, new PrintWriter(w)); - return w.toString(); - } - public void testTrie1() { - Node alt = new Node(null, new ArrayList()); - alt.addBranch("ac,"); - // specifically, should not have empty string as match. - assertEquals("(null)\n" + - " \"ac,\"\n", dump(alt)); - alt.addBranch("ac,com,"); - assertEquals("(null)\n" + - " \"ac,\"\n" + - " \"com,\"\n" + - " \"\"\n", dump(alt)); - alt.addBranch("ac,edu,"); - assertEquals("(null)\n" + - " \"ac,\"\n" + - " \"com,\"\n" + - " \"edu,\"\n" + - " \"\"\n", dump(alt)); - } - public void testTrie2() { - Node alt = new Node(null, new ArrayList()); - alt.addBranch("ac,"); - alt.addBranch("*,"); - assertEquals("(null)\n" + - " \"ac,\"\n" + - " \"*,\"\n", dump(alt)); - } - - public void testTrie3() { - Node alt = new Node(null, new ArrayList()); - alt.addBranch("ac,"); - alt.addBranch("ac,!hoge,"); - alt.addBranch("ac,*,"); - // exception goes first. - assertEquals("(null)\n" + - " \"ac,\"\n" + - " \"!hoge,\"\n" + - " \"*,\"\n" + - " \"\"\n", dump(alt)); - } - - // test of higher-level functionality - - Matcher m = PublicSuffixes.getTopmostAssignedSurtPrefixPattern() - .matcher(""); - - public void testBasics() { - matchPrefix("com,example,www,", "com,example,"); - matchPrefix("com,example,", "com,example,"); - matchPrefix("org,archive,www,", "org,archive,"); - matchPrefix("org,archive,", "org,archive,"); - matchPrefix("fr,yahoo,www,", "fr,yahoo,"); - matchPrefix("fr,yahoo,", "fr,yahoo,"); - matchPrefix("au,com,foobar,www,", "au,com,foobar,"); - matchPrefix("au,com,foobar,", "au,com,foobar,"); - matchPrefix("uk,co,virgin,www,", "uk,co,virgin,"); - matchPrefix("uk,co,virgin,", "uk,co,virgin,"); - matchPrefix("au,com,example,www,", "au,com,example,"); - matchPrefix("au,com,example,", "au,com,example,"); - matchPrefix("jp,tokyo,public,assigned,www,", - "jp,tokyo,public,assigned,"); - matchPrefix("jp,tokyo,public,assigned,", "jp,tokyo,public,assigned,"); - } - - public void testDomainWithDash() { - matchPrefix("de,bad-site,www", "de,bad-site,"); - } - - public void testDomainWithNumbers() { - matchPrefix("de,archive4u,www", "de,archive4u,"); - } - - public void testIPV4() { - assertEquals("unexpected reduction", - "1.2.3.4", - PublicSuffixes.reduceSurtToAssignmentLevel("1.2.3.4")); - } - - public void testIPV6() { - assertEquals("unexpected reduction", - "[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]", - PublicSuffixes.reduceSurtToAssignmentLevel( - "[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]")); - } - - public void testExceptions() { - matchPrefix("uk,bl,www,", "uk,bl,"); - matchPrefix("uk,bl,", "uk,bl,"); - matchPrefix("jp,tokyo,metro,subdomain,", "jp,tokyo,metro,"); - matchPrefix("jp,tokyo,metro,", "jp,tokyo,metro,"); - } - - public void testFakeTLD() { - // we assume any new/unknonwn TLD should be assumed as 2-level; - // this is preferable for our grouping purpose but might not be - // for a cookie-assigning browser (original purpose of publicsuffixlist) - matchPrefix("zzz,example,www,", "zzz,example,"); - } - - public void testUnsegmentedHostname() { - m.reset("example"); - assertFalse("unexpected match found in 'example'", m.find()); - } - - public void testTopmostAssignedCaching() { - assertSame("topmostAssignedSurtPrefixPattern not cached",PublicSuffixes.getTopmostAssignedSurtPrefixPattern(),PublicSuffixes.getTopmostAssignedSurtPrefixPattern()); - assertSame("topmostAssignedSurtPrefixRegex not cached",PublicSuffixes.getTopmostAssignedSurtPrefixRegex(),PublicSuffixes.getTopmostAssignedSurtPrefixRegex()); - } - - // TODO: test UTF domains? - - protected void matchPrefix(String surtDomain, String expectedAssignedPrefix) { - m.reset(surtDomain); - assertTrue("expected match not found in '" + surtDomain, m.find()); - assertEquals("expected match not found", expectedAssignedPrefix, m - .group()); - } -} diff --git a/contrib/pom.xml b/contrib/pom.xml index c6c7ec38..f0994523 100644 --- a/contrib/pom.xml +++ b/contrib/pom.xml @@ -4,7 +4,7 @@ org.archive heritrix - 3.1.2-SNAPSHOT + 3.3.0-SNAPSHOT org.archive.heritrix heritrix-contrib @@ -45,21 +45,17 @@ org.archive.heritrix heritrix-engine - 3.1.2-SNAPSHOT + ${project.version} org.archive.heritrix heritrix-modules - 3.1.2-SNAPSHOT + ${project.version} compile - - builds.archive.org#8080,maven2 - http://builds.archive.org:8080/maven2 - repository.cloudera.com,artifactory,cloudera-repos https://repository.cloudera.com/artifactory/cloudera-repos/ diff --git a/dist/README.md b/dist/README.txt similarity index 91% rename from dist/README.md rename to dist/README.txt index 2ac16741..1279198d 100644 --- a/dist/README.md +++ b/dist/README.txt @@ -37,16 +37,15 @@ See the User Manual at . +See . For API documentation, see -and +and 5. Release History ------------------- See the Heritrix Release Notes at - + 6. License ----------- diff --git a/dist/pom.xml b/dist/pom.xml index dc60ec84..82835d84 100644 --- a/dist/pom.xml +++ b/dist/pom.xml @@ -3,7 +3,7 @@ org.archive heritrix - 3.2.0-SNAPSHOT + 3.3.0-SNAPSHOT 4.0.0 org.archive.heritrix @@ -11,25 +11,6 @@ pom Heritrix 3 (distribution bundles) - - - - true - daily - warn - - - true - never - fail - - internetarchive - Internet Archive Maven Repository - http://builds.archive.org:8080/maven2 - default - - - org.archive.heritrix diff --git a/dist/src/main/assembly/dist.xml b/dist/src/main/assembly/dist.xml index ff6ce131..5394120c 100644 --- a/dist/src/main/assembly/dist.xml +++ b/dist/src/main/assembly/dist.xml @@ -5,12 +5,12 @@ zip true - - - /lib - - - + + + false + /lib + + . diff --git a/engine/pom.xml b/engine/pom.xml index 8e4b7f3d..d11f3f7f 100644 --- a/engine/pom.xml +++ b/engine/pom.xml @@ -3,7 +3,7 @@ org.archive heritrix - 3.2.0-SNAPSHOT + 3.3.0-SNAPSHOT 4.0.0 org.archive.heritrix @@ -12,26 +12,8 @@ Heritrix 3: 'engine' subproject - - - true - daily - warn - - - true - never - fail - - internetarchive - Internet Archive Maven Repository - http://builds.archive.org:8080/maven2 - default - - maven-restlet - Public online Restlet repository http://maven.restlet.org diff --git a/engine/src/main/java/org/archive/crawler/framework/CheckpointService.java b/engine/src/main/java/org/archive/crawler/framework/CheckpointService.java index 0e939bca..8b7fc874 100644 --- a/engine/src/main/java/org/archive/crawler/framework/CheckpointService.java +++ b/engine/src/main/java/org/archive/crawler/framework/CheckpointService.java @@ -20,6 +20,8 @@ package org.archive.crawler.framework; import java.io.File; import java.io.FileFilter; +import java.io.IOException; +import java.text.ParseException; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; @@ -31,6 +33,7 @@ import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; +import org.apache.commons.io.FileUtils; import org.apache.commons.io.comparator.LastModifiedFileComparator; import org.apache.commons.io.filefilter.FileFilterUtils; import org.archive.checkpointing.Checkpoint; @@ -40,7 +43,6 @@ import org.archive.spring.ConfigPath; import org.archive.spring.ConfigPathConfigurer; import org.archive.spring.HasValidator; import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -69,31 +71,34 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha protected Checkpoint checkpointInProgress; + protected Checkpoint lastCheckpoint; + protected CrawlStatSnapshot lastCheckpointSnapshot = null; /** service for auto-checkpoint tasks at an interval */ protected Timer timer = new Timer(true); protected TimerTask checkpointTask = null; - /** - * Checkpoints directory - */ protected ConfigPath checkpointsDir = new ConfigPath("checkpoints subdirectory","checkpoints"); public ConfigPath getCheckpointsDir() { return checkpointsDir; } + /** + * Checkpoints directory + */ public void setCheckpointsDir(ConfigPath checkpointsDir) { this.checkpointsDir = checkpointsDir; } + protected long checkpointIntervalMinutes = -1; + + public long getCheckpointIntervalMinutes() { + return checkpointIntervalMinutes; + } /** * Period at which to create automatic checkpoints; -1 means * no auto checkpointing. */ - protected long checkpointIntervalMinutes = -1; - public long getCheckpointIntervalMinutes() { - return checkpointIntervalMinutes; - } public void setCheckpointIntervalMinutes(long interval) { long oldVal = checkpointIntervalMinutes; this.checkpointIntervalMinutes = interval; @@ -102,6 +107,23 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha } } + protected boolean forgetAllButLatest = false; + public boolean getForgetAllButLatest() { + return forgetAllButLatest; + } + + /** + * True to save only the latest checkpoint, false to save all of them. + * Default is false. + */ + public void setForgetAllButLatest(boolean forgetAllButLatest) { + boolean oldVal = this.forgetAllButLatest; + this.forgetAllButLatest = forgetAllButLatest; + if (this.forgetAllButLatest != oldVal) { + setupCheckpointTask(); + } + } + protected Checkpoint recoveryCheckpoint; @Autowired(required=false) public void setRecoveryCheckpoint(Checkpoint checkpoint) { @@ -146,7 +168,15 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha +"' missing validity stamp file; checkpoint data " +"may be missing or otherwise corrupt."); } - } + this.lastCheckpoint = getRecoveryCheckpoint(); + String serial = getRecoveryCheckpoint().getShortName().substring(2); + try { + Number lastCheckpointNumber = Checkpoint.INDEX_FORMAT.parse(serial); + this.nextCheckpointNumber = lastCheckpointNumber.intValue() + 1; + } catch (ParseException e) { + LOGGER.warning("failed to parse serial from " + lastCheckpoint.getShortName() + " - " + e); + } + } this.isRunning = true; setupCheckpointTask(); } @@ -186,7 +216,8 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha periodMs + " milliseconds."); } - protected boolean isRunning = false; + protected boolean isRunning = false; + public synchronized boolean isRunning() { return isRunning; } @@ -213,8 +244,8 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha throw new IllegalStateException("Checkpoint already running."); } - // prevent redundant auto-checkpoints when crawler paused - if(controller.isPaused()) { + // prevent redundant auto-checkpoints when crawler paused or stopping + if(controller.isPaused() || controller.getState().equals(CrawlController.State.STOPPING)) { if (controller.getStatisticsTracker().getSnapshot().sameProgressAs(lastCheckpointSnapshot)) { LOGGER.info("no progress since last checkpoint; ignoring"); System.err.println("no progress since last checkpoint; ignoring"); @@ -222,6 +253,7 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha } } + long checkpointStart = System.currentTimeMillis(); Map toCheckpoint = appCtx.getBeansOfType(Checkpointable.class); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("checkpointing beans " + toCheckpoint); @@ -229,25 +261,48 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha checkpointInProgress = new Checkpoint(); try { - checkpointInProgress.generateFrom(getCheckpointsDir(),getNextCheckpointNumber()); - + checkpointInProgress.setForgetAllButLatest(getForgetAllButLatest()); + checkpointInProgress.generateFrom(getCheckpointsDir(), + getNextCheckpointNumber()); + // pre (incl. acquire necessary locks) -// long startMs = System.currentTimeMillis(); - for(Checkpointable c : toCheckpoint.values()) { + long startStart = System.currentTimeMillis(); + for (Checkpointable c : toCheckpoint.values()) { c.startCheckpoint(checkpointInProgress); } -// long duration = System.currentTimeMillis() - startMs; -// System.err.println("all startCheckpoint() completed in "+duration+"ms"); - + LOGGER.info("all startCheckpoint() completed in " + + (System.currentTimeMillis() - startStart) + "ms"); + // flush/write - for(Checkpointable c : toCheckpoint.values()) { -// long doMs = System.currentTimeMillis(); + long doStart = System.currentTimeMillis(); + for (Checkpointable c : toCheckpoint.values()) { + long doMs = System.currentTimeMillis(); c.doCheckpoint(checkpointInProgress); -// long doDuration = System.currentTimeMillis() - doMs; -// System.err.println("doCheckpoint() "+c+" in "+doDuration+"ms"); + long doDuration = System.currentTimeMillis() - doMs; + LOGGER.fine("doCheckpoint() " + c + " in " + doDuration + "ms"); } - checkpointInProgress.setSuccess(true); - appCtx.publishEvent(new CheckpointSuccessEvent(this,checkpointInProgress)); + LOGGER.info("all doCheckpoint() completed in " + + (System.currentTimeMillis() - doStart) + "ms"); + + if (getForgetAllButLatest() && lastCheckpoint != null) { + try { + long deleteStart = System.currentTimeMillis(); + FileUtils.deleteDirectory(lastCheckpoint.getCheckpointDir().getFile()); + lastCheckpoint = null; + LOGGER.info("deleted old checkpoint in " + + (System.currentTimeMillis() - deleteStart) + "ms"); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, + "problem deleting last checkpoint directory " + + lastCheckpoint.getCheckpointDir().getFile(), + e); + } + } + + checkpointInProgress.setSuccess(true); + + appCtx.publishEvent(new CheckpointSuccessEvent(this, + checkpointInProgress)); } catch (Exception e) { checkpointFailed(e); } finally { @@ -255,14 +310,19 @@ public class CheckpointService implements Lifecycle, ApplicationContextAware, Ha controller.getStatisticsTracker().getProgressStamp()); lastCheckpointSnapshot = controller.getStatisticsTracker().getSnapshot(); // close (incl. release locks) - for(Checkpointable c : toCheckpoint.values()) { + long finishStart = System.currentTimeMillis(); + for (Checkpointable c : toCheckpoint.values()) { c.finishCheckpoint(checkpointInProgress); } + LOGGER.info("all finishCheckpoint() completed in " + + (System.currentTimeMillis() - finishStart) + "ms"); } - + LOGGER.info("completed checkpoint " + checkpointInProgress.getName() + + " in " + (System.currentTimeMillis() - checkpointStart) + "ms"); + this.nextCheckpointNumber++; - LOGGER.info("finished checkpoint "+checkpointInProgress.getName()); String nameToReport = checkpointInProgress.getSuccess() ? checkpointInProgress.getName() : null; + this.lastCheckpoint = this.checkpointInProgress; this.checkpointInProgress = null; return nameToReport; } diff --git a/engine/src/main/java/org/archive/crawler/framework/CrawlController.java b/engine/src/main/java/org/archive/crawler/framework/CrawlController.java index 6139aea2..9fb05b11 100644 --- a/engine/src/main/java/org/archive/crawler/framework/CrawlController.java +++ b/engine/src/main/java/org/archive/crawler/framework/CrawlController.java @@ -255,9 +255,9 @@ implements Serializable, private transient ToePool toePool; // emergency reserve of memory to allow some progress/reporting after OOM - private transient LinkedList reserveMemory; + private transient LinkedList reserveMemory; private static final int RESERVE_BLOCKS = 1; - private static final int RESERVE_BLOCK_SIZE = 6*1024*1024; // 6MB + private static final int RESERVE_BLOCK_SIZE = 12*1024*1024; // 12 MB /** * Crawl exit status. @@ -293,9 +293,9 @@ implements Serializable, // also cap size at 1 (we never wanta cached value; 0 is non-operative) Lookup.getDefaultCache(DClass.IN).setMaxEntries(1); - reserveMemory = new LinkedList(); + reserveMemory = new LinkedList(); for(int i = 0; i < RESERVE_BLOCKS; i++) { - reserveMemory.add(new char[RESERVE_BLOCK_SIZE]); + reserveMemory.add(new byte[RESERVE_BLOCK_SIZE]); } isRunning = true; } @@ -371,6 +371,10 @@ implements Serializable, * Called when the last toethread exits. */ protected void completeStop() { + if (!isRunning) { + return; + } + LOGGER.fine("Entered complete stop."); statisticsTracker.getSnapshot(); // ??? @@ -384,7 +388,9 @@ implements Serializable, LOGGER.fine("Finished crawl."); try { - appCtx.stop(); + if (appCtx.isRunning()) { + appCtx.stop(); + } } catch (RuntimeException re) { LOGGER.log(Level.SEVERE,re.getMessage(),re); } diff --git a/engine/src/main/java/org/archive/crawler/framework/CrawlJob.java b/engine/src/main/java/org/archive/crawler/framework/CrawlJob.java index 3dff8865..b0c30267 100644 --- a/engine/src/main/java/org/archive/crawler/framework/CrawlJob.java +++ b/engine/src/main/java/org/archive/crawler/framework/CrawlJob.java @@ -680,9 +680,11 @@ public class CrawlJob implements Comparable, ApplicationListener, ApplicationListener entry : hd.entrySet()) { // key is -count, value is hostname - CrawlHost host = stats.serverCache.getHostFor(entry.getValue()); - writeReportLine(writer, - host.getSubstats().getFetchSuccesses(), - host.getSubstats().getTotalBytes(), - fixup(host.getHostName()), - host.getSubstats().getRobotsDenials(), - host.getSubstats().getRemaining(), - host.getSubstats().getNovelUrls(), - host.getSubstats().getNovelBytes(), - host.getSubstats().getDupByHashUrls(), - host.getSubstats().getDupByHashBytes(), - host.getSubstats().getNotModifiedUrls(), - host.getSubstats().getNotModifiedBytes()); + try { + CrawlHost host = stats.serverCache.getHostFor(entry.getValue()); + writeReportLine(writer, + host.getSubstats().getFetchSuccesses(), + host.getSubstats().getTotalBytes(), + fixup(host.getHostName()), + host.getSubstats().getRobotsDenials(), + host.getSubstats().getRemaining(), + host.getSubstats().getNovelUrls(), + host.getSubstats().getNovelBytes(), + host.getSubstats().getDupByHashUrls(), + host.getSubstats().getDupByHashBytes(), + host.getSubstats().getNotModifiedUrls(), + host.getSubstats().getNotModifiedBytes()); + } catch (Exception e) { + logger.log(Level.WARNING, "unable to tally host stats for " + entry.getValue(), e); + } } hd.dispose(); } diff --git a/engine/src/main/java/org/archive/crawler/restlet/BaseResource.java b/engine/src/main/java/org/archive/crawler/restlet/BaseResource.java index d608d9c6..ef374ded 100644 --- a/engine/src/main/java/org/archive/crawler/restlet/BaseResource.java +++ b/engine/src/main/java/org/archive/crawler/restlet/BaseResource.java @@ -72,8 +72,4 @@ public abstract class BaseResource extends Resource { String rootRef = getRequest().getRootRef().toString(); return rootRef + "/engine/static/" + resource; } - - protected String getStylesheetRef() { - return getStaticRef("engine.css"); - } } diff --git a/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java b/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java index 8432ad1f..449363ec 100644 --- a/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java +++ b/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java @@ -231,7 +231,6 @@ public class BeanBrowseResource extends JobRelatedResource { ViewModel viewModel = new ViewModel(); viewModel.setFlashes(Flash.getFlashes(getRequest())); viewModel.put("baseRef",baseRef); - viewModel.put("cssRef", getStylesheetRef()); viewModel.put("model",makeDataModel()); try { diff --git a/engine/src/main/java/org/archive/crawler/restlet/EngineResource.java b/engine/src/main/java/org/archive/crawler/restlet/EngineResource.java index af283664..1b482788 100644 --- a/engine/src/main/java/org/archive/crawler/restlet/EngineResource.java +++ b/engine/src/main/java/org/archive/crawler/restlet/EngineResource.java @@ -225,7 +225,6 @@ public class EngineResource extends BaseResource { viewModel.put("baseRef",baseRef); viewModel.put("fileSeparator", File.separator); viewModel.put("engine", model); - viewModel.put("cssRef", getStylesheetRef()); try { Template template = tmpltCfg.getTemplate("Engine.ftl"); diff --git a/engine/src/main/java/org/archive/crawler/restlet/JobResource.java b/engine/src/main/java/org/archive/crawler/restlet/JobResource.java index baeea4d2..4b4a566e 100644 --- a/engine/src/main/java/org/archive/crawler/restlet/JobResource.java +++ b/engine/src/main/java/org/archive/crawler/restlet/JobResource.java @@ -141,7 +141,6 @@ public class JobResource extends BaseResource { ViewModel viewModel = new ViewModel(); viewModel.setFlashes(Flash.getFlashes(getRequest())); viewModel.put("baseRef",baseRef); - viewModel.put("cssRef", getStylesheetRef()); viewModel.put("job", makeDataModel()); viewModel.put("heapReport", getEngine().heapReportData()); diff --git a/engine/src/main/java/org/archive/crawler/restlet/ScriptResource.java b/engine/src/main/java/org/archive/crawler/restlet/ScriptResource.java index dd0fa55c..f284fdf0 100644 --- a/engine/src/main/java/org/archive/crawler/restlet/ScriptResource.java +++ b/engine/src/main/java/org/archive/crawler/restlet/ScriptResource.java @@ -188,7 +188,6 @@ public class ScriptResource extends JobRelatedResource { ViewModel viewModel = new ViewModel(); viewModel.setFlashes(Flash.getFlashes(getRequest())); viewModel.put("baseRef",baseRef); - viewModel.put("cssRef", getStylesheetRef()); viewModel.put("staticRef", getStaticRef("")); viewModel.put("baseResourceRef",getRequest().getRootRef().toString()+"/engine/static/"); viewModel.put("model", makeDataModel()); diff --git a/engine/src/main/java/org/archive/crawler/util/BdbUriUniqFilter.java b/engine/src/main/java/org/archive/crawler/util/BdbUriUniqFilter.java index dfff305a..b4b9105d 100644 --- a/engine/src/main/java/org/archive/crawler/util/BdbUriUniqFilter.java +++ b/engine/src/main/java/org/archive/crawler/util/BdbUriUniqFilter.java @@ -303,17 +303,17 @@ implements Lifecycle, Checkpointable, BeanNameAware, DisposableBean { */ public static long createKey(CharSequence uri) { String url = uri.toString(); - long schemeHostKeyPart = calcSchemeHostKeyPart(url); - return schemeHostKeyPart | (FPGenerator.std40.fp(url) >>> 24); + long schemeAuthorityKeyPart = calcSchemeAuthorityKeyBytes(url); + return schemeAuthorityKeyPart | (FPGenerator.std40.fp(url) >>> 24); } - protected static long calcSchemeHostKeyPart(String url) { + protected static long calcSchemeAuthorityKeyBytes(String url) { int index = url.indexOf(COLON_SLASH_SLASH); if (index > 0) { index = url.indexOf('/', index + COLON_SLASH_SLASH.length()); } - CharSequence hostPlusScheme = (index == -1)? url: url.subSequence(0, index); - return FPGenerator.std24.fp(hostPlusScheme); + CharSequence schemeAuthority = (index == -1)? url: url.subSequence(0, index); + return FPGenerator.std24.fp(schemeAuthority); } protected boolean setAdd(CharSequence uri) { @@ -400,7 +400,7 @@ implements Lifecycle, Checkpointable, BeanNameAware, DisposableBean { } /** - * Forget all entries that match the scheme+host+port of the given key, so + * Forget all entries that match the scheme+host+port of the given url, so * that they can be crawled again if discovered again. Expensive operation. * *

@@ -408,26 +408,46 @@ implements Lifecycle, Checkpointable, BeanNameAware, DisposableBean { * grouping of urls that is feasible to forget in bulk. See * {@link #createKey(CharSequence)} * - * @param schemeHost + *

+ * WARNING: Value collisions in this 24-bit schemeAuthority part are going + * to be fairly common, by 'birthday problem' over 50% likely to show up + * with as few as 2^12 unique schemeAuthority strings. So the forgetting may + * forget other hosts. + * + * @param url + * whose scheme+host+port should be forgotten (remainder of url + * is ignored) */ - public void forgetSchemeHost(String schemeHost) { - long schemeHostKeyPart = calcSchemeHostKeyPart(schemeHost); + public void forgetAllSchemeAuthorityMatching(String url) { + long schemeAuthorityKeyLong = calcSchemeAuthorityKeyBytes(url); DatabaseEntry key = new DatabaseEntry(); DatabaseEntry value = new DatabaseEntry(); + + LongBinding.longToEntry(schemeAuthorityKeyLong, key); + byte[] schemeAuthorityKeyBytes = key.getData(); + Cursor cursor = alreadySeen.openCursor(null, null); long forgottenCount = 0l; - while (cursor.getNext(key, value, null) == OperationStatus.SUCCESS) { - long alreadySeenKey = LongBinding.entryToLong(key); - // System.out.printf("schemeHostKeyPart=%017x alreadySeenKey=%017x\n", schemeHostKeyPart, alreadySeenKey); - if ((alreadySeenKey & 0xffffff0000000000l) == schemeHostKeyPart) { + + for (OperationStatus status = cursor.getSearchKeyRange(key, value, null); + status == OperationStatus.SUCCESS; + status = cursor.getNext(key, value, null)) { + + byte[] keyData = key.getData(); + if (keyData[0] == schemeAuthorityKeyBytes[0] + && keyData[1] == schemeAuthorityKeyBytes[1] + && keyData[2] == schemeAuthorityKeyBytes[2]) { cursor.delete(); - count.decrementAndGet(); forgottenCount++; + } else { + break; } } + cursor.close(); - logger.info("forgot " + forgottenCount + " urls from scheme+host+port " + schemeHost + " (" + count.get() + " urls left)"); + long newCount = count.addAndGet(-forgottenCount); + logger.info("forgot " + forgottenCount + " urls from scheme+authority of url " + url + " (leaving " + newCount + " urls from other scheme+authorities)"); } } //EOC \ No newline at end of file diff --git a/engine/src/main/java/org/archive/crawler/util/CrawledBytesHistotable.java b/engine/src/main/java/org/archive/crawler/util/CrawledBytesHistotable.java index bff074e6..cf5fe10e 100644 --- a/engine/src/main/java/org/archive/crawler/util/CrawledBytesHistotable.java +++ b/engine/src/main/java/org/archive/crawler/util/CrawledBytesHistotable.java @@ -22,7 +22,6 @@ package org.archive.crawler.util; import org.apache.commons.httpclient.HttpStatus; import org.archive.modules.CoreAttributeConstants; import org.archive.modules.CrawlURI; -import org.archive.modules.deciderules.recrawl.IdenticalDigestDecideRule; import org.archive.util.ArchiveUtils; import org.archive.util.Histotable; @@ -45,10 +44,7 @@ implements CoreAttributeConstants { if(curi.getFetchStatus()==HttpStatus.SC_NOT_MODIFIED) { tally(NOTMODIFIED, curi.getContentSize()); tally(NOTMODIFIEDCOUNT,1); - } else if (IdenticalDigestDecideRule.hasIdenticalDigest(curi)) { - tally(DUPLICATE,curi.getContentSize()); - tally(DUPLICATECOUNT,1); - } else if (curi.getAnnotations().contains("duplicate:uriAgnosticDigest")) { + } else if (curi.getAnnotations().contains("duplicate:digest")) { tally(DUPLICATE,curi.getContentSize()); tally(DUPLICATECOUNT,1); } else { diff --git a/engine/src/main/resources/org/archive/crawler/restlet/Beans.ftl b/engine/src/main/resources/org/archive/crawler/restlet/Beans.ftl index cd74c3b8..8c0b39f4 100644 --- a/engine/src/main/resources/org/archive/crawler/restlet/Beans.ftl +++ b/engine/src/main/resources/org/archive/crawler/restlet/Beans.ftl @@ -1,44 +1,112 @@ + + + + + + + Crawl beans in ${model.crawlJobShortName} - + -

Crawl beans in built job ${model.crawlJobShortName}

- Enter a bean path of the form beanName, beanName.property, beanName.property[indexOrKey], etc. -
- - -
+
+ +
+
+
+

Crawl beans in built job ${model.crawlJobShortName}

+
+
+
+ Enter a bean path of the form beanName, beanName.property, beanName.property[indexOrKey], etc. + + + + +
+
- - <#else> - <@beanTemplate bean=model.bean /> - +
+
+ +<#if model.beanPath?? && (model.beanPath?length >0)> +
+
+

Bean path ${model.beanPath}

+
+
+ <#if model.problem??> +
+ problem: ${model.problem} +
+ <#elseif model.editable> +
+
+ ${model.beanPath} = + <@beanTemplate bean=model.bean /> edit +
+ +
+ <#else> + <@beanTemplate bean=model.bean /> + +
+ +
+
+
+ + -

All named crawl beans

-
    -<#list model.allNamedCrawlBeans as bean> - <@beanListItem bean=bean /> - -
+
+
+

All named crawl beans

+
+
+
+
    + <#list model.allNamedCrawlBeans as bean> + <@beanListItem bean=bean /> + +
+
+
+
+
+
@@ -56,9 +124,9 @@ <#macro beanTemplate bean> <#if bean.field?? && (bean.field?length>0)> - + <#if bean.field?contains("#")>${bean.field}<#else>${bean.field}: - + <#if bean.propValuePreviouslyDescribed??> @@ -80,9 +148,9 @@ <#if (!bean.propValue?? && !bean.properties?? && bean.get("class")??) || bean.properties?? || (bean.propValue?? && bean.propValue?is_collection)> -
+
${bean.get("class")} - +
<#if bean.properties??> <#list bean.properties as property> <@beanTemplate bean=property /> diff --git a/engine/src/main/resources/org/archive/crawler/restlet/Engine.ftl b/engine/src/main/resources/org/archive/crawler/restlet/Engine.ftl index 917bddf8..d746f69f 100644 --- a/engine/src/main/resources/org/archive/crawler/restlet/Engine.ftl +++ b/engine/src/main/resources/org/archive/crawler/restlet/Engine.ftl @@ -1,95 +1,179 @@ - -Heritrix Engine ${engine.heritrixVersion} - - + + + + + + + Heritrix Engine ${engine.heritrixVersion} + + + + + + + +
+ +
-

Heritrix Engine ${engine.heritrixVersion}

- - -<#list flashes as flash> -
- ${flash.message} +
+
+ + <#list flashes as flash> +
+ ${flash.message} +
+ +

Engine

+
+
+
+
+
    +
  • Memory: +
      +
    • ${(engine.heapReport.usedBytes/1024)?string("0")} KiB used; ${(engine.heapReport.totalBytes/1024)?string("0")} KiB current heap; ${(engine.heapReport.maxBytes/1024)?string("0")} KiB max heap + +
    • +
    +
  • +
  • Jobs Directory: + +
  • +
+
+ +
+
- - -
- Memory: - ${(engine.heapReport.usedBytes/1024)?string("0")} KiB used; ${(engine.heapReport.totalBytes/1024)?string("0")} KiB current heap; ${(engine.heapReport.maxBytes/1024)?string("0")} KiB max heap - - - -

-Jobs Directory: ${engine.jobsDir} -

- -

Job Directories (${engine.jobs?size}) -

- - -
    -<#list engine.jobs as crawlJob> -
  • -
    -${crawlJob.shortName} -<#if crawlJob.hasApplicationContext> - «${crawlJob.statusDescription}» - -<#if crawlJob.isLaunchInfoPartial> - at least - -${crawlJob.launchCount} launches
    -
    -${crawlJob.primaryConfig} + +
    +
    +
    +

    Job Directories

    +
    +
    +
    + (${engine.jobs?size}) detected +
    +
      + <#list engine.jobs as crawlJob> +
    • +
      + ${crawlJob.shortName} + <#if crawlJob.hasApplicationContext> + «${crawlJob.statusDescription}» + + <#if crawlJob.isLaunchInfoPartial> + at least + + ${crawlJob.launchCount} launches +
      +
        +
      • +
        + ${crawlJob.primaryConfig} +
        +
      • + <#if crawlJob.lastLaunch??> +
      • (last at ${crawlJob.lastLaunch})
      • + +
      +
    • + +
    +
    +
    +
    +
    +
    -<#if crawlJob.lastLaunch??> -
    (last at ${crawlJob.lastLaunch})
    - -
  • - -
- -

Add Job Directory

- -
-Create new job directory with recommended starting configuration
-Path: ${engine.jobsDir}${fileSeparator} - - - -
- Specify a path to a pre-existing job directory
- Path: - - - -

-You may also compose or copy a valid job directory into the main jobs directory via outside means, then use the 'rescan' button above to make it appear in this interface. Or, use the 'copy' functionality at the botton of any existing job's detail page. -

- -

Exit Java

This exits the Java process running Heritrix. To restart -will then require access to the hosting machine. You should -cleanly terminate and teardown any jobs in progress first.
-
- -<#list engine.jobs as crawlJob> -<#if crawlJob.hasApplicationContext> -
Job ${crawlJob.key} still « ${crawlJob.statusDescription} »
- - -
- - - -
- - +
+
+

Add Job Directory

+
+
+
+ + Create new job directory with recommended starting configuration
+ Path: ${engine.jobsDir}${fileSeparator} + + + +
+ Specify a path to a pre-existing job directory
+ Path: + + +

+ You may also compose or copy a valid job directory into the main jobs directory via outside means, then use the 'rescan' button above to make it appear in this interface. Or, use the 'copy' functionality at the botton of any existing job's detail page. +

+
+
+
+
- + +
+
+

Exit Java

+
+
+
+

This exits the Java process running Heritrix. To restart + will then require access to the hosting machine. You should + cleanly terminate and teardown any jobs in progress first.

+
+
+
    + <#list engine.jobs as crawlJob> + <#if crawlJob.hasApplicationContext> +
  • +
    Job ${crawlJob.key} still « ${crawlJob.statusDescription} »
    +
      +
    • + +
    • +
    +
  • + + +
  • + +
      +
    • + +
    • +
    +
  • +
+ +
+
+
+
+
+ diff --git a/engine/src/main/resources/org/archive/crawler/restlet/Job.ftl b/engine/src/main/resources/org/archive/crawler/restlet/Job.ftl index d9d6475e..96908e38 100644 --- a/engine/src/main/resources/org/archive/crawler/restlet/Job.ftl +++ b/engine/src/main/resources/org/archive/crawler/restlet/Job.ftl @@ -1,204 +1,349 @@ - + + + + + + + + + ${job.shortName} - ${job.statusDescription} - Job main page - + -

- Job ${job.shortName} (<#if job.isLaunchInfoPartial>at least ${job.launchCount} - launches<#if job.lastLaunch??>, last ${job.lastLaunchTime} ago) -

- - - - <#list flashes as flash> -
- ${flash.message} +
+
+ +
+
+
+

Job ${job.shortName}

(<#if job.isLaunchInfoPartial>at least ${job.launchCount} + launches<#if job.lastLaunch??>, last ${job.lastLaunchTime} ago)

+
+
+ +
    +
  • +
  • +
+
    +
  • +
  • +
  • +
+
    +
  • +
  • +
+
+
+
+ <#assign checkpointName=job.checkpointName! /> + <#assign checkpoints=job.checkpointFiles! /> + <#if checkpointName?has_content > +
recover from ${checkpointName}
+ <#elseif checkpoints?has_content > +
select an available checkpoint before launch to recover: + +
+ +
+
- - - <#if job.isProfile> +
+ +
+
+ + <#list flashes as flash> +
+ ${flash.message} +
+ + <#if job.isProfile>

- As a profile, this job may be built for testing purposes but not launched. Use the 'copy job to' - functionality at bottom to copy this profile to a launchable job. + As a profile, this job may be built for testing purposes but not launched. Use the 'copy job' + functionality in the menu to copy this profile to a launchable job.

+
+
-
-
- - disabled='disabled' title='build job' /> - disabled='disabled' title='profiles cannot be launched' - - <#if !job.availableActions?seq_contains("launch")> - disabled='disabled' - - /> - - - disabled type='submit' name='action' value='pause' /> - disabled type='submit' name='action' value='unpause' /> - disabled type='submit' name='action' value='checkpoint' /> - - - disabled type='submit' name='action' value='terminate' /> - disabled='disabled' title='no instance' /> - -
- <#assign checkpointName=job.checkpointName! /> - <#assign checkpoints=job.checkpointFiles! /> - <#if checkpointName?has_content > -
recover from ${checkpointName}
- <#elseif checkpoints?has_content > -
select an available checkpoint before launch to recover: - +
- - - -
- configuration: ${job.configurationFilePath} [edit] +
+
- -

Job Log (more)

-
- <#list job.jobLogTail as line> -
${line?html}
- -
-

Job is ${job.statusDescription}

- <#if job.hasApplicationContext> -
-
Totals
-
-
- <#if !job.uriTotalsReport??> - n/a - <#else> - ${job.uriTotalsReport.downloadedUriCount} downloaded + ${job.uriTotalsReport.queuedUriCount} queued = ${job.uriTotalsReport.totalUriCount} total - <#if (job.uriTotalsReport.futureUriCount > 0)> (${job.uriTotalsReport.futureUriCount} future) - -
-
- <#if !job.sizeTotalsReport??> - n/a - <#else> - ${job.formatBytes(job.sizeTotalsReport.total)} crawled (${job.formatBytes(job.sizeTotalsReport.novel)} novel, ${job.formatBytes(job.sizeTotalsReport.dupByHash)} dupByHash, ${job.formatBytes(job.sizeTotalsReport.notModified)} notModified) - +
+
+
+

Job is ${job.statusDescription}

+ <#if job.hasApplicationContext> +
+
+
+
    +
  • Totals +
      + <#if !job.uriTotalsReport??> +
    • n/a
    • + <#else> +
    • ${job.uriTotalsReport.downloadedUriCount} downloaded + ${job.uriTotalsReport.queuedUriCount} queued = ${job.uriTotalsReport.totalUriCount} total + <#if (job.uriTotalsReport.futureUriCount > 0)> (${job.uriTotalsReport.futureUriCount} future) +
    • + + <#if !job.sizeTotalsReport??> +
    • n/a
    • + <#else> +
    • ${job.formatBytes(job.sizeTotalsReport.total)} crawled (${job.formatBytes(job.sizeTotalsReport.novel)} novel, ${job.formatBytes(job.sizeTotalsReport.dupByHash)} dupByHash, ${job.formatBytes(job.sizeTotalsReport.notModified)} notModified)
    • + +
    +
  • +
  • Alerts +
      + <#if job.alertCount == 0 > +
    • none
    • + <#else> +
    • ${job.alertCount} + tail alert log...
    • + +
    +
  • +
  • Rates +
      + <#if !job.rateReport??> +
    • n/a
    • + <#else> +
    • ${job.doubleToString(job.rateReport.currentDocsPerSecond,2)} URIs/sec (${job.doubleToString(job.rateReport.averageDocsPerSecond,2)} avg); ${job.rateReport.currentKiBPerSec} KB/sec (${job.rateReport.averageKiBPerSec} avg)
    • + +
    +
  • +
  • Load +
      + <#if !job.loadReport??> +
    • n/a
    • + <#else> +
    • ${job.loadReport.busyThreads} active of ${job.loadReport.totalThreads} threads; ${job.doubleToString(job.loadReport.congestionRatio,2)} congestion ratio; ${job.loadReport.deepestQueueDepth} deepest queue; ${job.loadReport.averageQueueDepth} average depth
    • + +
    +
  • +
  • Elapsed +
      + <#if !job.elapsedReport??> +
    • n/a
    • + <#else> +
    • ${job.elapsedReport.elapsedPretty}
    • + +
    +
  • +
  • Threads +
      + <#if !job.threadReport??> +
    • n/a
    • + <#else> +
    • + ${job.threadReport.toeCount} threads: + <#list job.threadReport.steps as step>${step}<#if step_has_next>, ; + <#list job.threadReport.processors as proc>${proc}<#if proc_has_next>, +
    • + +
    +
  • +
  • Frontier +
      + <#if !job.frontierReport??> +
    • n/a
    • + <#else> +
    • ${job.frontierReport.lastReachedState} - ${job.frontierReport.totalQueues} URI queues: ${job.frontierReport.activeQueues} active (${job.frontierReport.inProcessQueues} in-process; ${job.frontierReport.readyQueues} ready; ${job.frontierReport.snoozedQueues} snoozed); ${job.frontierReport.inactiveQueues} inactive; ${job.frontierReport.ineligibleQueues} ineligible; ${job.frontierReport.retiredQueues} retired; ${job.frontierReport.exhaustedQueues} exhausted
    • + +
    +
  • +
  • Memory +
      +
    • ${(heapReport.usedBytes/1024)?string("0")} KiB used; ${(heapReport.totalBytes/1024)?string("0")} KiB current heap; ${(heapReport.maxBytes/1024)?string("0")} KiB max heap
    • +
    +
  • +
-
-
Alerts
-
- <#if job.alertCount == 0 >none<#else>${job.alertCount} - tail alert log... - -
-
Rates
-
<#if !job.rateReport??>n/a - <#else> - ${job.doubleToString(job.rateReport.currentDocsPerSecond,2)} URIs/sec (${job.doubleToString(job.rateReport.averageDocsPerSecond,2)} avg); ${job.rateReport.currentKiBPerSec} KB/sec (${job.rateReport.averageKiBPerSec} avg) - -
-
Load
-
- <#if !job.loadReport??>n/a - <#else> - ${job.loadReport.busyThreads} active of ${job.loadReport.totalThreads} threads; ${job.doubleToString(job.loadReport.congestionRatio,2)} congestion ratio; ${job.loadReport.deepestQueueDepth} deepest queue; ${job.loadReport.averageQueueDepth} average depth - -
-
Elapsed
-
- <#if !job.elapsedReport??>n/a - <#else> - ${job.elapsedReport.elapsedPretty} - -
-
Threads
-
- <#if !job.threadReport??>n/a - <#else> - ${job.threadReport.toeCount} threads: - <#list job.threadReport.steps as step>${step}<#if step_has_next>, ; - <#list job.threadReport.processors as proc>${proc}<#if proc_has_next>, - -
-
Frontier
-
- <#if !job.frontierReport??>n/a - <#else> - ${job.frontierReport.lastReachedState} - ${job.frontierReport.totalQueues} URI queues: ${job.frontierReport.activeQueues} active (${job.frontierReport.inProcessQueues} in-process; ${job.frontierReport.readyQueues} ready; ${job.frontierReport.snoozedQueues} snoozed); ${job.frontierReport.inactiveQueues} inactive; ${job.frontierReport.ineligibleQueues} ineligible; ${job.frontierReport.retiredQueues} retired; ${job.frontierReport.exhaustedQueues} exhausted - -
-
Memory
-
- ${(heapReport.usedBytes/1024)?string("0")} KiB used; ${(heapReport.totalBytes/1024)?string("0")} KiB current heap; ${(heapReport.maxBytes/1024)?string("0")} KiB max heap - -
-
- - <#if (job.isRunning || (job.hasApplicationContext && !job.isLaunchable))> -

Crawl Log more

-
-		<#list job.crawlLogTail as line>
-${line?html}
-		
-		
+
+
- +
+
- <#if job.hasApplicationContext> -

Reports

- <#list job.reports as report> - ${report.shortName} - - +<#if (job.isRunning || (job.hasApplicationContext && !job.isLaunchable))> +
+
+

Crawl Log more

+
+
+
+
    + <#list job.crawlLogTail as line> +
  • ${line?html}
  • + +
+
+
+
+
+
+ -

Files

-

Browse Job Directory

-

Configuration-referenced Paths

- <#assign configRefPaths=job.configFiles! /> - <#if !configRefPaths?has_content > - build the job to discover referenced paths - <#else> -
- <#list configRefPaths as config> -
- ${config.key}: ${config.name} -
-
- <#if config.path??> - ${config.path}<#if config.editable> [edit] - <#else> - unset - -
+<#if job.hasApplicationContext> +
+
+

Reports

+
- + + + + -

Advanced

-

Scripting console

- <#if !job.hasApplicationContext> - build the job to browse bean instances - <#else> -

Browse beans

- -

Copy

- Copy job to - - - +
+
+

Configuration-referenced Paths

+
+
+
+ <#assign configRefPaths=job.configFiles! /> + <#if !configRefPaths?has_content > + build the job to discover referenced paths + <#else> +
    + <#list configRefPaths as config> +
  • ${config.key}: ${config.name} +
      +
    • + <#if config.path??> + ${config.path}<#if config.editable> [edit] + <#else> + unset + +
    • +
    +
  • + +
+ +
+
+
+
+
+ + + + + +
+

Copy Job

+ +
+
+
+ + +
+
+
+
+
+
+
+
+
+
+
+ +
+
+
- + × +
+ diff --git a/engine/src/main/resources/org/archive/crawler/restlet/Script.ftl b/engine/src/main/resources/org/archive/crawler/restlet/Script.ftl index 9201c258..4d95125f 100644 --- a/engine/src/main/resources/org/archive/crawler/restlet/Script.ftl +++ b/engine/src/main/resources/org/archive/crawler/restlet/Script.ftl @@ -1,8 +1,17 @@ + + + + + + + + + Script in ${model.crawlJobShortName} - + @@ -14,55 +23,126 @@ -

Execute script for job ${model.crawlJobShortName}

- <#if (model.linesExecuted > 0)> - ${model.linesExecuted} ${(model.linesExecuted>1)?string("lines","line")} executed - - <#if model.failure> -
${model.stackTrace}
-	
- - <#assign htmlOutput=model.htmlOutput> - <#if (htmlOutput?length > 0)> -
htmlOut - ${htmlOutput} -
- - <#assign rawOutput=model.rawOutput> - <#if (rawOutput?length > 0)> -
rawOutput -
${rawOutput}
-		
-
- +
+ +
+
+
+

Execute script for job ${model.crawlJobShortName}

+
+
+
+ <#if (model.linesExecuted > 0)> + ${model.linesExecuted} ${(model.linesExecuted>1)?string("lines","line")} executed + + <#if model.failure> +
${model.stackTrace}
+						
+ + <#assign htmlOutput=model.htmlOutput> + <#if (htmlOutput?length > 0)> +
htmlOut + ${htmlOutput} +
+ + <#assign rawOutput=model.rawOutput> + <#if (rawOutput?length > 0)> +
rawOutput +
${rawOutput}
+							
+
+ +
+
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+
+ +
+
+ The script will be executed in an engine preloaded + with (global) variables: +
+
+
    + <#list model.availableGlobalVariables as v> +
  • ${v.variable}: ${v.description?html}
  • + +
+
+
+
+
+ -
- - - - - - The script will be executed in an engine preloaded - with (global) variables: -
    - <#list model.availableGlobalVariables as v> -
  • ${v.variable}: ${v.description?html}
  • - -
- + diff --git a/engine/src/main/resources/org/archive/crawler/restlet/codemirror/codemirror.css b/engine/src/main/resources/org/archive/crawler/restlet/codemirror/codemirror.css index 2d79f4aa..dbb8589d 100644 --- a/engine/src/main/resources/org/archive/crawler/restlet/codemirror/codemirror.css +++ b/engine/src/main/resources/org/archive/crawler/restlet/codemirror/codemirror.css @@ -1,6 +1,7 @@ .CodeMirror { line-height: 1em; font-family: monospace; + background-color:white; } .CodeMirror-scroll { @@ -29,6 +30,7 @@ .CodeMirror-lines { padding: .4em; white-space: pre; + } .CodeMirror pre { diff --git a/engine/src/main/resources/org/archive/crawler/restlet/css/foundation.css b/engine/src/main/resources/org/archive/crawler/restlet/css/foundation.css new file mode 100644 index 00000000..519efd85 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/css/foundation.css @@ -0,0 +1,3848 @@ +*, +*:before, +*:after { + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; } + +html, +body { + font-size: 100%; } + +body { + background: white; + color: #222222; + padding: 0; + margin: 0; + font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif; + font-weight: normal; + font-style: normal; + line-height: 1; + position: relative; } + +a:focus { + outline: none; } + +img, +object, +embed { + max-width: 100%; + height: auto; } + +object, +embed { + height: 100%; } + +img { + -ms-interpolation-mode: bicubic; } + +#map_canvas img, +#map_canvas embed, +#map_canvas object, +.map_canvas img, +.map_canvas embed, +.map_canvas object { + max-width: none !important; } + +.left { + float: left !important; } + +.right { + float: right !important; } + +.text-left { + text-align: left !important; } + +.text-right { + text-align: right !important; } + +.text-center { + text-align: center !important; } + +.text-justify { + text-align: justify !important; } + +.hide { + display: none; } + +.antialiased { + -webkit-font-smoothing: antialiased; } + +img { + display: inline-block; } + +textarea { + height: auto; + min-height: 50px; } + +select { + width: 100%; } + +/* Grid HTML Classes */ +.row { + width: 100%; + margin-left: auto; + margin-right: auto; + margin-top: 0; + margin-bottom: 0; + max-width: 62.5em; + *zoom: 1; } + .row:before, .row:after { + content: " "; + display: table; } + .row:after { + clear: both; } + .row .column, + .row .columns { + position: relative; + padding-left: 0.9375em; + padding-right: 0.9375em; + width: 100%; + float: left; } + .row.collapse .column, + .row.collapse .columns { + position: relative; + padding-left: 0; + padding-right: 0; + float: left; } + .row .row { + width: auto; + margin-left: -0.9375em; + margin-right: -0.9375em; + margin-top: 0; + margin-bottom: 0; + max-width: none; + *zoom: 1; } + .row .row:before, .row .row:after { + content: " "; + display: table; } + .row .row:after { + clear: both; } + .row .row.collapse { + width: auto; + margin: 0; + max-width: none; + *zoom: 1; } + .row .row.collapse:before, .row .row.collapse:after { + content: " "; + display: table; } + .row .row.collapse:after { + clear: both; } + +@media only screen { + .row .column, + .row .columns { + position: relative; + padding-left: 0.9375em; + padding-right: 0.9375em; + float: left; } + + .row .small-1 { + position: relative; + width: 8.33333%; } + + .row .small-2 { + position: relative; + width: 16.66667%; } + + .row .small-3 { + position: relative; + width: 25%; } + + .row .small-4 { + position: relative; + width: 33.33333%; } + + .row .small-5 { + position: relative; + width: 41.66667%; } + + .row .small-6 { + position: relative; + width: 50%; } + + .row .small-7 { + position: relative; + width: 58.33333%; } + + .row .small-8 { + position: relative; + width: 66.66667%; } + + .row .small-9 { + position: relative; + width: 75%; } + + .row .small-10 { + position: relative; + width: 83.33333%; } + + .row .small-11 { + position: relative; + width: 91.66667%; } + + .row .small-12 { + position: relative; + width: 100%; } + + .row .small-offset-1 { + position: relative; + margin-left: 8.33333%; } + + .row .small-offset-2 { + position: relative; + margin-left: 16.66667%; } + + .row .small-offset-3 { + position: relative; + margin-left: 25%; } + + .row .small-offset-4 { + position: relative; + margin-left: 33.33333%; } + + .row .small-offset-5 { + position: relative; + margin-left: 41.66667%; } + + .row .small-offset-6 { + position: relative; + margin-left: 50%; } + + .row .small-offset-7 { + position: relative; + margin-left: 58.33333%; } + + .row .small-offset-8 { + position: relative; + margin-left: 66.66667%; } + + .row .small-offset-9 { + position: relative; + margin-left: 75%; } + + .row .small-offset-10 { + position: relative; + margin-left: 83.33333%; } + + [class*="column"] + [class*="column"]:last-child { + float: right; } + + [class*="column"] + [class*="column"].end { + float: left; } + + .column.small-centered, + .columns.small-centered { + position: relative; + margin-left: auto; + margin-right: auto; + float: none !important; } } +/* Styles for screens that are atleast 768px; */ +@media only screen and (min-width: 48em) { + .row .large-1 { + position: relative; + width: 8.33333%; } + + .row .large-2 { + position: relative; + width: 16.66667%; } + + .row .large-3 { + position: relative; + width: 25%; } + + .row .large-4 { + position: relative; + width: 33.33333%; } + + .row .large-5 { + position: relative; + width: 41.66667%; } + + .row .large-6 { + position: relative; + width: 50%; } + + .row .large-7 { + position: relative; + width: 58.33333%; } + + .row .large-8 { + position: relative; + width: 66.66667%; } + + .row .large-9 { + position: relative; + width: 75%; } + + .row .large-10 { + position: relative; + width: 83.33333%; } + + .row .large-11 { + position: relative; + width: 91.66667%; } + + .row .large-12 { + position: relative; + width: 100%; } + + .row .large-offset-1 { + position: relative; + margin-left: 8.33333%; } + + .row .large-offset-2 { + position: relative; + margin-left: 16.66667%; } + + .row .large-offset-3 { + position: relative; + margin-left: 25%; } + + .row .large-offset-4 { + position: relative; + margin-left: 33.33333%; } + + .row .large-offset-5 { + position: relative; + margin-left: 41.66667%; } + + .row .large-offset-6 { + position: relative; + margin-left: 50%; } + + .row .large-offset-7 { + position: relative; + margin-left: 58.33333%; } + + .row .large-offset-8 { + position: relative; + margin-left: 66.66667%; } + + .row .large-offset-9 { + position: relative; + margin-left: 75%; } + + .row .large-offset-10 { + position: relative; + margin-left: 83.33333%; } + + .push-2 { + position: relative; + left: 16.66667%; + right: auto; } + + .pull-2 { + position: relative; + right: 16.66667%; + left: auto; } + + .push-3 { + position: relative; + left: 25%; + right: auto; } + + .pull-3 { + position: relative; + right: 25%; + left: auto; } + + .push-4 { + position: relative; + left: 33.33333%; + right: auto; } + + .pull-4 { + position: relative; + right: 33.33333%; + left: auto; } + + .push-5 { + position: relative; + left: 41.66667%; + right: auto; } + + .pull-5 { + position: relative; + right: 41.66667%; + left: auto; } + + .push-6 { + position: relative; + left: 50%; + right: auto; } + + .pull-6 { + position: relative; + right: 50%; + left: auto; } + + .push-7 { + position: relative; + left: 58.33333%; + right: auto; } + + .pull-7 { + position: relative; + right: 58.33333%; + left: auto; } + + .push-8 { + position: relative; + left: 66.66667%; + right: auto; } + + .pull-8 { + position: relative; + right: 66.66667%; + left: auto; } + + .push-9 { + position: relative; + left: 75%; + right: auto; } + + .pull-9 { + position: relative; + right: 75%; + left: auto; } + + .push-10 { + position: relative; + left: 83.33333%; + right: auto; } + + .pull-10 { + position: relative; + right: 83.33333%; + left: auto; } + + .small-push-2 { + left: inherit; } + + .small-pull-2 { + right: inherit; } + + .small-push-3 { + left: inherit; } + + .small-pull-3 { + right: inherit; } + + .small-push-4 { + left: inherit; } + + .small-pull-4 { + right: inherit; } + + .small-push-5 { + left: inherit; } + + .small-pull-5 { + right: inherit; } + + .small-push-6 { + left: inherit; } + + .small-pull-6 { + right: inherit; } + + .small-push-7 { + left: inherit; } + + .small-pull-7 { + right: inherit; } + + .small-push-8 { + left: inherit; } + + .small-pull-8 { + right: inherit; } + + .small-push-9 { + left: inherit; } + + .small-pull-9 { + right: inherit; } + + .small-push-10 { + left: inherit; } + + .small-pull-10 { + right: inherit; } + + .column.large-centered, + .columns.large-centered { + position: relative; + margin-left: auto; + margin-right: auto; + float: none !important; } } +/* Foundation Visibility HTML Classes */ +.show-for-small, +.show-for-medium-down, +.show-for-large-down { + display: inherit !important; } + +.show-for-medium, +.show-for-medium-up, +.show-for-large, +.show-for-large-up, +.show-for-xlarge { + display: none !important; } + +.hide-for-medium, +.hide-for-medium-up, +.hide-for-large, +.hide-for-large-up, +.hide-for-xlarge { + display: inherit !important; } + +.hide-for-small, +.hide-for-medium-down, +.hide-for-large-down { + display: none !important; } + +/* Specific visilbity for tables */ +table.show-for-small, table.show-for-medium-down, table.show-for-large-down, table.hide-for-medium, table.hide-for-medium-up, table.hide-for-large, table.hide-for-large-up, table.hide-for-xlarge { + display: table; } + +thead.show-for-small, thead.show-for-medium-down, thead.show-for-large-down, thead.hide-for-medium, thead.hide-for-medium-up, thead.hide-for-large, thead.hide-for-large-up, thead.hide-for-xlarge { + display: table-header-group !important; } + +tbody.show-for-small, tbody.show-for-medium-down, tbody.show-for-large-down, tbody.hide-for-medium, tbody.hide-for-medium-up, tbody.hide-for-large, tbody.hide-for-large-up, tbody.hide-for-xlarge { + display: table-row-group !important; } + +tr.show-for-small, tr.show-for-medium-down, tr.show-for-large-down, tr.hide-for-medium, tr.hide-for-medium-up, tr.hide-for-large, tr.hide-for-large-up, tr.hide-for-xlarge { + display: table-row !important; } + +td.show-for-small, td.show-for-medium-down, td.show-for-large-down, td.hide-for-medium, td.hide-for-medium-up, td.hide-for-large, td.hide-for-large-up, td.hide-for-xlarge, +th.show-for-small, +th.show-for-medium-down, +th.show-for-large-down, +th.hide-for-medium, +th.hide-for-medium-up, +th.hide-for-large, +th.hide-for-large-up, +th.hide-for-xlarge { + display: table-cell !important; } + +/* Medium Displays: 768px - 1279px */ +@media only screen and (min-width: 48em) { + .show-for-medium, + .show-for-medium-up { + display: inherit !important; } + + .show-for-small { + display: none !important; } + + .hide-for-small { + display: inherit !important; } + + .hide-for-medium, + .hide-for-medium-up { + display: none !important; } + + /* Specific visilbity for tables */ + table.show-for-medium, table.show-for-medium-up, table.hide-for-small { + display: table; } + + thead.show-for-medium, thead.show-for-medium-up, thead.hide-for-small { + display: table-header-group !important; } + + tbody.show-for-medium, tbody.show-for-medium-up, tbody.hide-for-small { + display: table-row-group !important; } + + tr.show-for-medium, tr.show-for-medium-up, tr.hide-for-small { + display: table-row !important; } + + td.show-for-medium, td.show-for-medium-up, td.hide-for-small, + th.show-for-medium, + th.show-for-medium-up, + th.hide-for-small { + display: table-cell !important; } } +/* Large Displays: 1280px - 1440px */ +@media only screen and (min-width: 80em) { + .show-for-large, + .show-for-large-up { + display: inherit !important; } + + .show-for-medium, + .show-for-medium-down { + display: none !important; } + + .hide-for-medium, + .hide-for-medium-down { + display: inherit !important; } + + .hide-for-large, + .hide-for-large-up { + display: none !important; } + + /* Specific visilbity for tables */ + table.show-for-large, table.show-for-large-up, table.hide-for-medium, table.hide-for-medium-down { + display: table; } + + thead.show-for-large, thead.show-for-large-up, thead.hide-for-medium, thead.hide-for-medium-down { + display: table-header-group !important; } + + tbody.show-for-large, tbody.show-for-large-up, tbody.hide-for-medium, tbody.hide-for-medium-down { + display: table-row-group !important; } + + tr.show-for-large, tr.show-for-large-up, tr.hide-for-medium, tr.hide-for-medium-down { + display: table-row !important; } + + td.show-for-large, td.show-for-large-up, td.hide-for-medium, td.hide-for-medium-down, + th.show-for-large, + th.show-for-large-up, + th.hide-for-medium, + th.hide-for-medium-down { + display: table-cell !important; } } +/* X-Large Displays: 1400px and up */ +@media only screen and (min-width: 90em) { + .show-for-xlarge { + display: inherit !important; } + + .show-for-large, + .show-for-large-down { + display: none !important; } + + .hide-for-large, + .hide-for-large-down { + display: inherit !important; } + + .hide-for-xlarge { + display: none !important; } + + /* Specific visilbity for tables */ + table.show-for-xlarge, table.hide-for-large, table.hide-for-large-down { + display: table; } + + thead.show-for-xlarge, thead.hide-for-large, thead.hide-for-large-down { + display: table-header-group !important; } + + tbody.show-for-xlarge, tbody.hide-for-large, tbody.hide-for-large-down { + display: table-row-group !important; } + + tr.show-for-xlarge, tr.hide-for-large, tr.hide-for-large-down { + display: table-row !important; } + + td.show-for-xlarge, td.hide-for-large, td.hide-for-large-down, + th.show-for-xlarge, + th.hide-for-large, + th.hide-for-large-down { + display: table-cell !important; } } +/* Orientation targeting */ +.show-for-landscape, +.hide-for-portrait { + display: inherit !important; } + +.hide-for-landscape, +.show-for-portrait { + display: none !important; } + +/* Specific visilbity for tables */ +table.hide-for-landscape, table.show-for-portrait { + display: table; } + +thead.hide-for-landscape, thead.show-for-portrait { + display: table-header-group !important; } + +tbody.hide-for-landscape, tbody.show-for-portrait { + display: table-row-group !important; } + +tr.hide-for-landscape, tr.show-for-portrait { + display: table-row !important; } + +td.hide-for-landscape, td.show-for-portrait, +th.hide-for-landscape, +th.show-for-portrait { + display: table-cell !important; } + +@media only screen and (orientation: landscape) { + .show-for-landscape, + .hide-for-portrait { + display: inherit !important; } + + .hide-for-landscape, + .show-for-portrait { + display: none !important; } + + /* Specific visilbity for tables */ + table.show-for-landscape, table.hide-for-portrait { + display: table; } + + thead.show-for-landscape, thead.hide-for-portrait { + display: table-header-group !important; } + + tbody.show-for-landscape, tbody.hide-for-portrait { + display: table-row-group !important; } + + tr.show-for-landscape, tr.hide-for-portrait { + display: table-row !important; } + + td.show-for-landscape, td.hide-for-portrait, + th.show-for-landscape, + th.hide-for-portrait { + display: table-cell !important; } } +@media only screen and (orientation: portrait) { + .show-for-portrait, + .hide-for-landscape { + display: inherit !important; } + + .hide-for-portrait, + .show-for-landscape { + display: none !important; } + + /* Specific visilbity for tables */ + table.show-for-portrait, table.hide-for-landscape { + display: table; } + + thead.show-for-portrait, thead.hide-for-landscape { + display: table-header-group !important; } + + tbody.show-for-portrait, tbody.hide-for-landscape { + display: table-row-group !important; } + + tr.show-for-portrait, tr.hide-for-landscape { + display: table-row !important; } + + td.show-for-portrait, td.hide-for-landscape, + th.show-for-portrait, + th.hide-for-landscape { + display: table-cell !important; } } +/* Touch-enabled device targeting */ +.show-for-touch { + display: none !important; } + +.hide-for-touch { + display: inherit !important; } + +.touch .show-for-touch { + display: inherit !important; } + +.touch .hide-for-touch { + display: none !important; } + +/* Specific visilbity for tables */ +table.hide-for-touch { + display: table; } + +.touch table.show-for-touch { + display: table; } + +thead.hide-for-touch { + display: table-header-group !important; } + +.touch thead.show-for-touch { + display: table-header-group !important; } + +tbody.hide-for-touch { + display: table-row-group !important; } + +.touch tbody.show-for-touch { + display: table-row-group !important; } + +tr.hide-for-touch { + display: table-row !important; } + +.touch tr.show-for-touch { + display: table-row !important; } + +td.hide-for-touch { + display: table-cell !important; } + +.touch td.show-for-touch { + display: table-cell !important; } + +th.hide-for-touch { + display: table-cell !important; } + +.touch th.show-for-touch { + display: table-cell !important; } + +/* Foundation Block Grids for below small breakpoint */ +@media only screen { + [class*="block-grid-"] { + display: block; + padding: 0; + margin: 0 -10px; + *zoom: 1; } + [class*="block-grid-"]:before, [class*="block-grid-"]:after { + content: " "; + display: table; } + [class*="block-grid-"]:after { + clear: both; } + [class*="block-grid-"] > li { + display: block; + height: auto; + float: left; + padding: 0 10px 10px; } + + .small-block-grid-1 > li { + width: 100%; + padding: 0 10px 10px; } + .small-block-grid-1 > li:nth-of-type(1n+1) { + clear: both; } + + .small-block-grid-2 > li { + width: 50%; + padding: 0 10px 10px; } + .small-block-grid-2 > li:nth-of-type(2n+1) { + clear: both; } + + .small-block-grid-3 > li { + width: 33.33333%; + padding: 0 10px 10px; } + .small-block-grid-3 > li:nth-of-type(3n+1) { + clear: both; } + + .small-block-grid-4 > li { + width: 25%; + padding: 0 10px 10px; } + .small-block-grid-4 > li:nth-of-type(4n+1) { + clear: both; } + + .small-block-grid-5 > li { + width: 20%; + padding: 0 10px 10px; } + .small-block-grid-5 > li:nth-of-type(5n+1) { + clear: both; } + + .small-block-grid-6 > li { + width: 16.66667%; + padding: 0 10px 10px; } + .small-block-grid-6 > li:nth-of-type(6n+1) { + clear: both; } + + .small-block-grid-7 > li { + width: 14.28571%; + padding: 0 10px 10px; } + .small-block-grid-7 > li:nth-of-type(7n+1) { + clear: both; } + + .small-block-grid-8 > li { + width: 12.5%; + padding: 0 10px 10px; } + .small-block-grid-8 > li:nth-of-type(8n+1) { + clear: both; } + + .small-block-grid-9 > li { + width: 11.11111%; + padding: 0 10px 10px; } + .small-block-grid-9 > li:nth-of-type(9n+1) { + clear: both; } + + .small-block-grid-10 > li { + width: 10%; + padding: 0 10px 10px; } + .small-block-grid-10 > li:nth-of-type(10n+1) { + clear: both; } + + .small-block-grid-11 > li { + width: 9.09091%; + padding: 0 10px 10px; } + .small-block-grid-11 > li:nth-of-type(11n+1) { + clear: both; } + + .small-block-grid-12 > li { + width: 8.33333%; + padding: 0 10px 10px; } + .small-block-grid-12 > li:nth-of-type(12n+1) { + clear: both; } } +/* Foundation Block Grids for above small breakpoint */ +@media only screen and (min-width: 48em) { + .large-block-grid-1 > li { + width: 100%; + padding: 0 10px 10px; } + .large-block-grid-1 > li:nth-of-type(1n+1) { + clear: both; } + + .large-block-grid-2 > li { + width: 50%; + padding: 0 10px 10px; } + .large-block-grid-2 > li:nth-of-type(2n+1) { + clear: both; } + + .large-block-grid-3 > li { + width: 33.33333%; + padding: 0 10px 10px; } + .large-block-grid-3 > li:nth-of-type(3n+1) { + clear: both; } + + .large-block-grid-4 > li { + width: 25%; + padding: 0 10px 10px; } + .large-block-grid-4 > li:nth-of-type(4n+1) { + clear: both; } + + .large-block-grid-5 > li { + width: 20%; + padding: 0 10px 10px; } + .large-block-grid-5 > li:nth-of-type(5n+1) { + clear: both; } + + .large-block-grid-6 > li { + width: 16.66667%; + padding: 0 10px 10px; } + .large-block-grid-6 > li:nth-of-type(6n+1) { + clear: both; } + + .large-block-grid-7 > li { + width: 14.28571%; + padding: 0 10px 10px; } + .large-block-grid-7 > li:nth-of-type(7n+1) { + clear: both; } + + .large-block-grid-8 > li { + width: 12.5%; + padding: 0 10px 10px; } + .large-block-grid-8 > li:nth-of-type(8n+1) { + clear: both; } + + .large-block-grid-9 > li { + width: 11.11111%; + padding: 0 10px 10px; } + .large-block-grid-9 > li:nth-of-type(9n+1) { + clear: both; } + + .large-block-grid-10 > li { + width: 10%; + padding: 0 10px 10px; } + .large-block-grid-10 > li:nth-of-type(10n+1) { + clear: both; } + + .large-block-grid-11 > li { + width: 9.09091%; + padding: 0 10px 10px; } + .large-block-grid-11 > li:nth-of-type(11n+1) { + clear: both; } + + .large-block-grid-12 > li { + width: 8.33333%; + padding: 0 10px 10px; } + .large-block-grid-12 > li:nth-of-type(12n+1) { + clear: both; } + + [class*="small-block-grid-"] > li { + clear: none !important; } } +p.lead { + font-size: 1.21875em; + line-height: 1.6; } + +.subheader { + line-height: 1.4; + color: #6f6f6f; + font-weight: 300; + margin-top: 0.2em; + margin-bottom: 0.5em; } + +/* Typography resets */ +div, +dl, +dt, +dd, +ul, +ol, +li, +h1, +h2, +h3, +h4, +h5, +h6, +pre, +form, +p, +blockquote, +th, +td { + margin: 0; + padding: 0; + direction: ltr; } + +/* Default Link Styles */ +a { + color: #2ba6cb; + text-decoration: none; + line-height: inherit; } + a:hover, a:focus { + color: #2795b6; } + a img { + border: none; } + +/* Default paragraph styles */ +p { + font-family: inherit; + font-weight: normal; + font-size: 1em; + line-height: 1.6; + margin-bottom: 1.25em; + text-rendering: optimizeLegibility; } + p aside { + font-size: 0.875em; + line-height: 1.35; + font-style: italic; } + +/* Default header styles */ +h1, h2, h3, h4, h5, h6 { + font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif; + font-weight: bold; + font-style: normal; + color: #222222; + text-rendering: optimizeLegibility; + margin-top: 0.2em; + margin-bottom: 0.5em; + line-height: 1.2125em; } + h1 small, h2 small, h3 small, h4 small, h5 small, h6 small { + font-size: 60%; + color: #6f6f6f; + line-height: 0; } + +h1 { + font-size: 2.125em; } + +h2 { + font-size: 1.6875em; } + +h3 { + font-size: 1.375em; } + +h4 { + font-size: 1.125em; } + +h5 { + font-size: 1.125em; } + +h6 { + font-size: 1em; } + +hr { + border: solid #dddddd; + border-width: 1px 0 0; + clear: both; + margin: 1.25em 0 1.1875em; + height: 0; } + +/* Helpful Typography Defaults */ +em, +i { + font-style: italic; + line-height: inherit; } + +strong, +b { + font-weight: bold; + line-height: inherit; } + +small { + font-size: 60%; + line-height: inherit; } + +code { + font-family: Consolas, "Liberation Mono", Courier, monospace; + font-weight: bold; + color: #7f0a0c; } + +/* Lists */ +ul, +ol, +dl { + font-size: 1em; + line-height: 1.6; + margin-bottom: 1.25em; + list-style-position: outside; + font-family: inherit; } + +/* Unordered Lists */ +ul li ul, +ul li ol { + margin-left: 1.25em; + margin-bottom: 0; + font-size: 1em; + /* Override nested font-size change */ } +ul.square li ul, ul.circle li ul, ul.disc li ul { + list-style: inherit; } +ul.square { + list-style-type: square; } +ul.circle { + list-style-type: circle; } +ul.disc { + list-style-type: disc; } +ul.no-bullet { + list-style: none; } + +/* Ordered Lists */ +ol li ul, +ol li ol { + margin-left: 1.25em; + margin-bottom: 0; } + +/* Definition Lists */ +dl dt { + margin-bottom: 0.3em; + font-weight: bold; } +dl dd { + margin-bottom: 0.75em; } + +/* Abbreviations */ +abbr, +acronym { + text-transform: uppercase; + font-size: 90%; + color: #222222; + border-bottom: 1px dotted #dddddd; + cursor: help; } + +abbr { + text-transform: none; } + +/* Blockquotes */ +blockquote { + margin: 0 0 1.25em; + padding: 0.5625em 1.25em 0 1.1875em; + border-left: 1px solid #dddddd; } + blockquote cite { + display: block; + font-size: 0.8125em; + color: #555555; } + blockquote cite:before { + content: "\2014 \0020"; } + blockquote cite a, + blockquote cite a:visited { + color: #555555; } + +blockquote, +blockquote p { + line-height: 1.6; + color: #6f6f6f; } + +/* Microformats */ +.vcard { + display: inline-block; + margin: 0 0 1.25em 0; + border: 1px solid #dddddd; + padding: 0.625em 0.75em; } + .vcard li { + margin: 0; + display: block; } + .vcard .fn { + font-weight: bold; + font-size: 0.9375em; } + +.vevent .summary { + font-weight: bold; } +.vevent abbr { + cursor: default; + text-decoration: none; + font-weight: bold; + border: none; + padding: 0 0.0625em; } + +@media only screen and (min-width: 48em) { + h1, h2, h3, h4, h5, h6 { + line-height: 1.4; } + + h1 { + font-size: 2.75em; } + + h2 { + font-size: 2.3125em; } + + h3 { + font-size: 1.6875em; } + + h4 { + font-size: 1.4375em; } } +/* + * Print styles. + * + * Inlined to avoid required HTTP connection: www.phpied.com/delay-loading-your-print-css/ + * Credit to Paul Irish and HTML5 Boilerplate (html5boilerplate.com) +*/ +.print-only { + display: none !important; } + +@media print { + * { + background: transparent !important; + color: black !important; + /* Black prints faster: h5bp.com/s */ + box-shadow: none !important; + text-shadow: none !important; } + + a, + a:visited { + text-decoration: underline; } + + a[href]:after { + content: " (" attr(href) ")"; } + + abbr[title]:after { + content: " (" attr(title) ")"; } + + .ir a:after, + a[href^="javascript:"]:after, + a[href^="#"]:after { + content: ""; } + + pre, + blockquote { + border: 1px solid #999999; + page-break-inside: avoid; } + + thead { + display: table-header-group; + /* h5bp.com/t */ } + + tr, + img { + page-break-inside: avoid; } + + img { + max-width: 100% !important; } + + @page { + margin: 0.5cm; } + + p, + h2, + h3 { + orphans: 3; + widows: 3; } + + h2, + h3 { + page-break-after: avoid; } + + .hide-on-print { + display: none !important; } + + .print-only { + display: block !important; } + + .hide-for-print { + display: none !important; } + + .show-for-print { + display: inherit !important; } } +button, .button { + border-style: solid; + border-width: 1px; + cursor: pointer; + font-family: inherit; + font-weight: bold; + line-height: 1; + margin: 0 0 1.25em; + position: relative; + text-decoration: none; + text-align: center; + display: inline-block; + padding-top: 0.75em; + padding-right: 1.5em; + padding-bottom: 0.8125em; + padding-left: 1.5em; + font-size: 1em; + background-color: #2ba6cb; + border-color: #2284a1; + color: white; } + button:hover, button:focus, .button:hover, .button:focus { + background-color: #2284a1; } + button:hover, button:focus, .button:hover, .button:focus { + color: white; } + button.secondary, .button.secondary { + background-color: #e9e9e9; + border-color: #d0d0d0; + color: #333333; } + button.secondary:hover, button.secondary:focus, .button.secondary:hover, .button.secondary:focus { + background-color: #d0d0d0; } + button.secondary:hover, button.secondary:focus, .button.secondary:hover, .button.secondary:focus { + color: #333333; } + button.success, .button.success { + background-color: #5da423; + border-color: #457a1a; + color: white; } + button.success:hover, button.success:focus, .button.success:hover, .button.success:focus { + background-color: #457a1a; } + button.success:hover, button.success:focus, .button.success:hover, .button.success:focus { + color: white; } + button.alert, .button.alert { + background-color: #c60f13; + border-color: #970b0e; + color: white; } + button.alert:hover, button.alert:focus, .button.alert:hover, .button.alert:focus { + background-color: #970b0e; } + button.alert:hover, button.alert:focus, .button.alert:hover, .button.alert:focus { + color: white; } + button.large, .button.large { + padding-top: 1em; + padding-right: 2em; + padding-bottom: 1.0625em; + padding-left: 2em; + font-size: 1.25em; } + button.small, .button.small { + padding-top: 0.5625em; + padding-right: 1.125em; + padding-bottom: 0.625em; + padding-left: 1.125em; + font-size: 0.8125em; } + button.tiny, .button.tiny { + padding-top: 0.4375em; + padding-right: 0.875em; + padding-bottom: 0.5em; + padding-left: 0.875em; + font-size: 0.6875em; } + button.expand, .button.expand { + padding-top: false; + padding-right: 0px; + padding-bottom: false0.0625em; + padding-left: 0px; + width: 100%; } + button.left-align, .button.left-align { + text-align: left; + text-indent: 0.75em; } + button.right-align, .button.right-align { + text-align: right; + padding-right: 0.75em; } + button.disabled, button[disabled], .button.disabled, .button[disabled] { + background-color: #2ba6cb; + border-color: #2284a1; + color: white; + cursor: default; + opacity: 0.6; + -webkit-box-shadow: none; + box-shadow: none; } + button.disabled:hover, button.disabled:focus, button[disabled]:hover, button[disabled]:focus, .button.disabled:hover, .button.disabled:focus, .button[disabled]:hover, .button[disabled]:focus { + background-color: #2284a1; } + button.disabled:hover, button.disabled:focus, button[disabled]:hover, button[disabled]:focus, .button.disabled:hover, .button.disabled:focus, .button[disabled]:hover, .button[disabled]:focus { + color: white; } + button.disabled:hover, button.disabled:focus, button[disabled]:hover, button[disabled]:focus, .button.disabled:hover, .button.disabled:focus, .button[disabled]:hover, .button[disabled]:focus { + background-color: #2ba6cb; } + button.disabled.secondary, button[disabled].secondary, .button.disabled.secondary, .button[disabled].secondary { + background-color: #e9e9e9; + border-color: #d0d0d0; + color: #333333; + cursor: default; + opacity: 0.6; + -webkit-box-shadow: none; + box-shadow: none; } + button.disabled.secondary:hover, button.disabled.secondary:focus, button[disabled].secondary:hover, button[disabled].secondary:focus, .button.disabled.secondary:hover, .button.disabled.secondary:focus, .button[disabled].secondary:hover, .button[disabled].secondary:focus { + background-color: #d0d0d0; } + button.disabled.secondary:hover, button.disabled.secondary:focus, button[disabled].secondary:hover, button[disabled].secondary:focus, .button.disabled.secondary:hover, .button.disabled.secondary:focus, .button[disabled].secondary:hover, .button[disabled].secondary:focus { + color: #333333; } + button.disabled.secondary:hover, button.disabled.secondary:focus, button[disabled].secondary:hover, button[disabled].secondary:focus, .button.disabled.secondary:hover, .button.disabled.secondary:focus, .button[disabled].secondary:hover, .button[disabled].secondary:focus { + background-color: #e9e9e9; } + button.disabled.success, button[disabled].success, .button.disabled.success, .button[disabled].success { + background-color: #5da423; + border-color: #457a1a; + color: white; + cursor: default; + opacity: 0.6; + -webkit-box-shadow: none; + box-shadow: none; } + button.disabled.success:hover, button.disabled.success:focus, button[disabled].success:hover, button[disabled].success:focus, .button.disabled.success:hover, .button.disabled.success:focus, .button[disabled].success:hover, .button[disabled].success:focus { + background-color: #457a1a; } + button.disabled.success:hover, button.disabled.success:focus, button[disabled].success:hover, button[disabled].success:focus, .button.disabled.success:hover, .button.disabled.success:focus, .button[disabled].success:hover, .button[disabled].success:focus { + color: white; } + button.disabled.success:hover, button.disabled.success:focus, button[disabled].success:hover, button[disabled].success:focus, .button.disabled.success:hover, .button.disabled.success:focus, .button[disabled].success:hover, .button[disabled].success:focus { + background-color: #5da423; } + button.disabled.alert, button[disabled].alert, .button.disabled.alert, .button[disabled].alert { + background-color: #c60f13; + border-color: #970b0e; + color: white; + cursor: default; + opacity: 0.6; + -webkit-box-shadow: none; + box-shadow: none; } + button.disabled.alert:hover, button.disabled.alert:focus, button[disabled].alert:hover, button[disabled].alert:focus, .button.disabled.alert:hover, .button.disabled.alert:focus, .button[disabled].alert:hover, .button[disabled].alert:focus { + background-color: #970b0e; } + button.disabled.alert:hover, button.disabled.alert:focus, button[disabled].alert:hover, button[disabled].alert:focus, .button.disabled.alert:hover, .button.disabled.alert:focus, .button[disabled].alert:hover, .button[disabled].alert:focus { + color: white; } + button.disabled.alert:hover, button.disabled.alert:focus, button[disabled].alert:hover, button[disabled].alert:focus, .button.disabled.alert:hover, .button.disabled.alert:focus, .button[disabled].alert:hover, .button[disabled].alert:focus { + background-color: #c60f13; } + +input.button, +button.button { + padding-top: 0.8125em; + padding-bottom: 0.75em; } + input.button.tiny, + button.button.tiny { + padding-top: 0.5em; + padding-bottom: 0.4375em; } + input.button.small, + button.button.small { + padding-top: 0.625em; + padding-bottom: 0.5625em; } + input.button.large, + button.button.large { + padding-top: 1.03125em; + padding-bottom: 1.03125em; } + +@media only screen { + .button { + -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset; + box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset; + -webkit-transition: background-color 300ms ease-out; + -moz-transition: background-color 300ms ease-out; + transition: background-color 300ms ease-out; } + .button:active { + -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2) inset; + box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2) inset; } + .button.radius { + -webkit-border-radius: 3px; + border-radius: 3px; } + .button.round { + -webkit-border-radius: 1000px; + border-radius: 1000px; } } +@media only screen and (min-width: 48em) { + .button { + display: inline-block; } } +/* Standard Forms */ +form { + margin: 0 0 1em; } + +/* Using forms within rows, we need to set some defaults */ +form .row .row { + margin: -0.5em; } + form .row .row .column, + form .row .row .columns { + padding: 0 0.5em; } + form .row .row.collapse { + margin: 0; } + form .row .row.collapse .column, + form .row .row.collapse .columns { + padding: 0; } +form .row input.column, +form .row input.columns { + padding-left: 0.5em; } + +/* Label Styles */ +label { + font-size: 0.875em; + color: #4d4d4d; + cursor: pointer; + display: block; + font-weight: 500; + margin-bottom: 0.1875em; } + label.right { + float: none; + text-align: right; } + label.inline { + margin: 0 0 1em 0; + padding: 0.625em 0; } + +/* Attach elements to the beginning or end of an input */ +.prefix, +.postfix { + display: block; + position: relative; + z-index: 2; + text-align: center; + width: 100%; + padding-top: 0; + padding-bottom: 0; + border-style: solid; + border-width: 1px; + overflow: hidden; + font-size: 0.875em; + height: 2.3125em; + line-height: 2.3125em; } + +/* Adjust padding, alignment and radius if pre/post element is a button */ +.postfix.button { + padding-left: 0; + padding-right: 0; + padding-top: 0; + padding-bottom: 0; + text-align: center; + line-height: 2.125em; } + +.prefix.button { + padding-left: 0; + padding-right: 0; + padding-top: 0; + padding-bottom: 0; + text-align: center; + line-height: 2.125em; } + +.prefix.button.radius { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-bottomleft: 3px; + -moz-border-radius-topleft: 3px; + -webkit-border-bottom-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + border-top-left-radius: 3px; } + +.postfix.button.radius { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 3px; + -moz-border-radius-bottomright: 3px; + -webkit-border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; } + +.prefix.button.round { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-bottomleft: 1000px; + -moz-border-radius-topleft: 1000px; + -webkit-border-bottom-left-radius: 1000px; + -webkit-border-top-left-radius: 1000px; + border-bottom-left-radius: 1000px; + border-top-left-radius: 1000px; } + +.postfix.button.round { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 1000px; + -moz-border-radius-bottomright: 1000px; + -webkit-border-top-right-radius: 1000px; + -webkit-border-bottom-right-radius: 1000px; + border-top-right-radius: 1000px; + border-bottom-right-radius: 1000px; } + +/* Separate prefix and postfix styles when on span so buttons keep their own */ +span.prefix { + background: #f2f2f2; + border-color: #d9d9d9; + border-right: none; + color: #333333; } + span.prefix.radius { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-bottomleft: 3px; + -moz-border-radius-topleft: 3px; + -webkit-border-bottom-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + border-top-left-radius: 3px; } + +span.postfix { + background: #f2f2f2; + border-color: #cccccc; + border-left: none; + color: #333333; } + span.postfix.radius { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 3px; + -moz-border-radius-bottomright: 3px; + -webkit-border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; } + +/* Input groups will automatically style first and last elements of the group */ +.input-group.radius > *:first-child, .input-group.radius > *:first-child * { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-bottomleft: 3px; + -moz-border-radius-topleft: 3px; + -webkit-border-bottom-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + border-top-left-radius: 3px; } +.input-group.radius > *:last-child, .input-group.radius > *:last-child * { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 3px; + -moz-border-radius-bottomright: 3px; + -webkit-border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; } +.input-group.round > *:first-child, .input-group.round > *:first-child * { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-bottomleft: 1000px; + -moz-border-radius-topleft: 1000px; + -webkit-border-bottom-left-radius: 1000px; + -webkit-border-top-left-radius: 1000px; + border-bottom-left-radius: 1000px; + border-top-left-radius: 1000px; } +.input-group.round > *:last-child, .input-group.round > *:last-child * { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 1000px; + -moz-border-radius-bottomright: 1000px; + -webkit-border-top-right-radius: 1000px; + -webkit-border-bottom-right-radius: 1000px; + border-top-right-radius: 1000px; + border-bottom-right-radius: 1000px; } + +/* We use this to get basic styling on all basic form elements */ +input[type="text"], +input[type="password"], +input[type="date"], +input[type="datetime"], +input[type="datetime-local"], +input[type="month"], +input[type="week"], +input[type="email"], +input[type="number"], +input[type="search"], +input[type="tel"], +input[type="time"], +input[type="url"], +textarea { + background-color: white; + font-family: inherit; + border: 1px solid #cccccc; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + color: rgba(0, 0, 0, 0.75); + display: block; + font-size: 0.875em; + margin: 0 0 1em 0; + padding: 0.5em; + height: 2.3125em; + width: 100%; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + -webkit-transition: all 0.15s linear; + -moz-transition: all 0.15s linear; + transition: all 0.15s linear; } + input[type="text"]:focus, + input[type="password"]:focus, + input[type="date"]:focus, + input[type="datetime"]:focus, + input[type="datetime-local"]:focus, + input[type="month"]:focus, + input[type="week"]:focus, + input[type="email"]:focus, + input[type="number"]:focus, + input[type="search"]:focus, + input[type="tel"]:focus, + input[type="time"]:focus, + input[type="url"]:focus, + textarea:focus { + background: #fafafa; + border-color: #999999; + outline: none; } + input[type="text"][disabled], + input[type="password"][disabled], + input[type="date"][disabled], + input[type="datetime"][disabled], + input[type="datetime-local"][disabled], + input[type="month"][disabled], + input[type="week"][disabled], + input[type="email"][disabled], + input[type="number"][disabled], + input[type="search"][disabled], + input[type="tel"][disabled], + input[type="time"][disabled], + input[type="url"][disabled], + textarea[disabled] { + background-color: #dddddd; } + +/* We add basic fieldset styling */ +fieldset { + border: solid 1px #dddddd; + padding: 1.25em; + margin: 1.125em 0; } + fieldset legend { + font-weight: bold; + background: white; + padding: 0 0.1875em; + margin: 0; + margin-left: -0.1875em; } + +/* Error Handling */ +.error input, +input.error, +.error textarea, +textarea.error { + border-color: #c60f13; + background-color: rgba(198, 15, 19, 0.1); } + .error input:focus, + input.error:focus, + .error textarea:focus, + textarea.error:focus { + background: #fafafa; + border-color: #999999; } + +.error label, +label.error { + color: #c60f13; } + +.error small, +small.error { + display: block; + padding: 0.375em 0.25em; + margin-top: -1.3125em; + margin-bottom: 1em; + font-size: 0.75em; + font-weight: bold; + background: #c60f13; + color: white; } + +/* Custom Checkbox and Radio Inputs */ +form.custom .custom { + display: inline-block; + width: 16px; + height: 16px; + position: relative; + top: 2px; + border: solid 1px #cccccc; + background: white; } + form.custom .custom.radio { + -webkit-border-radius: 1000px; + border-radius: 1000px; } + form.custom .custom.checkbox:before { + content: ""; + display: block; + line-height: 0.8; + height: 14px; + width: 14px; + text-align: center; + position: absolute; + top: 0; + left: 0; + font-size: 14px; + color: #fff; } + form.custom .custom.radio.checked:before { + content: ""; + display: block; + width: 8px; + height: 8px; + -webkit-border-radius: 1000px; + border-radius: 1000px; + background: #222222; + position: relative; + top: 3px; + left: 3px; } + form.custom .custom.checkbox.checked:before { + content: "\00d7"; + color: #222222; } + +/* Custom Select Options and Dropdowns */ +form.custom { + /* Custom input, disabled */ } + form.custom .custom.dropdown { + display: block; + position: relative; + top: 0; + height: 2.3125em; + margin-bottom: 1.25em; + margin-top: 0px; + padding: 0px; + width: 100%; + background: white; + background: -moz-linear-gradient(top, white 0%, #f3f3f3 100%); + background: -webkit-linear-gradient(top, white 0%, #f3f3f3 100%); + background: linear-gradient(to bottom, white 0%, #f3f3f3 100%); + -webkit-box-shadow: none; + box-shadow: none; + font-size: 0.875em; + vertical-align: top; } + form.custom .custom.dropdown ul { + overflow-y: auto; + max-height: 200px; } + form.custom .custom.dropdown .current { + cursor: default; + white-space: nowrap; + line-height: 2.25em; + color: rgba(0, 0, 0, 0.75); + text-decoration: none; + overflow: hidden; + display: block; + margin-left: 0.5em; + margin-right: 2.3125em; } + form.custom .custom.dropdown .selector { + cursor: default; + position: absolute; + width: 2.5em; + height: 2.3125em; + display: block; + right: 0; + top: 0; } + form.custom .custom.dropdown .selector:after { + content: ""; + display: block; + content: ""; + display: block; + width: 0; + height: 0; + border: solid 5px; + border-color: #aaaaaa transparent transparent transparent; + position: absolute; + left: 0.9375em; + top: 50%; + margin-top: -3px; } + form.custom .custom.dropdown:hover a.selector:after, form.custom .custom.dropdown.open a.selector:after { + content: ""; + display: block; + width: 0; + height: 0; + border: solid 5px; + border-color: #222222 transparent transparent transparent; } + form.custom .custom.dropdown .disabled { + color: #888888; } + form.custom .custom.dropdown .disabled:hover { + background: transparent; + color: #888888; } + form.custom .custom.dropdown .disabled:hover:after { + display: none; } + form.custom .custom.dropdown.open ul { + display: block; + z-index: 10; + min-width: 100%; + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; + box-sizing: content-box; } + form.custom .custom.dropdown.small { + max-width: 134px; } + form.custom .custom.dropdown.medium { + max-width: 254px; } + form.custom .custom.dropdown.large { + max-width: 434px; } + form.custom .custom.dropdown.expand { + width: 100% !important; } + form.custom .custom.dropdown.open.small ul { + min-width: 134px; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; } + form.custom .custom.dropdown.open.medium ul { + min-width: 254px; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; } + form.custom .custom.dropdown.open.large ul { + min-width: 434px; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; } + form.custom .custom.dropdown ul { + position: absolute; + width: auto; + display: none; + margin: 0; + left: -1px; + top: auto; + -webkit-box-shadow: 0 2px 2px 0px rgba(0, 0, 0, 0.1); + box-shadow: 0 2px 2px 0px rgba(0, 0, 0, 0.1); + margin: 0; + padding: 0; + background: white; + border: solid 1px #cccccc; + font-size: 16px; } + form.custom .custom.dropdown ul li { + color: #555555; + font-size: 0.875em; + cursor: default; + padding-top: 0.25em; + padding-bottom: 0.25em; + padding-left: 0.375em; + padding-right: 2.375em; + min-height: 1.5em; + line-height: 1.5em; + margin: 0; + white-space: nowrap; + list-style: none; } + form.custom .custom.dropdown ul li.selected { + background: #eeeeee; + color: black; } + form.custom .custom.dropdown ul li:hover { + background-color: #e4e4e4; + color: black; } + form.custom .custom.dropdown ul li.selected:hover { + background: #eeeeee; + cursor: default; + color: black; } + form.custom .custom.dropdown ul.show { + display: block; } + form.custom .custom.disabled { + background-color: #dddddd; } + +/* Button Groups */ +.button-group { + list-style: none; + margin: 0; + *zoom: 1; } + .button-group:before, .button-group:after { + content: " "; + display: table; } + .button-group:after { + clear: both; } + .button-group > * { + margin: 0 0 0 -1px; + float: left; } + .button-group > *:first-child { + margin-left: 0; } + .button-group.radius > *:first-child, .button-group.radius > *:first-child > a, .button-group.radius > *:first-child > button { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-bottomleft: 3px; + -moz-border-radius-topleft: 3px; + -webkit-border-bottom-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + border-top-left-radius: 3px; } + .button-group.radius > *:last-child, .button-group.radius > *:last-child > a, .button-group.radius > *:last-child > button { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 3px; + -moz-border-radius-bottomright: 3px; + -webkit-border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; } + .button-group.round > *:first-child, .button-group.round > *:first-child > a, .button-group.round > *:first-child > button { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-bottomleft: 1000px; + -moz-border-radius-topleft: 1000px; + -webkit-border-bottom-left-radius: 1000px; + -webkit-border-top-left-radius: 1000px; + border-bottom-left-radius: 1000px; + border-top-left-radius: 1000px; } + .button-group.round > *:last-child, .button-group.round > *:last-child > a, .button-group.round > *:last-child > button { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 1000px; + -moz-border-radius-bottomright: 1000px; + -webkit-border-top-right-radius: 1000px; + -webkit-border-bottom-right-radius: 1000px; + border-top-right-radius: 1000px; + border-bottom-right-radius: 1000px; } + .button-group.even-2 li { + width: 50%; } + .button-group.even-2 li .button { + width: 100%; } + .button-group.even-3 li { + width: 33.33333%; } + .button-group.even-3 li .button { + width: 100%; } + .button-group.even-4 li { + width: 25%; } + .button-group.even-4 li .button { + width: 100%; } + .button-group.even-5 li { + width: 20%; } + .button-group.even-5 li .button { + width: 100%; } + .button-group.even-6 li { + width: 16.66667%; } + .button-group.even-6 li .button { + width: 100%; } + .button-group.even-7 li { + width: 14.28571%; } + .button-group.even-7 li .button { + width: 100%; } + .button-group.even-8 li { + width: 12.5%; } + .button-group.even-8 li .button { + width: 100%; } + +.button-bar { + *zoom: 1; } + .button-bar:before, .button-bar:after { + content: " "; + display: table; } + .button-bar:after { + clear: both; } + .button-bar .button-group { + float: left; + margin-right: 0.625em; } + .button-bar .button-group div { + overflow: hidden; } + +/* Dropdown Button */ +.dropdown.button { + position: relative; + padding-right: 3.1875em; } + .dropdown.button:before { + position: absolute; + content: ""; + width: 0; + height: 0; + display: block; + border-style: solid; + border-color: white transparent transparent transparent; + top: 50%; } + .dropdown.button:before { + border-width: 0.5625em; + right: 1.5em; + margin-top: -0.25em; } + .dropdown.button:before { + border-color: white transparent transparent transparent; } + .dropdown.button.tiny { + padding-right: 2.1875em; } + .dropdown.button.tiny:before { + border-width: 0.4375em; + right: 0.875em; + margin-top: -0.15625em; } + .dropdown.button.tiny:before { + border-color: white transparent transparent transparent; } + .dropdown.button.small { + padding-right: 2.8125em; } + .dropdown.button.small:before { + border-width: 0.5625em; + right: 1.125em; + margin-top: -0.21875em; } + .dropdown.button.small:before { + border-color: white transparent transparent transparent; } + .dropdown.button.large { + padding-right: 4em; } + .dropdown.button.large:before { + border-width: 0.625em; + right: 1.75em; + margin-top: -0.3125em; } + .dropdown.button.large:before { + border-color: white transparent transparent transparent; } + .dropdown.button.secondary:before { + border-color: #333333 transparent transparent transparent; } + +/* Split Buttons */ +.split.button { + position: relative; + padding-right: 4.8em; } + .split.button span { + display: block; + height: 100%; + position: absolute; + right: 0; + top: 0; + border-left: solid 1px; } + .split.button span:before { + position: absolute; + content: ""; + width: 0; + height: 0; + display: block; + border-style: solid; + left: 50%; } + .split.button span:active { + background-color: rgba(0, 0, 0, 0.1); } + .split.button span { + border-left-color: #1e728c; } + .split.button span { + width: 3em; } + .split.button span:before { + border-width: 0.5625em; + top: 1.125em; + margin-left: -0.5625em; } + .split.button span:before { + border-color: white transparent transparent transparent; } + .split.button.secondary span { + border-left-color: #c3c3c3; } + .split.button.secondary span:before { + border-color: white transparent transparent transparent; } + .split.button.alert span { + border-left-color: #7f0a0c; } + .split.button.success span { + border-left-color: #396516; } + .split.button.tiny { + padding-right: 3.9375em; } + .split.button.tiny span { + width: 2.84375em; } + .split.button.tiny span:before { + border-width: 0.4375em; + top: 0.875em; + margin-left: -0.3125em; } + .split.button.small { + padding-right: 3.9375em; } + .split.button.small span { + width: 2.8125em; } + .split.button.small span:before { + border-width: 0.5625em; + top: 0.84375em; + margin-left: -0.5625em; } + .split.button.large { + padding-right: 6em; } + .split.button.large span { + width: 3.75em; } + .split.button.large span:before { + border-width: 0.625em; + top: 1.3125em; + margin-left: -0.5625em; } + .split.button.secondary span:before { + border-color: #333333 transparent transparent transparent; } + .split.button.radius span { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 3px; + -moz-border-radius-bottomright: 3px; + -webkit-border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; } + .split.button.round span { + -webkit-border-radius: 0; + border-radius: 0; + -moz-border-radius-topright: 1000px; + -moz-border-radius-bottomright: 1000px; + -webkit-border-top-right-radius: 1000px; + -webkit-border-bottom-right-radius: 1000px; + border-top-right-radius: 1000px; + border-bottom-right-radius: 1000px; } + +/* Flex Video */ +.flex-video { + position: relative; + padding-top: 1.5625em; + padding-bottom: 67.5%; + height: 0; + margin-bottom: 1em; + overflow: hidden; } + .flex-video.widescreen { + padding-bottom: 57.25%; } + .flex-video.vimeo { + padding-top: 0; } + .flex-video iframe, + .flex-video object, + .flex-video embed, + .flex-video video { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; } + +/* Sections */ +.section-container, .section-container.auto { + width: 100%; + display: block; + margin-bottom: 1.25em; + border: 1px solid #cccccc; + border-top: none; } + .section-container section, + .section-container .section, .section-container.auto section, + .section-container.auto .section { + border-top: 1px solid #cccccc; + position: relative; } + .section-container section .title, + .section-container .section .title, .section-container.auto section .title, + .section-container.auto .section .title { + top: 0; + cursor: pointer; + width: 100%; + margin: 0; + background-color: #efefef; } + .section-container section .title a, + .section-container .section .title a, .section-container.auto section .title a, + .section-container.auto .section .title a { + padding: 0.9375em; + display: inline-block; + color: #333333; + font-size: 0.875em; + white-space: nowrap; + width: 100%; } + .section-container section .title:hover, + .section-container .section .title:hover, .section-container.auto section .title:hover, + .section-container.auto .section .title:hover { + background-color: #e2e2e2; } + .section-container section .content, + .section-container .section .content, .section-container.auto section .content, + .section-container.auto .section .content { + display: none; + padding: 0.9375em; + background-color: white; } + .section-container section .content > *:last-child, + .section-container .section .content > *:last-child, .section-container.auto section .content > *:last-child, + .section-container.auto .section .content > *:last-child { + margin-bottom: 0; } + .section-container section .content > *:first-child, + .section-container .section .content > *:first-child, .section-container.auto section .content > *:first-child, + .section-container.auto .section .content > *:first-child { + padding-top: 0; } + .section-container section .content > *:last-child, + .section-container .section .content > *:last-child, .section-container.auto section .content > *:last-child, + .section-container.auto .section .content > *:last-child { + padding-bottom: 0; } + .section-container section.active .content, + .section-container .section.active .content, .section-container.auto section.active .content, + .section-container.auto .section.active .content { + display: block; } + .section-container section.active .title, + .section-container .section.active .title, .section-container.auto section.active .title, + .section-container.auto .section.active .title { + background: #d5d5d5; } + +.section-container.tabs { + border: 0; + position: relative; } + .section-container.tabs section, + .section-container.tabs .section { + padding-top: 0; + border: 0; + position: static; } + .section-container.tabs section .title, + .section-container.tabs .section .title { + width: auto; + border: 1px solid #cccccc; + border-right: 0; + border-bottom: 0; + position: absolute; + z-index: 1; } + .section-container.tabs section .title a, + .section-container.tabs .section .title a { + width: 100%; } + .section-container.tabs section:last-child .title, + .section-container.tabs .section:last-child .title { + border-right: 1px solid #cccccc; } + .section-container.tabs section .content, + .section-container.tabs .section .content { + border: 1px solid #cccccc; + position: absolute; + z-index: 10; + top: -1px; } + .section-container.tabs section.active .title, + .section-container.tabs .section.active .title { + background-color: white; + z-index: 11; + border-bottom: 0; } + .section-container.tabs section.active .content, + .section-container.tabs .section.active .content { + position: relative; } + +@media only screen and (min-width: 48em) { + .section-container.auto { + border: 0; + position: relative; } + .section-container.auto section, + .section-container.auto .section { + padding-top: 0; + border: 0; + position: static; } + .section-container.auto section .title, + .section-container.auto .section .title { + width: auto; + border: 1px solid #cccccc; + border-right: 0; + border-bottom: 0; + position: absolute; + z-index: 1; } + .section-container.auto section .title a, + .section-container.auto .section .title a { + width: 100%; } + .section-container.auto section:last-child .title, + .section-container.auto .section:last-child .title { + border-right: 1px solid #cccccc; } + .section-container.auto section .content, + .section-container.auto .section .content { + border: 1px solid #cccccc; + position: absolute; + z-index: 10; + top: -1px; } + .section-container.auto section.active .title, + .section-container.auto .section.active .title { + background-color: white; + z-index: 11; + border-bottom: 0; } + .section-container.auto section.active .content, + .section-container.auto .section.active .content { + position: relative; } + + .section-container.accordion .section { + padding-top: 0 !important; } + + .section-container.vertical-nav { + border: 1px solid #cccccc; + border-top: none; } + .section-container.vertical-nav section, + .section-container.vertical-nav .section { + padding-top: 0 !important; } + .section-container.vertical-nav section .title a, + .section-container.vertical-nav .section .title a { + display: block; + width: 100%; } + .section-container.vertical-nav section .content, + .section-container.vertical-nav .section .content { + display: none; } + .section-container.vertical-nav section.active .content, + .section-container.vertical-nav .section.active .content { + display: block; + position: absolute; + left: 100%; + top: -1px; + z-index: 999; + min-width: 12.5em; + border: 1px solid #cccccc; } + + .section-container.horizontal-nav { + position: relative; + background: #efefef; + border: 1px solid #cccccc; } + .section-container.horizontal-nav section, + .section-container.horizontal-nav .section { + padding-top: 0; + border: 0; + position: static; } + .section-container.horizontal-nav section .title, + .section-container.horizontal-nav .section .title { + width: auto; + border: 1px solid #cccccc; + border-left: 0; + top: -1px; + position: absolute; + z-index: 1; } + .section-container.horizontal-nav section .title a, + .section-container.horizontal-nav .section .title a { + width: 100%; } + .section-container.horizontal-nav section .content, + .section-container.horizontal-nav .section .content { + display: none; } + .section-container.horizontal-nav section.active .content, + .section-container.horizontal-nav .section.active .content { + display: block; + position: absolute; + z-index: 999; + left: 0; + top: -2px; + min-width: 12.5em; + border: 1px solid #cccccc; } } +/* Wrapped around .top-bar to contain to grid width */ +.contain-to-grid { + width: 100%; + background: #111111; } + +.fixed { + width: 100%; + left: 0; + position: fixed; + top: 0; + z-index: 99; } + +.top-bar { + overflow: hidden; + height: 45px; + line-height: 45px; + position: relative; + background: #111111; + margin-bottom: 1.875em; } + .top-bar ul { + margin-bottom: 0; + list-style: none; } + .top-bar .row { + max-width: none; } + .top-bar form, + .top-bar input { + margin-bottom: 0; } + .top-bar input { + height: 2.45em; } + .top-bar .button { + padding-top: .5em; + padding-bottom: .5em; + margin-bottom: 0; } + .top-bar .title-area { + position: relative; } + .top-bar .name { + height: 45px; + margin: 0; + font-size: 16px; } + .top-bar .name h1 { + line-height: 45px; + font-size: 1.0625em; + margin: 0; } + .top-bar .name h1 a { + font-weight: bold; + color: white; + width: 50%; + display: block; + padding: 0 15px; } + .top-bar .toggle-topbar { + position: absolute; + right: 0; + top: 0; } + .top-bar .toggle-topbar a { + color: white; + text-transform: uppercase; + font-size: 0.8125em; + font-weight: bold; + position: relative; + display: block; + padding: 0 15px; + height: 45px; + line-height: 45px; } + .top-bar .toggle-topbar.menu-icon { + right: 15px; + top: 50%; + margin-top: -16px; + padding-left: 40px; } + .top-bar .toggle-topbar.menu-icon a { + text-indent: -48px; + width: 34px; + height: 34px; + line-height: 33px; + padding: 0; + color: white; } + .top-bar .toggle-topbar.menu-icon a span { + position: absolute; + right: 0; + display: block; + width: 16px; + height: 0; + -webkit-box-shadow: 0 10px 0 1px white, 0 16px 0 1px white, 0 22px 0 1px white; + box-shadow: 0 10px 0 1px white, 0 16px 0 1px white, 0 22px 0 1px white; } + .top-bar.expanded { + height: auto; + background: transparent; } + .top-bar.expanded .title-area { + background: #111111; } + .top-bar.expanded .toggle-topbar a { + color: #888888; } + .top-bar.expanded .toggle-topbar a span { + -webkit-box-shadow: 0 10px 0 1px #888888, 0 16px 0 1px #888888, 0 22px 0 1px #888888; + box-shadow: 0 10px 0 1px #888888, 0 16px 0 1px #888888, 0 22px 0 1px #888888; } + +.top-bar-section { + left: 0; + position: relative; + width: auto; + -webkit-transition: left 300ms ease-out; + -moz-transition: left 300ms ease-out; + transition: left 300ms ease-out; } + .top-bar-section ul { + width: 100%; + height: auto; + display: block; + background: #333333; + font-size: 16px; + margin: 0; } + .top-bar-section .divider { + border-bottom: solid 1px #4d4d4d; + border-top: solid 1px #1a1a1a; + clear: both; + height: 1px; + width: 100%; } + .top-bar-section ul li > a { + display: block; + width: 100%; + color: white; + padding: 12px 0 12px 0; + padding-left: 15px; + font-size: 0.8125em; + font-weight: bold; + background: #333333; + height: 45px; } + .top-bar-section ul li > a:hover { + background: #2b2b2b; } + .top-bar-section ul li > a.button { + background: #2ba6cb; + font-size: 0.8125em; } + .top-bar-section ul li > a.button:hover { + background: #2284a1; } + .top-bar-section ul li > a.button.secondary { + background: #e9e9e9; } + .top-bar-section ul li > a.button.secondary:hover { + background: #d0d0d0; } + .top-bar-section ul li > a.button.success { + background: #5da423; } + .top-bar-section ul li > a.button.success:hover { + background: #457a1a; } + .top-bar-section ul li > a.button.alert { + background: #c60f13; } + .top-bar-section ul li > a.button.alert:hover { + background: #970b0e; } + .top-bar-section ul li.active > a { + background: #2b2b2b; } + .top-bar-section .has-form { + padding: 15px; } + .top-bar-section .has-dropdown { + position: relative; } + .top-bar-section .has-dropdown > a:after { + content: ""; + display: block; + width: 0; + height: 0; + border: solid 5px; + border-color: transparent transparent transparent rgba(255, 255, 255, 0.5); + margin-right: 15px; + margin-top: -4.5px; + position: absolute; + top: 22px; + right: 0; } + .top-bar-section .has-dropdown.moved { + position: static; } + .top-bar-section .has-dropdown.moved > .dropdown { + visibility: visible; } + .top-bar-section .dropdown { + position: absolute; + left: 100%; + top: 0; + visibility: hidden; + z-index: 99; } + .top-bar-section .dropdown li { + width: 100%; } + .top-bar-section .dropdown li a { + font-weight: normal; + padding: 8px 15px; } + .top-bar-section .dropdown li.title h5 { + margin-bottom: 0; } + .top-bar-section .dropdown li.title h5 a { + color: white; + line-height: 22.5px; + display: block; } + .top-bar-section .dropdown label { + padding: 8px 15px 2px; + margin-bottom: 0; + text-transform: uppercase; + color: #555555; + font-weight: bold; + font-size: 0.625em; } + +.top-bar-js-breakpoint { + width: 58.75em !important; + visibility: hidden; } + +.js-generated { + display: block; } + +@media only screen and (min-width: 58.75em) { + .top-bar { + background: #111111; + *zoom: 1; + overflow: visible; } + .top-bar:before, .top-bar:after { + content: " "; + display: table; } + .top-bar:after { + clear: both; } + .top-bar .toggle-topbar { + display: none; } + .top-bar .title-area { + float: left; } + .top-bar .name h1 a { + width: auto; } + .top-bar input, + .top-bar .button { + line-height: 2em; + font-size: 0.875em; + height: 2em; + padding: 0 10px; + position: relative; + top: 8px; } + .top-bar.expanded { + background: #111111; } + + .contain-to-grid .top-bar { + max-width: 62.5em; + margin: 0 auto; } + + .top-bar-section { + -webkit-transition: none 0 0; + -moz-transition: none 0 0; + transition: none 0 0; + left: 0 !important; } + .top-bar-section ul { + width: auto; + height: auto !important; + display: inline; } + .top-bar-section ul li { + float: left; } + .top-bar-section ul li .js-generated { + display: none; } + .top-bar-section li a:not(.button) { + padding: 0 15px; + line-height: 45px; + background: #111111; } + .top-bar-section li a:not(.button):hover { + background: black; } + .top-bar-section .has-dropdown > a { + padding-right: 35px !important; } + .top-bar-section .has-dropdown > a:after { + content: ""; + display: block; + width: 0; + height: 0; + border: solid 5px; + border-color: rgba(255, 255, 255, 0.5) transparent transparent transparent; + margin-top: -2.5px; } + .top-bar-section .has-dropdown.moved { + position: relative; } + .top-bar-section .has-dropdown.moved > .dropdown { + visibility: hidden; } + .top-bar-section .has-dropdown:hover > .dropdown, .top-bar-section .has-dropdown:active > .dropdown { + visibility: visible; } + .top-bar-section .has-dropdown .dropdown li.has-dropdown > a:after { + border: none; + content: "\00bb"; + margin-top: -7px; + right: 5px; } + .top-bar-section .dropdown { + left: 0; + top: auto; + background: transparent; + min-width: 100%; } + .top-bar-section .dropdown li a { + color: white; + line-height: 1; + white-space: nowrap; + padding: 7px 15px; + background: #1e1e1e; } + .top-bar-section .dropdown li label { + white-space: nowrap; + background: #1e1e1e; } + .top-bar-section .dropdown li .dropdown { + left: 100%; + top: 0; } + .top-bar-section > ul > .divider { + border-bottom: none; + border-top: none; + border-right: solid 1px #2b2b2b; + border-left: solid 1px black; + clear: none; + height: 45px; + width: 0px; } + .top-bar-section .has-form { + background: #111111; + padding: 0 15px; + height: 45px; } + .top-bar-section ul.right li .dropdown { + left: auto; + right: 0; } + .top-bar-section ul.right li .dropdown li .dropdown { + right: 100%; } } +.orbit-container { + overflow: hidden; + width: 100%; + position: relative; + background: whitesmoke; } + .orbit-container .orbit-slides-container { + list-style: none; + margin: 0; + padding: 0; + position: relative; } + .orbit-container .orbit-slides-container img { + display: block; } + .orbit-container .orbit-slides-container > * { + position: relative; + float: left; + height: 100%; } + .orbit-container .orbit-slides-container > * .orbit-caption { + position: absolute; + bottom: 0; + background-color: black; + background-color: rgba(0, 0, 0, 0.6); + color: #fff; + width: 100%; + padding: 10px 14px; + font-size: 0.875em; } + .orbit-container .orbit-slides-container > * .orbit-caption * { + color: white; } + .orbit-container .orbit-slide-number { + position: absolute; + top: 10px; + left: 10px; + font-size: 12px; } + .orbit-container .orbit-slide-number span { + font-weight: 700; } + .orbit-container .orbit-timer { + position: absolute; + top: 10px; + right: 10px; + height: 6px; + width: 100px; } + .orbit-container .orbit-timer .orbit-progress { + height: 100%; + background-color: black; + background-color: rgba(0, 0, 0, 0.6); + display: block; + width: 0%; } + .orbit-container .orbit-timer > span { + display: none; + position: absolute; + top: 10px; + right: 0px; + width: 11px; + height: 14px; + border: solid 4px black; + border-top: none; + border-bottom: none; } + .orbit-container .orbit-timer.paused > span { + right: -6px; + top: 9px; + width: 11px; + height: 14px; + border: solid 8px; + border-color: transparent transparent transparent black; } + .orbit-container:hover .orbit-timer > span { + display: block; } + .orbit-container .orbit-prev, + .orbit-container .orbit-next { + position: absolute; + top: 50%; + margin-top: -25px; + background-color: black; + background-color: rgba(0, 0, 0, 0.6); + width: 50px; + height: 60px; + line-height: 50px; + color: white; + text-indent: -9999px !important; } + .orbit-container .orbit-prev > span, + .orbit-container .orbit-next > span { + position: absolute; + top: 50%; + margin-top: -16px; + display: block; + width: 0; + height: 0; + border: solid 16px; } + .orbit-container .orbit-prev { + left: 0; } + .orbit-container .orbit-prev > span { + border-color: transparent; + border-right-color: #fff; } + .orbit-container .orbit-prev:hover > span { + border-right-color: #ccc; } + .orbit-container .orbit-next { + right: 0; } + .orbit-container .orbit-next > span { + border-color: transparent; + border-left-color: #fff; + left: 50%; + margin-left: -8px; } + .orbit-container .orbit-next:hover > span { + border-left-color: #ccc; } + +.orbit-bullets { + margin: 0 auto 30px auto; + overflow: hidden; + position: relative; + top: 10px; } + .orbit-bullets li { + display: block; + width: 18px; + height: 18px; + background: #fff; + float: left; + margin-right: 6px; + border: solid 2px black; + -webkit-border-radius: 1000px; + border-radius: 1000px; } + .orbit-bullets li.active { + background: #000; } + .orbit-bullets li:last-child { + margin-right: 0; } + +.touch .orbit-container .orbit-prev, +.touch .orbit-container .orbit-next { + display: none; } +.touch .orbit-bullets { + display: none; } + +@media only screen and (min-width: 48em) { + .touch .orbit-container .orbit-prev, + .touch .orbit-container .orbit-next { + display: inherit; } + .touch .orbit-bullets { + display: block; } } +.reveal-modal-bg { + position: fixed; + height: 100%; + width: 100%; + background: black; + background: rgba(0, 0, 0, 0.45); + z-index: 98; + display: none; + top: 0; + left: 0; } + +.reveal-modal { + visibility: hidden; + display: none; + position: absolute; + left: 50%; + z-index: 99; + height: auto; + background-color: #fff; + margin-left: -40%; + width: 80%; + background-color: white; + padding: 1.25em; + border: solid 1px #666666; + -webkit-box-shadow: 0 0 10px rgba(0, 0, 0, 0.4); + box-shadow: 0 0 10px rgba(0, 0, 0, 0.4); + top: 50px; } + .reveal-modal .column, + .reveal-modal .columns { + min-width: 0; } + .reveal-modal > :first-child { + margin-top: 0; } + .reveal-modal > :last-child { + margin-bottom: 0; } + .reveal-modal .close-reveal-modal { + font-size: 1.375em; + line-height: 1; + position: absolute; + top: 0.5em; + right: 0.6875em; + color: #aaaaaa; + font-weight: bold; + cursor: pointer; } + +@media only screen and (min-width: 48em) { + .reveal-modal { + padding: 1.875em; + top: 6.25em; } + .reveal-modal.small { + margin-left: -15%; + width: 30%; } + .reveal-modal.medium { + margin-left: -20%; + width: 40%; } + .reveal-modal.large { + margin-left: -30%; + width: 60%; } + .reveal-modal.xlarge { + margin-left: -35%; + width: 70%; } + .reveal-modal.expand { + margin-left: -47.5%; + width: 95%; } } +@media print { + div:not(.reveal-modal) { + display: none; } } +/* Foundation Joyride */ +.joyride-list { + display: none; } + +/* Default styles for the container */ +.joyride-tip-guide { + display: none; + position: absolute; + background: black; + color: white; + z-index: 101; + top: 0; + left: 2.5%; + font-family: inherit; + font-weight: normal; + width: 95%; } + +.lt-ie9 .joyride-tip-guide { + max-width: 800px; + left: 50%; + margin-left: -400px; } + +.joyride-content-wrapper { + width: 100%; + padding: 1.125em 1.25em 1.5em; } + .joyride-content-wrapper .button { + margin-bottom: 0 !important; } + +/* Add a little css triangle pip, older browser just miss out on the fanciness of it */ +.joyride-tip-guide .joyride-nub { + display: block; + position: absolute; + left: 22px; + width: 0; + height: 0; + border: solid 14px; } + .joyride-tip-guide .joyride-nub.top { + border-color: black; + border-top-color: transparent !important; + border-left-color: transparent !important; + border-right-color: transparent !important; + top: -28px; + bottom: none; } + .joyride-tip-guide .joyride-nub.bottom { + border-color: black !important; + border-bottom-color: transparent !important; + border-left-color: transparent !important; + border-right-color: transparent !important; + bottom: -28px; + bottom: none; } + .joyride-tip-guide .joyride-nub.right { + right: -28px; } + .joyride-tip-guide .joyride-nub.left { + left: -28px; } + +/* Typography */ +.joyride-tip-guide h1, +.joyride-tip-guide h2, +.joyride-tip-guide h3, +.joyride-tip-guide h4, +.joyride-tip-guide h5, +.joyride-tip-guide h6 { + line-height: 1.25; + margin: 0; + font-weight: bold; + color: white; } + +.joyride-tip-guide p { + margin: 0 0 1.125em 0; + font-size: 0.875em; + line-height: 1.3; } + +.joyride-timer-indicator-wrap { + width: 50px; + height: 3px; + border: solid 1px #555555; + position: absolute; + right: 1.0625em; + bottom: 1em; } + +.joyride-timer-indicator { + display: block; + width: 0; + height: inherit; + background: #666666; } + +.joyride-close-tip { + position: absolute; + right: 12px; + top: 10px; + color: #777777 !important; + text-decoration: none; + font-size: 30px; + font-weight: normal; + line-height: 0.5 !important; } + .joyride-close-tip:hover, .joyride-close-tip:focus { + color: #eeeeee !important; } + +.joyride-modal-bg { + position: fixed; + height: 100%; + width: 100%; + background: transparent; + background: rgba(0, 0, 0, 0.5); + z-index: 100; + display: none; + top: 0; + left: 0; + cursor: pointer; } + +.joyride-expose-wrapper { + background-color: #ffffff; + position: absolute; + border-radius: 3px; + z-index: 102; + -moz-box-shadow: 0px 0px 30px white; + -webkit-box-shadow: 0px 0px 15px white; + box-shadow: 0px 0px 15px white; } + +.joyride-expose-cover { + background: transparent; + border-radius: 3px; + position: absolute; + z-index: 9999; + top: 0px; + left: 0px; } + +/* Styles for screens that are atleast 768px; */ +@media only screen and (min-width: 48em) { + .joyride-tip-guide { + width: 300px; + left: inherit; } + .joyride-tip-guide .joyride-nub.bottom { + border-color: black !important; + border-bottom-color: transparent !important; + border-left-color: transparent !important; + border-right-color: transparent !important; + bottom: -28px; + bottom: none; } + .joyride-tip-guide .joyride-nub.right { + border-color: black !important; + border-top-color: transparent !important; + border-right-color: transparent !important; + border-bottom-color: transparent !important; + top: 22px; + bottom: none; + left: auto; + right: -28px; } + .joyride-tip-guide .joyride-nub.left { + border-color: black !important; + border-top-color: transparent !important; + border-left-color: transparent !important; + border-bottom-color: transparent !important; + top: 22px; + left: -28px; + right: auto; + bottom: none; } } +/* Clearing Styles */ +[data-clearing] { + *zoom: 1; + margin-bottom: 0; } + [data-clearing]:before, [data-clearing]:after { + content: " "; + display: table; } + [data-clearing]:after { + clear: both; } + +.clearing-blackout { + background: #111111; + position: fixed; + width: 100%; + height: 100%; + top: 0; + left: 0; + z-index: 998; } + .clearing-blackout .clearing-close { + display: block; } + +.clearing-container { + position: relative; + z-index: 998; + height: 100%; + overflow: hidden; + margin: 0; } + +.visible-img { + height: 95%; + position: relative; } + .visible-img img { + position: absolute; + left: 50%; + top: 50%; + margin-left: -50%; + max-height: 100%; + max-width: 100%; } + +.clearing-caption { + color: white; + line-height: 1.3; + margin-bottom: 0; + text-align: center; + bottom: 0; + background: #111111; + width: 100%; + padding: 10px 30px; + position: absolute; + left: 0; } + +.clearing-close { + z-index: 999; + padding-left: 20px; + padding-top: 10px; + font-size: 40px; + line-height: 1; + color: white; + display: none; } + .clearing-close:hover, .clearing-close:focus { + color: #ccc; } + +.clearing-assembled .clearing-container { + height: 100%; } + .clearing-assembled .clearing-container .carousel > ul { + display: none; } + +@media only screen and (min-width: 48em) { + .clearing-main-prev, + .clearing-main-next { + position: absolute; + height: 100%; + width: 40px; + top: 0; } + .clearing-main-prev > span, + .clearing-main-next > span { + position: absolute; + top: 50%; + display: block; + width: 0; + height: 0; + border: solid 16px; } + + .clearing-main-prev { + left: 0; } + .clearing-main-prev > span { + left: 5px; + border-color: transparent; + border-right-color: white; } + + .clearing-main-next { + right: 0; } + .clearing-main-next > span { + border-color: transparent; + border-left-color: white; } + + .clearing-main-prev.disabled, + .clearing-main-next.disabled { + opacity: 0.5; } + + .clearing-feature ~ li { + display: none; } + + .clearing-assembled .clearing-container .carousel { + background: #111111; + height: 150px; + margin-top: 5px; } + .clearing-assembled .clearing-container .carousel > ul { + display: block; + z-index: 999; + width: 200%; + height: 100%; + margin-left: 0; + position: relative; + left: 0; } + .clearing-assembled .clearing-container .carousel > ul li { + display: block; + width: 175px; + height: inherit; + padding: 0; + float: left; + overflow: hidden; + margin-right: 1px; + position: relative; + cursor: pointer; + opacity: 0.4; } + .clearing-assembled .clearing-container .carousel > ul li.fix-height img { + min-height: 100%; + height: 100%; + max-width: none; } + .clearing-assembled .clearing-container .carousel > ul li a.th { + border: none; + -webkit-box-shadow: none; + box-shadow: none; + display: block; } + .clearing-assembled .clearing-container .carousel > ul li img { + cursor: pointer !important; + min-width: 100% !important; } + .clearing-assembled .clearing-container .carousel > ul li.visible { + opacity: 1; } + .clearing-assembled .clearing-container .visible-img { + background: #111111; + overflow: hidden; + height: 75%; } + + .clearing-close { + position: absolute; + top: 10px; + right: 20px; + padding-left: 0; + padding-top: 0; } } +/* Foundation Alerts */ +.alert-box { + border-style: solid; + border-width: 1px; + display: block; + font-weight: bold; + margin-bottom: 1.25em; + position: relative; + padding: 0.6875em 1.3125em 0.75em 0.6875em; + font-size: 0.875em; + background-color: #2ba6cb; + border-color: #2284a1; + color: white; } + .alert-box .close { + font-size: 1.375em; + padding: 5px 4px 4px; + line-height: 0; + position: absolute; + top: 0.4375em; + right: 0.3125em; + color: #333333; + opacity: 0.3; } + .alert-box .close:hover, .alert-box .close:focus { + opacity: 0.5; } + .alert-box.radius { + -webkit-border-radius: 3px; + border-radius: 3px; } + .alert-box.round { + -webkit-border-radius: 1000px; + border-radius: 1000px; } + .alert-box.success { + background-color: #5da423; + border-color: #457a1a; + color: white; } + .alert-box.alert { + background-color: #c60f13; + border-color: #970b0e; + color: white; } + .alert-box.secondary { + background-color: #e9e9e9; + border-color: #d0d0d0; + color: #505050; } + +/* Breadcrumbs */ +.breadcrumbs { + display: block; + padding: 0.375em 0.875em 0.5625em; + overflow: hidden; + margin-left: 0; + list-style: none; + border-style: solid; + border-width: 1px; + background-color: #f6f6f6; + border-color: gainsboro; + -webkit-border-radius: 3px; + border-radius: 3px; } + .breadcrumbs li { + margin: 0; + padding: 0 0.75em 0 0; + float: left; } + .breadcrumbs li:hover a, .breadcrumbs li:focus a { + text-decoration: underline; } + .breadcrumbs li a, + .breadcrumbs li span { + font-size: 0.6875em; + padding-left: 0.75em; + text-transform: uppercase; + color: #2ba6cb; } + .breadcrumbs li.current a { + cursor: default; + color: #333333; } + .breadcrumbs li.current:hover a, .breadcrumbs li.current:focus a { + text-decoration: none; } + .breadcrumbs li.unavailable a { + color: #999999; } + .breadcrumbs li.unavailable:hover a, + .breadcrumbs li.unavailable a:focus { + text-decoration: none; + color: #999999; + cursor: default; } + .breadcrumbs li:before { + content: "/"; + color: #aaaaaa; + position: relative; + top: 1px; } + .breadcrumbs li:first-child a, .breadcrumbs li:first-child span { + padding-left: 0; } + .breadcrumbs li:first-child:before { + content: " "; } + +/* Keystroke Characters */ +.keystroke, +kbd { + background-color: #ededed; + border-color: #dbdbdb; + color: #222222; + border-style: solid; + border-width: 1px; + margin: 0; + font-family: "Consolas", "Menlo", "Courier", monospace; + font-size: 0.9375em; + padding: 0.125em 0.25em 0em; + -webkit-border-radius: 3px; + border-radius: 3px; } + +/* Labels */ +.label { + font-weight: 500; + text-align: center; + text-decoration: none; + line-height: 1; + white-space: nowrap; + display: inline-block; + position: relative; + padding: 0.1875em 0.625em 0.25em; + font-size: 0.875em; + background-color: #2ba6cb; + color: #fff; } + .label.radius { + -webkit-border-radius: 3px; + border-radius: 3px; } + .label.round { + -webkit-border-radius: 1000px; + border-radius: 1000px; } + .label.alert { + background-color: #c60f13; + color: #fff; } + .label.success { + background-color: #5da423; + color: #fff; } + .label.secondary { + background-color: #e9e9e9; + color: #333; } + +/* Inline Lists */ +.inline-list { + margin: 0 auto 1.0625em auto; + margin-left: -1.375em; + margin-right: 0; + padding: 0; + list-style: none; + overflow: hidden; } + .inline-list > li { + list-style: none; + float: left; + margin-left: 1.375em; + display: block; } + .inline-list > li > * { + display: block; } + +/* Pagination */ +.pagination { + display: block; + height: 1.5em; + margin-left: -0.3125em; } + .pagination li { + display: block; + float: left; + height: 1.5em; + color: #222222; + font-size: 0.875em; + margin-left: 0.3125em; } + .pagination li a { + display: block; + padding: 0.0625em 0.4375em 0.0625em; + color: #999999; } + .pagination li:hover a, + .pagination li a:focus { + background: #e6e6e6; } + .pagination li.unavailable a { + cursor: default; + color: #999999; } + .pagination li.unavailable:hover a, .pagination li.unavailable a:focus { + background: transparent; } + .pagination li.current a { + background: #2ba6cb; + color: white; + font-weight: bold; + cursor: default; } + .pagination li.current a:hover, .pagination li.current a:focus { + background: #2ba6cb; } + +.pagination-centered { + text-align: center; } + .pagination-centered ul > li { + float: none; + display: inline-block; } + +/* Panels */ +.panel { + border-style: solid; + border-width: 1px; + border-color: #d9d9d9; + margin-bottom: 1.25em; + padding: 1.25em; + background: #f2f2f2; } + .panel h1, .panel h2, .panel h3, .panel h4, .panel h5, .panel h6, .panel p { + color: #333333; } + .panel > :first-child { + margin-top: 0; } + .panel > :last-child { + margin-bottom: 0; } + .panel h1, .panel h2, .panel h3, .panel h4, .panel h5, .panel h6 { + line-height: 1; + margin-bottom: 0.625em; } + .panel h1.subheader, .panel h2.subheader, .panel h3.subheader, .panel h4.subheader, .panel h5.subheader, .panel h6.subheader { + line-height: 1.4; } + .panel.callout { + border-style: solid; + border-width: 1px; + border-color: #2284a1; + margin-bottom: 1.25em; + padding: 1.25em; + background: #2ba6cb; + -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset; + box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset; } + .panel.callout h1, .panel.callout h2, .panel.callout h3, .panel.callout h4, .panel.callout h5, .panel.callout h6, .panel.callout p { + color: white; } + .panel.callout > :first-child { + margin-top: 0; } + .panel.callout > :last-child { + margin-bottom: 0; } + .panel.callout h1, .panel.callout h2, .panel.callout h3, .panel.callout h4, .panel.callout h5, .panel.callout h6 { + line-height: 1; + margin-bottom: 0.625em; } + .panel.callout h1.subheader, .panel.callout h2.subheader, .panel.callout h3.subheader, .panel.callout h4.subheader, .panel.callout h5.subheader, .panel.callout h6.subheader { + line-height: 1.4; } + .panel.radius { + -webkit-border-radius: 3px; + border-radius: 3px; } + +/* Pricing Tables */ +.pricing-table { + border: solid 1px #dddddd; + margin-left: 0; + margin-bottom: 1.25em; } + .pricing-table * { + list-style: none; + line-height: 1; } + .pricing-table .title { + background-color: #dddddd; + padding: 0.9375em 1.25em; + text-align: center; + color: #333333; + font-weight: bold; + font-size: 1em; } + .pricing-table .price { + background-color: #eeeeee; + padding: 0.9375em 1.25em; + text-align: center; + color: #333333; + font-weight: normal; + font-size: 1.25em; } + .pricing-table .description { + background-color: white; + padding: 0.9375em; + text-align: center; + color: #777777; + font-size: 0.75em; + font-weight: normal; + line-height: 1.4; + border-bottom: dotted 1px #dddddd; } + .pricing-table .bullet-item { + background-color: white; + padding: 0.9375em; + text-align: center; + color: #333333; + font-size: 0.875em; + font-weight: normal; + border-bottom: dotted 1px #dddddd; } + .pricing-table .cta-button { + background-color: whitesmoke; + text-align: center; + padding: 1.25em 1.25em 0; } + +/* Progress Bar */ +.progress { + background-color: transparent; + height: 1.5625em; + border: 1px solid #cccccc; + padding: 0.125em; + margin-bottom: 0.625em; } + .progress .meter { + background: #2ba6cb; + height: 100%; + display: block; } + .progress.secondary .meter { + background: #e9e9e9; + height: 100%; + display: block; } + .progress.success .meter { + background: #5da423; + height: 100%; + display: block; } + .progress.alert .meter { + background: #c60f13; + height: 100%; + display: block; } + .progress.radius { + -webkit-border-radius: 3px; + border-radius: 3px; } + .progress.radius .meter { + -webkit-border-radius: 2px; + border-radius: 2px; } + .progress.round { + -webkit-border-radius: 1000px; + border-radius: 1000px; } + .progress.round .meter { + -webkit-border-radius: 999px; + border-radius: 999px; } + +/* Side Nav */ +.side-nav { + display: block; + margin: 0; + padding: 0.875em 0; + list-style-type: none; + list-style-position: inside; } + .side-nav li { + margin: 0 0 0.4375em 0; + font-size: 0.875em; } + .side-nav li a { + display: block; + color: #2ba6cb; } + .side-nav li.active a { + color: #4d4d4d; + font-weight: bold; } + .side-nav li.divider { + border-top: 1px solid; + height: 0; + padding: 0; + list-style: none; + border-top-color: #e6e6e6; } + +/* Side Nav */ +.sub-nav { + display: block; + width: auto; + overflow: hidden; + margin: -0.25em 0 1.125em; + padding-top: 0.25em; + margin-right: 0; + margin-left: -0.5625em; } + .sub-nav dt, + .sub-nav dd { + float: left; + display: inline; + margin-left: 0.5625em; + margin-bottom: 0.625em; + font-weight: normal; + font-size: 0.875em; } + .sub-nav dt a, + .sub-nav dd a { + color: #999999; + text-decoration: none; } + .sub-nav dt.active a, + .sub-nav dd.active a { + -webkit-border-radius: 1000px; + border-radius: 1000px; + font-weight: bold; + background: #2ba6cb; + padding: 0.1875em 0.5625em; + cursor: default; + color: white; } + +/* Foundation Switches */ +@media only screen { + div.switch { + position: relative; + width: 100%; + padding: 0; + display: block; + overflow: hidden; + border-style: solid; + border-width: 1px; + margin-bottom: 1.25em; + -webkit-animation: webkitSiblingBugfix infinite 1s; + height: 36px; + background: white; + border-color: #cccccc; } + div.switch label { + position: relative; + left: 0; + z-index: 2; + float: left; + width: 50%; + height: 100%; + margin: 0; + font-weight: bold; + text-align: left; + -webkit-transition: all 0.1s ease-out; + -moz-transition: all 0.1s ease-out; + transition: all 0.1s ease-out; } + div.switch input { + position: absolute; + z-index: 3; + opacity: 0; + width: 100%; + height: 100%; } + div.switch input:hover, div.switch input:focus { + cursor: pointer; } + div.switch > span { + position: absolute; + top: -1px; + left: -1px; + z-index: 1; + display: block; + padding: 0; + border-width: 1px; + border-style: solid; + -webkit-transition: all 0.1s ease-out; + -moz-transition: all 0.1s ease-out; + transition: all 0.1s ease-out; } + div.switch input:not(:checked) + label { + opacity: 0; } + div.switch input:checked { + display: none !important; } + div.switch input { + left: 0; + display: block !important; } + div.switch input:first-of-type + label, + div.switch input:first-of-type + span + label { + left: -50%; } + div.switch input:first-of-type:checked + label, + div.switch input:first-of-type:checked + span + label { + left: 0%; } + div.switch input:last-of-type + label, + div.switch input:last-of-type + span + label { + right: -50%; + left: auto; + text-align: right; } + div.switch input:last-of-type:checked + label, + div.switch input:last-of-type:checked + span + label { + right: 0%; + left: auto; } + div.switch span.custom { + display: none !important; } + div.switch label { + padding: 0 0.375em; + line-height: 2.3em; + font-size: 0.875em; } + div.switch input:first-of-type:checked ~ span { + left: 100%; + margin-left: -2.1875em; } + div.switch > span { + width: 2.25em; + height: 2.25em; } + div.switch > span { + border-color: #b3b3b3; + background: white; + background: -moz-linear-gradient(top, white 0%, #f2f2f2 100%); + background: -webkit-linear-gradient(top, white 0%, #f2f2f2 100%); + background: linear-gradient(to bottom, white 0%, #f2f2f2 100%); + -webkit-box-shadow: 2px 0 10px 0 rgba(0, 0, 0, 0.07), 1000px 0 0 1000px #e1f5d1, -2px 0 10px 0 rgba(0, 0, 0, 0.07), -1000px 0 0 1000px whitesmoke; + box-shadow: 2px 0 10px 0 rgba(0, 0, 0, 0.07), 1000px 0 0 980px #e1f5d1, -2px 0 10px 0 rgba(0, 0, 0, 0.07), -1000px 0 0 1000px whitesmoke; } + div.switch:hover > span, div.switch:focus > span { + background: white; + background: -moz-linear-gradient(top, white 0%, #e6e6e6 100%); + background: -webkit-linear-gradient(top, white 0%, #e6e6e6 100%); + background: linear-gradient(to bottom, white 0%, #e6e6e6 100%); } + div.switch:active { + background: transparent; } + div.switch.large { + height: 44px; } + div.switch.large label { + padding: 0 0.375em; + line-height: 2.3em; + font-size: 1.0625em; } + div.switch.large input:first-of-type:checked ~ span { + left: 100%; + margin-left: -2.6875em; } + div.switch.large > span { + width: 2.75em; + height: 2.75em; } + div.switch.small { + height: 28px; } + div.switch.small label { + padding: 0 0.375em; + line-height: 2.1em; + font-size: 0.75em; } + div.switch.small input:first-of-type:checked ~ span { + left: 100%; + margin-left: -1.6875em; } + div.switch.small > span { + width: 1.75em; + height: 1.75em; } + div.switch.tiny { + height: 22px; } + div.switch.tiny label { + padding: 0 0.375em; + line-height: 1.9em; + font-size: 0.6875em; } + div.switch.tiny input:first-of-type:checked ~ span { + left: 100%; + margin-left: -1.3125em; } + div.switch.tiny > span { + width: 1.375em; + height: 1.375em; } + div.switch.radius { + -webkit-border-radius: 4px; + border-radius: 4px; } + div.switch.radius > span { + -webkit-border-radius: 3px; + border-radius: 3px; } + div.switch.round { + -webkit-border-radius: 1000px; + border-radius: 1000px; } + div.switch.round > span { + -webkit-border-radius: 999px; + border-radius: 999px; } + div.switch.round label { + padding: 0 0.5625em; } + + @-webkit-keyframes webkitSiblingBugfix { + from { + position: relative; } + + to { + position: relative; } } } +[data-magellan-expedition] { + background: white; + z-index: 50; + min-width: 100%; + padding: 10px; } + [data-magellan-expedition] .sub-nav { + margin-bottom: 0; } + [data-magellan-expedition] .sub-nav dd { + margin-bottom: 0; } + +/* Tables */ +table { + background: white; + margin-bottom: 1.25em; + border: solid 1px #dddddd; } + table thead, + table tfoot { + background: whitesmoke; + font-weight: bold; } + table thead tr th, + table thead tr td, + table tfoot tr th, + table tfoot tr td { + padding: 0.5em 0.625em 0.625em; + font-size: 0.875em; + color: #222222; + text-align: left; } + table tr th, + table tr td { + padding: 0.5625em 0.625em; + font-size: 0.875em; + color: #222222; } + table tr.even, table tr.alt, table tr:nth-of-type(even) { + background: #f9f9f9; } + table thead tr th, + table tfoot tr th, + table tbody tr td, + table tr td, + table tfoot tr td { + display: table-cell; + line-height: 1.125em; } + +/* Image Thumbnails */ +.th { + display: inline-block; + border: solid 4px white; + -webkit-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2); + -webkit-transition: all 200ms ease-out; + -moz-transition: all 200ms ease-out; + transition: all 200ms ease-out; } + .th:hover, .th:focus { + -webkit-box-shadow: 0 0 6px 1px rgba(43, 166, 203, 0.5); + box-shadow: 0 0 6px 1px rgba(43, 166, 203, 0.5); } + .th.radius { + -webkit-border-radius: 3px; + border-radius: 3px; } + +/* Tooltips */ +.has-tip { + border-bottom: dotted 1px #cccccc; + cursor: help; + font-weight: bold; + color: #333333; } + .has-tip:hover, .has-tip:focus { + border-bottom: dotted 1px #196177; + color: #2ba6cb; } + .has-tip.tip-left, .has-tip.tip-right { + float: none !important; } + +.tooltip { + display: none; + position: absolute; + z-index: 999; + font-weight: bold; + font-size: 0.9375em; + line-height: 1.3; + padding: 0.5em; + max-width: 85%; + left: 50%; + width: 100%; + color: white; + background: black; + -webkit-border-radius: 3px; + border-radius: 3px; } + .tooltip > .nub { + display: block; + left: 5px; + position: absolute; + width: 0; + height: 0; + border: solid 5px; + border-color: transparent transparent black transparent; + top: -10px; } + .tooltip.opened { + color: #2ba6cb !important; + border-bottom: dotted 1px #196177 !important; } + +.tap-to-close { + display: block; + font-size: 0.625em; + color: #888888; + font-weight: normal; } + +@media only screen and (min-width: 48em) { + .tooltip > .nub { + border-color: transparent transparent black transparent; + top: -10px; } + .tooltip.tip-top > .nub { + border-color: black transparent transparent transparent; + top: auto; + bottom: -10px; } + .tooltip.tip-left, .tooltip.tip-right { + float: none !important; } + .tooltip.tip-left > .nub { + border-color: transparent transparent transparent black; + right: -10px; + left: auto; + top: 50%; + margin-top: -5px; } + .tooltip.tip-right > .nub { + border-color: transparent black transparent transparent; + right: auto; + left: -10px; + top: 50%; + margin-top: -5px; } } +@media only screen and (max-width: 767px) { + .f-dropdown { + max-width: 100%; + left: 0; } } +/* Foundation Dropdowns */ +.f-dropdown { + position: absolute; + top: -9999px; + list-style: none; + padding: 1.25em; + width: 100%; + height: auto; + max-height: none; + background: white; + border: solid 1px #cccccc; + font-size: 16px; + z-index: 99; + margin-top: 2px; + max-width: 200px; } + .f-dropdown *:first-child { + margin-top: 0; } + .f-dropdown *:last-child { + margin-bottom: 0; } + .f-dropdown:before { + content: ""; + display: block; + width: 0; + height: 0; + border: solid 6px; + border-color: transparent transparent white transparent; + position: absolute; + top: -12px; + left: 10px; + z-index: 99; } + .f-dropdown:after { + content: ""; + display: block; + width: 0; + height: 0; + border: solid 7px; + border-color: transparent transparent #cccccc transparent; + position: absolute; + top: -14px; + left: 9px; + z-index: 98; } + .f-dropdown.right:before { + left: auto; + right: 10px; } + .f-dropdown.right:after { + left: auto; + right: 9px; } + .f-dropdown li { + font-size: 0.875em; + cursor: pointer; + padding: 0.3125em 0.625em; + line-height: 1.125em; + margin: 0; } + .f-dropdown li:hover, .f-dropdown li:focus { + background: #eeeeee; } + .f-dropdown li a { + color: #555555; } + .f-dropdown.content { + position: absolute; + top: -9999px; + list-style: none; + padding: 1.25em; + width: 100%; + height: auto; + max-height: none; + background: white; + border: solid 1px #cccccc; + font-size: 16px; + z-index: 99; + max-width: 200px; } + .f-dropdown.content *:first-child { + margin-top: 0; } + .f-dropdown.content *:last-child { + margin-bottom: 0; } + .f-dropdown.tiny { + max-width: 200px; } + .f-dropdown.small { + max-width: 300px; } + .f-dropdown.medium { + max-width: 500px; } + .f-dropdown.large { + max-width: 800px; } + .monospace{ + font-family:courier; + } + .scroll_y { + overflow:auto; + white-space:nowrap; + } diff --git a/engine/src/main/resources/org/archive/crawler/restlet/css/foundation.min.css b/engine/src/main/resources/org/archive/crawler/restlet/css/foundation.min.css new file mode 100644 index 00000000..50186fd7 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/css/foundation.min.css @@ -0,0 +1 @@ +*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}html,body{font-size:100%}body{background:#fff;color:#222;padding:0;margin:0;font-family:"Helvetica Neue","Helvetica",Helvetica,Arial,sans-serif;font-weight:normal;font-style:normal;line-height:1;position:relative}a:focus{outline:none}img,object,embed{max-width:100%;height:auto}object,embed{height:100%}img{-ms-interpolation-mode:bicubic}#map_canvas img,#map_canvas embed,#map_canvas object,.map_canvas img,.map_canvas embed,.map_canvas object{max-width:none !important}.left{float:left !important}.right{float:right !important}.text-left{text-align:left !important}.text-right{text-align:right !important}.text-center{text-align:center !important}.text-justify{text-align:justify !important}.hide{display:none}.antialiased{-webkit-font-smoothing:antialiased}img{display:inline-block}textarea{height:auto;min-height:50px}select{width:100%}.row{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1}.row:before,.row:after{content:" ";display:table}.row:after{clear:both}.row .column,.row .columns{position:relative;padding-left:0.9375em;padding-right:0.9375em;width:100%;float:left}.row.collapse .column,.row.collapse .columns{position:relative;padding-left:0;padding-right:0;float:left}.row .row{width:auto;margin-left:-0.9375em;margin-right:-0.9375em;margin-top:0;margin-bottom:0;max-width:none;*zoom:1}.row .row:before,.row .row:after{content:" ";display:table}.row .row:after{clear:both}.row .row.collapse{width:auto;margin:0;max-width:none;*zoom:1}.row .row.collapse:before,.row .row.collapse:after{content:" ";display:table}.row .row.collapse:after{clear:both}@media only screen{.row .column,.row .columns{position:relative;padding-left:0.9375em;padding-right:0.9375em;float:left}.row .small-1{position:relative;width:8.33333%}.row .small-2{position:relative;width:16.66667%}.row .small-3{position:relative;width:25%}.row .small-4{position:relative;width:33.33333%}.row .small-5{position:relative;width:41.66667%}.row .small-6{position:relative;width:50%}.row .small-7{position:relative;width:58.33333%}.row .small-8{position:relative;width:66.66667%}.row .small-9{position:relative;width:75%}.row .small-10{position:relative;width:83.33333%}.row .small-11{position:relative;width:91.66667%}.row .small-12{position:relative;width:100%}.row .small-offset-1{position:relative;margin-left:8.33333%}.row .small-offset-2{position:relative;margin-left:16.66667%}.row .small-offset-3{position:relative;margin-left:25%}.row .small-offset-4{position:relative;margin-left:33.33333%}.row .small-offset-5{position:relative;margin-left:41.66667%}.row .small-offset-6{position:relative;margin-left:50%}.row .small-offset-7{position:relative;margin-left:58.33333%}.row .small-offset-8{position:relative;margin-left:66.66667%}.row .small-offset-9{position:relative;margin-left:75%}.row .small-offset-10{position:relative;margin-left:83.33333%}[class*="column"]+[class*="column"]:last-child{float:right}[class*="column"]+[class*="column"].end{float:left}.column.small-centered,.columns.small-centered{position:relative;margin-left:auto;margin-right:auto;float:none !important}}@media only screen and (min-width: 48em){.row .large-1{position:relative;width:8.33333%}.row .large-2{position:relative;width:16.66667%}.row .large-3{position:relative;width:25%}.row .large-4{position:relative;width:33.33333%}.row .large-5{position:relative;width:41.66667%}.row .large-6{position:relative;width:50%}.row .large-7{position:relative;width:58.33333%}.row .large-8{position:relative;width:66.66667%}.row .large-9{position:relative;width:75%}.row .large-10{position:relative;width:83.33333%}.row .large-11{position:relative;width:91.66667%}.row .large-12{position:relative;width:100%}.row .large-offset-1{position:relative;margin-left:8.33333%}.row .large-offset-2{position:relative;margin-left:16.66667%}.row .large-offset-3{position:relative;margin-left:25%}.row .large-offset-4{position:relative;margin-left:33.33333%}.row .large-offset-5{position:relative;margin-left:41.66667%}.row .large-offset-6{position:relative;margin-left:50%}.row .large-offset-7{position:relative;margin-left:58.33333%}.row .large-offset-8{position:relative;margin-left:66.66667%}.row .large-offset-9{position:relative;margin-left:75%}.row .large-offset-10{position:relative;margin-left:83.33333%}.push-2{position:relative;left:16.66667%;right:auto}.pull-2{position:relative;right:16.66667%;left:auto}.push-3{position:relative;left:25%;right:auto}.pull-3{position:relative;right:25%;left:auto}.push-4{position:relative;left:33.33333%;right:auto}.pull-4{position:relative;right:33.33333%;left:auto}.push-5{position:relative;left:41.66667%;right:auto}.pull-5{position:relative;right:41.66667%;left:auto}.push-6{position:relative;left:50%;right:auto}.pull-6{position:relative;right:50%;left:auto}.push-7{position:relative;left:58.33333%;right:auto}.pull-7{position:relative;right:58.33333%;left:auto}.push-8{position:relative;left:66.66667%;right:auto}.pull-8{position:relative;right:66.66667%;left:auto}.push-9{position:relative;left:75%;right:auto}.pull-9{position:relative;right:75%;left:auto}.push-10{position:relative;left:83.33333%;right:auto}.pull-10{position:relative;right:83.33333%;left:auto}.small-push-2{left:inherit}.small-pull-2{right:inherit}.small-push-3{left:inherit}.small-pull-3{right:inherit}.small-push-4{left:inherit}.small-pull-4{right:inherit}.small-push-5{left:inherit}.small-pull-5{right:inherit}.small-push-6{left:inherit}.small-pull-6{right:inherit}.small-push-7{left:inherit}.small-pull-7{right:inherit}.small-push-8{left:inherit}.small-pull-8{right:inherit}.small-push-9{left:inherit}.small-pull-9{right:inherit}.small-push-10{left:inherit}.small-pull-10{right:inherit}.column.large-centered,.columns.large-centered{position:relative;margin-left:auto;margin-right:auto;float:none !important}}.show-for-small,.show-for-medium-down,.show-for-large-down{display:inherit !important}.show-for-medium,.show-for-medium-up,.show-for-large,.show-for-large-up,.show-for-xlarge{display:none !important}.hide-for-medium,.hide-for-medium-up,.hide-for-large,.hide-for-large-up,.hide-for-xlarge{display:inherit !important}.hide-for-small,.hide-for-medium-down,.hide-for-large-down{display:none !important}table.show-for-small,table.show-for-medium-down,table.show-for-large-down,table.hide-for-medium,table.hide-for-medium-up,table.hide-for-large,table.hide-for-large-up,table.hide-for-xlarge{display:table}thead.show-for-small,thead.show-for-medium-down,thead.show-for-large-down,thead.hide-for-medium,thead.hide-for-medium-up,thead.hide-for-large,thead.hide-for-large-up,thead.hide-for-xlarge{display:table-header-group !important}tbody.show-for-small,tbody.show-for-medium-down,tbody.show-for-large-down,tbody.hide-for-medium,tbody.hide-for-medium-up,tbody.hide-for-large,tbody.hide-for-large-up,tbody.hide-for-xlarge{display:table-row-group !important}tr.show-for-small,tr.show-for-medium-down,tr.show-for-large-down,tr.hide-for-medium,tr.hide-for-medium-up,tr.hide-for-large,tr.hide-for-large-up,tr.hide-for-xlarge{display:table-row !important}td.show-for-small,td.show-for-medium-down,td.show-for-large-down,td.hide-for-medium,td.hide-for-medium-up,td.hide-for-large,td.hide-for-large-up,td.hide-for-xlarge,th.show-for-small,th.show-for-medium-down,th.show-for-large-down,th.hide-for-medium,th.hide-for-medium-up,th.hide-for-large,th.hide-for-large-up,th.hide-for-xlarge{display:table-cell !important}@media only screen and (min-width: 48em){.show-for-medium,.show-for-medium-up{display:inherit !important}.show-for-small{display:none !important}.hide-for-small{display:inherit !important}.hide-for-medium,.hide-for-medium-up{display:none !important}table.show-for-medium,table.show-for-medium-up,table.hide-for-small{display:table}thead.show-for-medium,thead.show-for-medium-up,thead.hide-for-small{display:table-header-group !important}tbody.show-for-medium,tbody.show-for-medium-up,tbody.hide-for-small{display:table-row-group !important}tr.show-for-medium,tr.show-for-medium-up,tr.hide-for-small{display:table-row !important}td.show-for-medium,td.show-for-medium-up,td.hide-for-small,th.show-for-medium,th.show-for-medium-up,th.hide-for-small{display:table-cell !important}}@media only screen and (min-width: 80em){.show-for-large,.show-for-large-up{display:inherit !important}.show-for-medium,.show-for-medium-down{display:none !important}.hide-for-medium,.hide-for-medium-down{display:inherit !important}.hide-for-large,.hide-for-large-up{display:none !important}table.show-for-large,table.show-for-large-up,table.hide-for-medium,table.hide-for-medium-down{display:table}thead.show-for-large,thead.show-for-large-up,thead.hide-for-medium,thead.hide-for-medium-down{display:table-header-group !important}tbody.show-for-large,tbody.show-for-large-up,tbody.hide-for-medium,tbody.hide-for-medium-down{display:table-row-group !important}tr.show-for-large,tr.show-for-large-up,tr.hide-for-medium,tr.hide-for-medium-down{display:table-row !important}td.show-for-large,td.show-for-large-up,td.hide-for-medium,td.hide-for-medium-down,th.show-for-large,th.show-for-large-up,th.hide-for-medium,th.hide-for-medium-down{display:table-cell !important}}@media only screen and (min-width: 90em){.show-for-xlarge{display:inherit !important}.show-for-large,.show-for-large-down{display:none !important}.hide-for-large,.hide-for-large-down{display:inherit !important}.hide-for-xlarge{display:none !important}table.show-for-xlarge,table.hide-for-large,table.hide-for-large-down{display:table}thead.show-for-xlarge,thead.hide-for-large,thead.hide-for-large-down{display:table-header-group !important}tbody.show-for-xlarge,tbody.hide-for-large,tbody.hide-for-large-down{display:table-row-group !important}tr.show-for-xlarge,tr.hide-for-large,tr.hide-for-large-down{display:table-row !important}td.show-for-xlarge,td.hide-for-large,td.hide-for-large-down,th.show-for-xlarge,th.hide-for-large,th.hide-for-large-down{display:table-cell !important}}.show-for-landscape,.hide-for-portrait{display:inherit !important}.hide-for-landscape,.show-for-portrait{display:none !important}table.hide-for-landscape,table.show-for-portrait{display:table}thead.hide-for-landscape,thead.show-for-portrait{display:table-header-group !important}tbody.hide-for-landscape,tbody.show-for-portrait{display:table-row-group !important}tr.hide-for-landscape,tr.show-for-portrait{display:table-row !important}td.hide-for-landscape,td.show-for-portrait,th.hide-for-landscape,th.show-for-portrait{display:table-cell !important}@media only screen and (orientation: landscape){.show-for-landscape,.hide-for-portrait{display:inherit !important}.hide-for-landscape,.show-for-portrait{display:none !important}table.show-for-landscape,table.hide-for-portrait{display:table}thead.show-for-landscape,thead.hide-for-portrait{display:table-header-group !important}tbody.show-for-landscape,tbody.hide-for-portrait{display:table-row-group !important}tr.show-for-landscape,tr.hide-for-portrait{display:table-row !important}td.show-for-landscape,td.hide-for-portrait,th.show-for-landscape,th.hide-for-portrait{display:table-cell !important}}@media only screen and (orientation: portrait){.show-for-portrait,.hide-for-landscape{display:inherit !important}.hide-for-portrait,.show-for-landscape{display:none !important}table.show-for-portrait,table.hide-for-landscape{display:table}thead.show-for-portrait,thead.hide-for-landscape{display:table-header-group !important}tbody.show-for-portrait,tbody.hide-for-landscape{display:table-row-group !important}tr.show-for-portrait,tr.hide-for-landscape{display:table-row !important}td.show-for-portrait,td.hide-for-landscape,th.show-for-portrait,th.hide-for-landscape{display:table-cell !important}}.show-for-touch{display:none !important}.hide-for-touch{display:inherit !important}.touch .show-for-touch{display:inherit !important}.touch .hide-for-touch{display:none !important}table.hide-for-touch{display:table}.touch table.show-for-touch{display:table}thead.hide-for-touch{display:table-header-group !important}.touch thead.show-for-touch{display:table-header-group !important}tbody.hide-for-touch{display:table-row-group !important}.touch tbody.show-for-touch{display:table-row-group !important}tr.hide-for-touch{display:table-row !important}.touch tr.show-for-touch{display:table-row !important}td.hide-for-touch{display:table-cell !important}.touch td.show-for-touch{display:table-cell !important}th.hide-for-touch{display:table-cell !important}.touch th.show-for-touch{display:table-cell !important}@media only screen{[class*="block-grid-"]{display:block;padding:0;margin:0 -10px;*zoom:1}[class*="block-grid-"]:before,[class*="block-grid-"]:after{content:" ";display:table}[class*="block-grid-"]:after{clear:both}[class*="block-grid-"]>li{display:block;height:auto;float:left;padding:0 10px 10px}.small-block-grid-1>li{width:100%;padding:0 10px 10px}.small-block-grid-1>li:nth-of-type(1n+1){clear:both}.small-block-grid-2>li{width:50%;padding:0 10px 10px}.small-block-grid-2>li:nth-of-type(2n+1){clear:both}.small-block-grid-3>li{width:33.33333%;padding:0 10px 10px}.small-block-grid-3>li:nth-of-type(3n+1){clear:both}.small-block-grid-4>li{width:25%;padding:0 10px 10px}.small-block-grid-4>li:nth-of-type(4n+1){clear:both}.small-block-grid-5>li{width:20%;padding:0 10px 10px}.small-block-grid-5>li:nth-of-type(5n+1){clear:both}.small-block-grid-6>li{width:16.66667%;padding:0 10px 10px}.small-block-grid-6>li:nth-of-type(6n+1){clear:both}.small-block-grid-7>li{width:14.28571%;padding:0 10px 10px}.small-block-grid-7>li:nth-of-type(7n+1){clear:both}.small-block-grid-8>li{width:12.5%;padding:0 10px 10px}.small-block-grid-8>li:nth-of-type(8n+1){clear:both}.small-block-grid-9>li{width:11.11111%;padding:0 10px 10px}.small-block-grid-9>li:nth-of-type(9n+1){clear:both}.small-block-grid-10>li{width:10%;padding:0 10px 10px}.small-block-grid-10>li:nth-of-type(10n+1){clear:both}.small-block-grid-11>li{width:9.09091%;padding:0 10px 10px}.small-block-grid-11>li:nth-of-type(11n+1){clear:both}.small-block-grid-12>li{width:8.33333%;padding:0 10px 10px}.small-block-grid-12>li:nth-of-type(12n+1){clear:both}}@media only screen and (min-width: 48em){.large-block-grid-1>li{width:100%;padding:0 10px 10px}.large-block-grid-1>li:nth-of-type(1n+1){clear:both}.large-block-grid-2>li{width:50%;padding:0 10px 10px}.large-block-grid-2>li:nth-of-type(2n+1){clear:both}.large-block-grid-3>li{width:33.33333%;padding:0 10px 10px}.large-block-grid-3>li:nth-of-type(3n+1){clear:both}.large-block-grid-4>li{width:25%;padding:0 10px 10px}.large-block-grid-4>li:nth-of-type(4n+1){clear:both}.large-block-grid-5>li{width:20%;padding:0 10px 10px}.large-block-grid-5>li:nth-of-type(5n+1){clear:both}.large-block-grid-6>li{width:16.66667%;padding:0 10px 10px}.large-block-grid-6>li:nth-of-type(6n+1){clear:both}.large-block-grid-7>li{width:14.28571%;padding:0 10px 10px}.large-block-grid-7>li:nth-of-type(7n+1){clear:both}.large-block-grid-8>li{width:12.5%;padding:0 10px 10px}.large-block-grid-8>li:nth-of-type(8n+1){clear:both}.large-block-grid-9>li{width:11.11111%;padding:0 10px 10px}.large-block-grid-9>li:nth-of-type(9n+1){clear:both}.large-block-grid-10>li{width:10%;padding:0 10px 10px}.large-block-grid-10>li:nth-of-type(10n+1){clear:both}.large-block-grid-11>li{width:9.09091%;padding:0 10px 10px}.large-block-grid-11>li:nth-of-type(11n+1){clear:both}.large-block-grid-12>li{width:8.33333%;padding:0 10px 10px}.large-block-grid-12>li:nth-of-type(12n+1){clear:both}[class*="small-block-grid-"]>li{clear:none !important}}p.lead{font-size:1.21875em;line-height:1.6}.subheader{line-height:1.4;color:#6f6f6f;font-weight:300;margin-top:0.2em;margin-bottom:0.5em}div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}a{color:#2ba6cb;text-decoration:none;line-height:inherit}a:hover,a:focus{color:#2795b6}a img{border:none}p{font-family:inherit;font-weight:normal;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}p aside{font-size:0.875em;line-height:1.35;font-style:italic}h1,h2,h3,h4,h5,h6{font-family:"Helvetica Neue","Helvetica",Helvetica,Arial,sans-serif;font-weight:bold;font-style:normal;color:#222;text-rendering:optimizeLegibility;margin-top:0.2em;margin-bottom:0.5em;line-height:1.2125em}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-size:60%;color:#6f6f6f;line-height:0}h1{font-size:2.125em}h2{font-size:1.6875em}h3{font-size:1.375em}h4{font-size:1.125em}h5{font-size:1.125em}h6{font-size:1em}hr{border:solid #ddd;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}em,i{font-style:italic;line-height:inherit}strong,b{font-weight:bold;line-height:inherit}small{font-size:60%;line-height:inherit}code{font-family:Consolas,"Liberation Mono",Courier,monospace;font-weight:bold;color:#7f0a0c}ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}ul.square{list-style-type:square}ul.circle{list-style-type:circle}ul.disc{list-style-type:disc}ul.no-bullet{list-style:none}ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}dl dt{margin-bottom:0.3em;font-weight:bold}dl dd{margin-bottom:0.75em}abbr,acronym{text-transform:uppercase;font-size:90%;color:#222;border-bottom:1px dotted #ddd;cursor:help}abbr{text-transform:none}blockquote{margin:0 0 1.25em;padding:0.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}blockquote cite{display:block;font-size:0.8125em;color:#555}blockquote cite:before{content:"\2014 \0020"}blockquote cite a,blockquote cite a:visited{color:#555}blockquote,blockquote p{line-height:1.6;color:#6f6f6f}.vcard{display:inline-block;margin:0 0 1.25em 0;border:1px solid #ddd;padding:0.625em 0.75em}.vcard li{margin:0;display:block}.vcard .fn{font-weight:bold;font-size:0.9375em}.vevent .summary{font-weight:bold}.vevent abbr{cursor:default;text-decoration:none;font-weight:bold;border:none;padding:0 0.0625em}@media only screen and (min-width: 48em){h1,h2,h3,h4,h5,h6{line-height:1.4}h1{font-size:2.75em}h2{font-size:2.3125em}h3{font-size:1.6875em}h4{font-size:1.4375em}}.print-only{display:none !important}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.hide-on-print{display:none !important}.print-only{display:block !important}.hide-for-print{display:none !important}.show-for-print{display:inherit !important}}button,.button{border-style:solid;border-width:1px;cursor:pointer;font-family:inherit;font-weight:bold;line-height:1;margin:0 0 1.25em;position:relative;text-decoration:none;text-align:center;display:inline-block;padding-top:0.75em;padding-right:1.5em;padding-bottom:0.8125em;padding-left:1.5em;font-size:1em;background-color:#2ba6cb;border-color:#2284a1;color:#fff}button:hover,button:focus,.button:hover,.button:focus{background-color:#2284a1}button:hover,button:focus,.button:hover,.button:focus{color:#fff}button.secondary,.button.secondary{background-color:#e9e9e9;border-color:#d0d0d0;color:#333}button.secondary:hover,button.secondary:focus,.button.secondary:hover,.button.secondary:focus{background-color:#d0d0d0}button.secondary:hover,button.secondary:focus,.button.secondary:hover,.button.secondary:focus{color:#333}button.success,.button.success{background-color:#5da423;border-color:#457a1a;color:#fff}button.success:hover,button.success:focus,.button.success:hover,.button.success:focus{background-color:#457a1a}button.success:hover,button.success:focus,.button.success:hover,.button.success:focus{color:#fff}button.alert,.button.alert{background-color:#c60f13;border-color:#970b0e;color:#fff}button.alert:hover,button.alert:focus,.button.alert:hover,.button.alert:focus{background-color:#970b0e}button.alert:hover,button.alert:focus,.button.alert:hover,.button.alert:focus{color:#fff}button.large,.button.large{padding-top:1em;padding-right:2em;padding-bottom:1.0625em;padding-left:2em;font-size:1.25em}button.small,.button.small{padding-top:0.5625em;padding-right:1.125em;padding-bottom:0.625em;padding-left:1.125em;font-size:0.8125em}button.tiny,.button.tiny{padding-top:0.4375em;padding-right:0.875em;padding-bottom:0.5em;padding-left:0.875em;font-size:0.6875em}button.expand,.button.expand{padding-top:false;padding-right:0px;padding-bottom:false0.0625em;padding-left:0px;width:100%}button.left-align,.button.left-align{text-align:left;text-indent:0.75em}button.right-align,.button.right-align{text-align:right;padding-right:0.75em}button.disabled,button[disabled],.button.disabled,.button[disabled]{background-color:#2ba6cb;border-color:#2284a1;color:#fff;cursor:default;opacity:0.6;-webkit-box-shadow:none;box-shadow:none}button.disabled:hover,button.disabled:focus,button[disabled]:hover,button[disabled]:focus,.button.disabled:hover,.button.disabled:focus,.button[disabled]:hover,.button[disabled]:focus{background-color:#2284a1}button.disabled:hover,button.disabled:focus,button[disabled]:hover,button[disabled]:focus,.button.disabled:hover,.button.disabled:focus,.button[disabled]:hover,.button[disabled]:focus{color:#fff}button.disabled:hover,button.disabled:focus,button[disabled]:hover,button[disabled]:focus,.button.disabled:hover,.button.disabled:focus,.button[disabled]:hover,.button[disabled]:focus{background-color:#2ba6cb}button.disabled.secondary,button[disabled].secondary,.button.disabled.secondary,.button[disabled].secondary{background-color:#e9e9e9;border-color:#d0d0d0;color:#333;cursor:default;opacity:0.6;-webkit-box-shadow:none;box-shadow:none}button.disabled.secondary:hover,button.disabled.secondary:focus,button[disabled].secondary:hover,button[disabled].secondary:focus,.button.disabled.secondary:hover,.button.disabled.secondary:focus,.button[disabled].secondary:hover,.button[disabled].secondary:focus{background-color:#d0d0d0}button.disabled.secondary:hover,button.disabled.secondary:focus,button[disabled].secondary:hover,button[disabled].secondary:focus,.button.disabled.secondary:hover,.button.disabled.secondary:focus,.button[disabled].secondary:hover,.button[disabled].secondary:focus{color:#333}button.disabled.secondary:hover,button.disabled.secondary:focus,button[disabled].secondary:hover,button[disabled].secondary:focus,.button.disabled.secondary:hover,.button.disabled.secondary:focus,.button[disabled].secondary:hover,.button[disabled].secondary:focus{background-color:#e9e9e9}button.disabled.success,button[disabled].success,.button.disabled.success,.button[disabled].success{background-color:#5da423;border-color:#457a1a;color:#fff;cursor:default;opacity:0.6;-webkit-box-shadow:none;box-shadow:none}button.disabled.success:hover,button.disabled.success:focus,button[disabled].success:hover,button[disabled].success:focus,.button.disabled.success:hover,.button.disabled.success:focus,.button[disabled].success:hover,.button[disabled].success:focus{background-color:#457a1a}button.disabled.success:hover,button.disabled.success:focus,button[disabled].success:hover,button[disabled].success:focus,.button.disabled.success:hover,.button.disabled.success:focus,.button[disabled].success:hover,.button[disabled].success:focus{color:#fff}button.disabled.success:hover,button.disabled.success:focus,button[disabled].success:hover,button[disabled].success:focus,.button.disabled.success:hover,.button.disabled.success:focus,.button[disabled].success:hover,.button[disabled].success:focus{background-color:#5da423}button.disabled.alert,button[disabled].alert,.button.disabled.alert,.button[disabled].alert{background-color:#c60f13;border-color:#970b0e;color:#fff;cursor:default;opacity:0.6;-webkit-box-shadow:none;box-shadow:none}button.disabled.alert:hover,button.disabled.alert:focus,button[disabled].alert:hover,button[disabled].alert:focus,.button.disabled.alert:hover,.button.disabled.alert:focus,.button[disabled].alert:hover,.button[disabled].alert:focus{background-color:#970b0e}button.disabled.alert:hover,button.disabled.alert:focus,button[disabled].alert:hover,button[disabled].alert:focus,.button.disabled.alert:hover,.button.disabled.alert:focus,.button[disabled].alert:hover,.button[disabled].alert:focus{color:#fff}button.disabled.alert:hover,button.disabled.alert:focus,button[disabled].alert:hover,button[disabled].alert:focus,.button.disabled.alert:hover,.button.disabled.alert:focus,.button[disabled].alert:hover,.button[disabled].alert:focus{background-color:#c60f13}input.button,button.button{padding-top:0.8125em;padding-bottom:0.75em}input.button.tiny,button.button.tiny{padding-top:0.5em;padding-bottom:0.4375em}input.button.small,button.button.small{padding-top:0.625em;padding-bottom:0.5625em}input.button.large,button.button.large{padding-top:1.03125em;padding-bottom:1.03125em}@media only screen{.button{-webkit-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;-webkit-transition:background-color 300ms ease-out;-moz-transition:background-color 300ms ease-out;transition:background-color 300ms ease-out}.button:active{-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.2) inset;box-shadow:0 1px 0 rgba(0,0,0,0.2) inset}.button.radius{-webkit-border-radius:3px;border-radius:3px}.button.round{-webkit-border-radius:1000px;border-radius:1000px}}@media only screen and (min-width: 48em){.button{display:inline-block}}form{margin:0 0 1em}form .row .row{margin:-0.5em}form .row .row .column,form .row .row .columns{padding:0 0.5em}form .row .row.collapse{margin:0}form .row .row.collapse .column,form .row .row.collapse .columns{padding:0}form .row input.column,form .row input.columns{padding-left:0.5em}label{font-size:0.875em;color:#4d4d4d;cursor:pointer;display:block;font-weight:500;margin-bottom:0.1875em}label.right{float:none;text-align:right}label.inline{margin:0 0 1em 0;padding:0.625em 0}.prefix,.postfix{display:block;position:relative;z-index:2;text-align:center;width:100%;padding-top:0;padding-bottom:0;border-style:solid;border-width:1px;overflow:hidden;font-size:0.875em;height:2.3125em;line-height:2.3125em}.postfix.button{padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;text-align:center;line-height:2.125em}.prefix.button{padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;text-align:center;line-height:2.125em}.prefix.button.radius{-webkit-border-radius:0;border-radius:0;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px;-webkit-border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-bottom-left-radius:3px;border-top-left-radius:3px}.postfix.button.radius{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px;-webkit-border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-top-right-radius:3px;border-bottom-right-radius:3px}.prefix.button.round{-webkit-border-radius:0;border-radius:0;-moz-border-radius-bottomleft:1000px;-moz-border-radius-topleft:1000px;-webkit-border-bottom-left-radius:1000px;-webkit-border-top-left-radius:1000px;border-bottom-left-radius:1000px;border-top-left-radius:1000px}.postfix.button.round{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:1000px;-moz-border-radius-bottomright:1000px;-webkit-border-top-right-radius:1000px;-webkit-border-bottom-right-radius:1000px;border-top-right-radius:1000px;border-bottom-right-radius:1000px}span.prefix{background:#f2f2f2;border-color:#d9d9d9;border-right:none;color:#333}span.prefix.radius{-webkit-border-radius:0;border-radius:0;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px;-webkit-border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-bottom-left-radius:3px;border-top-left-radius:3px}span.postfix{background:#f2f2f2;border-color:#ccc;border-left:none;color:#333}span.postfix.radius{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px;-webkit-border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-top-right-radius:3px;border-bottom-right-radius:3px}.input-group.radius>*:first-child,.input-group.radius>*:first-child *{-webkit-border-radius:0;border-radius:0;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px;-webkit-border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-bottom-left-radius:3px;border-top-left-radius:3px}.input-group.radius>*:last-child,.input-group.radius>*:last-child *{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px;-webkit-border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-top-right-radius:3px;border-bottom-right-radius:3px}.input-group.round>*:first-child,.input-group.round>*:first-child *{-webkit-border-radius:0;border-radius:0;-moz-border-radius-bottomleft:1000px;-moz-border-radius-topleft:1000px;-webkit-border-bottom-left-radius:1000px;-webkit-border-top-left-radius:1000px;border-bottom-left-radius:1000px;border-top-left-radius:1000px}.input-group.round>*:last-child,.input-group.round>*:last-child *{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:1000px;-moz-border-radius-bottomright:1000px;-webkit-border-top-right-radius:1000px;-webkit-border-bottom-right-radius:1000px;border-top-right-radius:1000px;border-bottom-right-radius:1000px}input[type="text"],input[type="password"],input[type="date"],input[type="datetime"],input[type="datetime-local"],input[type="month"],input[type="week"],input[type="email"],input[type="number"],input[type="search"],input[type="tel"],input[type="time"],input[type="url"],textarea{background-color:#fff;font-family:inherit;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);color:rgba(0,0,0,0.75);display:block;font-size:0.875em;margin:0 0 1em 0;padding:0.5em;height:2.3125em;width:100%;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-transition:all 0.15s linear;-moz-transition:all 0.15s linear;transition:all 0.15s linear}input[type="text"]:focus,input[type="password"]:focus,input[type="date"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="month"]:focus,input[type="week"]:focus,input[type="email"]:focus,input[type="number"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="time"]:focus,input[type="url"]:focus,textarea:focus{background:#fafafa;border-color:#999;outline:none}input[type="text"][disabled],input[type="password"][disabled],input[type="date"][disabled],input[type="datetime"][disabled],input[type="datetime-local"][disabled],input[type="month"][disabled],input[type="week"][disabled],input[type="email"][disabled],input[type="number"][disabled],input[type="search"][disabled],input[type="tel"][disabled],input[type="time"][disabled],input[type="url"][disabled],textarea[disabled]{background-color:#ddd}fieldset{border:solid 1px #ddd;padding:1.25em;margin:1.125em 0}fieldset legend{font-weight:bold;background:#fff;padding:0 0.1875em;margin:0;margin-left:-0.1875em}.error input,input.error,.error textarea,textarea.error{border-color:#c60f13;background-color:rgba(198,15,19,0.1)}.error input:focus,input.error:focus,.error textarea:focus,textarea.error:focus{background:#fafafa;border-color:#999}.error label,label.error{color:#c60f13}.error small,small.error{display:block;padding:0.375em 0.25em;margin-top:-1.3125em;margin-bottom:1em;font-size:0.75em;font-weight:bold;background:#c60f13;color:#fff}form.custom .custom{display:inline-block;width:16px;height:16px;position:relative;top:2px;border:solid 1px #ccc;background:#fff}form.custom .custom.radio{-webkit-border-radius:1000px;border-radius:1000px}form.custom .custom.checkbox:before{content:"";display:block;line-height:0.8;height:14px;width:14px;text-align:center;position:absolute;top:0;left:0;font-size:14px;color:#fff}form.custom .custom.radio.checked:before{content:"";display:block;width:8px;height:8px;-webkit-border-radius:1000px;border-radius:1000px;background:#222;position:relative;top:3px;left:3px}form.custom .custom.checkbox.checked:before{content:"\00d7";color:#222}form.custom .custom.dropdown{display:block;position:relative;top:0;height:2.3125em;margin-bottom:1.25em;margin-top:0px;padding:0px;width:100%;background:#fff;background:-moz-linear-gradient(top, #fff 0%, #f3f3f3 100%);background:-webkit-linear-gradient(top, #fff 0%, #f3f3f3 100%);background:linear-gradient(to bottom, #fff 0%, #f3f3f3 100%);-webkit-box-shadow:none;box-shadow:none;font-size:0.875em;vertical-align:top}form.custom .custom.dropdown ul{overflow-y:auto;max-height:200px}form.custom .custom.dropdown .current{cursor:default;white-space:nowrap;line-height:2.25em;color:rgba(0,0,0,0.75);text-decoration:none;overflow:hidden;display:block;margin-left:0.5em;margin-right:2.3125em}form.custom .custom.dropdown .selector{cursor:default;position:absolute;width:2.5em;height:2.3125em;display:block;right:0;top:0}form.custom .custom.dropdown .selector:after{content:"";display:block;content:"";display:block;width:0;height:0;border:solid 5px;border-color:#aaa transparent transparent transparent;position:absolute;left:0.9375em;top:50%;margin-top:-3px}form.custom .custom.dropdown:hover a.selector:after,form.custom .custom.dropdown.open a.selector:after{content:"";display:block;width:0;height:0;border:solid 5px;border-color:#222 transparent transparent transparent}form.custom .custom.dropdown .disabled{color:#888}form.custom .custom.dropdown .disabled:hover{background:transparent;color:#888}form.custom .custom.dropdown .disabled:hover:after{display:none}form.custom .custom.dropdown.open ul{display:block;z-index:10;min-width:100%;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}form.custom .custom.dropdown.small{max-width:134px}form.custom .custom.dropdown.medium{max-width:254px}form.custom .custom.dropdown.large{max-width:434px}form.custom .custom.dropdown.expand{width:100% !important}form.custom .custom.dropdown.open.small ul{min-width:134px;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}form.custom .custom.dropdown.open.medium ul{min-width:254px;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}form.custom .custom.dropdown.open.large ul{min-width:434px;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}form.custom .custom.dropdown ul{position:absolute;width:auto;display:none;margin:0;left:-1px;top:auto;-webkit-box-shadow:0 2px 2px 0px rgba(0,0,0,0.1);box-shadow:0 2px 2px 0px rgba(0,0,0,0.1);margin:0;padding:0;background:#fff;border:solid 1px #ccc;font-size:16px}form.custom .custom.dropdown ul li{color:#555;font-size:0.875em;cursor:default;padding-top:0.25em;padding-bottom:0.25em;padding-left:0.375em;padding-right:2.375em;min-height:1.5em;line-height:1.5em;margin:0;white-space:nowrap;list-style:none}form.custom .custom.dropdown ul li.selected{background:#eee;color:#000}form.custom .custom.dropdown ul li:hover{background-color:#e4e4e4;color:#000}form.custom .custom.dropdown ul li.selected:hover{background:#eee;cursor:default;color:#000}form.custom .custom.dropdown ul.show{display:block}form.custom .custom.disabled{background-color:#ddd}.button-group{list-style:none;margin:0;*zoom:1}.button-group:before,.button-group:after{content:" ";display:table}.button-group:after{clear:both}.button-group>*{margin:0 0 0 -1px;float:left}.button-group>*:first-child{margin-left:0}.button-group.radius>*:first-child,.button-group.radius>*:first-child>a,.button-group.radius>*:first-child>button{-webkit-border-radius:0;border-radius:0;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px;-webkit-border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-bottom-left-radius:3px;border-top-left-radius:3px}.button-group.radius>*:last-child,.button-group.radius>*:last-child>a,.button-group.radius>*:last-child>button{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px;-webkit-border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-top-right-radius:3px;border-bottom-right-radius:3px}.button-group.round>*:first-child,.button-group.round>*:first-child>a,.button-group.round>*:first-child>button{-webkit-border-radius:0;border-radius:0;-moz-border-radius-bottomleft:1000px;-moz-border-radius-topleft:1000px;-webkit-border-bottom-left-radius:1000px;-webkit-border-top-left-radius:1000px;border-bottom-left-radius:1000px;border-top-left-radius:1000px}.button-group.round>*:last-child,.button-group.round>*:last-child>a,.button-group.round>*:last-child>button{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:1000px;-moz-border-radius-bottomright:1000px;-webkit-border-top-right-radius:1000px;-webkit-border-bottom-right-radius:1000px;border-top-right-radius:1000px;border-bottom-right-radius:1000px}.button-group.even-2 li{width:50%}.button-group.even-2 li .button{width:100%}.button-group.even-3 li{width:33.33333%}.button-group.even-3 li .button{width:100%}.button-group.even-4 li{width:25%}.button-group.even-4 li .button{width:100%}.button-group.even-5 li{width:20%}.button-group.even-5 li .button{width:100%}.button-group.even-6 li{width:16.66667%}.button-group.even-6 li .button{width:100%}.button-group.even-7 li{width:14.28571%}.button-group.even-7 li .button{width:100%}.button-group.even-8 li{width:12.5%}.button-group.even-8 li .button{width:100%}.button-bar{*zoom:1}.button-bar:before,.button-bar:after{content:" ";display:table}.button-bar:after{clear:both}.button-bar .button-group{float:left;margin-right:0.625em}.button-bar .button-group div{overflow:hidden}.dropdown.button{position:relative;padding-right:3.1875em}.dropdown.button:before{position:absolute;content:"";width:0;height:0;display:block;border-style:solid;border-color:#fff transparent transparent transparent;top:50%}.dropdown.button:before{border-width:0.5625em;right:1.5em;margin-top:-0.25em}.dropdown.button:before{border-color:#fff transparent transparent transparent}.dropdown.button.tiny{padding-right:2.1875em}.dropdown.button.tiny:before{border-width:0.4375em;right:0.875em;margin-top:-0.15625em}.dropdown.button.tiny:before{border-color:#fff transparent transparent transparent}.dropdown.button.small{padding-right:2.8125em}.dropdown.button.small:before{border-width:0.5625em;right:1.125em;margin-top:-0.21875em}.dropdown.button.small:before{border-color:#fff transparent transparent transparent}.dropdown.button.large{padding-right:4em}.dropdown.button.large:before{border-width:0.625em;right:1.75em;margin-top:-0.3125em}.dropdown.button.large:before{border-color:#fff transparent transparent transparent}.dropdown.button.secondary:before{border-color:#333 transparent transparent transparent}.split.button{position:relative;padding-right:4.8em}.split.button span{display:block;height:100%;position:absolute;right:0;top:0;border-left:solid 1px}.split.button span:before{position:absolute;content:"";width:0;height:0;display:block;border-style:solid;left:50%}.split.button span:active{background-color:rgba(0,0,0,0.1)}.split.button span{border-left-color:#1e728c}.split.button span{width:3em}.split.button span:before{border-width:0.5625em;top:1.125em;margin-left:-0.5625em}.split.button span:before{border-color:#fff transparent transparent transparent}.split.button.secondary span{border-left-color:#c3c3c3}.split.button.secondary span:before{border-color:#fff transparent transparent transparent}.split.button.alert span{border-left-color:#7f0a0c}.split.button.success span{border-left-color:#396516}.split.button.tiny{padding-right:3.9375em}.split.button.tiny span{width:2.84375em}.split.button.tiny span:before{border-width:0.4375em;top:0.875em;margin-left:-0.3125em}.split.button.small{padding-right:3.9375em}.split.button.small span{width:2.8125em}.split.button.small span:before{border-width:0.5625em;top:0.84375em;margin-left:-0.5625em}.split.button.large{padding-right:6em}.split.button.large span{width:3.75em}.split.button.large span:before{border-width:0.625em;top:1.3125em;margin-left:-0.5625em}.split.button.secondary span:before{border-color:#333 transparent transparent transparent}.split.button.radius span{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px;-webkit-border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-top-right-radius:3px;border-bottom-right-radius:3px}.split.button.round span{-webkit-border-radius:0;border-radius:0;-moz-border-radius-topright:1000px;-moz-border-radius-bottomright:1000px;-webkit-border-top-right-radius:1000px;-webkit-border-bottom-right-radius:1000px;border-top-right-radius:1000px;border-bottom-right-radius:1000px}.flex-video{position:relative;padding-top:1.5625em;padding-bottom:67.5%;height:0;margin-bottom:1em;overflow:hidden}.flex-video.widescreen{padding-bottom:57.25%}.flex-video.vimeo{padding-top:0}.flex-video iframe,.flex-video object,.flex-video embed,.flex-video video{position:absolute;top:0;left:0;width:100%;height:100%}.section-container,.section-container.auto{width:100%;display:block;margin-bottom:1.25em;border:1px solid #ccc;border-top:none}.section-container section,.section-container .section,.section-container.auto section,.section-container.auto .section{border-top:1px solid #ccc;position:relative}.section-container section .title,.section-container .section .title,.section-container.auto section .title,.section-container.auto .section .title{top:0;cursor:pointer;width:100%;margin:0;background-color:#efefef}.section-container section .title a,.section-container .section .title a,.section-container.auto section .title a,.section-container.auto .section .title a{padding:0.9375em;display:inline-block;color:#333;font-size:0.875em;white-space:nowrap;width:100%}.section-container section .title:hover,.section-container .section .title:hover,.section-container.auto section .title:hover,.section-container.auto .section .title:hover{background-color:#e2e2e2}.section-container section .content,.section-container .section .content,.section-container.auto section .content,.section-container.auto .section .content{display:none;padding:0.9375em;background-color:#fff}.section-container section .content>*:last-child,.section-container .section .content>*:last-child,.section-container.auto section .content>*:last-child,.section-container.auto .section .content>*:last-child{margin-bottom:0}.section-container section .content>*:first-child,.section-container .section .content>*:first-child,.section-container.auto section .content>*:first-child,.section-container.auto .section .content>*:first-child{padding-top:0}.section-container section .content>*:last-child,.section-container .section .content>*:last-child,.section-container.auto section .content>*:last-child,.section-container.auto .section .content>*:last-child{padding-bottom:0}.section-container section.active .content,.section-container .section.active .content,.section-container.auto section.active .content,.section-container.auto .section.active .content{display:block}.section-container section.active .title,.section-container .section.active .title,.section-container.auto section.active .title,.section-container.auto .section.active .title{background:#d5d5d5}.section-container.tabs{border:0;position:relative}.section-container.tabs section,.section-container.tabs .section{padding-top:0;border:0;position:static}.section-container.tabs section .title,.section-container.tabs .section .title{width:auto;border:1px solid #ccc;border-right:0;border-bottom:0;position:absolute;z-index:1}.section-container.tabs section .title a,.section-container.tabs .section .title a{width:100%}.section-container.tabs section:last-child .title,.section-container.tabs .section:last-child .title{border-right:1px solid #ccc}.section-container.tabs section .content,.section-container.tabs .section .content{border:1px solid #ccc;position:absolute;z-index:10;top:-1px}.section-container.tabs section.active .title,.section-container.tabs .section.active .title{background-color:#fff;z-index:11;border-bottom:0}.section-container.tabs section.active .content,.section-container.tabs .section.active .content{position:relative}@media only screen and (min-width: 48em){.section-container.auto{border:0;position:relative}.section-container.auto section,.section-container.auto .section{padding-top:0;border:0;position:static}.section-container.auto section .title,.section-container.auto .section .title{width:auto;border:1px solid #ccc;border-right:0;border-bottom:0;position:absolute;z-index:1}.section-container.auto section .title a,.section-container.auto .section .title a{width:100%}.section-container.auto section:last-child .title,.section-container.auto .section:last-child .title{border-right:1px solid #ccc}.section-container.auto section .content,.section-container.auto .section .content{border:1px solid #ccc;position:absolute;z-index:10;top:-1px}.section-container.auto section.active .title,.section-container.auto .section.active .title{background-color:#fff;z-index:11;border-bottom:0}.section-container.auto section.active .content,.section-container.auto .section.active .content{position:relative}.section-container.accordion .section{padding-top:0 !important}.section-container.vertical-nav{border:1px solid #ccc;border-top:none}.section-container.vertical-nav section,.section-container.vertical-nav .section{padding-top:0 !important}.section-container.vertical-nav section .title a,.section-container.vertical-nav .section .title a{display:block;width:100%}.section-container.vertical-nav section .content,.section-container.vertical-nav .section .content{display:none}.section-container.vertical-nav section.active .content,.section-container.vertical-nav .section.active .content{display:block;position:absolute;left:100%;top:-1px;z-index:999;min-width:12.5em;border:1px solid #ccc}.section-container.horizontal-nav{position:relative;background:#efefef;border:1px solid #ccc}.section-container.horizontal-nav section,.section-container.horizontal-nav .section{padding-top:0;border:0;position:static}.section-container.horizontal-nav section .title,.section-container.horizontal-nav .section .title{width:auto;border:1px solid #ccc;border-left:0;top:-1px;position:absolute;z-index:1}.section-container.horizontal-nav section .title a,.section-container.horizontal-nav .section .title a{width:100%}.section-container.horizontal-nav section .content,.section-container.horizontal-nav .section .content{display:none}.section-container.horizontal-nav section.active .content,.section-container.horizontal-nav .section.active .content{display:block;position:absolute;z-index:999;left:0;top:-2px;min-width:12.5em;border:1px solid #ccc}}.contain-to-grid{width:100%;background:#111}.fixed{width:100%;left:0;position:fixed;top:0;z-index:99}.top-bar{overflow:hidden;height:45px;line-height:45px;position:relative;background:#111;margin-bottom:1.875em}.top-bar ul{margin-bottom:0;list-style:none}.top-bar .row{max-width:none}.top-bar form,.top-bar input{margin-bottom:0}.top-bar input{height:2.45em}.top-bar .button{padding-top:.5em;padding-bottom:.5em;margin-bottom:0}.top-bar .title-area{position:relative}.top-bar .name{height:45px;margin:0;font-size:16px}.top-bar .name h1{line-height:45px;font-size:1.0625em;margin:0}.top-bar .name h1 a{font-weight:bold;color:#fff;width:50%;display:block;padding:0 15px}.top-bar .toggle-topbar{position:absolute;right:0;top:0}.top-bar .toggle-topbar a{color:#fff;text-transform:uppercase;font-size:0.8125em;font-weight:bold;position:relative;display:block;padding:0 15px;height:45px;line-height:45px}.top-bar .toggle-topbar.menu-icon{right:15px;top:50%;margin-top:-16px;padding-left:40px}.top-bar .toggle-topbar.menu-icon a{text-indent:-48px;width:34px;height:34px;line-height:33px;padding:0;color:#fff}.top-bar .toggle-topbar.menu-icon a span{position:absolute;right:0;display:block;width:16px;height:0;-webkit-box-shadow:0 10px 0 1px #fff,0 16px 0 1px #fff,0 22px 0 1px #fff;box-shadow:0 10px 0 1px #fff,0 16px 0 1px #fff,0 22px 0 1px #fff}.top-bar.expanded{height:auto;background:transparent}.top-bar.expanded .title-area{background:#111}.top-bar.expanded .toggle-topbar a{color:#888}.top-bar.expanded .toggle-topbar a span{-webkit-box-shadow:0 10px 0 1px #888,0 16px 0 1px #888,0 22px 0 1px #888;box-shadow:0 10px 0 1px #888,0 16px 0 1px #888,0 22px 0 1px #888}.top-bar-section{left:0;position:relative;width:auto;-webkit-transition:left 300ms ease-out;-moz-transition:left 300ms ease-out;transition:left 300ms ease-out}.top-bar-section ul{width:100%;height:auto;display:block;background:#333;font-size:16px;margin:0}.top-bar-section .divider{border-bottom:solid 1px #4d4d4d;border-top:solid 1px #1a1a1a;clear:both;height:1px;width:100%}.top-bar-section ul li>a{display:block;width:100%;color:#fff;padding:12px 0 12px 0;padding-left:15px;font-size:0.8125em;font-weight:bold;background:#333;height:45px}.top-bar-section ul li>a:hover{background:#2b2b2b}.top-bar-section ul li>a.button{background:#2ba6cb;font-size:0.8125em}.top-bar-section ul li>a.button:hover{background:#2284a1}.top-bar-section ul li>a.button.secondary{background:#e9e9e9}.top-bar-section ul li>a.button.secondary:hover{background:#d0d0d0}.top-bar-section ul li>a.button.success{background:#5da423}.top-bar-section ul li>a.button.success:hover{background:#457a1a}.top-bar-section ul li>a.button.alert{background:#c60f13}.top-bar-section ul li>a.button.alert:hover{background:#970b0e}.top-bar-section ul li.active>a{background:#2b2b2b}.top-bar-section .has-form{padding:15px}.top-bar-section .has-dropdown{position:relative}.top-bar-section .has-dropdown>a:after{content:"";display:block;width:0;height:0;border:solid 5px;border-color:transparent transparent transparent rgba(255,255,255,0.5);margin-right:15px;margin-top:-4.5px;position:absolute;top:22px;right:0}.top-bar-section .has-dropdown.moved{position:static}.top-bar-section .has-dropdown.moved>.dropdown{visibility:visible}.top-bar-section .dropdown{position:absolute;left:100%;top:0;visibility:hidden;z-index:99}.top-bar-section .dropdown li{width:100%}.top-bar-section .dropdown li a{font-weight:normal;padding:8px 15px}.top-bar-section .dropdown li.title h5{margin-bottom:0}.top-bar-section .dropdown li.title h5 a{color:#fff;line-height:22.5px;display:block}.top-bar-section .dropdown label{padding:8px 15px 2px;margin-bottom:0;text-transform:uppercase;color:#555;font-weight:bold;font-size:0.625em}.top-bar-js-breakpoint{width:58.75em !important;visibility:hidden}.js-generated{display:block}@media only screen and (min-width: 58.75em){.top-bar{background:#111;*zoom:1;overflow:visible}.top-bar:before,.top-bar:after{content:" ";display:table}.top-bar:after{clear:both}.top-bar .toggle-topbar{display:none}.top-bar .title-area{float:left}.top-bar .name h1 a{width:auto}.top-bar input,.top-bar .button{line-height:2em;font-size:0.875em;height:2em;padding:0 10px;position:relative;top:8px}.top-bar.expanded{background:#111}.contain-to-grid .top-bar{max-width:62.5em;margin:0 auto}.top-bar-section{-webkit-transition:none 0 0;-moz-transition:none 0 0;transition:none 0 0;left:0 !important}.top-bar-section ul{width:auto;height:auto !important;display:inline}.top-bar-section ul li{float:left}.top-bar-section ul li .js-generated{display:none}.top-bar-section li a:not(.button){padding:0 15px;line-height:45px;background:#111}.top-bar-section li a:not(.button):hover{background:#000}.top-bar-section .has-dropdown>a{padding-right:35px !important}.top-bar-section .has-dropdown>a:after{content:"";display:block;width:0;height:0;border:solid 5px;border-color:rgba(255,255,255,0.5) transparent transparent transparent;margin-top:-2.5px}.top-bar-section .has-dropdown.moved{position:relative}.top-bar-section .has-dropdown.moved>.dropdown{visibility:hidden}.top-bar-section .has-dropdown:hover>.dropdown,.top-bar-section .has-dropdown:active>.dropdown{visibility:visible}.top-bar-section .has-dropdown .dropdown li.has-dropdown>a:after{border:none;content:"\00bb";margin-top:-7px;right:5px}.top-bar-section .dropdown{left:0;top:auto;background:transparent;min-width:100%}.top-bar-section .dropdown li a{color:#fff;line-height:1;white-space:nowrap;padding:7px 15px;background:#1e1e1e}.top-bar-section .dropdown li label{white-space:nowrap;background:#1e1e1e}.top-bar-section .dropdown li .dropdown{left:100%;top:0}.top-bar-section>ul>.divider{border-bottom:none;border-top:none;border-right:solid 1px #2b2b2b;border-left:solid 1px #000;clear:none;height:45px;width:0px}.top-bar-section .has-form{background:#111;padding:0 15px;height:45px}.top-bar-section ul.right li .dropdown{left:auto;right:0}.top-bar-section ul.right li .dropdown li .dropdown{right:100%}}.orbit-container{overflow:hidden;width:100%;position:relative;background:#f5f5f5}.orbit-container .orbit-slides-container{list-style:none;margin:0;padding:0;position:relative}.orbit-container .orbit-slides-container img{display:block}.orbit-container .orbit-slides-container>*{position:relative;float:left;height:100%}.orbit-container .orbit-slides-container>* .orbit-caption{position:absolute;bottom:0;background-color:#000;background-color:rgba(0,0,0,0.6);color:#fff;width:100%;padding:10px 14px;font-size:0.875em}.orbit-container .orbit-slides-container>* .orbit-caption *{color:#fff}.orbit-container .orbit-slide-number{position:absolute;top:10px;left:10px;font-size:12px}.orbit-container .orbit-slide-number span{font-weight:700}.orbit-container .orbit-timer{position:absolute;top:10px;right:10px;height:6px;width:100px}.orbit-container .orbit-timer .orbit-progress{height:100%;background-color:#000;background-color:rgba(0,0,0,0.6);display:block;width:0%}.orbit-container .orbit-timer>span{display:none;position:absolute;top:10px;right:0px;width:11px;height:14px;border:solid 4px #000;border-top:none;border-bottom:none}.orbit-container .orbit-timer.paused>span{right:-6px;top:9px;width:11px;height:14px;border:solid 8px;border-color:transparent transparent transparent #000}.orbit-container:hover .orbit-timer>span{display:block}.orbit-container .orbit-prev,.orbit-container .orbit-next{position:absolute;top:50%;margin-top:-25px;background-color:#000;background-color:rgba(0,0,0,0.6);width:50px;height:60px;line-height:50px;color:white;text-indent:-9999px !important}.orbit-container .orbit-prev>span,.orbit-container .orbit-next>span{position:absolute;top:50%;margin-top:-16px;display:block;width:0;height:0;border:solid 16px}.orbit-container .orbit-prev{left:0}.orbit-container .orbit-prev>span{border-color:transparent;border-right-color:#fff}.orbit-container .orbit-prev:hover>span{border-right-color:#ccc}.orbit-container .orbit-next{right:0}.orbit-container .orbit-next>span{border-color:transparent;border-left-color:#fff;left:50%;margin-left:-8px}.orbit-container .orbit-next:hover>span{border-left-color:#ccc}.orbit-bullets{margin:0 auto 30px auto;overflow:hidden;position:relative;top:10px}.orbit-bullets li{display:block;width:18px;height:18px;background:#fff;float:left;margin-right:6px;border:solid 2px #000;-webkit-border-radius:1000px;border-radius:1000px}.orbit-bullets li.active{background:#000}.orbit-bullets li:last-child{margin-right:0}.touch .orbit-container .orbit-prev,.touch .orbit-container .orbit-next{display:none}.touch .orbit-bullets{display:none}@media only screen and (min-width: 48em){.touch .orbit-container .orbit-prev,.touch .orbit-container .orbit-next{display:inherit}.touch .orbit-bullets{display:block}}.reveal-modal-bg{position:fixed;height:100%;width:100%;background:#000;background:rgba(0,0,0,0.45);z-index:98;display:none;top:0;left:0}.reveal-modal{visibility:hidden;display:none;position:absolute;left:50%;z-index:99;height:auto;background-color:#fff;margin-left:-40%;width:80%;background-color:#fff;padding:1.25em;border:solid 1px #666;-webkit-box-shadow:0 0 10px rgba(0,0,0,0.4);box-shadow:0 0 10px rgba(0,0,0,0.4);top:50px}.reveal-modal .column,.reveal-modal .columns{min-width:0}.reveal-modal>:first-child{margin-top:0}.reveal-modal>:last-child{margin-bottom:0}.reveal-modal .close-reveal-modal{font-size:1.375em;line-height:1;position:absolute;top:0.5em;right:0.6875em;color:#aaa;font-weight:bold;cursor:pointer}@media only screen and (min-width: 48em){.reveal-modal{padding:1.875em;top:6.25em}.reveal-modal.small{margin-left:-15%;width:30%}.reveal-modal.medium{margin-left:-20%;width:40%}.reveal-modal.large{margin-left:-30%;width:60%}.reveal-modal.xlarge{margin-left:-35%;width:70%}.reveal-modal.expand{margin-left:-47.5%;width:95%}}@media print{div:not(.reveal-modal){display:none}}.joyride-list{display:none}.joyride-tip-guide{display:none;position:absolute;background:#000;color:#fff;z-index:101;top:0;left:2.5%;font-family:inherit;font-weight:normal;width:95%}.lt-ie9 .joyride-tip-guide{max-width:800px;left:50%;margin-left:-400px}.joyride-content-wrapper{width:100%;padding:1.125em 1.25em 1.5em}.joyride-content-wrapper .button{margin-bottom:0 !important}.joyride-tip-guide .joyride-nub{display:block;position:absolute;left:22px;width:0;height:0;border:solid 14px}.joyride-tip-guide .joyride-nub.top{border-color:#000;border-top-color:transparent !important;border-left-color:transparent !important;border-right-color:transparent !important;top:-28px;bottom:none}.joyride-tip-guide .joyride-nub.bottom{border-color:#000 !important;border-bottom-color:transparent !important;border-left-color:transparent !important;border-right-color:transparent !important;bottom:-28px;bottom:none}.joyride-tip-guide .joyride-nub.right{right:-28px}.joyride-tip-guide .joyride-nub.left{left:-28px}.joyride-tip-guide h1,.joyride-tip-guide h2,.joyride-tip-guide h3,.joyride-tip-guide h4,.joyride-tip-guide h5,.joyride-tip-guide h6{line-height:1.25;margin:0;font-weight:bold;color:#fff}.joyride-tip-guide p{margin:0 0 1.125em 0;font-size:0.875em;line-height:1.3}.joyride-timer-indicator-wrap{width:50px;height:3px;border:solid 1px #555;position:absolute;right:1.0625em;bottom:1em}.joyride-timer-indicator{display:block;width:0;height:inherit;background:#666}.joyride-close-tip{position:absolute;right:12px;top:10px;color:#777 !important;text-decoration:none;font-size:30px;font-weight:normal;line-height:0.5 !important}.joyride-close-tip:hover,.joyride-close-tip:focus{color:#eee !important}.joyride-modal-bg{position:fixed;height:100%;width:100%;background:transparent;background:rgba(0,0,0,0.5);z-index:100;display:none;top:0;left:0;cursor:pointer}.joyride-expose-wrapper{background-color:#ffffff;position:absolute;border-radius:3px;z-index:102;-moz-box-shadow:0px 0px 30px #fff;-webkit-box-shadow:0px 0px 15px #fff;box-shadow:0px 0px 15px #fff}.joyride-expose-cover{background:transparent;border-radius:3px;position:absolute;z-index:9999;top:0px;left:0px}@media only screen and (min-width: 48em){.joyride-tip-guide{width:300px;left:inherit}.joyride-tip-guide .joyride-nub.bottom{border-color:#000 !important;border-bottom-color:transparent !important;border-left-color:transparent !important;border-right-color:transparent !important;bottom:-28px;bottom:none}.joyride-tip-guide .joyride-nub.right{border-color:#000 !important;border-top-color:transparent !important;border-right-color:transparent !important;border-bottom-color:transparent !important;top:22px;bottom:none;left:auto;right:-28px}.joyride-tip-guide .joyride-nub.left{border-color:#000 !important;border-top-color:transparent !important;border-left-color:transparent !important;border-bottom-color:transparent !important;top:22px;left:-28px;right:auto;bottom:none}}[data-clearing]{*zoom:1;margin-bottom:0}[data-clearing]:before,[data-clearing]:after{content:" ";display:table}[data-clearing]:after{clear:both}.clearing-blackout{background:#111;position:fixed;width:100%;height:100%;top:0;left:0;z-index:998}.clearing-blackout .clearing-close{display:block}.clearing-container{position:relative;z-index:998;height:100%;overflow:hidden;margin:0}.visible-img{height:95%;position:relative}.visible-img img{position:absolute;left:50%;top:50%;margin-left:-50%;max-height:100%;max-width:100%}.clearing-caption{color:#fff;line-height:1.3;margin-bottom:0;text-align:center;bottom:0;background:#111;width:100%;padding:10px 30px;position:absolute;left:0}.clearing-close{z-index:999;padding-left:20px;padding-top:10px;font-size:40px;line-height:1;color:#fff;display:none}.clearing-close:hover,.clearing-close:focus{color:#ccc}.clearing-assembled .clearing-container{height:100%}.clearing-assembled .clearing-container .carousel>ul{display:none}@media only screen and (min-width: 48em){.clearing-main-prev,.clearing-main-next{position:absolute;height:100%;width:40px;top:0}.clearing-main-prev>span,.clearing-main-next>span{position:absolute;top:50%;display:block;width:0;height:0;border:solid 16px}.clearing-main-prev{left:0}.clearing-main-prev>span{left:5px;border-color:transparent;border-right-color:#fff}.clearing-main-next{right:0}.clearing-main-next>span{border-color:transparent;border-left-color:#fff}.clearing-main-prev.disabled,.clearing-main-next.disabled{opacity:0.5}.clearing-feature ~ li{display:none}.clearing-assembled .clearing-container .carousel{background:#111;height:150px;margin-top:5px}.clearing-assembled .clearing-container .carousel>ul{display:block;z-index:999;width:200%;height:100%;margin-left:0;position:relative;left:0}.clearing-assembled .clearing-container .carousel>ul li{display:block;width:175px;height:inherit;padding:0;float:left;overflow:hidden;margin-right:1px;position:relative;cursor:pointer;opacity:0.4}.clearing-assembled .clearing-container .carousel>ul li.fix-height img{min-height:100%;height:100%;max-width:none}.clearing-assembled .clearing-container .carousel>ul li a.th{border:none;-webkit-box-shadow:none;box-shadow:none;display:block}.clearing-assembled .clearing-container .carousel>ul li img{cursor:pointer !important;min-width:100% !important}.clearing-assembled .clearing-container .carousel>ul li.visible{opacity:1}.clearing-assembled .clearing-container .visible-img{background:#111;overflow:hidden;height:75%}.clearing-close{position:absolute;top:10px;right:20px;padding-left:0;padding-top:0}}.alert-box{border-style:solid;border-width:1px;display:block;font-weight:bold;margin-bottom:1.25em;position:relative;padding:0.6875em 1.3125em 0.75em 0.6875em;font-size:0.875em;background-color:#2ba6cb;border-color:#2284a1;color:#fff}.alert-box .close{font-size:1.375em;padding:5px 4px 4px;line-height:0;position:absolute;top:0.4375em;right:0.3125em;color:#333;opacity:0.3}.alert-box .close:hover,.alert-box .close:focus{opacity:0.5}.alert-box.radius{-webkit-border-radius:3px;border-radius:3px}.alert-box.round{-webkit-border-radius:1000px;border-radius:1000px}.alert-box.success{background-color:#5da423;border-color:#457a1a;color:#fff}.alert-box.alert{background-color:#c60f13;border-color:#970b0e;color:#fff}.alert-box.secondary{background-color:#e9e9e9;border-color:#d0d0d0;color:#505050}.breadcrumbs{display:block;padding:0.375em 0.875em 0.5625em;overflow:hidden;margin-left:0;list-style:none;border-style:solid;border-width:1px;background-color:#f6f6f6;border-color:#dcdcdc;-webkit-border-radius:3px;border-radius:3px}.breadcrumbs li{margin:0;padding:0 0.75em 0 0;float:left}.breadcrumbs li:hover a,.breadcrumbs li:focus a{text-decoration:underline}.breadcrumbs li a,.breadcrumbs li span{font-size:0.6875em;padding-left:0.75em;text-transform:uppercase;color:#2ba6cb}.breadcrumbs li.current a{cursor:default;color:#333}.breadcrumbs li.current:hover a,.breadcrumbs li.current:focus a{text-decoration:none}.breadcrumbs li.unavailable a{color:#999}.breadcrumbs li.unavailable:hover a,.breadcrumbs li.unavailable a:focus{text-decoration:none;color:#999;cursor:default}.breadcrumbs li:before{content:"/";color:#aaa;position:relative;top:1px}.breadcrumbs li:first-child a,.breadcrumbs li:first-child span{padding-left:0}.breadcrumbs li:first-child:before{content:" "}.keystroke,kbd{background-color:#ededed;border-color:#dbdbdb;color:#222;border-style:solid;border-width:1px;margin:0;font-family:"Consolas","Menlo","Courier",monospace;font-size:0.9375em;padding:0.125em 0.25em 0em;-webkit-border-radius:3px;border-radius:3px}.label{font-weight:500;text-align:center;text-decoration:none;line-height:1;white-space:nowrap;display:inline-block;position:relative;padding:0.1875em 0.625em 0.25em;font-size:0.875em;background-color:#2ba6cb;color:#fff}.label.radius{-webkit-border-radius:3px;border-radius:3px}.label.round{-webkit-border-radius:1000px;border-radius:1000px}.label.alert{background-color:#c60f13;color:#fff}.label.success{background-color:#5da423;color:#fff}.label.secondary{background-color:#e9e9e9;color:#333}.inline-list{margin:0 auto 1.0625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}.inline-list>li{list-style:none;float:left;margin-left:1.375em;display:block}.inline-list>li>*{display:block}.pagination{display:block;height:1.5em;margin-left:-0.3125em}.pagination li{display:block;float:left;height:1.5em;color:#222;font-size:0.875em;margin-left:0.3125em}.pagination li a{display:block;padding:0.0625em 0.4375em 0.0625em;color:#999}.pagination li:hover a,.pagination li a:focus{background:#e6e6e6}.pagination li.unavailable a{cursor:default;color:#999}.pagination li.unavailable:hover a,.pagination li.unavailable a:focus{background:transparent}.pagination li.current a{background:#2ba6cb;color:#fff;font-weight:bold;cursor:default}.pagination li.current a:hover,.pagination li.current a:focus{background:#2ba6cb}.pagination-centered{text-align:center}.pagination-centered ul>li{float:none;display:inline-block}.panel{border-style:solid;border-width:1px;border-color:#d9d9d9;margin-bottom:1.25em;padding:1.25em;background:#f2f2f2}.panel h1,.panel h2,.panel h3,.panel h4,.panel h5,.panel h6,.panel p{color:#333}.panel>:first-child{margin-top:0}.panel>:last-child{margin-bottom:0}.panel h1,.panel h2,.panel h3,.panel h4,.panel h5,.panel h6{line-height:1;margin-bottom:0.625em}.panel h1.subheader,.panel h2.subheader,.panel h3.subheader,.panel h4.subheader,.panel h5.subheader,.panel h6.subheader{line-height:1.4}.panel.callout{border-style:solid;border-width:1px;border-color:#2284a1;margin-bottom:1.25em;padding:1.25em;background:#2ba6cb;-webkit-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;box-shadow:0 1px 0 rgba(255,255,255,0.5) inset}.panel.callout h1,.panel.callout h2,.panel.callout h3,.panel.callout h4,.panel.callout h5,.panel.callout h6,.panel.callout p{color:#fff}.panel.callout>:first-child{margin-top:0}.panel.callout>:last-child{margin-bottom:0}.panel.callout h1,.panel.callout h2,.panel.callout h3,.panel.callout h4,.panel.callout h5,.panel.callout h6{line-height:1;margin-bottom:0.625em}.panel.callout h1.subheader,.panel.callout h2.subheader,.panel.callout h3.subheader,.panel.callout h4.subheader,.panel.callout h5.subheader,.panel.callout h6.subheader{line-height:1.4}.panel.radius{-webkit-border-radius:3px;border-radius:3px}.pricing-table{border:solid 1px #ddd;margin-left:0;margin-bottom:1.25em}.pricing-table *{list-style:none;line-height:1}.pricing-table .title{background-color:#ddd;padding:0.9375em 1.25em;text-align:center;color:#333;font-weight:bold;font-size:1em}.pricing-table .price{background-color:#eee;padding:0.9375em 1.25em;text-align:center;color:#333;font-weight:normal;font-size:1.25em}.pricing-table .description{background-color:#fff;padding:0.9375em;text-align:center;color:#777;font-size:0.75em;font-weight:normal;line-height:1.4;border-bottom:dotted 1px #ddd}.pricing-table .bullet-item{background-color:#fff;padding:0.9375em;text-align:center;color:#333;font-size:0.875em;font-weight:normal;border-bottom:dotted 1px #ddd}.pricing-table .cta-button{background-color:#f5f5f5;text-align:center;padding:1.25em 1.25em 0}.progress{background-color:transparent;height:1.5625em;border:1px solid #ccc;padding:0.125em;margin-bottom:0.625em}.progress .meter{background:#2ba6cb;height:100%;display:block}.progress.secondary .meter{background:#e9e9e9;height:100%;display:block}.progress.success .meter{background:#5da423;height:100%;display:block}.progress.alert .meter{background:#c60f13;height:100%;display:block}.progress.radius{-webkit-border-radius:3px;border-radius:3px}.progress.radius .meter{-webkit-border-radius:2px;border-radius:2px}.progress.round{-webkit-border-radius:1000px;border-radius:1000px}.progress.round .meter{-webkit-border-radius:999px;border-radius:999px}.side-nav{display:block;margin:0;padding:0.875em 0;list-style-type:none;list-style-position:inside}.side-nav li{margin:0 0 0.4375em 0;font-size:0.875em}.side-nav li a{display:block;color:#2ba6cb}.side-nav li.active a{color:#4d4d4d;font-weight:bold}.side-nav li.divider{border-top:1px solid;height:0;padding:0;list-style:none;border-top-color:#e6e6e6}.sub-nav{display:block;width:auto;overflow:hidden;margin:-0.25em 0 1.125em;padding-top:0.25em;margin-right:0;margin-left:-0.5625em}.sub-nav dt,.sub-nav dd{float:left;display:inline;margin-left:0.5625em;margin-bottom:0.625em;font-weight:normal;font-size:0.875em}.sub-nav dt a,.sub-nav dd a{color:#999;text-decoration:none}.sub-nav dt.active a,.sub-nav dd.active a{-webkit-border-radius:1000px;border-radius:1000px;font-weight:bold;background:#2ba6cb;padding:0.1875em 0.5625em;cursor:default;color:#fff}@media only screen{div.switch{position:relative;width:100%;padding:0;display:block;overflow:hidden;border-style:solid;border-width:1px;margin-bottom:1.25em;-webkit-animation:webkitSiblingBugfix infinite 1s;height:36px;background:#fff;border-color:#ccc}div.switch label{position:relative;left:0;z-index:2;float:left;width:50%;height:100%;margin:0;font-weight:bold;text-align:left;-webkit-transition:all 0.1s ease-out;-moz-transition:all 0.1s ease-out;transition:all 0.1s ease-out}div.switch input{position:absolute;z-index:3;opacity:0;width:100%;height:100%}div.switch input:hover,div.switch input:focus{cursor:pointer}div.switch>span{position:absolute;top:-1px;left:-1px;z-index:1;display:block;padding:0;border-width:1px;border-style:solid;-webkit-transition:all 0.1s ease-out;-moz-transition:all 0.1s ease-out;transition:all 0.1s ease-out}div.switch input:not(:checked)+label{opacity:0}div.switch input:checked{display:none !important}div.switch input{left:0;display:block !important}div.switch input:first-of-type+label,div.switch input:first-of-type+span+label{left:-50%}div.switch input:first-of-type:checked+label,div.switch input:first-of-type:checked+span+label{left:0%}div.switch input:last-of-type+label,div.switch input:last-of-type+span+label{right:-50%;left:auto;text-align:right}div.switch input:last-of-type:checked+label,div.switch input:last-of-type:checked+span+label{right:0%;left:auto}div.switch span.custom{display:none !important}div.switch label{padding:0 0.375em;line-height:2.3em;font-size:0.875em}div.switch input:first-of-type:checked ~ span{left:100%;margin-left:-2.1875em}div.switch>span{width:2.25em;height:2.25em}div.switch>span{border-color:#b3b3b3;background:#fff;background:-moz-linear-gradient(top, #fff 0%, #f2f2f2 100%);background:-webkit-linear-gradient(top, #fff 0%, #f2f2f2 100%);background:linear-gradient(to bottom, #fff 0%, #f2f2f2 100%);-webkit-box-shadow:2px 0 10px 0 rgba(0,0,0,0.07),1000px 0 0 1000px #e1f5d1,-2px 0 10px 0 rgba(0,0,0,0.07),-1000px 0 0 1000px #f5f5f5;box-shadow:2px 0 10px 0 rgba(0,0,0,0.07),1000px 0 0 980px #e1f5d1,-2px 0 10px 0 rgba(0,0,0,0.07),-1000px 0 0 1000px #f5f5f5}div.switch:hover>span,div.switch:focus>span{background:#fff;background:-moz-linear-gradient(top, #fff 0%, #e6e6e6 100%);background:-webkit-linear-gradient(top, #fff 0%, #e6e6e6 100%);background:linear-gradient(to bottom, #fff 0%, #e6e6e6 100%)}div.switch:active{background:transparent}div.switch.large{height:44px}div.switch.large label{padding:0 0.375em;line-height:2.3em;font-size:1.0625em}div.switch.large input:first-of-type:checked ~ span{left:100%;margin-left:-2.6875em}div.switch.large>span{width:2.75em;height:2.75em}div.switch.small{height:28px}div.switch.small label{padding:0 0.375em;line-height:2.1em;font-size:0.75em}div.switch.small input:first-of-type:checked ~ span{left:100%;margin-left:-1.6875em}div.switch.small>span{width:1.75em;height:1.75em}div.switch.tiny{height:22px}div.switch.tiny label{padding:0 0.375em;line-height:1.9em;font-size:0.6875em}div.switch.tiny input:first-of-type:checked ~ span{left:100%;margin-left:-1.3125em}div.switch.tiny>span{width:1.375em;height:1.375em}div.switch.radius{-webkit-border-radius:4px;border-radius:4px}div.switch.radius>span{-webkit-border-radius:3px;border-radius:3px}div.switch.round{-webkit-border-radius:1000px;border-radius:1000px}div.switch.round>span{-webkit-border-radius:999px;border-radius:999px}div.switch.round label{padding:0 0.5625em}@-webkit-keyframes webkitSiblingBugfix{from{position:relative}to{position:relative}}}[data-magellan-expedition]{background:#fff;z-index:50;min-width:100%;padding:10px}[data-magellan-expedition] .sub-nav{margin-bottom:0}[data-magellan-expedition] .sub-nav dd{margin-bottom:0}table{background:#fff;margin-bottom:1.25em;border:solid 1px #ddd}table thead,table tfoot{background:#f5f5f5;font-weight:bold}table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:0.5em 0.625em 0.625em;font-size:0.875em;color:#222;text-align:left}table tr th,table tr td{padding:0.5625em 0.625em;font-size:0.875em;color:#222}table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f9f9f9}table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.125em}.th{display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px rgba(0,0,0,0.2);box-shadow:0 0 0 1px rgba(0,0,0,0.2);-webkit-transition:all 200ms ease-out;-moz-transition:all 200ms ease-out;transition:all 200ms ease-out}.th:hover,.th:focus{-webkit-box-shadow:0 0 6px 1px rgba(43,166,203,0.5);box-shadow:0 0 6px 1px rgba(43,166,203,0.5)}.th.radius{-webkit-border-radius:3px;border-radius:3px}.has-tip{border-bottom:dotted 1px #ccc;cursor:help;font-weight:bold;color:#333}.has-tip:hover,.has-tip:focus{border-bottom:dotted 1px #196177;color:#2ba6cb}.has-tip.tip-left,.has-tip.tip-right{float:none !important}.tooltip{display:none;position:absolute;z-index:999;font-weight:bold;font-size:0.9375em;line-height:1.3;padding:0.5em;max-width:85%;left:50%;width:100%;color:#fff;background:#000;-webkit-border-radius:3px;border-radius:3px}.tooltip>.nub{display:block;left:5px;position:absolute;width:0;height:0;border:solid 5px;border-color:transparent transparent #000 transparent;top:-10px}.tooltip.opened{color:#2ba6cb !important;border-bottom:dotted 1px #196177 !important}.tap-to-close{display:block;font-size:0.625em;color:#888;font-weight:normal}@media only screen and (min-width: 48em){.tooltip>.nub{border-color:transparent transparent #000 transparent;top:-10px}.tooltip.tip-top>.nub{border-color:#000 transparent transparent transparent;top:auto;bottom:-10px}.tooltip.tip-left,.tooltip.tip-right{float:none !important}.tooltip.tip-left>.nub{border-color:transparent transparent transparent #000;right:-10px;left:auto;top:50%;margin-top:-5px}.tooltip.tip-right>.nub{border-color:transparent #000 transparent transparent;right:auto;left:-10px;top:50%;margin-top:-5px}}@media only screen and (max-width: 767px){.f-dropdown{max-width:100%;left:0}}.f-dropdown{position:absolute;top:-9999px;list-style:none;padding:1.25em;width:100%;height:auto;max-height:none;background:#fff;border:solid 1px #ccc;font-size:16px;z-index:99;margin-top:2px;max-width:200px}.f-dropdown *:first-child{margin-top:0}.f-dropdown *:last-child{margin-bottom:0}.f-dropdown:before{content:"";display:block;width:0;height:0;border:solid 6px;border-color:transparent transparent #fff transparent;position:absolute;top:-12px;left:10px;z-index:99}.f-dropdown:after{content:"";display:block;width:0;height:0;border:solid 7px;border-color:transparent transparent #ccc transparent;position:absolute;top:-14px;left:9px;z-index:98}.f-dropdown.right:before{left:auto;right:10px}.f-dropdown.right:after{left:auto;right:9px}.f-dropdown li{font-size:0.875em;cursor:pointer;padding:0.3125em 0.625em;line-height:1.125em;margin:0}.f-dropdown li:hover,.f-dropdown li:focus{background:#eee}.f-dropdown li a{color:#555}.f-dropdown.content{position:absolute;top:-9999px;list-style:none;padding:1.25em;width:100%;height:auto;max-height:none;background:#fff;border:solid 1px #ccc;font-size:16px;z-index:99;max-width:200px}.f-dropdown.content *:first-child{margin-top:0}.f-dropdown.content *:last-child{margin-bottom:0}.f-dropdown.tiny{max-width:200px}.f-dropdown.small{max-width:300px}.f-dropdown.medium{max-width:500px}.f-dropdown.large{max-width:800px} diff --git a/engine/src/main/resources/org/archive/crawler/restlet/css/heritrix.css b/engine/src/main/resources/org/archive/crawler/restlet/css/heritrix.css new file mode 100644 index 00000000..1da7ae62 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/css/heritrix.css @@ -0,0 +1,47 @@ +.flashACK { + margin-bottom: 16px; + padding: 8px; + background-color: palegreen; +} +.flashNACK { + margin-bottom: 16px; + padding: 8px; + background-color: pink; +} +.flashADVISORY { + margin-bottom: 16px; + padding: 8px; + background-color: khaki; +} +fieldset table.beans { + display: inline; + table-layout: fixed; + width: 100%; + border:none; +} +fieldset table.beans tbody { + border: solid 1px #dddddd; +} +fieldset table.beans tbody td { + word-wrap:break-word; +} +fieldset table.beans tbody tr { + text-align:right; + vertical-align:top +} +fieldset table.beans tbody td { + text-align:left; +} +div.panel ul { + margin-left: 1.25em; +} +.scroll_y { + overflow:auto; + white-space:nowrap; +} +.monospace{ + /*font-family:courier;*/ + font-family: monospace; + white-space: pre; + line-height:0.6; +} \ No newline at end of file diff --git a/engine/src/main/resources/org/archive/crawler/restlet/css/normalize.css b/engine/src/main/resources/org/archive/crawler/restlet/css/normalize.css new file mode 100644 index 00000000..a9c6f52f --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/css/normalize.css @@ -0,0 +1,396 @@ +/*! normalize.css v2.1.0 | MIT License | git.io/normalize */ + +/* ========================================================================== + HTML5 display definitions + ========================================================================== */ + +/** + * Correct `block` display not defined in IE 8/9. + */ + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +main, +nav, +section, +summary { + display: block; +} + +/** + * Correct `inline-block` display not defined in IE 8/9. + */ + +audio, +canvas, +video { + display: inline-block; +} + +/** + * Prevent modern browsers from displaying `audio` without controls. + * Remove excess height in iOS 5 devices. + */ + +audio:not([controls]) { + display: none; + height: 0; +} + +/** + * Address styling not present in IE 8/9. + */ + +[hidden] { + display: none; +} + +/* ========================================================================== + Base + ========================================================================== */ + +/** + * 1. Set default font family to sans-serif. + * 2. Prevent iOS text size adjust after orientation change, without disabling + * user zoom. + */ + +html { + font-family: sans-serif; /* 1 */ + -webkit-text-size-adjust: 100%; /* 2 */ + -ms-text-size-adjust: 100%; /* 2 */ +} + +/** + * Remove default margin. + */ + +body { + margin: 0; +} + +/* ========================================================================== + Links + ========================================================================== */ + +/** + * Address `outline` inconsistency between Chrome and other browsers. + */ + +a:focus { + outline: thin dotted; +} + +/** + * Improve readability when focused and also mouse hovered in all browsers. + */ + +a:active, +a:hover { + outline: 0; +} + +/* ========================================================================== + Typography + ========================================================================== */ + +/** + * Address variable `h1` font-size and margin within `section` and `article` + * contexts in Firefox 4+, Safari 5, and Chrome. + */ + +h1 { + font-size: 2em; + margin: 0.67em 0; +} + +/** + * Address styling not present in IE 8/9, Safari 5, and Chrome. + */ + +abbr[title] { + border-bottom: 1px dotted; +} + +/** + * Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome. + */ + +b, +strong { + font-weight: bold; +} + +/** + * Address styling not present in Safari 5 and Chrome. + */ + +dfn { + font-style: italic; +} + +/** + * Address differences between Firefox and other browsers. + */ + +hr { + -moz-box-sizing: content-box; + box-sizing: content-box; + height: 0; +} + +/** + * Address styling not present in IE 8/9. + */ + +mark { + background: #ff0; + color: #000; +} + +/** + * Correct font family set oddly in Safari 5 and Chrome. + */ + +code, +kbd, +pre, +samp { + font-family: monospace, serif; + font-size: 1em; +} + +/** + * Improve readability of pre-formatted text in all browsers. + */ + +pre { + white-space: pre-wrap; +} + +/** + * Set consistent quote types. + */ + +q { + quotes: "\201C" "\201D" "\2018" "\2019"; +} + +/** + * Address inconsistent and variable font size in all browsers. + */ + +small { + font-size: 80%; +} + +/** + * Prevent `sub` and `sup` affecting `line-height` in all browsers. + */ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +/* ========================================================================== + Embedded content + ========================================================================== */ + +/** + * Remove border when inside `a` element in IE 8/9. + */ + +img { + border: 0; +} + +/** + * Correct overflow displayed oddly in IE 9. + */ + +svg:not(:root) { + overflow: hidden; +} + +/* ========================================================================== + Figures + ========================================================================== */ + +/** + * Address margin not present in IE 8/9 and Safari 5. + */ + +figure { + margin: 0; +} + +/* ========================================================================== + Forms + ========================================================================== */ + +/** + * Define consistent border, margin, and padding. + */ + +fieldset { + border: 1px solid #c0c0c0; + margin: 0 2px; + padding: 0.35em 0.625em 0.75em; +} + +/** + * 1. Correct `color` not being inherited in IE 8/9. + * 2. Remove padding so people aren't caught out if they zero out fieldsets. + */ + +legend { + border: 0; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * 1. Correct font family not being inherited in all browsers. + * 2. Correct font size not being inherited in all browsers. + * 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome. + */ + +button, +input, +select, +textarea { + font-family: inherit; /* 1 */ + font-size: 100%; /* 2 */ + margin: 0; /* 3 */ +} + +/** + * Address Firefox 4+ setting `line-height` on `input` using `!important` in + * the UA stylesheet. + */ + +button, +input { + line-height: normal; +} + +/** + * Address inconsistent `text-transform` inheritance for `button` and `select`. + * All other form control elements do not inherit `text-transform` values. + * Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+. + * Correct `select` style inheritance in Firefox 4+ and Opera. + */ + +button, +select { + text-transform: none; +} + +/** + * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` + * and `video` controls. + * 2. Correct inability to style clickable `input` types in iOS. + * 3. Improve usability and consistency of cursor style between image-type + * `input` and others. + */ + +button, +html input[type="button"], /* 1 */ +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; /* 2 */ + cursor: pointer; /* 3 */ +} + +/** + * Re-set default cursor for disabled elements. + */ + +button[disabled], +html input[disabled] { + cursor: default; +} + +/** + * 1. Address box sizing set to `content-box` in IE 8/9. + * 2. Remove excess padding in IE 8/9. + */ + +input[type="checkbox"], +input[type="radio"] { + box-sizing: border-box; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome. + * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome + * (include `-moz` to future-proof). + */ + +input[type="search"] { + -webkit-appearance: textfield; /* 1 */ + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; /* 2 */ + box-sizing: content-box; +} + +/** + * Remove inner padding and search cancel button in Safari 5 and Chrome + * on OS X. + */ + +input[type="search"]::-webkit-search-cancel-button, +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} + +/** + * Remove inner padding and border in Firefox 4+. + */ + +button::-moz-focus-inner, +input::-moz-focus-inner { + border: 0; + padding: 0; +} + +/** + * 1. Remove default vertical scrollbar in IE 8/9. + * 2. Improve readability and alignment in all browsers. + */ + +textarea { + overflow: auto; /* 1 */ + vertical-align: top; /* 2 */ +} + +/* ========================================================================== + Tables + ========================================================================== */ + +/** + * Remove most spacing between table cells. + */ + +table { + border-collapse: collapse; + border-spacing: 0; +} diff --git a/engine/src/main/resources/org/archive/crawler/restlet/engine.css b/engine/src/main/resources/org/archive/crawler/restlet/engine.css deleted file mode 100644 index 7bab473e..00000000 --- a/engine/src/main/resources/org/archive/crawler/restlet/engine.css +++ /dev/null @@ -1,31 +0,0 @@ -.bgroup { - margin-right: 1em; -} -.log { - font-family: monospace; - white-space: normal; - text-indent: -10px; - padding-left: 10px; -} -dl#jobstats dt { - font-weight: bold; -} -dl#jobstats dd { - margin-left: 1em; -} -.flashACK { - margin-bottom: 16px; - padding: 8px; - background-color: palegreen; -} -.flashNACK { - margin-bottom: 16px; - padding: 8px; - background-color: pink; -} -.flashADVISORY { - margin-bottom: 16px; - padding: 8px; - background-color: khaki; -} - diff --git a/engine/src/main/resources/org/archive/crawler/restlet/img/heritrix-logo.gif b/engine/src/main/resources/org/archive/crawler/restlet/img/heritrix-logo.gif new file mode 100644 index 00000000..036db3eb Binary files /dev/null and b/engine/src/main/resources/org/archive/crawler/restlet/img/heritrix-logo.gif differ diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation.min.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation.min.js new file mode 100644 index 00000000..e689cd33 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation.min.js @@ -0,0 +1,15 @@ +/* + * Foundation Responsive Library + * http://foundation.zurb.com + * Copyright 2013, ZURB + * Free to use under the MIT license. + * http://www.opensource.org/licenses/mit-license.php +*/ +/*jslint unparam: true, browser: true, indent: 2 */ +// Accommodate running jQuery or Zepto in noConflict() mode by +// using an anonymous function to redefine the $ shorthand name. +// See http://docs.jquery.com/Using_jQuery_with_Other_Libraries +// and http://zeptojs.com/ +var libFuncName=null;if(typeof jQuery=="undefined"&&typeof Zepto=="undefined"&&typeof $=="function")libFuncName=$;else if(typeof jQuery=="function")libFuncName=jQuery;else{if(typeof Zepto!="function")throw new TypeError;libFuncName=Zepto}(function(e){(function(){Array.prototype.filter||(Array.prototype.filter=function(e){"use strict";if(this==null)throw new TypeError;var t=Object(this),n=t.length>>>0;if(typeof e!="function")try{throw new TypeError}catch(r){return}var i=[],s=arguments[1];for(var o=0;o0)for(var l=u.length-1;l>=0;l--)f.push(this.init_lib(u[l],a))}else for(var c in this.libs)f.push(this.init_lib(c,a));return typeof n=="function"&&a.unshift(n),this.response_obj(f,a)},response_obj:function(e,t){for(var n=0,r=t.length;n=0;r--)this.lib_methods.hasOwnProperty(n[r])&&(this.libs[e.name][n[r]]=this.lib_methods[n[r]])},random_str:function(e){var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".split("");e||(e=Math.floor(Math.random()*t.length));var n="";for(var r=0;r=0;r--)i=s[r].split(":"),/true/i.test(i[1])&&(i[1]=!0),/false/i.test(i[1])&&(i[1]=!1),u(i[1])&&(i[1]=parseInt(i[1],10)),i.length===2&&i[0].length>0&&(n[a(i[0])]=a(i[1]));return n},delay:function(e,t){return setTimeout(e,t)},scrollTo:function(n,r,i){if(i<0)return;var s=r-e(t).scrollTop(),o=s/i*10;this.scrollToTimerCache=setTimeout(function(){isNaN(parseInt(o,10))||(t.scrollTo(0,e(t).scrollTop()+o),this.scrollTo(n,r,i-10))}.bind(this),10)},scrollLeft:function(e){if(!e.length)return;return"scrollLeft"in e[0]?e[0].scrollLeft:e[0].pageXOffset},empty:function(e){if(e.length&&e.length>0)return!1;if(e.length&&e.length===0)return!0;for(var t in e)if(hasOwnProperty.call(e,t))return!1;return!0}},fix_outer:function(e){e.outerHeight=function(e,t){return typeof Zepto=="function"?e.height():typeof t!="undefined"?e.outerHeight(t):e.outerHeight()},e.outerWidth=function(e){return typeof Zepto=="function"?e.width():typeof bool!="undefined"?e.outerWidth(bool):e.outerWidth()}},error:function(e){return e.name+" "+e.message+"; "+e.more},off:function(){return e(this.scope).off(".fndtn"),e(t).off(".fndtn"),!0},zj:function(){try{return Zepto}catch(e){return jQuery}}()},e.fn.foundation=function(){var e=Array.prototype.slice.call(arguments,0);return this.each(function(){return Foundation.init.apply(Foundation,[this].concat(e)),this})}}(this,this.document)})(libFuncName),function(e,t,n,r){"use strict";Foundation.libs.alerts={name:"alerts",version:"4.0.0",settings:{speed:300,callback:function(){}},init:function(t,n,r){return this.scope=t||this.scope,typeof n=="object"&&e.extend(!0,this.settings,n),typeof n!="string"?(this.settings.init||this.events(),this.settings.init):this[n].call(this,r)},events:function(){var t=this;e(this.scope).on("click.fndtn.alerts","[data-alert] a.close",function(n){n.preventDefault(),e(this).closest("[data-alert]").fadeOut(t.speed,function(){e(this).remove(),t.settings.callback()})}),this.settings.init=!0},off:function(){e(this.scope).off(".fndtn.alerts")}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs.clearing={name:"clearing",version:"4.1.2",settings:{templates:{viewing:'×'},close_selectors:".clearing-close",init:!1,locked:!1},init:function(t,n,r){var i=this;return Foundation.inherit(this,"set_data get_data remove_data throttle data_options"),typeof n=="object"&&(r=e.extend(!0,this.settings,n)),typeof n!="string"?(e(this.scope).find("ul[data-clearing]").each(function(){var t=e(this),n=n||{},r=t.find("li"),s=i.get_data(t);!s&&r.length>0&&(n.$parent=t.parent(),i.set_data(t,e.extend({},i.settings,n,i.data_options(t))),i.assemble(t.find("li")),i.settings.init||i.events().swipe_events())}),this.settings.init):this[n].call(this,r)},events:function(){var n=this;return e(this.scope).on("click.fndtn.clearing","ul[data-clearing] li",function(t,r,i){var r=r||e(this),i=i||r,s=r.next("li"),o=n.get_data(r.parent()),u=e(t.target);t.preventDefault(),o||n.init(),i.hasClass("visible")&&r[0]===i[0]&&s.length>0&&n.is_open(r)&&(i=s,u=i.find("img")),n.open(u,r,i),n.update_paddles(i)}).on("click.fndtn.clearing",".clearing-main-next",function(e){this.nav(e,"next")}.bind(this)).on("click.fndtn.clearing",".clearing-main-prev",function(e){this.nav(e,"prev")}.bind(this)).on("click.fndtn.clearing",this.settings.close_selectors,function(e){Foundation.libs.clearing.close(e,this)}).on("keydown.fndtn.clearing",function(e){this.keydown(e)}.bind(this)),e(t).on("resize.fndtn.clearing",function(e){this.resize()}.bind(this)),this.settings.init=!0,this},swipe_events:function(){var t=this;e(this.scope).on("touchstart.fndtn.clearing",".visible-img",function(t){t.touches||(t=t.originalEvent);var n={start_page_x:t.touches[0].pageX,start_page_y:t.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:r};e(this).data("swipe-transition",n),t.stopPropagation()}).on("touchmove.fndtn.clearing",".visible-img",function(n){n.touches||(n=n.originalEvent);if(n.touches.length>1||n.scale&&n.scale!==1)return;var r=e(this).data("swipe-transition");typeof r=="undefined"&&(r={}),r.delta_x=n.touches[0].pageX-r.start_page_x,typeof r.is_scrolling=="undefined"&&(r.is_scrolling=!!(r.is_scrolling||Math.abs(r.delta_x)');var r=e("#foundationClearingHolder"),i=this.get_data(n),s=n.detach(),o={grid:'",viewing:i.templates.viewing},u='
'+o.viewing+o.grid+"
";return r.after(u).remove()},open:function(e,t,n){var r=n.closest(".clearing-assembled"),i=r.find("div").first(),s=i.find(".visible-img"),o=s.find("img").not(e);this.locked()||(o.attr("src",this.load(e)).css("visibility","hidden"),this.loaded(o,function(){o.css("visibility","visible"),r.addClass("clearing-blackout"),i.addClass("clearing-container"),s.show(),this.fix_height(n).caption(s.find(".clearing-caption"),e).center(o).shift(t,n,function(){n.siblings().removeClass("visible"),n.addClass("visible")})}.bind(this)))},close:function(t,n){t.preventDefault();var r=function(e){return/blackout/.test(e.selector)?e:e.closest(".clearing-blackout")}(e(n)),i,s;return n===t.target&&r&&(i=r.find("div").first(),s=i.find(".visible-img"),this.settings.prev_index=0,r.find("ul[data-clearing]").attr("style","").closest(".clearing-blackout").removeClass("clearing-blackout"),i.removeClass("clearing-container"),s.hide()),!1},is_open:function(e){return e.parent().attr("style").length>0},keydown:function(t){var n=e(".clearing-blackout").find("ul[data-clearing]");t.which===39&&this.go(n,"next"),t.which===37&&this.go(n,"prev"),t.which===27&&e("a.clearing-close").trigger("click")},nav:function(t,n){var r=e(".clearing-blackout").find("ul[data-clearing]");t.preventDefault(),this.go(r,n)},resize:function(){var t=e(".clearing-blackout .visible-img").find("img");t.length&&this.center(t)},fix_height:function(t){var n=t.parent().children(),r=this;return n.each(function(){var t=e(this),n=t.find("img");t.height()>r.outerHeight(n)&&t.addClass("fix-height")}).closest("ul").width(n.length*100+"%"),this},update_paddles:function(e){var t=e.closest(".carousel").siblings(".visible-img");e.next().length>0?t.find(".clearing-main-next").removeClass("disabled"):t.find(".clearing-main-next").addClass("disabled"),e.prev().length>0?t.find(".clearing-main-prev").removeClass("disabled"):t.find(".clearing-main-prev").addClass("disabled")},center:function(e){return this.rtl?e.css({marginRight:-(this.outerWidth(e)/2),marginTop:-(this.outerHeight(e)/2)}):e.css({marginLeft:-(this.outerWidth(e)/2),marginTop:-(this.outerHeight(e)/2)}),this},load:function(e){var t=e.parent().attr("href");return this.preload(e),t?t:e.attr("src")},preload:function(e){this.img(e.closest("li").next()).img(e.closest("li").prev())},loaded:function(e,t){function n(){t()}function r(){this.one("load",n);if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){var e=this.attr("src"),t=e.match(/\?/)?"&":"?";t+="random="+(new Date).getTime(),this.attr("src",e+t)}}if(!e.attr("src")){n();return}e[0].complete||e[0].readyState===4?n():r.call(e)},img:function(e){if(e.length){var t=new Image,n=e.find("a");n.length?t.src=n.attr("href"):t.src=e.find("img").attr("src")}return this},caption:function(e,t){var n=t.data("caption");return n?e.text(n).show():e.text("").hide(),this},go:function(e,t){var n=e.find(".visible"),r=n[t]();r.length&&r.find("img").trigger("click",[n,r])},shift:function(e,t,n){var r=t.parent(),i=this.settings.prev_index||t.index(),s=this.direction(r,e,t),o=parseInt(r.css("left"),10),u=this.outerWidth(t),a;t.index()!==i&&!/skip/.test(s)?/left/.test(s)?(this.lock(),r.animate({left:o+u},300,this.unlock())):/right/.test(s)&&(this.lock(),r.animate({left:o-u},300,this.unlock())):/skip/.test(s)&&(a=t.index()-this.settings.up_count,this.lock(),a>0?r.animate({left:-(a*u)},300,this.unlock()):r.animate({left:0},300,this.unlock())),n()},direction:function(t,n,r){var i=t.find("li"),s=this.outerWidth(i)+this.outerWidth(i)/4,o=Math.floor(this.outerWidth(e(".clearing-container"))/s)-1,u=i.index(r),a;return this.settings.up_count=o,this.adjacent(this.settings.prev_index,u)?u>o&&u>this.settings.prev_index?a="right":u>o-1&&u<=this.settings.prev_index?a="left":a=!1:a="skip",this.settings.prev_index=u,a},adjacent:function(e,t){for(var n=t+1;n>=t-1;n--)if(n===e)return!0;return!1},lock:function(){this.settings.locked=!0},unlock:function(){this.settings.locked=!1},locked:function(){return this.settings.locked},outerHTML:function(e){return e.outerHTML||(new XMLSerializer).serializeToString(e)},off:function(){e(this.scope).off(".fndtn.clearing"),e(t).off(".fndtn.clearing"),this.remove_data(),this.settings.init=!1},reflow:function(){this.init()}}}(Foundation.zj,this,this.document),function(e,t,n){function i(e){return e}function s(e){return decodeURIComponent(e.replace(r," "))}var r=/\+/g,o=e.cookie=function(r,u,a){if(u!==n){a=e.extend({},o.defaults,a),u===null&&(a.expires=-1);if(typeof a.expires=="number"){var f=a.expires,l=a.expires=new Date;l.setDate(l.getDate()+f)}return u=o.json?JSON.stringify(u):String(u),t.cookie=[encodeURIComponent(r),"=",o.raw?u:encodeURIComponent(u),a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}var c=o.raw?i:s,h=t.cookie.split("; ");for(var p=0,d=h.length;p0&&(e(t.target).is("[data-dropdown-content]")||e.contains(r.first()[0],t.target))){t.stopPropagation();return}e("[data-dropdown-content]").css(Foundation.rtl?"right":"left","-99999px").removeClass(n.settings.activeClass)}),e(t).on("resize.fndtn.dropdown",n.throttle(function(){n.resize.call(n)},50)).trigger("resize"),this.settings.init=!0},toggle:function(t,n){var r=e("#"+t.data("dropdown"));e("[data-dropdown-content]").not(r).css(Foundation.rtl?"right":"left","-99999px").removeClass(this.settings.activeClass),r.hasClass(this.settings.activeClass)?r.css(Foundation.rtl?"right":"left","-99999px").removeClass(this.settings.activeClass):this.css(r.addClass(this.settings.activeClass),t)},resize:function(){var t=e("[data-dropdown-content].open"),n=e("[data-dropdown='"+t.attr("id")+"']");t.length&&n.length&&this.css(t,n)},css:function(n,r){var i=r.position();i.top+=r.offsetParent().offset().top,i.left+=r.offsetParent().offset().left;if(this.small())n.css({position:"absolute",width:"95%",left:"2.5%","max-width":"none",top:i.top+this.outerHeight(r)});else{if(!Foundation.rtl&&e(t).width()>this.outerWidth(n)+r.offset().left)var s=i.left;else{n.hasClass("right")||n.addClass("right");var s=i.left-(this.outerWidth(n)-this.outerWidth(r))}n.attr("style","").css({position:"absolute",top:i.top+this.outerHeight(r),left:s})}return n},small:function(){return e(t).width()<768||e("html").hasClass("lt-ie9")},off:function(){e(this.scope).off(".fndtn.dropdown"),e("html, body").off(".fndtn.dropdown"),e(t).off(".fndtn.dropdown"),e("[data-dropdown-content]").off(".fndtn.dropdown"),this.settings.init=!1}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs.forms={name:"forms",version:"4.0.4",settings:{disable_class:"no-custom"},init:function(t,n,r){return this.scope=t||this.scope,typeof n=="object"&&e.extend(!0,this.settings,n),typeof n!="string"?(this.settings.init||this.events(),this.assemble(),this.settings.init):this[n].call(this,r)},assemble:function(){e('form.custom input[type="radio"]',e(this.scope)).not('[data-customforms="disabled"]').each(this.append_custom_markup),e('form.custom input[type="checkbox"]',e(this.scope)).not('[data-customforms="disabled"]').each(this.append_custom_markup),e("form.custom select",e(this.scope)).not('[data-customforms="disabled"]').each(this.append_custom_select)},events:function(){var r=this;e(this.scope).on("click.fndtn.forms","form.custom span.custom.checkbox",function(t){t.preventDefault(),t.stopPropagation(),r.toggle_checkbox(e(this))}).on("click.fndtn.forms","form.custom span.custom.radio",function(t){t.preventDefault(),t.stopPropagation(),r.toggle_radio(e(this))}).on("change.fndtn.forms",'form.custom select:not([data-customforms="disabled"])',function(t){r.refresh_custom_select(e(this))}).on("click.fndtn.forms","form.custom label",function(t){var n=e("#"+r.escape(e(this).attr("for"))+':not([data-customforms="disabled"])'),i,s;n.length!==0&&(n.attr("type")==="checkbox"?(t.preventDefault(),i=e(this).find("span.custom.checkbox"),i.length==0&&(i=n.add(this).siblings("span.custom.checkbox").first()),r.toggle_checkbox(i)):n.attr("type")==="radio"&&(t.preventDefault(),s=e(this).find("span.custom.radio"),s.length==0&&(s=n.add(this).siblings("span.custom.radio").first()),r.toggle_radio(s)))}).on("click.fndtn.forms","form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector",function(t){var n=e(this),i=n.closest("div.custom.dropdown"),s=i.prev();i.hasClass("open")||e(r.scope).trigger("click"),t.preventDefault();if(!1===s.is(":disabled"))return i.toggleClass("open"),i.hasClass("open")?e(r.scope).on("click.fndtn.forms.customdropdown",function(){i.removeClass("open"),e(r.scope).off(".fndtn.forms.customdropdown")}):e(r.scope).on(".fndtn.forms.customdropdown"),!1}).on("click.fndtn.forms touchend.fndtn.forms","form.custom div.custom.dropdown li",function(t){var n=e(this),r=n.closest("div.custom.dropdown"),i=r.prev(),s=0;t.preventDefault(),t.stopPropagation();if(!e(this).hasClass("disabled")){e("div.dropdown").not(r).removeClass("open");var o=n.closest("ul").find("li.selected");o.removeClass("selected"),n.addClass("selected"),r.removeClass("open").find("a.current").html(n.html()),n.closest("ul").find("li").each(function(e){n[0]==this&&(s=e)}),i[0].selectedIndex=s,i.data("prevalue",o.html()),i.trigger("change")}}),e(t).on("keydown",function(t){var r=n.activeElement,i=e(".custom.dropdown.open");if(i.length>0){t.preventDefault(),t.which===13&&i.find("li.selected").trigger("click");if(t.which===38){var s=i.find("li.selected"),o=s.prev(":not(.disabled)");o.length>0&&(s.removeClass("selected"),o.addClass("selected"))}else if(t.which===40){var s=i.find("li.selected"),u=s.next(":not(.disabled)");u.length>0&&(s.removeClass("selected"),u.addClass("selected"))}}}),this.settings.init=!0},append_custom_markup:function(t,n){var r=e(n).hide(),i=r.attr("type"),s=r.next("span.custom."+i);s.length===0&&(s=e('').insertAfter(r)),s.toggleClass("checked",r.is(":checked")),s.toggleClass("disabled",r.is(":disabled"))},append_custom_select:function(t,n){var r=Foundation.libs.forms,i=e(n),s=i.next("div.custom.dropdown"),o=s.find("ul"),u=s.find(".current"),a=s.find(".selector"),f=i.find("option"),l=f.filter(":selected"),c=i.attr("class")?i.attr("class").split(" "):[],h=0,p="",d,v=!1;if(i.hasClass(r.settings.disable_class))return;if(s.length===0){var m=i.hasClass("small")?"small":i.hasClass("medium")?"medium":i.hasClass("large")?"large":i.hasClass("expand")?"expand":"";s=e('
    '),a=s.find(".selector"),o=s.find("ul"),p=f.map(function(){return"
  • "+e(this).html()+"
  • "}).get().join(""),o.append(p),v=s.prepend(''+l.html()+"").find(".current"),i.after(s).hide()}else p=f.map(function(){return"
  • "+e(this).html()+"
  • "}).get().join(""),o.html("").append(p);s.toggleClass("disabled",i.is(":disabled")),d=o.find("li"),f.each(function(t){this.selected&&(d.eq(t).addClass("selected"),v&&v.html(e(this).html())),e(this).is(":disabled")&&d.eq(t).addClass("disabled")});if(!s.is(".small, .medium, .large, .expand")){s.addClass("open");var r=Foundation.libs.forms;r.hidden_fix.adjust(o),h=r.outerWidth(d)>h?r.outerWidth(d):h,Foundation.libs.forms.hidden_fix.reset(),s.removeClass("open")}},refresh_custom_select:function(t){var n=this,r=0,i=t.next(),s=t.find("option");i.find("ul").html(""),s.each(function(){var t=e("
  • "+e(this).html()+"
  • ");i.find("ul").append(t)}),s.each(function(t){this.selected&&(i.find("li").eq(t).addClass("selected"),i.find(".current").html(e(this).html())),e(this).is(":disabled")&&i.find("li").eq(t).addClass("disabled")}),i.removeAttr("style").find("ul").removeAttr("style"),i.find("li").each(function(){i.addClass("open"),n.outerWidth(e(this))>r&&(r=n.outerWidth(e(this))),i.removeClass("open")})},toggle_checkbox:function(e){var t=e.prev(),n=t[0];!1===t.is(":disabled")&&(n.checked=n.checked?!1:!0,e.toggleClass("checked"),t.trigger("change"))},toggle_radio:function(e){var t=e.prev(),n=t.closest("form.custom"),r=t[0];!1===t.is(":disabled")&&(n.find('input[type="radio"][name="'+this.escape(t.attr("name"))+'"]').next().not(e).removeClass("checked"),e.hasClass("checked")||e.toggleClass("checked"),r.checked=e.hasClass("checked"),t.trigger("change"))},escape:function(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},hidden_fix:{tmp:[],hidden:null,adjust:function(t){var n=this;n.hidden=t.parents().andSelf().filter(":hidden"),n.hidden.each(function(){var t=e(this);n.tmp.push(t.attr("style")),t.css({visibility:"hidden",display:"block"})})},reset:function(){var t=this;t.hidden.each(function(n){var i=e(this),s=t.tmp[n];s===r?i.removeAttr("style"):i.attr("style",s)}),t.tmp=[],t.hidden=null}},off:function(){e(this.scope).off(".fndtn.forms")}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs.joyride={name:"joyride",version:"4.1.2",defaults:{expose:!1,modal:!1,tipLocation:"bottom",nubPosition:"auto",scrollSpeed:300,timer:0,startTimerOnClick:!0,startOffset:0,nextButton:!0,tipAnimation:"fade",pauseAfter:[],exposed:[],tipAnimationFadeSpeed:300,cookieMonster:!1,cookieName:"joyride",cookieDomain:!1,cookieExpires:365,tipContainer:"body",postRideCallback:function(){},postStepCallback:function(){},preStepCallback:function(){},preRideCallback:function(){},postExposeCallback:function(){},template:{link:'×',timer:'
    ',tip:'
    ',wrapper:'
    ',button:'',modal:'
    ',expose:'
    ',exposeCover:'
    '}},settings:{},init:function(t,n,r){return this.scope=t||this.scope,Foundation.inherit(this,"throttle data_options scrollTo scrollLeft delay"),typeof n=="object"?e.extend(!0,this.settings,this.defaults,n):e.extend(!0,this.settings,this.defaults,r),typeof n!="string"?(this.settings.init||this.events(),this.settings.init):this[n].call(this,r)},events:function(){var n=this;e(this.scope).on("click.joyride",".joyride-next-tip, .joyride-modal-bg",function(e){e.preventDefault(),this.settings.$li.next().length<1?this.end():this.settings.timer>0?(clearTimeout(this.settings.automate),this.hide(),this.show(),this.startTimer()):(this.hide(),this.show())}.bind(this)).on("click.joyride",".joyride-close-tip",function(e){e.preventDefault(),this.end()}.bind(this)),e(t).on("resize.fndtn.joyride",n.throttle(function(){if(e("[data-joyride]").length>0&&n.settings.$next_tip){if(n.settings.exposed.length>0){var t=e(n.settings.exposed);t.each(function(){var t=e(this);n.un_expose(t),n.expose(t)})}n.is_phone()?n.pos_phone():n.pos_default(!1,!0)}},100)),this.settings.init=!0},start:function(){var t=this,n=e(this.scope).find("[data-joyride]"),r=["timer","scrollSpeed","startOffset","tipAnimationFadeSpeed","cookieExpires"],i=r.length;this.settings.init||this.init(),this.settings.$content_el=n,this.settings.$body=e(this.settings.tipContainer),this.settings.body_offset=e(this.settings.tipContainer).position(),this.settings.$tip_content=this.settings.$content_el.find("> li"),this.settings.paused=!1,this.settings.attempts=0,this.settings.tipLocationPatterns={top:["bottom"],bottom:[],left:["right","top","bottom"],right:["left","top","bottom"]},typeof e.cookie!="function"&&(this.settings.cookieMonster=!1);if(!this.settings.cookieMonster||this.settings.cookieMonster&&e.cookie(this.settings.cookieName)===null)this.settings.$tip_content.each(function(n){var s=e(this);e.extend(!0,t.settings,t.data_options(s));for(var o=i-1;o>=0;o--)t.settings[r[o]]=parseInt(t.settings[r[o]],10);t.create({$li:s,index:n})}),!this.settings.startTimerOnClick&&this.settings.timer>0?(this.show("init"),this.startTimer()):this.show("init")},resume:function(){this.set_li(),this.show()},tip_template:function(t){var n,r;return t.tip_class=t.tip_class||"",n=e(this.settings.template.tip).addClass(t.tip_class),r=e.trim(e(t.li).html())+this.button_text(t.button_text)+this.settings.template.link+this.timer_instance(t.index),n.append(e(this.settings.template.wrapper)),n.first().attr("data-index",t.index),e(".joyride-content-wrapper",n).append(r),n[0]},timer_instance:function(t){var n;return t===0&&this.settings.startTimerOnClick&&this.settings.timer>0||this.settings.timer===0?n="":n=this.outerHTML(e(this.settings.template.timer)[0]),n},button_text:function(t){return this.settings.nextButton?(t=e.trim(t)||"Next",t=this.outerHTML(e(this.settings.template.button).append(t)[0])):t="",t},create:function(t){var n=t.$li.attr("data-button")||t.$li.attr("data-text"),r=t.$li.attr("class"),i=e(this.tip_template({tip_class:r,index:t.index,button_text:n,li:t.$li}));e(this.settings.tipContainer).append(i)},show:function(t){var n=null;this.settings.$li===r||e.inArray(this.settings.$li.index(),this.settings.pauseAfter)===-1?(this.settings.paused?this.settings.paused=!1:this.set_li(t),this.settings.attempts=0,this.settings.$li.length&&this.settings.$target.length>0?(t&&(this.settings.preRideCallback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.show_modal()),this.settings.preStepCallback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.settings.expose&&this.expose(),this.settings.tipSettings=e.extend(this.settings,this.data_options(this.settings.$li)),this.settings.timer=parseInt(this.settings.timer,10),this.settings.tipSettings.tipLocationPattern=this.settings.tipLocationPatterns[this.settings.tipSettings.tipLocation],/body/i.test(this.settings.$target.selector)||this.scroll_to(),this.is_phone()?this.pos_phone(!0):this.pos_default(!0),n=this.settings.$next_tip.find(".joyride-timer-indicator"),/pop/i.test(this.settings.tipAnimation)?(n.width(0),this.settings.timer>0?(this.settings.$next_tip.show(),this.delay(function(){n.animate({width:n.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tipAnimationFadeSpeed)):this.settings.$next_tip.show()):/fade/i.test(this.settings.tipAnimation)&&(n.width(0),this.settings.timer>0?(this.settings.$next_tip.fadeIn(this.settings.tipAnimationFadeSpeed).show(),this.delay(function(){n.animate({width:n.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tipAnimationFadeSpeed)):this.settings.$next_tip.fadeIn(this.settings.tipAnimationFadeSpeed)),this.settings.$current_tip=this.settings.$next_tip):this.settings.$li&&this.settings.$target.length<1?this.show():this.end()):this.settings.paused=!0},is_phone:function(){return Modernizr?Modernizr.mq("only screen and (max-width: 767px)")||e(".lt-ie9").length>0:this.settings.$window.width()<767?!0:!1},hide:function(){this.settings.modal&&this.settings.expose&&this.un_expose(),this.settings.modal||e(".joyride-modal-bg").hide(),this.settings.$current_tip.hide(),this.settings.postStepCallback(this.settings.$li.index(),this.settings.$current_tip)},set_li:function(e){e?(this.settings.$li=this.settings.$tip_content.eq(this.settings.startOffset),this.set_next_tip(),this.settings.$current_tip=this.settings.$next_tip):(this.settings.$li=this.settings.$li.next(),this.set_next_tip()),this.set_target()},set_next_tip:function(){this.settings.$next_tip=e(".joyride-tip-guide[data-index='"+this.settings.$li.index()+"']"),this.settings.$next_tip.data("closed","")},set_target:function(){var t=this.settings.$li.attr("data-class"),r=this.settings.$li.attr("data-id"),i=function(){return r?e(n.getElementById(r)):t?e("."+t).first():e("body")};this.settings.$target=i()},scroll_to:function(){var n,r;n=e(t).height()/2,r=Math.ceil(this.settings.$target.offset().top-n+this.outerHeight(this.settings.$next_tip)),r>0&&this.scrollTo(e("html, body"),r,this.settings.scrollSpeed)},paused:function(){return e.inArray(this.settings.$li.index()+1,this.settings.pauseAfter)===-1?!0:!1},restart:function(){this.hide(),this.settings.$li=r,this.show("init")},pos_default:function(n,r){var i=Math.ceil(e(t).height()/2),s=this.settings.$next_tip.offset(),o=this.settings.$next_tip.find(".joyride-nub"),u=Math.ceil(this.outerWidth(o)/2),a=Math.ceil(this.outerHeight(o)/2),f=n||!1;f&&(this.settings.$next_tip.css("visibility","hidden"),this.settings.$next_tip.show()),typeof r=="undefined"&&(r=!1);if(!/body/i.test(this.settings.$target.selector)){if(this.bottom()){var l=this.settings.$target.offset().left;Foundation.rtl&&(l=this.settings.$target.offset().width-this.settings.$next_tip.width()+l),this.settings.$next_tip.css({top:this.settings.$target.offset().top+a+this.outerHeight(this.settings.$target),left:l}),this.nub_position(o,this.settings.tipSettings.nubPosition,"top")}else if(this.top()){var l=this.settings.$target.offset().left;Foundation.rtl&&(l=this.settings.$target.offset().width-this.settings.$next_tip.width()+l),this.settings.$next_tip.css({top:this.settings.$target.offset().top-this.outerHeight(this.settings.$next_tip)-a,left:l}),this.nub_position(o,this.settings.tipSettings.nubPosition,"bottom")}else this.right()?(this.settings.$next_tip.css({top:this.settings.$target.offset().top,left:this.outerWidth(this.settings.$target)+this.settings.$target.offset().left+u}),this.nub_position(o,this.settings.tipSettings.nubPosition,"left")):this.left()&&(this.settings.$next_tip.css({top:this.settings.$target.offset().top,left:this.settings.$target.offset().left-this.outerWidth(this.settings.$next_tip)-u}),this.nub_position(o,this.settings.tipSettings.nubPosition,"right"));!this.visible(this.corners(this.settings.$next_tip))&&this.settings.attempts0&&arguments[0]instanceof e)i=arguments[0];else{if(!this.settings.$target||!!/body/i.test(this.settings.$target.selector))return!1;i=this.settings.$target}if(i.length<1)return t.console&&console.error("element not valid",i),!1;n=e(this.settings.template.expose),this.settings.$body.append(n),n.css({top:i.offset().top,left:i.offset().left,width:this.outerWidth(i,!0),height:this.outerHeight(i,!0)}),r=e(this.settings.template.exposeCover),s={zIndex:i.css("z-index"),position:i.css("position")},i.css("z-index",n.css("z-index")*1+1),s.position=="static"&&i.css("position","relative"),i.data("expose-css",s),r.css({top:i.offset().top,left:i.offset().left,width:this.outerWidth(i,!0),height:this.outerHeight(i,!0)}),this.settings.$body.append(r),n.addClass(o),r.addClass(o),i.data("expose",o),this.settings.postExposeCallback(this.settings.$li.index(),this.settings.$next_tip,i),this.add_exposed(i)},un_expose:function(){var n,r,i,s,o=!1;if(arguments.length>0&&arguments[0]instanceof e)r=arguments[0];else{if(!this.settings.$target||!!/body/i.test(this.settings.$target.selector))return!1;r=this.settings.$target}if(r.length<1)return t.console&&console.error("element not valid",r),!1;n=r.data("expose"),i=e("."+n),arguments.length>1&&(o=arguments[1]),o===!0?e(".joyride-expose-wrapper,.joyride-expose-cover").remove():i.remove(),s=r.data("expose-css"),s.zIndex=="auto"?r.css("z-index",""):r.css("z-index",s.zIndex),s.position!=r.css("position")&&(s.position=="static"?r.css("position",""):r.css("position",s.position)),r.removeData("expose"),r.removeData("expose-z-index"),this.remove_exposed(r)},add_exposed:function(t){this.settings.exposed=this.settings.exposed||[],t instanceof e||typeof t=="object"?this.settings.exposed.push(t[0]):typeof t=="string"&&this.settings.exposed.push(t)},remove_exposed:function(t){var n,r;t instanceof e?n=t[0]:typeof t=="string"&&(n=t),this.settings.exposed=this.settings.exposed||[],r=this.settings.exposed.length;for(var i=0;ia&&(a=u),[n.offset().topn.offset().left]},visible:function(e){var t=e.length;while(t--)if(e[t])return!1;return!0},nub_position:function(e,t,n){t==="auto"?e.addClass(n):e.addClass(t)},startTimer:function(){this.settings.$li.length?this.settings.automate=setTimeout(function(){this.hide(),this.show(),this.startTimer()}.bind(this),this.settings.timer):clearTimeout(this.settings.automate)},end:function(){this.settings.cookieMonster&&e.cookie(this.settings.cookieName,"ridden",{expires:this.settings.cookieExpires,domain:this.settings.cookieDomain}),this.settings.timer>0&&clearTimeout(this.settings.automate),this.settings.modal&&this.settings.expose&&this.un_expose(),this.settings.$next_tip.data("closed",!0),e(".joyride-modal-bg").hide(),this.settings.$current_tip.hide(),this.settings.postStepCallback(this.settings.$li.index(),this.settings.$current_tip),this.settings.postRideCallback(this.settings.$li.index(),this.settings.$current_tip)},outerHTML:function(e){return e.outerHTML||(new XMLSerializer).serializeToString(e)},off:function(){e(this.scope).off(".joyride"),e(t).off(".joyride"),e(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off(".joyride"),e(".joyride-tip-guide, .joyride-modal-bg").remove(),clearTimeout(this.settings.automate),this.settings={}}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs.magellan={name:"magellan",version:"4.0.0",settings:{activeClass:"active"},init:function(t,n,r){return this.scope=t||this.scope,Foundation.inherit(this,"data_options"),typeof n=="object"&&e.extend(!0,this.settings,n),typeof n!="string"?(this.settings.init||(this.fixed_magellan=e("[data-magellan-expedition]"),this.set_threshold(),this.last_destination=e("[data-magellan-destination]").last(),this.events()),this.settings.init):this[n].call(this,r)},events:function(){var n=this;e(this.scope).on("arrival.fndtn.magellan","[data-magellan-arrival]",function(t){var r=e(this),i=r.closest("[data-magellan-expedition]"),s=i.attr("data-magellan-active-class")||n.settings.activeClass;r.closest("[data-magellan-expedition]").find("[data-magellan-arrival]").not(r).removeClass(s),r.addClass(s)}),this.fixed_magellan.on("update-position.fndtn.magellan",function(){var t=e(this)}).trigger("update-position"),e(t).on("resize.fndtn.magellan",function(){this.fixed_magellan.trigger("update-position")}.bind(this)).on("scroll.fndtn.magellan",function(){var r=e(t).scrollTop();n.fixed_magellan.each(function(){var t=e(this);typeof t.data("magellan-top-offset")=="undefined"&&t.data("magellan-top-offset",t.offset().top),typeof t.data("magellan-fixed-position")=="undefined"&&t.data("magellan-fixed-position",!1);var i=r+n.settings.threshold>t.data("magellan-top-offset"),s=t.attr("data-magellan-top-offset");t.data("magellan-fixed-position")!=i&&(t.data("magellan-fixed-position",i),i?t.css({position:"fixed",top:0}):t.css({position:"",top:""}),i&&typeof s!="undefined"&&s!=0&&t.css({position:"fixed",top:s+"px"}))})}),this.last_destination.length>0&&e(t).on("scroll.fndtn.magellan",function(r){var i=e(t).scrollTop(),s=i+e(t).height(),o=Math.ceil(n.last_destination.offset().top);e("[data-magellan-destination]").each(function(){var t=e(this),r=t.attr("data-magellan-destination"),u=t.offset().top-i;u<=n.settings.threshold&&e("[data-magellan-arrival='"+r+"']").trigger("arrival"),s>=e(n.scope).height()&&o>i&&o0?this.outerHeight(this.fixed_magellan,!0):0)},off:function(){e(this.scope).off(".fndtn.magellan")}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs=Foundation.libs||{},Foundation.libs.orbit={name:"orbit",version:"4.1.0",settings:{timer_speed:1e4,animation_speed:500,bullets:!0,stack_on_small:!0,container_class:"orbit-container",stack_on_small_class:"orbit-stack-on-small",next_class:"orbit-next",prev_class:"orbit-prev",timer_container_class:"orbit-timer",timer_paused_class:"paused",timer_progress_class:"orbit-progress",slides_container_class:"orbit-slides-container",bullets_container_class:"orbit-bullets",bullets_active_class:"active",slide_number_class:"orbit-slide-number",caption_class:"orbit-caption",active_slide_class:"active",orbit_transition_class:"orbit-transitioning"},init:function(t,n,r){var i=this;Foundation.inherit(i,"data_options"),typeof n=="object"&&e.extend(!0,i.settings,n),e("[data-orbit]",t).each(function(t,n){var r=e.extend(!0,{},i);r._init(t,n)})},_container_html:function(){var e=this;return'
    '},_bullets_container_html:function(t){var n=this,r=e('
      ');return t.each(function(t,i){var s=e('
    1. ');t===0&&s.addClass(n.settings.bullets_active_class),r.append(s)}),r},_slide_number_html:function(t,n){var r=this,i=e('
      ');return i.append(""+t+" of "+n+""),i},_timer_html:function(){var e=this;return typeof e.settings.timer_speed=="number"&&e.settings.timer_speed>0?'
      ':""},_next_html:function(){var e=this;return'Next '},_prev_html:function(){var e=this;return'Prev '},_init:function(t,n){var r=this,i=e(n),s=i.wrap(r._container_html()).parent(),o=i.children();e.extend(!0,r.settings,r.data_options(i)),s.append(r._prev_html()),s.append(r._next_html()),i.addClass(r.settings.slides_container_class),r.settings.stack_on_small&&s.addClass(r.settings.stack_on_small_class),s.append(r._slide_number_html(1,o.length)),s.append(r._timer_html()),r.settings.bullets&&s.after(r._bullets_container_html(o)),i.append(o.first().clone().attr("data-orbit-slide","")),i.prepend(o.last().clone().attr("data-orbit-slide","")),i.css("marginLeft","-100%"),o.first().addClass(r.settings.active_slide_class),r._init_events(i),r._init_dimensions(i),r._start_timer(i)},_init_events:function(i){var s=this,o=i.parent();e(t).on("load.fndtn.orbit",function(){i.height(""),i.height(i.height(o.height())),i.trigger("orbit:ready")}).on("resize.fndtn.orbit",function(){i.height(""),i.height(i.height(o.height()))}),e(n).on("click.fndtn.orbit","[data-orbit-link]",function(t){t.preventDefault();var n=e(t.currentTarget).attr("data-orbit-link"),r=i.find("[data-orbit-slide="+n+"]").first();r.length===1&&(s._reset_timer(i,!0),s._goto(i,r.index(),function(){}))}),o.siblings("."+s.settings.bullets_container_class).on("click.fndtn.orbit","[data-orbit-slide-number]",function(t){t.preventDefault(),s._reset_timer(i,!0),s._goto(i,e(t.currentTarget).data("orbit-slide-number"),function(){})}),o.on("orbit:after-slide-change.fndtn.orbit",function(e,t){var n=o.find("."+s.settings.slide_number_class);n.length===1&&n.replaceWith(s._slide_number_html(t.slide_number,t.total_slides))}).on("orbit:next-slide.fndtn.orbit click.fndtn.orbit","."+s.settings.next_class,function(e){e.preventDefault(),s._reset_timer(i,!0),s._goto(i,"next",function(){})}).on("orbit:prev-slide.fndtn.orbit click.fndtn.orbit","."+s.settings.prev_class,function(e){e.preventDefault(),s._reset_timer(i,!0),s._goto(i,"prev",function(){})}).on("orbit:toggle-play-pause.fndtn.orbit click.fndtn.orbit touchstart.fndtn.orbit","."+s.settings.timer_container_class,function(t){t.preventDefault();var n=e(t.currentTarget).toggleClass(s.settings.timer_paused_class),r=n.closest("."+s.settings.container_class).find("."+s.settings.slides_container_class);n.hasClass(s.settings.timer_paused_class)?s._stop_timer(r):s._start_timer(r)}).on("touchstart.fndtn.orbit",function(e){e.touches||(e=e.originalEvent);var t={start_page_x:e.touches[0].pageX,start_page_y:e.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:r};o.data("swipe-transition",t),e.stopPropagation()}).on("touchmove.fndtn.orbit",function(e){e.touches||(e=e.originalEvent);if(e.touches.length>1||e.scale&&e.scale!==1)return;var t=o.data("swipe-transition");typeof t=="undefined"&&(t={}),t.delta_x=e.touches[0].pageX-t.start_page_x,typeof t.is_scrolling=="undefined"&&(t.is_scrolling=!!(t.is_scrolling||Math.abs(t.delta_x)").attr(n.extend(f(this),{type:"text"}))}e.removeAttr("name").data({"placeholder-password":!0,"placeholder-id":s}).bind("focus.placeholder",l),r.data({"placeholder-textinput":e,"placeholder-id":s}).before(e)}r=r.removeAttr("id").hide().prev().attr("id",s).show()}r.addClass("placeholder"),r[0].value=r.attr("placeholder")}else r.removeClass("placeholder")}var r="placeholder"in t.createElement("input"),i="placeholder"in t.createElement("textarea"),s=n.fn,o=n.valHooks,u,a;r&&i?(a=s.placeholder=function(){return this},a.input=a.textarea=!0):(a=s.placeholder=function(){var e=this;return e.filter((r?"textarea":":input")+"[placeholder]").not(".placeholder").bind({"focus.placeholder":l,"blur.placeholder":c}).data("placeholder-enabled",!0).trigger("blur.placeholder"),e},a.input=r,a.textarea=i,u={get:function(e){var t=n(e);return t.data("placeholder-enabled")&&t.hasClass("placeholder")?"":e.value},set:function(e,r){var i=n(e);return i.data("placeholder-enabled")?(r==""?(e.value=r,e!=t.activeElement&&c.call(e)):i.hasClass("placeholder")?l.call(e,!0,r)||(e.value=r):e.value=r,i):e.value=r}},r||(o.input=u),i||(o.textarea=u),n(function(){n(t).delegate("form","submit.placeholder",function(){var e=n(".placeholder",this).each(l);setTimeout(function(){e.each(c)},10)})}),n(e).bind("beforeunload.placeholder",function(){n(".placeholder").each(function(){this.value=""})}))}(this,document,Foundation.zj),function(e,t,n,r){"use strict";Foundation.libs.reveal={name:"reveal",version:"4.1.2",locked:!1,settings:{animation:"fadeAndPop",animationSpeed:250,closeOnBackgroundClick:!0,dismissModalClass:"close-reveal-modal",bgClass:"reveal-modal-bg",open:function(){},opened:function(){},close:function(){},closed:function(){},bg:e(".reveal-modal-bg"),css:{open:{opacity:0,visibility:"visible",display:"block"},close:{opacity:1,visibility:"hidden",display:"none"}}},init:function(t,n,r){return this.scope=t||this.scope,Foundation.inherit(this,"data_options delay"),typeof n=="object"?e.extend(!0,this.settings,n):typeof r!="undefined"&&e.extend(!0,this.settings,r),typeof n!="string"?(this.events(),this.settings.init):this[n].call(this,r)},events:function(){var t=this;return e(this.scope).off(".fndtn.reveal").on("click.fndtn.reveal","[data-reveal-id]",function(n){n.preventDefault(),t.locked||(t.locked=!0,t.open.call(t,e(this)))}).on("click.fndtn.reveal touchend.click.fndtn.reveal",this.close_targets(),function(n){n.preventDefault(),t.locked||(t.locked=!0,t.close.call(t,e(this).closest(".reveal-modal")))}).on("open.fndtn.reveal",".reveal-modal",this.settings.open).on("opened.fndtn.reveal",".reveal-modal",this.settings.opened).on("opened.fndtn.reveal",".reveal-modal",this.open_video).on("close.fndtn.reveal",".reveal-modal",this.settings.close).on("closed.fndtn.reveal",".reveal-modal",this.settings.closed).on("closed.fndtn.reveal",".reveal-modal",this.close_video),!0},open:function(t){if(t)var n=e("#"+t.data("reveal-id"));else var n=e(this.scope);if(!n.hasClass("open")){var r=e(".reveal-modal.open");typeof n.data("css-top")=="undefined"&&n.data("css-top",parseInt(n.css("top"),10)).data("offset",this.cache_offset(n)),n.trigger("open"),r.length<1&&this.toggle_bg(n),this.hide(r,this.settings.css.open),this.show(n,this.settings.css.open)}},close:function(t){var t=t||e(this.scope),n=e(".reveal-modal.open");n.length>0&&(this.locked=!0,t.trigger("close"),this.toggle_bg(t),this.hide(n,this.settings.css.close))},close_targets:function(){var e="."+this.settings.dismissModalClass;return this.settings.closeOnBackgroundClick?e+", ."+this.settings.bgClass:e},toggle_bg:function(t){e(".reveal-modal-bg").length===0&&(this.settings.bg=e("
      ",{"class":this.settings.bgClass}).appendTo("body")),this.settings.bg.filter(":visible").length>0?this.hide(this.settings.bg):this.show(this.settings.bg)},show:function(n,r){if(r){if(/pop/i.test(this.settings.animation)){r.top=e(t).scrollTop()-n.data("offset")+"px";var i={top:e(t).scrollTop()+n.data("css-top")+"px",opacity:1};return this.delay(function(){return n.css(r).animate(i,this.settings.animationSpeed,"linear",function(){this.locked=!1,n.trigger("opened")}.bind(this)).addClass("open")}.bind(this),this.settings.animationSpeed/2)}if(/fade/i.test(this.settings.animation)){var i={opacity:1};return this.delay(function(){return n.css(r).animate(i,this.settings.animationSpeed,"linear",function(){this.locked=!1,n.trigger("opened")}.bind(this)).addClass("open")}.bind(this),this.settings.animationSpeed/2)}return n.css(r).show().css({opacity:1}).addClass("open").trigger("opened")}return/fade/i.test(this.settings.animation)?n.fadeIn(this.settings.animationSpeed/2):n.show()},hide:function(n,r){if(r){if(/pop/i.test(this.settings.animation)){var i={top:-e(t).scrollTop()-n.data("offset")+"px",opacity:0};return this.delay(function(){return n.animate(i,this.settings.animationSpeed,"linear",function(){this.locked=!1,n.css(r).trigger("closed")}.bind(this)).removeClass("open")}.bind(this),this.settings.animationSpeed/2)}if(/fade/i.test(this.settings.animation)){var i={opacity:0};return this.delay(function(){return n.animate(i,this.settings.animationSpeed,"linear",function(){this.locked=!1,n.css(r).trigger("closed")}.bind(this)).removeClass("open")}.bind(this),this.settings.animationSpeed/2)}return n.hide().css(r).removeClass("open").trigger("closed")}return/fade/i.test(this.settings.animation)?n.fadeOut(this.settings.animationSpeed/2):n.hide()},close_video:function(t){var n=e(this).find(".flex-video"),r=n.find("iframe");r.length>0&&(r.attr("data-src",r[0].src),r.attr("src","about:blank"),n.fadeOut(100).hide())},open_video:function(t){var n=e(this).find(".flex-video"),r=n.find("iframe");if(r.length>0){var i=r.attr("data-src");typeof i=="string"&&(r[0].src=r.attr("data-src")),n.show().fadeIn(100)}},cache_offset:function(e){var t=e.show().height()+parseInt(e.css("top"),10);return e.hide(),t},off:function(){e(this.scope).off(".fndtn.reveal")}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs.section={name:"section",version:"4.1.2",settings:{deep_linking:!1,one_up:!0,callback:function(){}},init:function(e,t,n){var r=this;return Foundation.inherit(this,"throttle data_options position_right offset_right"),typeof t!="string"?(this.set_active_from_hash(),this.events(),!0):this[t].call(this,n)},events:function(){var r=this;e(this.scope).on("click.fndtn.section","[data-section] .title, [data-section] [data-section-title]",function(t){var n=e(this),i=n.closest("[data-section]");r.toggle_active.call(this,t,r)}),e(t).on("resize.fndtn.section",r.throttle(function(){r.resize.call(this)},30)).on("hashchange",function(){r.settings.toggled||(r.set_active_from_hash(),e(this).trigger("resize"))}).trigger("resize"),e(n).on("click.fndtn.section",function(t){e(t.target).closest(".title, [data-section-title]").length<1&&e('[data-section="vertical-nav"], [data-section="horizontal-nav"]').find("section, .section, [data-section-region]").removeClass("active").attr("style","")})},toggle_active:function(t,n){var r=e(this),i=r.closest("section, .section, [data-section-region]"),s=i.find(".content, [data-section-content]"),o=i.closest("[data-section]"),n=Foundation.libs.section,u=e.extend({},n.settings,n.data_options(o));n.settings.toggled=!0,!u.deep_linking&&s.length>0&&t.preventDefault();if(i.hasClass("active"))(n.small(o)||n.is_vertical(o)||n.is_horizontal(o)||n.is_accordion(o))&&i.removeClass("active").attr("style","");else{var a=null,f=n.outerHeight(i.find(".title, [data-section-title]"));if(n.small(o)||u.one_up)a=r.closest("[data-section]").find("section.active, .section.active, .active[data-section-region]"),n.small(o)?a.attr("style",""):a.attr("style","visibility: hidden; padding-top: "+f+"px;");n.small(o)?i.attr("style",""):i.css("padding-top",f),i.addClass("active"),a!==null&&a.removeClass("active").attr("style","")}setTimeout(function(){n.settings.toggled=!1},300),u.callback()},resize:function(){var t=e("[data-section]"),n=Foundation.libs.section;t.each(function(){var t=e(this),r=t.find("section.active, .section.active, .active[data-section-region]"),i=e.extend({},n.settings,n.data_options(t));if(r.length>1)r.not(":first").removeClass("active").attr("style","");else if(r.length<1&&!n.is_vertical(t)&&!n.is_horizontal(t)&&!n.is_accordion(t)){var s=t.find("section, .section, [data-section-region]").first();i.one_up&&s.addClass("active"),n.small(t)?s.attr("style",""):s.css("padding-top",n.outerHeight(s.find(".title, [data-section-title]")))}n.small(t)?r.attr("style",""):r.css("padding-top",n.outerHeight(r.find(".title, [data-section-title]"))),n.position_titles(t),n.is_horizontal(t)&&!n.small(t)?n.position_content(t):n.position_content(t,!1)})},is_vertical:function(e){return/vertical-nav/i.test(e.data("section"))},is_horizontal:function(e){return/horizontal-nav/i.test(e.data("section"))},is_accordion:function(e){return/accordion/i.test(e.data("section"))},is_tabs:function(e){return/tabs/i.test(e.data("section"))},set_active_from_hash:function(){var n=t.location.hash.substring(1),r=e("[data-section]"),i=this;r.each(function(){var t=e(this),r=e.extend({},i.settings,i.data_options(t));n.length>0&&r.deep_linking&&(t.find("section, .section, [data-section-region]").attr("style","").removeClass("active"),t.find('.content[data-slug="'+n+'"], [data-section-content][data-slug="'+n+'"]').closest("section, .section, [data-section-region]").addClass("active"))})},position_titles:function(t,n){var r=t.find(".title, [data-section-title]"),i=0,s=this;typeof n=="boolean"?r.attr("style",""):r.each(function(){s.rtl?e(this).css("right",i):e(this).css("left",i),i+=s.outerWidth(e(this))})},position_content:function(t,n){var r=t.find(".title, [data-section-title]"),i=t.find(".content, [data-section-content]"),s=this;typeof n=="boolean"?(i.attr("style",""),t.attr("style","")):(t.find("section, .section, [data-section-region]").each(function(){var t=e(this).find(".title, [data-section-title]"),n=e(this).find(".content, [data-section-content]");s.rtl?n.css({right:s.position_right(t)+1,top:s.outerHeight(t)-2}):n.css({left:t.position().left-1,top:s.outerHeight(t)-2})}),typeof Zepto=="function"?t.height(this.outerHeight(r.first())):t.height(this.outerHeight(r.first())-2))},position_right:function(e){var t=e.closest("[data-section]"),n=e.closest("[data-section]").width(),r=t.find(".title, [data-section-title]").length;return n-e.position().left-e.width()*(e.index()+1)-r},reflow:function(){e("[data-section]").trigger("resize")},small:function(t){var n=e.extend({},this.settings,this.data_options(t));return this.is_tabs(t)?!1:t&&this.is_accordion(t)?!0:e("html").hasClass("lt-ie9")?!0:e("html").hasClass("ie8compat")?!0:e(this.scope).width()<768},off:function(){e(this.scope).off(".fndtn.section"),e(t).off(".fndtn.section"),e(n).off(".fndtn.section")}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs.tooltips={name:"tooltips",version:"4.1.0",settings:{selector:".has-tip",additionalInheritableClasses:[],tooltipClass:".tooltip",tipTemplate:function(e,t){return''+t+''}},cache:{},init:function(t,n,r){var i=this;this.scope=t||this.scope,typeof n=="object"&&e.extend(!0,this.settings,n);if(typeof n=="string")return this[n].call(this,r);Modernizr.touch?e(this.scope).on("click.fndtn.tooltip touchstart.fndtn.tooltip touchend.fndtn.tooltip","[data-tooltip]",function(t){t.preventDefault(),e(i.settings.tooltipClass).hide(),i.showOrCreateTip(e(this))}).on("click.fndtn.tooltip touchstart.fndtn.tooltip touchend.fndtn.tooltip",this.settings.tooltipClass,function(t){t.preventDefault(),e(this).fadeOut(150)}):e(this.scope).on("mouseenter.fndtn.tooltip mouseleave.fndtn.tooltip","[data-tooltip]",function(t){var n=e(this);t.type==="mouseover"||t.type==="mouseenter"?i.showOrCreateTip(n):(t.type==="mouseout"||t.type==="mouseleave")&&i.hide(n)})},showOrCreateTip:function(e){var t=this.getTip(e);return t&&t.length>0?this.show(e):this.create(e)},getTip:function(t){var n=this.selector(t),r=null;return n&&(r=e("span[data-selector="+n+"]"+this.settings.tooltipClass)),typeof r=="object"?r:!1},selector:function(e){var t=e.attr("id"),n=e.attr("data-tooltip")||e.attr("data-selector");return(t&&t.length<1||!t)&&typeof n!="string"&&(n="tooltip"+Math.random().toString(36).substring(7),e.attr("data-selector",n)),t&&t.length>0?t:n},create:function(t){var n=e(this.settings.tipTemplate(this.selector(t),e("
      ").html(t.attr("title")).html())),r=this.inheritable_classes(t);n.addClass(r).appendTo("body"),Modernizr.touch&&n.append('tap to close '),t.removeAttr("title").attr("title",""),this.show(t)},reposition:function(n,r,i){var s,o,u,a,f,l;r.css("visibility","hidden").show(),s=n.data("width"),o=r.children(".nub"),u=this.outerHeight(o),a=this.outerHeight(o),l=function(e,t,n,r,i,s){return e.css({top:t?t:"auto",bottom:r?r:"auto",left:i?i:"auto",right:n?n:"auto",width:s?s:"auto"}).end()},l(r,n.offset().top+this.outerHeight(n)+10,"auto","auto",n.offset().left,s);if(e(t).width()<767)l(r,n.offset().top+this.outerHeight(n)+10,"auto","auto",12.5,e(this.scope).width()),r.addClass("tip-override"),l(o,-u,"auto","auto",n.offset().left);else{var c=n.offset().left;Foundation.rtl&&(c=n.offset().left+n.offset().width-this.outerWidth(r)),l(r,n.offset().top+this.outerHeight(n)+10,"auto","auto",c,s),r.removeClass("tip-override"),i&&i.indexOf("tip-top")>-1?l(r,n.offset().top-this.outerHeight(r),"auto","auto",c,s).removeClass("tip-override"):i&&i.indexOf("tip-left")>-1?l(r,n.offset().top+this.outerHeight(n)/2-u*2.5,"auto","auto",n.offset().left-this.outerWidth(r)-u,s).removeClass("tip-override"):i&&i.indexOf("tip-right")>-1&&l(r,n.offset().top+this.outerHeight(n)/2-u*2.5,"auto","auto",n.offset().left+this.outerWidth(n)+u,s).removeClass("tip-override")}r.css("visibility","visible").hide()},inheritable_classes:function(t){var n=["tip-top","tip-left","tip-bottom","tip-right","noradius"].concat(this.settings.additionalInheritableClasses),r=t.attr("class"),i=r?e.map(r.split(" "),function(t,r){if(e.inArray(t,n)!==-1)return t}).join(" "):"";return e.trim(i)},show:function(e){var t=this.getTip(e);this.reposition(e,t,e.attr("class")),t.fadeIn(150)},hide:function(e){var t=this.getTip(e);t.fadeOut(150)},reload:function(){var t=e(this);return t.data("fndtn-tooltips")?t.foundationTooltips("destroy").foundationTooltips("init"):t.foundationTooltips("init")},off:function(){e(this.scope).off(".fndtn.tooltip"),e(this.settings.tooltipClass).each(function(t){e("[data-tooltip]").get(t).attr("title",e(this).text())}).remove()}}}(Foundation.zj,this,this.document),function(e,t,n,r){"use strict";Foundation.libs.topbar={name:"topbar",version:"4.1.2",settings:{index:0,stickyClass:"sticky",custom_back_text:!0,back_text:"Back",init:!1},init:function(n,r,i){var s=this;return typeof r=="object"&&e.extend(!0,this.settings,r),typeof r!="string"?(e(".top-bar").each(function(){s.settings.$w=e(t),s.settings.$topbar=e(this),s.settings.$section=s.settings.$topbar.find("section"),s.settings.$titlebar=s.settings.$topbar.children("ul").first(),s.settings.$topbar.data("index",0);var n=e("
      ").insertAfter(s.settings.$topbar);s.settings.breakPoint=n.width(),n.remove(),s.assemble(),s.settings.$topbar.parent().hasClass("fixed")&&e("body").css("padding-top",s.outerHeight(s.settings.$topbar))}),s.settings.init||this.events(),this.settings.init):this[r].call(this,i)},events:function(){var n=this,r=this.outerHeight(e(".top-bar"));e(this.scope).on("click.fndtn.topbar",".top-bar .toggle-topbar",function(i){var s=e(this).closest(".top-bar"),o=s.find("section, .section"),u=s.children("ul").first();s.data("height")||n.largestUL(),i.preventDefault(),n.breakpoint()&&s.toggleClass("expanded").css("min-height",""),s.hasClass("expanded")?s.parent().hasClass("fixed")&&(s.parent().removeClass("fixed"),s.addClass("fixed"),e("body").css("padding-top","0"),t.scrollTo(0,0)):(n.rtl?(o.css({right:"0%"}),o.find(">.name").css({right:"100%"})):(o.css({left:"0%"}),o.find(">.name").css({left:"100%"})),o.find("li.moved").removeClass("moved"),s.data("index",0),s.hasClass("fixed")&&(s.parent().addClass("fixed"),s.removeClass("fixed"),e("body").css("padding-top",r)))}).on("click.fndtn.topbar",".top-bar .has-dropdown>a",function(t){var r=e(this).closest(".top-bar"),i=r.find("section, .section"),s=r.children("ul").first();(Modernizr.touch||n.breakpoint())&&t.preventDefault();if(n.breakpoint()){var o=e(this),u=o.closest("li");r.data("index",r.data("index")+1),u.addClass("moved"),n.rtl?(i.css({right:-(100*r.data("index"))+"%"}),i.find(">.name").css({right:100*r.data("index")+"%"})):(i.css({left:-(100*r.data("index"))+"%"}),i.find(">.name").css({left:100*r.data("index")+"%"})),o.siblings("ul").height(r.data("height")+n.outerHeight(s,!0)),r.css("min-height",r.data("height")+n.outerHeight(s,!0)*2)}}),e(t).on("resize.fndtn.topbar",function(){n.breakpoint()||e(".top-bar").css("min-height","").removeClass("expanded")}.bind(this)),e(this.scope).on("click.fndtn",".top-bar .has-dropdown .back",function(t){t.preventDefault();var r=e(this),i=r.closest(".top-bar"),s=i.find("section, .section"),o=r.closest("li.moved"),u=o.parent();i.data("index",i.data("index")-1),n.rtl?(s.css({right:-(100*i.data("index"))+"%"}),s.find(">.name").css({right:100*i.data("index")+"%"})):(s.css({left:-(100*i.data("index"))+"%"}),s.find(">.name").css({left:100*i.data("index")+"%" +})),i.data("index")===0&&i.css("min-height",0),setTimeout(function(){o.removeClass("moved")},300)})},breakpoint:function(){return e(t).width()<=this.settings.breakPoint||e("html").hasClass("lt-ie9")},assemble:function(){var t=this;this.settings.$section.detach(),this.settings.$section.find(".has-dropdown>a").each(function(){var n=e(this),r=n.siblings(".dropdown"),i=e('
    2. ');t.settings.custom_back_text==1?i.find("h5>a").html("« "+t.settings.back_text):i.find("h5>a").html("« "+n.html()),r.prepend(i)}),this.settings.$section.appendTo(this.settings.$topbar),this.sticky()},largestUL:function(){var t=this.settings.$topbar.find("section ul ul"),n=t.first(),r=0,i=this;t.each(function(){e(this).children("li").length>n.children("li").length&&(n=e(this))}),n.children("li").each(function(){r+=i.outerHeight(e(this),!0)}),this.settings.$topbar.data("height",r)},sticky:function(){var n="."+this.settings.stickyClass;if(e(n).length>0){var r=e(n).length?e(n).offset().top:0,i=e(t),s=this.outerHeight(e(".top-bar"));i.scroll(function(){i.scrollTop()>=r?(e(n).addClass("fixed"),e("body").css("padding-top",s)):i.scrollTop()×' + + '' + }, + + // comma delimited list of selectors that, on click, will close clearing, + // add 'div.clearing-blackout, div.visible-img' to close on background click + close_selectors : '.clearing-close', + + // event initializers and locks + init : false, + locked : false + }, + + init : function (scope, method, options) { + var self = this; + Foundation.inherit(this, 'set_data get_data remove_data throttle data_options'); + + if (typeof method === 'object') { + options = $.extend(true, this.settings, method); + } + + if (typeof method != 'string') { + $(this.scope).find('ul[data-clearing]').each(function () { + var $el = $(this), + options = options || {}, + lis = $el.find('li'), + settings = self.get_data($el); + + if (!settings && lis.length > 0) { + options.$parent = $el.parent(); + + self.set_data($el, $.extend({}, self.settings, options, self.data_options($el))); + + self.assemble($el.find('li')); + + if (!self.settings.init) { + self.events().swipe_events(); + } + } + }); + + return this.settings.init; + } else { + // fire method + return this[method].call(this, options); + } + }, + + // event binding and initial setup + + events : function () { + var self = this; + + $(this.scope) + .on('click.fndtn.clearing', 'ul[data-clearing] li', + function (e, current, target) { + var current = current || $(this), + target = target || current, + next = current.next('li'), + settings = self.get_data(current.parent()), + image = $(e.target); + + e.preventDefault(); + if (!settings) self.init(); + + // if clearing is open and the current image is + // clicked, go to the next image in sequence + if (target.hasClass('visible') + && current[0] === target[0] + && next.length > 0 && self.is_open(current)) { + target = next; + image = target.find('img'); + } + + // set current and target to the clicked li if not otherwise defined. + self.open(image, current, target); + self.update_paddles(target); + }) + + .on('click.fndtn.clearing', '.clearing-main-next', + function (e) { this.nav(e, 'next') }.bind(this)) + .on('click.fndtn.clearing', '.clearing-main-prev', + function (e) { this.nav(e, 'prev') }.bind(this)) + .on('click.fndtn.clearing', this.settings.close_selectors, + function (e) { Foundation.libs.clearing.close(e, this) }) + .on('keydown.fndtn.clearing', + function (e) { this.keydown(e) }.bind(this)); + + $(window).on('resize.fndtn.clearing', + function (e) { this.resize() }.bind(this)); + + this.settings.init = true; + return this; + }, + + swipe_events : function () { + var self = this; + + $(this.scope) + .on('touchstart.fndtn.clearing', '.visible-img', function(e) { + if (!e.touches) { e = e.originalEvent; } + var data = { + start_page_x: e.touches[0].pageX, + start_page_y: e.touches[0].pageY, + start_time: (new Date()).getTime(), + delta_x: 0, + is_scrolling: undefined + }; + + $(this).data('swipe-transition', data); + e.stopPropagation(); + }) + .on('touchmove.fndtn.clearing', '.visible-img', function(e) { + if (!e.touches) { e = e.originalEvent; } + // Ignore pinch/zoom events + if(e.touches.length > 1 || e.scale && e.scale !== 1) return; + + var data = $(this).data('swipe-transition'); + + if (typeof data === 'undefined') { + data = {}; + } + + data.delta_x = e.touches[0].pageX - data.start_page_x; + + if ( typeof data.is_scrolling === 'undefined') { + data.is_scrolling = !!( data.is_scrolling || Math.abs(data.delta_x) < Math.abs(e.touches[0].pageY - data.start_page_y) ); + } + + if (!data.is_scrolling && !data.active) { + e.preventDefault(); + var direction = (data.delta_x < 0) ? 'next' : 'prev'; + data.active = true; + self.nav(e, direction); + } + }) + .on('touchend.fndtn.clearing', '.visible-img', function(e) { + $(this).data('swipe-transition', {}); + e.stopPropagation(); + }); + }, + + assemble : function ($li) { + var $el = $li.parent(); + $el.after('
      '); + + var holder = $('#foundationClearingHolder'), + settings = this.get_data($el), + grid = $el.detach(), + data = { + grid: '', + viewing: settings.templates.viewing + }, + wrapper = '
      ' + data.viewing + + data.grid + '
      '; + + return holder.after(wrapper).remove(); + }, + + // event callbacks + + open : function ($image, current, target) { + var root = target.closest('.clearing-assembled'), + container = root.find('div').first(), + visible_image = container.find('.visible-img'), + image = visible_image.find('img').not($image); + + if (!this.locked()) { + // set the image to the selected thumbnail + image + .attr('src', this.load($image)) + .css('visibility', 'hidden'); + + this.loaded(image, function () { + image.css('visibility', 'visible'); + // toggle the gallery + root.addClass('clearing-blackout'); + container.addClass('clearing-container'); + visible_image.show(); + this.fix_height(target) + .caption(visible_image.find('.clearing-caption'), $image) + .center(image) + .shift(current, target, function () { + target.siblings().removeClass('visible'); + target.addClass('visible'); + }); + }.bind(this)); + } + }, + + close : function (e, el) { + e.preventDefault(); + + var root = (function (target) { + if (/blackout/.test(target.selector)) { + return target; + } else { + return target.closest('.clearing-blackout'); + } + }($(el))), container, visible_image; + + if (el === e.target && root) { + container = root.find('div').first(), + visible_image = container.find('.visible-img'); + this.settings.prev_index = 0; + root.find('ul[data-clearing]') + .attr('style', '').closest('.clearing-blackout') + .removeClass('clearing-blackout'); + container.removeClass('clearing-container'); + visible_image.hide(); + } + + return false; + }, + + is_open : function (current) { + return current.parent().attr('style').length > 0; + }, + + keydown : function (e) { + var clearing = $('.clearing-blackout').find('ul[data-clearing]'); + + if (e.which === 39) this.go(clearing, 'next'); + if (e.which === 37) this.go(clearing, 'prev'); + if (e.which === 27) $('a.clearing-close').trigger('click'); + }, + + nav : function (e, direction) { + var clearing = $('.clearing-blackout').find('ul[data-clearing]'); + + e.preventDefault(); + this.go(clearing, direction); + }, + + resize : function () { + var image = $('.clearing-blackout .visible-img').find('img'); + + if (image.length) { + this.center(image); + } + }, + + // visual adjustments + fix_height : function (target) { + var lis = target.parent().children(), + self = this; + + lis.each(function () { + var li = $(this), + image = li.find('img'); + + if (li.height() > self.outerHeight(image)) { + li.addClass('fix-height'); + } + }) + .closest('ul') + .width(lis.length * 100 + '%'); + + return this; + }, + + update_paddles : function (target) { + var visible_image = target + .closest('.carousel') + .siblings('.visible-img'); + + if (target.next().length > 0) { + visible_image + .find('.clearing-main-next') + .removeClass('disabled'); + } else { + visible_image + .find('.clearing-main-next') + .addClass('disabled'); + } + + if (target.prev().length > 0) { + visible_image + .find('.clearing-main-prev') + .removeClass('disabled'); + } else { + visible_image + .find('.clearing-main-prev') + .addClass('disabled'); + } + }, + + center : function (target) { + if (!this.rtl) { + target.css({ + marginLeft : -(this.outerWidth(target) / 2), + marginTop : -(this.outerHeight(target) / 2) + }); + } else { + target.css({ + marginRight : -(this.outerWidth(target) / 2), + marginTop : -(this.outerHeight(target) / 2) + }); + } + return this; + }, + + // image loading and preloading + + load : function ($image) { + var href = $image.parent().attr('href'); + + this.preload($image); + + if (href) return href; + return $image.attr('src'); + }, + + preload : function ($image) { + this + .img($image.closest('li').next()) + .img($image.closest('li').prev()); + }, + + loaded : function (image, callback) { + // based on jquery.imageready.js + // @weblinc, @jsantell, (c) 2012 + + function loaded () { + callback(); + } + + function bindLoad () { + this.one('load', loaded); + + if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { + var src = this.attr( 'src' ), + param = src.match( /\?/ ) ? '&' : '?'; + + param += 'random=' + (new Date()).getTime(); + this.attr('src', src + param); + } + } + + if (!image.attr('src')) { + loaded(); + return; + } + + if (image[0].complete || image[0].readyState === 4) { + loaded(); + } else { + bindLoad.call(image); + } + }, + + img : function (img) { + if (img.length) { + var new_img = new Image(), + new_a = img.find('a'); + + if (new_a.length) { + new_img.src = new_a.attr('href'); + } else { + new_img.src = img.find('img').attr('src'); + } + } + return this; + }, + + // image caption + + caption : function (container, $image) { + var caption = $image.data('caption'); + + if (caption) { + container + .text(caption) + .show(); + } else { + container + .text('') + .hide(); + } + return this; + }, + + // directional methods + + go : function ($ul, direction) { + var current = $ul.find('.visible'), + target = current[direction](); + + if (target.length) { + target + .find('img') + .trigger('click', [current, target]); + } + }, + + shift : function (current, target, callback) { + var clearing = target.parent(), + old_index = this.settings.prev_index || target.index(), + direction = this.direction(clearing, current, target), + left = parseInt(clearing.css('left'), 10), + width = this.outerWidth(target), + skip_shift; + + // we use jQuery animate instead of CSS transitions because we + // need a callback to unlock the next animation + if (target.index() !== old_index && !/skip/.test(direction)){ + if (/left/.test(direction)) { + this.lock(); + clearing.animate({left : left + width}, 300, this.unlock()); + } else if (/right/.test(direction)) { + this.lock(); + clearing.animate({left : left - width}, 300, this.unlock()); + } + } else if (/skip/.test(direction)) { + // the target image is not adjacent to the current image, so + // do we scroll right or not + skip_shift = target.index() - this.settings.up_count; + this.lock(); + + if (skip_shift > 0) { + clearing.animate({left : -(skip_shift * width)}, 300, this.unlock()); + } else { + clearing.animate({left : 0}, 300, this.unlock()); + } + } + + callback(); + }, + + direction : function ($el, current, target) { + var lis = $el.find('li'), + li_width = this.outerWidth(lis) + (this.outerWidth(lis) / 4), + up_count = Math.floor(this.outerWidth($('.clearing-container')) / li_width) - 1, + target_index = lis.index(target), + response; + + this.settings.up_count = up_count; + + if (this.adjacent(this.settings.prev_index, target_index)) { + if ((target_index > up_count) + && target_index > this.settings.prev_index) { + response = 'right'; + } else if ((target_index > up_count - 1) + && target_index <= this.settings.prev_index) { + response = 'left'; + } else { + response = false; + } + } else { + response = 'skip'; + } + + this.settings.prev_index = target_index; + + return response; + }, + + adjacent : function (current_index, target_index) { + for (var i = target_index + 1; i >= target_index - 1; i--) { + if (i === current_index) return true; + } + return false; + }, + + // lock management + + lock : function () { + this.settings.locked = true; + }, + + unlock : function () { + this.settings.locked = false; + }, + + locked : function () { + return this.settings.locked; + }, + + // plugin management/browser quirks + + outerHTML : function (el) { + // support FireFox < 11 + return el.outerHTML || new XMLSerializer().serializeToString(el); + }, + + off : function () { + $(this.scope).off('.fndtn.clearing'); + $(window).off('.fndtn.clearing'); + this.remove_data(); // empty settings cache + this.settings.init = false; + }, + + reflow : function () { + this.init(); + } + }; + +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.cookie.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.cookie.js new file mode 100644 index 00000000..862027c8 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.cookie.js @@ -0,0 +1,74 @@ +/*! + * jQuery Cookie Plugin v1.3 + * https://github.com/carhartl/jquery-cookie + * + * Copyright 2011, Klaus Hartl + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://www.opensource.org/licenses/mit-license.php + * http://www.opensource.org/licenses/GPL-2.0 + * + * Modified to work with Zepto.js by ZURB + */ +(function ($, document, undefined) { + + var pluses = /\+/g; + + function raw(s) { + return s; + } + + function decoded(s) { + return decodeURIComponent(s.replace(pluses, ' ')); + } + + var config = $.cookie = function (key, value, options) { + + // write + if (value !== undefined) { + options = $.extend({}, config.defaults, options); + + if (value === null) { + options.expires = -1; + } + + if (typeof options.expires === 'number') { + var days = options.expires, t = options.expires = new Date(); + t.setDate(t.getDate() + days); + } + + value = config.json ? JSON.stringify(value) : String(value); + + return (document.cookie = [ + encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), + options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE + options.path ? '; path=' + options.path : '', + options.domain ? '; domain=' + options.domain : '', + options.secure ? '; secure' : '' + ].join('')); + } + + // read + var decode = config.raw ? raw : decoded; + var cookies = document.cookie.split('; '); + for (var i = 0, l = cookies.length; i < l; i++) { + var parts = cookies[i].split('='); + if (decode(parts.shift()) === key) { + var cookie = decode(parts.join('=')); + return config.json ? JSON.parse(cookie) : cookie; + } + } + + return null; + }; + + config.defaults = {}; + + $.removeCookie = function (key, options) { + if ($.cookie(key) !== null) { + $.cookie(key, null, options); + return true; + } + return false; + }; + +})(Foundation.zj, document); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.dropdown.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.dropdown.js new file mode 100644 index 00000000..3e877b3a --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.dropdown.js @@ -0,0 +1,139 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.dropdown = { + name : 'dropdown', + + version : '4.1.0', + + settings : { + activeClass: 'open' + }, + + init : function (scope, method, options) { + this.scope = scope || this.scope; + Foundation.inherit(this, 'throttle scrollLeft'); + + if (typeof method === 'object') { + $.extend(true, this.settings, method); + } + + if (typeof method != 'string') { + + if (!this.settings.init) { + this.events(); + } + + return this.settings.init; + } else { + return this[method].call(this, options); + } + }, + + events : function () { + var self = this; + + $(this.scope).on('click.fndtn.dropdown', '[data-dropdown]', function (e) { + e.preventDefault(); + self.toggle($(this)); + }); + + $('body').on('click.fndtn.dropdown', function (e) { + var parent = $(e.target).closest('[data-dropdown-content]'); + + if ($(e.target).data('dropdown')) { + return; + } + if (parent.length > 0 && ($(e.target).is('[data-dropdown-content]') || $.contains(parent.first()[0], e.target))) { + e.stopPropagation(); + return; + } + + $('[data-dropdown-content]') + .css(Foundation.rtl ? 'right':'left', '-99999px') + .removeClass(self.settings.activeClass); + }); + + $(window).on('resize.fndtn.dropdown', self.throttle(function () { + self.resize.call(self); + }, 50)).trigger('resize'); + + this.settings.init = true; + }, + + toggle : function (target, resize) { + var dropdown = $('#' + target.data('dropdown')); + + $('[data-dropdown-content]') + .not(dropdown) + .css(Foundation.rtl ? 'right':'left', '-99999px') + .removeClass(this.settings.activeClass); + + if (dropdown.hasClass(this.settings.activeClass)) { + dropdown + .css(Foundation.rtl ? 'right':'left', '-99999px') + .removeClass(this.settings.activeClass); + } else { + this + .css(dropdown + .addClass(this.settings.activeClass), target); + } + }, + + resize : function () { + var dropdown = $('[data-dropdown-content].open'), + target = $("[data-dropdown='" + dropdown.attr('id') + "']"); + + if (dropdown.length && target.length) { + this.css(dropdown, target); + } + }, + + css : function (dropdown, target) { + var position = target.position(); + position.top += target.offsetParent().offset().top; + position.left += target.offsetParent().offset().left; + + if (this.small()) { + dropdown.css({ + position : 'absolute', + width: '95%', + left: '2.5%', + 'max-width': 'none', + top: position.top + this.outerHeight(target) + }); + } else { + if (!Foundation.rtl && $(window).width() > this.outerWidth(dropdown) + target.offset().left) { + var left = position.left; + } else { + if (!dropdown.hasClass('right')) { + dropdown.addClass('right'); + } + var left = position.left - (this.outerWidth(dropdown) - this.outerWidth(target)); + } + + dropdown.attr('style', '').css({ + position : 'absolute', + top: position.top + this.outerHeight(target), + left: left + }); + } + + return dropdown; + }, + + small : function () { + return $(window).width() < 768 || $('html').hasClass('lt-ie9'); + }, + + off: function () { + $(this.scope).off('.fndtn.dropdown'); + $('html, body').off('.fndtn.dropdown'); + $(window).off('.fndtn.dropdown'); + $('[data-dropdown-content]').off('.fndtn.dropdown'); + this.settings.init = false; + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.forms.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.forms.js new file mode 100644 index 00000000..d6eaf08b --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.forms.js @@ -0,0 +1,427 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.forms = { + name : 'forms', + + version : '4.0.4', + + settings : { + disable_class: 'no-custom' + }, + + init : function (scope, method, options) { + this.scope = scope || this.scope; + + if (typeof method === 'object') { + $.extend(true, this.settings, method); + } + + if (typeof method != 'string') { + if (!this.settings.init) { + this.events(); + } + + this.assemble(); + + return this.settings.init; + } else { + return this[method].call(this, options); + } + }, + + assemble : function () { + $('form.custom input[type="radio"]', $(this.scope)).not('[data-customforms="disabled"]') + .each(this.append_custom_markup); + $('form.custom input[type="checkbox"]', $(this.scope)).not('[data-customforms="disabled"]') + .each(this.append_custom_markup); + $('form.custom select', $(this.scope)).not('[data-customforms="disabled"]') + .each(this.append_custom_select); + }, + + events : function () { + var self = this; + + $(this.scope) + .on('click.fndtn.forms', 'form.custom span.custom.checkbox', function (e) { + e.preventDefault(); + e.stopPropagation(); + self.toggle_checkbox($(this)); + }) + .on('click.fndtn.forms', 'form.custom span.custom.radio', function (e) { + e.preventDefault(); + e.stopPropagation(); + self.toggle_radio($(this)); + }) + .on('change.fndtn.forms', 'form.custom select:not([data-customforms="disabled"])', function (e) { + self.refresh_custom_select($(this)); + }) + .on('click.fndtn.forms', 'form.custom label', function (e) { + var $associatedElement = $('#' + self.escape($(this).attr('for')) + ':not([data-customforms="disabled"])'), + $customCheckbox, + $customRadio; + if ($associatedElement.length !== 0) { + if ($associatedElement.attr('type') === 'checkbox') { + e.preventDefault(); + $customCheckbox = $(this).find('span.custom.checkbox'); + //the checkbox might be outside after the label or inside of another element + if ($customCheckbox.length == 0) { + $customCheckbox = $associatedElement.add(this).siblings('span.custom.checkbox').first(); + } + self.toggle_checkbox($customCheckbox); + } else if ($associatedElement.attr('type') === 'radio') { + e.preventDefault(); + $customRadio = $(this).find('span.custom.radio'); + //the radio might be outside after the label or inside of another element + if ($customRadio.length == 0) { + $customRadio = $associatedElement.add(this).siblings('span.custom.radio').first(); + } + self.toggle_radio($customRadio); + } + } + }) + .on('click.fndtn.forms', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (e) { + var $this = $(this), + $dropdown = $this.closest('div.custom.dropdown'), + $select = $dropdown.prev(); + + // make sure other dropdowns close + if(!$dropdown.hasClass('open')) + $(self.scope).trigger('click'); + + e.preventDefault(); + if (false === $select.is(':disabled')) { + $dropdown.toggleClass('open'); + + if ($dropdown.hasClass('open')) { + $(self.scope).on('click.fndtn.forms.customdropdown', function () { + $dropdown.removeClass('open'); + $(self.scope).off('.fndtn.forms.customdropdown'); + }); + } else { + $(self.scope).on('.fndtn.forms.customdropdown'); + } + return false; + } + }) + .on('click.fndtn.forms touchend.fndtn.forms', 'form.custom div.custom.dropdown li', function (e) { + var $this = $(this), + $customDropdown = $this.closest('div.custom.dropdown'), + $select = $customDropdown.prev(), + selectedIndex = 0; + + e.preventDefault(); + e.stopPropagation(); + + if ( ! $(this).hasClass('disabled')) { + $('div.dropdown').not($customDropdown).removeClass('open'); + + var $oldThis= $this + .closest('ul') + .find('li.selected'); + $oldThis.removeClass('selected'); + + $this.addClass('selected'); + + $customDropdown + .removeClass('open') + .find('a.current') + .html($this.html()); + + $this.closest('ul').find('li').each(function (index) { + if ($this[0] == this) { + selectedIndex = index; + } + + }); + $select[0].selectedIndex = selectedIndex; + + //store the old value in data + $select.data('prevalue', $oldThis.html()); + $select.trigger('change'); + } + }); + + $(window).on('keydown', function (e) { + var focus = document.activeElement, + dropdown = $('.custom.dropdown.open'); + + if (dropdown.length > 0) { + e.preventDefault(); + + if (e.which === 13) { + dropdown.find('li.selected').trigger('click'); + } + + if (e.which === 38) { + var current = dropdown.find('li.selected'), + prev = current.prev(':not(.disabled)'); + + if (prev.length > 0) { + current.removeClass('selected'); + prev.addClass('selected'); + } + } else if (e.which === 40) { + var current = dropdown.find('li.selected'), + next = current.next(':not(.disabled)'); + + if (next.length > 0) { + current.removeClass('selected'); + next.addClass('selected'); + } + } + } + }); + + this.settings.init = true; + }, + + append_custom_markup : function (idx, sel) { + var $this = $(sel).hide(), + type = $this.attr('type'), + $span = $this.next('span.custom.' + type); + + if ($span.length === 0) { + $span = $('').insertAfter($this); + } + + $span.toggleClass('checked', $this.is(':checked')); + $span.toggleClass('disabled', $this.is(':disabled')); + }, + + append_custom_select : function (idx, sel) { + var self = Foundation.libs.forms, + $this = $( sel ), + $customSelect = $this.next( 'div.custom.dropdown' ), + $customList = $customSelect.find( 'ul' ), + $selectCurrent = $customSelect.find( ".current" ), + $selector = $customSelect.find( ".selector" ), + $options = $this.find( 'option' ), + $selectedOption = $options.filter( ':selected' ), + copyClasses = $this.attr('class') ? $this.attr('class').split(' ') : [], + maxWidth = 0, + liHtml = '', + $listItems, + $currentSelect = false; + + if ($this.hasClass(self.settings.disable_class)) return; + + if ($customSelect.length === 0) { + var customSelectSize = $this.hasClass( 'small' ) ? 'small' : + $this.hasClass( 'medium' ) ? 'medium' : + $this.hasClass( 'large' ) ? 'large' : + $this.hasClass( 'expand' ) ? 'expand' : ''; + + $customSelect = $('
        '); + $selector = $customSelect.find(".selector"); + $customList = $customSelect.find("ul"); + liHtml = $options.map(function() { return "
      • " + $( this ).html() + "
      • "; } ).get().join( '' ); + $customList.append(liHtml); + $currentSelect = $customSelect.prepend('' + $selectedOption.html() + '' ).find( ".current" ); + $this + .after( $customSelect ) + .hide(); + + } else { + liHtml = $options.map(function() { + return "
      • " + $( this ).html() + "
      • "; + }) + .get().join(''); + $customList + .html('') + .append(liHtml); + + } // endif $customSelect.length === 0 + $customSelect.toggleClass('disabled', $this.is( ':disabled' ) ); + $listItems = $customList.find( 'li' ); + + $options.each( function ( index ) { + if ( this.selected ) { + $listItems.eq( index ).addClass( 'selected' ); + + if ($currentSelect) { + $currentSelect.html( $( this ).html() ); + } + + } + if ($(this).is(':disabled')) { + $listItems.eq( index ).addClass( 'disabled' ); + } + }); + + // + // If we're not specifying a predetermined form size. + // + if (!$customSelect.is('.small, .medium, .large, .expand')) { + + // ------------------------------------------------------------------------------------ + // This is a work-around for when elements are contained within hidden parents. + // For example, when custom-form elements are inside of a hidden reveal modal. + // + // We need to display the current custom list element as well as hidden parent elements + // in order to properly calculate the list item element's width property. + // ------------------------------------------------------------------------------------- + + $customSelect.addClass( 'open' ); + // + // Quickly, display all parent elements. + // This should help us calcualate the width of the list item's within the drop down. + // + var self = Foundation.libs.forms; + self.hidden_fix.adjust( $customList ); + + maxWidth = ( self.outerWidth($listItems) > maxWidth ) ? self.outerWidth($listItems) : maxWidth; + + Foundation.libs.forms.hidden_fix.reset(); + + $customSelect.removeClass( 'open' ); + + } // endif + + }, + + refresh_custom_select : function ($select) { + var self = this; + var maxWidth = 0, + $customSelect = $select.next(), + $options = $select.find('option'); + + $customSelect.find('ul').html(''); + + $options.each(function () { + var $li = $('
      • ' + $(this).html() + '
      • '); + $customSelect.find('ul').append($li); + }); + + // re-populate + $options.each(function (index) { + if (this.selected) { + $customSelect.find('li').eq(index).addClass('selected'); + $customSelect.find('.current').html($(this).html()); + } + if ($(this).is(':disabled')) { + $customSelect.find('li').eq(index).addClass('disabled'); + } + }); + + // fix width + $customSelect.removeAttr('style') + .find('ul').removeAttr('style'); + $customSelect.find('li').each(function () { + $customSelect.addClass('open'); + if (self.outerWidth($(this)) > maxWidth) { + maxWidth = self.outerWidth($(this)); + } + $customSelect.removeClass('open'); + }); + }, + + toggle_checkbox : function ($element) { + var $input = $element.prev(), + input = $input[0]; + + if (false === $input.is(':disabled')) { + input.checked = ((input.checked) ? false : true); + $element.toggleClass('checked'); + + $input.trigger('change'); + } + }, + + toggle_radio : function ($element) { + var $input = $element.prev(), + $form = $input.closest('form.custom'), + input = $input[0]; + + if (false === $input.is(':disabled')) { + $form.find('input[type="radio"][name="' + this.escape($input.attr('name')) + '"]').next().not($element).removeClass('checked'); + if ( !$element.hasClass('checked') ) { + $element.toggleClass('checked'); + } + input.checked = $element.hasClass('checked'); + + $input.trigger('change'); + } + }, + + escape : function (text) { + return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + }, + + hidden_fix : { + /** + * Sets all hidden parent elements and self to visibile. + * + * @method adjust + * @param {jQuery Object} $child + */ + + // We'll use this to temporarily store style properties. + tmp : [], + + // We'll use this to set hidden parent elements. + hidden : null, + + adjust : function( $child ) { + // Internal reference. + var _self = this; + + // Set all hidden parent elements, including this element. + _self.hidden = $child.parents().andSelf().filter( ":hidden" ); + + // Loop through all hidden elements. + _self.hidden.each( function() { + + // Cache the element. + var $elem = $( this ); + + // Store the style attribute. + // Undefined if element doesn't have a style attribute. + _self.tmp.push( $elem.attr( 'style' ) ); + + // Set the element's display property to block, + // but ensure it's visibility is hidden. + $elem.css( { 'visibility' : 'hidden', 'display' : 'block' } ); + }); + + }, // end adjust + + /** + * Resets the elements previous state. + * + * @method reset + */ + reset : function() { + // Internal reference. + var _self = this; + // Loop through our hidden element collection. + _self.hidden.each( function( i ) { + // Cache this element. + var $elem = $( this ), + _tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element. + + // If the stored value is undefined. + if( _tmp === undefined ) + // Remove the style attribute. + $elem.removeAttr( 'style' ); + else + // Otherwise, reset the element style attribute. + $elem.attr( 'style', _tmp ); + + }); + // Reset the tmp array. + _self.tmp = []; + // Reset the hidden elements variable. + _self.hidden = null; + + } // end reset + + }, + + off : function () { + $(this.scope).off('.fndtn.forms'); + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.joyride.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.joyride.js new file mode 100644 index 00000000..a2bc0674 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.joyride.js @@ -0,0 +1,833 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.joyride = { + name: 'joyride', + + version : '4.1.2', + + defaults : { + expose : false, // turn on or off the expose feature + modal : false, // Whether to cover page with modal during the tour + tipLocation : 'bottom', // 'top' or 'bottom' in relation to parent + nubPosition : 'auto', // override on a per tooltip bases + scrollSpeed : 300, // Page scrolling speed in milliseconds, 0 = no scroll animation + timer : 0, // 0 = no timer , all other numbers = timer in milliseconds + startTimerOnClick : true, // true or false - true requires clicking the first button start the timer + startOffset : 0, // the index of the tooltip you want to start on (index of the li) + nextButton : true, // true or false to control whether a next button is used + tipAnimation : 'fade', // 'pop' or 'fade' in each tip + pauseAfter : [], // array of indexes where to pause the tour after + exposed : [], // array of expose elements + tipAnimationFadeSpeed: 300, // when tipAnimation = 'fade' this is speed in milliseconds for the transition + cookieMonster : false, // true or false to control whether cookies are used + cookieName : 'joyride', // Name the cookie you'll use + cookieDomain : false, // Will this cookie be attached to a domain, ie. '.notableapp.com' + cookieExpires : 365, // set when you would like the cookie to expire. + tipContainer : 'body', // Where will the tip be attached + postRideCallback : function (){}, // A method to call once the tour closes (canceled or complete) + postStepCallback : function (){}, // A method to call after each step + preStepCallback : function (){}, // A method to call before each step + preRideCallback : function (){}, // A method to call before the tour starts (passed index, tip, and cloned exposed element) + postExposeCallback : function (){}, // A method to call after an element has been exposed + template : { // HTML segments for tip layout + link : '×', + timer : '
        ', + tip : '
        ', + wrapper : '
        ', + button : '', + modal : '
        ', + expose : '
        ', + exposeCover: '
        ' + } + }, + + settings : {}, + + init : function (scope, method, options) { + this.scope = scope || this.scope; + Foundation.inherit(this, 'throttle data_options scrollTo scrollLeft delay'); + + if (typeof method === 'object') { + $.extend(true, this.settings, this.defaults, method); + } else { + $.extend(true, this.settings, this.defaults, options); + } + + if (typeof method != 'string') { + if (!this.settings.init) this.events(); + + return this.settings.init; + } else { + return this[method].call(this, options); + } + }, + + events : function () { + var self = this; + + $(this.scope) + .on('click.joyride', '.joyride-next-tip, .joyride-modal-bg', function (e) { + e.preventDefault(); + + if (this.settings.$li.next().length < 1) { + this.end(); + } else if (this.settings.timer > 0) { + clearTimeout(this.settings.automate); + this.hide(); + this.show(); + this.startTimer(); + } else { + this.hide(); + this.show(); + } + + }.bind(this)) + + .on('click.joyride', '.joyride-close-tip', function (e) { + e.preventDefault(); + this.end(); + }.bind(this)); + + $(window).on('resize.fndtn.joyride', self.throttle(function () { + if ($('[data-joyride]').length > 0 && self.settings.$next_tip) { + if (self.settings.exposed.length > 0) { + var $els = $(self.settings.exposed); + + $els.each(function () { + var $this = $(this); + self.un_expose($this); + self.expose($this); + }); + } + + if (self.is_phone()) { + self.pos_phone(); + } else { + self.pos_default(false, true); + } + } + }, 100)); + + this.settings.init = true; + }, + + start : function () { + var self = this, + $this = $(this.scope).find('[data-joyride]'), + integer_settings = ['timer', 'scrollSpeed', 'startOffset', 'tipAnimationFadeSpeed', 'cookieExpires'], + int_settings_count = integer_settings.length; + + if (!this.settings.init) this.init(); + + // non configureable settings + this.settings.$content_el = $this; + this.settings.$body = $(this.settings.tipContainer); + this.settings.body_offset = $(this.settings.tipContainer).position(); + this.settings.$tip_content = this.settings.$content_el.find('> li'); + this.settings.paused = false; + this.settings.attempts = 0; + + this.settings.tipLocationPatterns = { + top: ['bottom'], + bottom: [], // bottom should not need to be repositioned + left: ['right', 'top', 'bottom'], + right: ['left', 'top', 'bottom'] + }; + + // can we create cookies? + if (typeof $.cookie !== 'function') { + this.settings.cookieMonster = false; + } + + // generate the tips and insert into dom. + if (!this.settings.cookieMonster || this.settings.cookieMonster && $.cookie(this.settings.cookieName) === null) { + this.settings.$tip_content.each(function (index) { + var $this = $(this); + $.extend(true, self.settings, self.data_options($this)); + // Make sure that settings parsed from data_options are integers where necessary + for (var i = int_settings_count - 1; i >= 0; i--) { + self.settings[integer_settings[i]] = parseInt(self.settings[integer_settings[i]], 10); + } + self.create({$li : $this, index : index}); + }); + + // show first tip + if (!this.settings.startTimerOnClick && this.settings.timer > 0) { + this.show('init'); + this.startTimer(); + } else { + this.show('init'); + } + + } + }, + + resume : function () { + this.set_li(); + this.show(); + }, + + tip_template : function (opts) { + var $blank, content; + + opts.tip_class = opts.tip_class || ''; + + $blank = $(this.settings.template.tip).addClass(opts.tip_class); + content = $.trim($(opts.li).html()) + + this.button_text(opts.button_text) + + this.settings.template.link + + this.timer_instance(opts.index); + + $blank.append($(this.settings.template.wrapper)); + $blank.first().attr('data-index', opts.index); + $('.joyride-content-wrapper', $blank).append(content); + + return $blank[0]; + }, + + timer_instance : function (index) { + var txt; + + if ((index === 0 && this.settings.startTimerOnClick && this.settings.timer > 0) || this.settings.timer === 0) { + txt = ''; + } else { + txt = this.outerHTML($(this.settings.template.timer)[0]); + } + return txt; + }, + + button_text : function (txt) { + if (this.settings.nextButton) { + txt = $.trim(txt) || 'Next'; + txt = this.outerHTML($(this.settings.template.button).append(txt)[0]); + } else { + txt = ''; + } + return txt; + }, + + create : function (opts) { + var buttonText = opts.$li.attr('data-button') || opts.$li.attr('data-text'), + tipClass = opts.$li.attr('class'), + $tip_content = $(this.tip_template({ + tip_class : tipClass, + index : opts.index, + button_text : buttonText, + li : opts.$li + })); + + $(this.settings.tipContainer).append($tip_content); + }, + + show : function (init) { + var $timer = null; + + // are we paused? + if (this.settings.$li === undefined + || ($.inArray(this.settings.$li.index(), this.settings.pauseAfter) === -1)) { + + // don't go to the next li if the tour was paused + if (this.settings.paused) { + this.settings.paused = false; + } else { + this.set_li(init); + } + + this.settings.attempts = 0; + + if (this.settings.$li.length && this.settings.$target.length > 0) { + if (init) { //run when we first start + this.settings.preRideCallback(this.settings.$li.index(), this.settings.$next_tip); + if (this.settings.modal) { + this.show_modal(); + } + } + + this.settings.preStepCallback(this.settings.$li.index(), this.settings.$next_tip); + + if (this.settings.modal && this.settings.expose) { + this.expose(); + } + + this.settings.tipSettings = $.extend(this.settings, this.data_options(this.settings.$li)); + + this.settings.timer = parseInt(this.settings.timer, 10); + + this.settings.tipSettings.tipLocationPattern = this.settings.tipLocationPatterns[this.settings.tipSettings.tipLocation]; + + // scroll if not modal + if (!/body/i.test(this.settings.$target.selector)) { + this.scroll_to(); + } + + if (this.is_phone()) { + this.pos_phone(true); + } else { + this.pos_default(true); + } + + $timer = this.settings.$next_tip.find('.joyride-timer-indicator'); + + if (/pop/i.test(this.settings.tipAnimation)) { + + $timer.width(0); + + if (this.settings.timer > 0) { + + this.settings.$next_tip.show(); + + this.delay(function () { + $timer.animate({ + width: $timer.parent().width() + }, this.settings.timer, 'linear'); + }.bind(this), this.settings.tipAnimationFadeSpeed); + + } else { + this.settings.$next_tip.show(); + + } + + + } else if (/fade/i.test(this.settings.tipAnimation)) { + + $timer.width(0); + + if (this.settings.timer > 0) { + + this.settings.$next_tip + .fadeIn(this.settings.tipAnimationFadeSpeed) + .show(); + + this.delay(function () { + $timer.animate({ + width: $timer.parent().width() + }, this.settings.timer, 'linear'); + }.bind(this), this.settings.tipAnimationFadeSpeed); + + } else { + this.settings.$next_tip.fadeIn(this.settings.tipAnimationFadeSpeed); + + } + } + + this.settings.$current_tip = this.settings.$next_tip; + + // skip non-existant targets + } else if (this.settings.$li && this.settings.$target.length < 1) { + + this.show(); + + } else { + + this.end(); + + } + } else { + + this.settings.paused = true; + + } + + }, + + is_phone : function () { + if (Modernizr) { + return Modernizr.mq('only screen and (max-width: 767px)') || $('.lt-ie9').length > 0; + } + + return (this.settings.$window.width() < 767) ? true : false; + }, + + hide : function () { + if (this.settings.modal && this.settings.expose) { + this.un_expose(); + } + + if (!this.settings.modal) { + $('.joyride-modal-bg').hide(); + } + this.settings.$current_tip.hide(); + this.settings.postStepCallback(this.settings.$li.index(), + this.settings.$current_tip); + }, + + set_li : function (init) { + if (init) { + this.settings.$li = this.settings.$tip_content.eq(this.settings.startOffset); + this.set_next_tip(); + this.settings.$current_tip = this.settings.$next_tip; + } else { + this.settings.$li = this.settings.$li.next(); + this.set_next_tip(); + } + + this.set_target(); + }, + + set_next_tip : function () { + this.settings.$next_tip = $(".joyride-tip-guide[data-index='" + this.settings.$li.index() + "']"); + this.settings.$next_tip.data('closed', ''); + }, + + set_target : function () { + var cl = this.settings.$li.attr('data-class'), + id = this.settings.$li.attr('data-id'), + $sel = function () { + if (id) { + return $(document.getElementById(id)); + } else if (cl) { + return $('.' + cl).first(); + } else { + return $('body'); + } + }; + + this.settings.$target = $sel(); + }, + + scroll_to : function () { + var window_half, tipOffset; + + window_half = $(window).height() / 2; + tipOffset = Math.ceil(this.settings.$target.offset().top - window_half + this.outerHeight(this.settings.$next_tip)); + if (tipOffset > 0) { + this.scrollTo($('html, body'), tipOffset, this.settings.scrollSpeed); + } + }, + + paused : function () { + if (($.inArray((this.settings.$li.index() + 1), this.settings.pauseAfter) === -1)) { + return true; + } + + return false; + }, + + restart : function () { + this.hide(); + this.settings.$li = undefined; + this.show('init'); + }, + + pos_default : function (init, resizing) { + var half_fold = Math.ceil($(window).height() / 2), + tip_position = this.settings.$next_tip.offset(), + $nub = this.settings.$next_tip.find('.joyride-nub'), + nub_width = Math.ceil(this.outerWidth($nub) / 2), + nub_height = Math.ceil(this.outerHeight($nub) / 2), + toggle = init || false; + + // tip must not be "display: none" to calculate position + if (toggle) { + this.settings.$next_tip.css('visibility', 'hidden'); + this.settings.$next_tip.show(); + } + + if (typeof resizing === 'undefined') { + resizing = false; + } + + if (!/body/i.test(this.settings.$target.selector)) { + + if (this.bottom()) { + var leftOffset = this.settings.$target.offset().left; + if (Foundation.rtl) { + leftOffset = this.settings.$target.offset().width - this.settings.$next_tip.width() + leftOffset; + } + this.settings.$next_tip.css({ + top: (this.settings.$target.offset().top + nub_height + this.outerHeight(this.settings.$target)), + left: leftOffset}); + + this.nub_position($nub, this.settings.tipSettings.nubPosition, 'top'); + + } else if (this.top()) { + var leftOffset = this.settings.$target.offset().left; + if (Foundation.rtl) { + leftOffset = this.settings.$target.offset().width - this.settings.$next_tip.width() + leftOffset; + } + this.settings.$next_tip.css({ + top: (this.settings.$target.offset().top - this.outerHeight(this.settings.$next_tip) - nub_height), + left: leftOffset}); + + this.nub_position($nub, this.settings.tipSettings.nubPosition, 'bottom'); + + } else if (this.right()) { + + this.settings.$next_tip.css({ + top: this.settings.$target.offset().top, + left: (this.outerWidth(this.settings.$target) + this.settings.$target.offset().left + nub_width)}); + + this.nub_position($nub, this.settings.tipSettings.nubPosition, 'left'); + + } else if (this.left()) { + + this.settings.$next_tip.css({ + top: this.settings.$target.offset().top, + left: (this.settings.$target.offset().left - this.outerWidth(this.settings.$next_tip) - nub_width)}); + + this.nub_position($nub, this.settings.tipSettings.nubPosition, 'right'); + + } + + if (!this.visible(this.corners(this.settings.$next_tip)) && this.settings.attempts < this.settings.tipSettings.tipLocationPattern.length) { + + $nub.removeClass('bottom') + .removeClass('top') + .removeClass('right') + .removeClass('left'); + + this.settings.tipSettings.tipLocation = this.settings.tipSettings.tipLocationPattern[this.settings.attempts]; + + this.settings.attempts++; + + this.pos_default(); + + } + + } else if (this.settings.$li.length) { + + this.pos_modal($nub); + + } + + if (toggle) { + this.settings.$next_tip.hide(); + this.settings.$next_tip.css('visibility', 'visible'); + } + + }, + + pos_phone : function (init) { + var tip_height = this.outerHeight(this.settings.$next_tip), + tip_offset = this.settings.$next_tip.offset(), + target_height = this.outerHeight(this.settings.$target), + $nub = $('.joyride-nub', this.settings.$next_tip), + nub_height = Math.ceil(this.outerHeight($nub) / 2), + toggle = init || false; + + $nub.removeClass('bottom') + .removeClass('top') + .removeClass('right') + .removeClass('left'); + + if (toggle) { + this.settings.$next_tip.css('visibility', 'hidden'); + this.settings.$next_tip.show(); + } + + if (!/body/i.test(this.settings.$target.selector)) { + + if (this.top()) { + + this.settings.$next_tip.offset({top: this.settings.$target.offset().top - tip_height - nub_height}); + $nub.addClass('bottom'); + + } else { + + this.settings.$next_tip.offset({top: this.settings.$target.offset().top + target_height + nub_height}); + $nub.addClass('top'); + + } + + } else if (this.settings.$li.length) { + this.pos_modal($nub); + } + + if (toggle) { + this.settings.$next_tip.hide(); + this.settings.$next_tip.css('visibility', 'visible'); + } + }, + + pos_modal : function ($nub) { + this.center(); + $nub.hide(); + + this.show_modal(); + }, + + show_modal : function () { + if (!this.settings.$next_tip.data('closed')) { + if ($('.joyride-modal-bg').length < 1) { + $('body').append(this.settings.template.modal).show(); + } + + if (/pop/i.test(this.settings.tipAnimation)) { + $('.joyride-modal-bg').show(); + } else { + $('.joyride-modal-bg').fadeIn(this.settings.tipAnimationFadeSpeed); + } + } + }, + + expose : function () { + var expose, + exposeCover, + el, + origCSS, + randId = 'expose-'+Math.floor(Math.random()*10000); + + if (arguments.length > 0 && arguments[0] instanceof $) { + el = arguments[0]; + } else if(this.settings.$target && !/body/i.test(this.settings.$target.selector)){ + el = this.settings.$target; + } else { + return false; + } + + if(el.length < 1){ + if(window.console){ + console.error('element not valid', el); + } + return false; + } + + expose = $(this.settings.template.expose); + this.settings.$body.append(expose); + expose.css({ + top: el.offset().top, + left: el.offset().left, + width: this.outerWidth(el, true), + height: this.outerHeight(el, true) + }); + + exposeCover = $(this.settings.template.exposeCover); + + origCSS = { + zIndex: el.css('z-index'), + position: el.css('position') + }; + + el.css('z-index',expose.css('z-index')*1+1); + + if (origCSS.position == 'static') { + el.css('position','relative'); + } + + el.data('expose-css',origCSS); + + exposeCover.css({ + top: el.offset().top, + left: el.offset().left, + width: this.outerWidth(el, true), + height: this.outerHeight(el, true) + }); + + this.settings.$body.append(exposeCover); + expose.addClass(randId); + exposeCover.addClass(randId); + el.data('expose', randId); + this.settings.postExposeCallback(this.settings.$li.index(), this.settings.$next_tip, el); + this.add_exposed(el); + }, + + un_expose : function () { + var exposeId, + el, + expose , + origCSS, + clearAll = false; + + if (arguments.length > 0 && arguments[0] instanceof $) { + el = arguments[0]; + } else if(this.settings.$target && !/body/i.test(this.settings.$target.selector)){ + el = this.settings.$target; + } else { + return false; + } + + if(el.length < 1){ + if (window.console) { + console.error('element not valid', el); + } + return false; + } + + exposeId = el.data('expose'); + expose = $('.' + exposeId); + + if (arguments.length > 1) { + clearAll = arguments[1]; + } + + if (clearAll === true) { + $('.joyride-expose-wrapper,.joyride-expose-cover').remove(); + } else { + expose.remove(); + } + + origCSS = el.data('expose-css'); + + if (origCSS.zIndex == 'auto') { + el.css('z-index', ''); + } else { + el.css('z-index', origCSS.zIndex); + } + + if (origCSS.position != el.css('position')) { + if(origCSS.position == 'static') {// this is default, no need to set it. + el.css('position', ''); + } else { + el.css('position', origCSS.position); + } + } + + el.removeData('expose'); + el.removeData('expose-z-index'); + this.remove_exposed(el); + }, + + add_exposed: function(el){ + this.settings.exposed = this.settings.exposed || []; + if (el instanceof $ || typeof el === 'object') { + this.settings.exposed.push(el[0]); + } else if (typeof el == 'string') { + this.settings.exposed.push(el); + } + }, + + remove_exposed: function(el){ + var search, count; + if (el instanceof $) { + search = el[0] + } else if (typeof el == 'string'){ + search = el; + } + + this.settings.exposed = this.settings.exposed || []; + count = this.settings.exposed.length; + + for (var i=0; i < count; i++) { + if (this.settings.exposed[i] == search) { + this.settings.exposed.splice(i, 1); + return; + } + } + }, + + center : function () { + var $w = $(window); + + this.settings.$next_tip.css({ + top : ((($w.height() - this.outerHeight(this.settings.$next_tip)) / 2) + $w.scrollTop()), + left : ((($w.width() - this.outerWidth(this.settings.$next_tip)) / 2) + this.scrollLeft($w)) + }); + + return true; + }, + + bottom : function () { + return /bottom/i.test(this.settings.tipSettings.tipLocation); + }, + + top : function () { + return /top/i.test(this.settings.tipSettings.tipLocation); + }, + + right : function () { + return /right/i.test(this.settings.tipSettings.tipLocation); + }, + + left : function () { + return /left/i.test(this.settings.tipSettings.tipLocation); + }, + + corners : function (el) { + var w = $(window), + window_half = w.height() / 2, + //using this to calculate since scroll may not have finished yet. + tipOffset = Math.ceil(this.settings.$target.offset().top - window_half + this.settings.$next_tip.outerHeight()), + right = w.width() + this.scrollLeft(w), + offsetBottom = w.height() + tipOffset, + bottom = w.height() + w.scrollTop(), + top = w.scrollTop(); + + if (tipOffset < top) { + if (tipOffset < 0) { + top = 0; + } else { + top = tipOffset; + } + } + + if (offsetBottom > bottom) { + bottom = offsetBottom; + } + + return [ + el.offset().top < top, + right < el.offset().left + el.outerWidth(), + bottom < el.offset().top + el.outerHeight(), + this.scrollLeft(w) > el.offset().left + ]; + }, + + visible : function (hidden_corners) { + var i = hidden_corners.length; + + while (i--) { + if (hidden_corners[i]) return false; + } + + return true; + }, + + nub_position : function (nub, pos, def) { + if (pos === 'auto') { + nub.addClass(def); + } else { + nub.addClass(pos); + } + }, + + startTimer : function () { + if (this.settings.$li.length) { + this.settings.automate = setTimeout(function () { + this.hide(); + this.show(); + this.startTimer(); + }.bind(this), this.settings.timer); + } else { + clearTimeout(this.settings.automate); + } + }, + + end : function () { + if (this.settings.cookieMonster) { + $.cookie(this.settings.cookieName, 'ridden', { expires: this.settings.cookieExpires, domain: this.settings.cookieDomain }); + } + + if (this.settings.timer > 0) { + clearTimeout(this.settings.automate); + } + + if (this.settings.modal && this.settings.expose) { + this.un_expose(); + } + + this.settings.$next_tip.data('closed', true); + + $('.joyride-modal-bg').hide(); + this.settings.$current_tip.hide(); + this.settings.postStepCallback(this.settings.$li.index(), this.settings.$current_tip); + this.settings.postRideCallback(this.settings.$li.index(), this.settings.$current_tip); + }, + + outerHTML : function (el) { + // support FireFox < 11 + return el.outerHTML || new XMLSerializer().serializeToString(el); + }, + + off : function () { + $(this.scope).off('.joyride'); + $(window).off('.joyride'); + $('.joyride-close-tip, .joyride-next-tip, .joyride-modal-bg').off('.joyride'); + $('.joyride-tip-guide, .joyride-modal-bg').remove(); + clearTimeout(this.settings.automate); + this.settings = {}; + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.js new file mode 100644 index 00000000..5919cf8f --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.js @@ -0,0 +1,378 @@ +/* + * Foundation Responsive Library + * http://foundation.zurb.com + * Copyright 2013, ZURB + * Free to use under the MIT license. + * http://www.opensource.org/licenses/mit-license.php +*/ + +/*jslint unparam: true, browser: true, indent: 2 */ + +// Accommodate running jQuery or Zepto in noConflict() mode by +// using an anonymous function to redefine the $ shorthand name. +// See http://docs.jquery.com/Using_jQuery_with_Other_Libraries +// and http://zeptojs.com/ +var libFuncName = null; +if (typeof jQuery === "undefined" && + typeof Zepto === "undefined" && + typeof $ === "function") { + libFuncName = $; +} else if (typeof jQuery === "function") { + libFuncName = jQuery; +} else if (typeof Zepto === "function") { + libFuncName = Zepto; +} else { + throw new TypeError(); +} + +(function ($) { + +(function () { + // add dusty browser stuff + if (!Array.prototype.filter) { + Array.prototype.filter = function(fun /*, thisp */) { + "use strict"; + + if (this == null) { + throw new TypeError(); + } + + var t = Object(this), + len = t.length >>> 0; + if (typeof fun != "function") { + try { + throw new TypeError(); + } catch (e) { + return; + } + } + + var res = [], + thisp = arguments[1]; + for (var i = 0; i < len; i++) { + if (i in t) { + var val = t[i]; // in case fun mutates this + if (fun && fun.call(thisp, val, i, t)) { + res.push(val); + } + } + } + + return res; + }; + + if (!Function.prototype.bind) { + Function.prototype.bind = function (oThis) { + if (typeof this !== "function") { + // closest thing possible to the ECMAScript 5 internal IsCallable function + throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); + } + + var aArgs = Array.prototype.slice.call(arguments, 1), + fToBind = this, + fNOP = function () {}, + fBound = function () { + return fToBind.apply(this instanceof fNOP && oThis + ? this + : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + + fNOP.prototype = this.prototype; + fBound.prototype = new fNOP(); + + return fBound; + }; + } + } + + // fake stop() for zepto. + $.fn.stop = $.fn.stop || function() { + return this; + }; +}()); + +;(function (window, document, undefined) { + 'use strict'; + + window.Foundation = { + name : 'Foundation', + + version : '4.1.0', + + // global Foundation cache object + cache : {}, + + init : function (scope, libraries, method, options, response, /* internal */ nc) { + var library_arr, + args = [scope, method, options, response], + responses = [], + nc = nc || false; + + // disable library error catching, + // used for development only + if (nc) this.nc = nc; + + + // check RTL + this.rtl = /rtl/i.test($('html').attr('dir')); + + // set foundation global scope + this.scope = scope || this.scope; + + if (libraries && typeof libraries === 'string') { + if (/off/i.test(libraries)) return this.off(); + + library_arr = libraries.split(' '); + + if (library_arr.length > 0) { + for (var i = library_arr.length - 1; i >= 0; i--) { + responses.push(this.init_lib(library_arr[i], args)); + } + } + } else { + for (var lib in this.libs) { + responses.push(this.init_lib(lib, args)); + } + } + + // if first argument is callback, add to args + if (typeof libraries === 'function') { + args.unshift(libraries); + } + + return this.response_obj(responses, args); + }, + + response_obj : function (response_arr, args) { + for (var i = 0, len = args.length; i < len; i++) { + if (typeof args[i] === 'function') { + return args[i]({ + errors: response_arr.filter(function (s) { + if (typeof s === 'string') return s; + }) + }); + } + } + + return response_arr; + }, + + init_lib : function (lib, args) { + return this.trap(function () { + if (this.libs.hasOwnProperty(lib)) { + this.patch(this.libs[lib]); + return this.libs[lib].init.apply(this.libs[lib], args); + } + }.bind(this), lib); + }, + + trap : function (fun, lib) { + if (!this.nc) { + try { + return fun(); + } catch (e) { + return this.error({name: lib, message: 'could not be initialized', more: e.name + ' ' + e.message}); + } + } + + return fun(); + }, + + patch : function (lib) { + this.fix_outer(lib); + lib.scope = this.scope; + lib.rtl = this.rtl; + }, + + inherit : function (scope, methods) { + var methods_arr = methods.split(' '); + + for (var i = methods_arr.length - 1; i >= 0; i--) { + if (this.lib_methods.hasOwnProperty(methods_arr[i])) { + this.libs[scope.name][methods_arr[i]] = this.lib_methods[methods_arr[i]]; + } + } + }, + + random_str : function (length) { + var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(''); + + if (!length) { + length = Math.floor(Math.random() * chars.length); + } + + var str = ''; + for (var i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; + }, + + libs : {}, + + // methods that can be inherited in libraries + lib_methods : { + set_data : function (node, data) { + // this.name references the name of the library calling this method + var id = [this.name,+new Date(),Foundation.random_str(5)].join('-'); + + Foundation.cache[id] = data; + node.attr('data-' + this.name + '-id', id); + return data; + }, + + get_data : function (node) { + return Foundation.cache[node.attr('data-' + this.name + '-id')]; + }, + + remove_data : function (node) { + if (node) { + delete Foundation.cache[node.attr('data-' + this.name + '-id')]; + node.attr('data-' + this.name + '-id', ''); + } else { + $('[data-' + this.name + '-id]').each(function () { + delete Foundation.cache[$(this).attr('data-' + this.name + '-id')]; + $(this).attr('data-' + this.name + '-id', ''); + }); + } + }, + + throttle : function(fun, delay) { + var timer = null; + return function () { + var context = this, args = arguments; + clearTimeout(timer); + timer = setTimeout(function () { + fun.apply(context, args); + }, delay); + }; + }, + + // parses data-options attribute on nodes and turns + // them into an object + data_options : function (el) { + var opts = {}, ii, p, + opts_arr = (el.attr('data-options') || ':').split(';'), + opts_len = opts_arr.length; + + function isNumber (o) { + return ! isNaN (o-0) && o !== null && o !== "" && o !== false && o !== true; + } + + function trim(str) { + if (typeof str === 'string') return $.trim(str); + return str; + } + + // parse options + for (ii = opts_len - 1; ii >= 0; ii--) { + p = opts_arr[ii].split(':'); + + if (/true/i.test(p[1])) p[1] = true; + if (/false/i.test(p[1])) p[1] = false; + if (isNumber(p[1])) p[1] = parseInt(p[1], 10); + + if (p.length === 2 && p[0].length > 0) { + opts[trim(p[0])] = trim(p[1]); + } + } + + return opts; + }, + + delay : function (fun, delay) { + return setTimeout(fun, delay); + }, + + // animated scrolling + scrollTo : function (el, to, duration) { + if (duration < 0) return; + var difference = to - $(window).scrollTop(); + var perTick = difference / duration * 10; + + this.scrollToTimerCache = setTimeout(function() { + if (!isNaN(parseInt(perTick, 10))) { + window.scrollTo(0, $(window).scrollTop() + perTick); + this.scrollTo(el, to, duration - 10); + } + }.bind(this), 10); + }, + + // not supported in core Zepto + scrollLeft : function (el) { + if (!el.length) return; + return ('scrollLeft' in el[0]) ? el[0].scrollLeft : el[0].pageXOffset; + }, + + // test for empty object or array + empty : function (obj) { + if (obj.length && obj.length > 0) return false; + if (obj.length && obj.length === 0) return true; + + for (var key in obj) { + if (hasOwnProperty.call(obj, key)) return false; + } + + return true; + } + }, + + fix_outer : function (lib) { + lib.outerHeight = function (el, bool) { + if (typeof Zepto === 'function') { + return el.height(); + } + + if (typeof bool !== 'undefined') { + return el.outerHeight(bool); + } + + return el.outerHeight(); + }; + + lib.outerWidth = function (el) { + if (typeof Zepto === 'function') { + return el.width(); + } + + if (typeof bool !== 'undefined') { + return el.outerWidth(bool); + } + + return el.outerWidth(); + }; + }, + + error : function (error) { + return error.name + ' ' + error.message + '; ' + error.more; + }, + + // remove all foundation events. + off: function () { + $(this.scope).off('.fndtn'); + $(window).off('.fndtn'); + return true; + }, + + zj : function () { + try { + return Zepto; + } catch (e) { + return jQuery; + } + }() + }, + + $.fn.foundation = function () { + var args = Array.prototype.slice.call(arguments, 0); + + return this.each(function () { + Foundation.init.apply(Foundation, [this].concat(args)); + return this; + }); + }; + +}(this, this.document)); + +})(libFuncName); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.magellan.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.magellan.js new file mode 100644 index 00000000..3cdef5b6 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.magellan.js @@ -0,0 +1,130 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.magellan = { + name : 'magellan', + + version : '4.0.0', + + settings : { + activeClass: 'active' + }, + + init : function (scope, method, options) { + this.scope = scope || this.scope; + Foundation.inherit(this, 'data_options'); + + if (typeof method === 'object') { + $.extend(true, this.settings, method); + } + + if (typeof method != 'string') { + if (!this.settings.init) { + this.fixed_magellan = $("[data-magellan-expedition]"); + this.set_threshold(); + this.last_destination = $('[data-magellan-destination]').last(); + this.events(); + } + + return this.settings.init; + } else { + return this[method].call(this, options); + } + }, + + events : function () { + var self = this; + $(this.scope).on('arrival.fndtn.magellan', '[data-magellan-arrival]', function (e) { + var $destination = $(this), + $expedition = $destination.closest('[data-magellan-expedition]'), + activeClass = $expedition.attr('data-magellan-active-class') + || self.settings.activeClass; + + $destination + .closest('[data-magellan-expedition]') + .find('[data-magellan-arrival]') + .not($destination) + .removeClass(activeClass); + $destination.addClass(activeClass); + }); + + this.fixed_magellan + .on('update-position.fndtn.magellan', function(){ + var $el = $(this); + // $el.data("magellan-fixed-position",""); + //$el.data("magellan-top-offset", ""); + }) + .trigger('update-position'); + + $(window) + .on('resize.fndtn.magellan', function() { + this.fixed_magellan.trigger('update-position'); + }.bind(this)) + + .on('scroll.fndtn.magellan', function() { + var windowScrollTop = $(window).scrollTop(); + self.fixed_magellan.each(function() { + var $expedition = $(this); + if (typeof $expedition.data('magellan-top-offset') === 'undefined') { + $expedition.data('magellan-top-offset', $expedition.offset().top); + } + if (typeof $expedition.data('magellan-fixed-position') === 'undefined') { + $expedition.data('magellan-fixed-position', false) + } + var fixed_position = (windowScrollTop + self.settings.threshold) > $expedition.data("magellan-top-offset"); + var attr = $expedition.attr('data-magellan-top-offset'); + + if ($expedition.data("magellan-fixed-position") != fixed_position) { + $expedition.data("magellan-fixed-position", fixed_position); + if (fixed_position) { + $expedition.css({position:"fixed", top:0}); + } else { + $expedition.css({position:"", top:""}); + } + if (fixed_position && typeof attr != 'undefined' && attr != false) { + $expedition.css({position:"fixed", top:attr + "px"}); + } + } + }); + }); + + + if (this.last_destination.length > 0) { + $(window).on('scroll.fndtn.magellan', function (e) { + var windowScrollTop = $(window).scrollTop(), + scrolltopPlusHeight = windowScrollTop + $(window).height(), + lastDestinationTop = Math.ceil(self.last_destination.offset().top); + + $('[data-magellan-destination]').each(function () { + var $destination = $(this), + destination_name = $destination.attr('data-magellan-destination'), + topOffset = $destination.offset().top - windowScrollTop; + + if (topOffset <= self.settings.threshold) { + $("[data-magellan-arrival='" + destination_name + "']").trigger('arrival'); + } + // In large screens we may hit the bottom of the page and dont reach the top of the last magellan-destination, so lets force it + if (scrolltopPlusHeight >= $(self.scope).height() && lastDestinationTop > windowScrollTop && lastDestinationTop < scrolltopPlusHeight) { + $('[data-magellan-arrival]').last().trigger('arrival'); + } + }); + }); + } + + this.settings.init = true; + }, + + set_threshold : function () { + if (!this.settings.threshold) { + this.settings.threshold = (this.fixed_magellan.length > 0) ? + this.outerHeight(this.fixed_magellan, true) : 0; + } + }, + + off : function () { + $(this.scope).off('.fndtn.magellan'); + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.orbit.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.orbit.js new file mode 100644 index 00000000..08c92065 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.orbit.js @@ -0,0 +1,367 @@ +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs = Foundation.libs || {}; + + Foundation.libs.orbit = { + name: 'orbit', + + version: '4.1.0', + + settings: { + timer_speed: 10000, + animation_speed: 500, + bullets: true, + stack_on_small: true, + container_class: 'orbit-container', + stack_on_small_class: 'orbit-stack-on-small', + next_class: 'orbit-next', + prev_class: 'orbit-prev', + timer_container_class: 'orbit-timer', + timer_paused_class: 'paused', + timer_progress_class: 'orbit-progress', + slides_container_class: 'orbit-slides-container', + bullets_container_class: 'orbit-bullets', + bullets_active_class: 'active', + slide_number_class: 'orbit-slide-number', + caption_class: 'orbit-caption', + active_slide_class: 'active', + orbit_transition_class: 'orbit-transitioning' + }, + + init: function (scope, method, options) { + var self = this; + Foundation.inherit(self, 'data_options'); + + if (typeof method === 'object') { + $.extend(true, self.settings, method); + } + + $('[data-orbit]', scope).each(function(idx, el) { + var scoped_self = $.extend(true, {}, self); + scoped_self._init(idx, el); + }); + }, + + _container_html: function() { + var self = this; + return '
        '; + }, + + _bullets_container_html: function($slides) { + var self = this, + $list = $('
          '); + $slides.each(function(idx, slide) { + var $item = $('
        1. '); + if (idx === 0) { + $item.addClass(self.settings.bullets_active_class); + } + $list.append($item); + }); + return $list; + }, + + _slide_number_html: function(slide_number, total_slides) { + var self = this, + $container = $('
          '); + $container.append('' + slide_number + ' of ' + total_slides + ''); + return $container; + }, + + _timer_html: function() { + var self = this; + if (typeof self.settings.timer_speed === 'number' && self.settings.timer_speed > 0) { + return '
          '; + } else { + return ''; + } + }, + + _next_html: function() { + var self = this; + return 'Next '; + }, + + _prev_html: function() { + var self = this; + return 'Prev '; + }, + + _init: function (idx, slider) { + var self = this, + $slides_container = $(slider), + $container = $slides_container.wrap(self._container_html()).parent(), + $slides = $slides_container.children(); + + $.extend(true, self.settings, self.data_options($slides_container)); + + $container.append(self._prev_html()); + $container.append(self._next_html()); + $slides_container.addClass(self.settings.slides_container_class); + if (self.settings.stack_on_small) { + $container.addClass(self.settings.stack_on_small_class); + } + $container.append(self._slide_number_html(1, $slides.length)); + $container.append(self._timer_html()); + if (self.settings.bullets) { + $container.after(self._bullets_container_html($slides)); + } + // To better support the "sliding" effect it's easier + // if we just clone the first and last slides + $slides_container.append($slides.first().clone().attr('data-orbit-slide','')); + $slides_container.prepend($slides.last().clone().attr('data-orbit-slide','')); + // Make the first "real" slide active + $slides_container.css('marginLeft', '-100%'); + $slides.first().addClass(self.settings.active_slide_class); + + self._init_events($slides_container); + self._init_dimensions($slides_container); + self._start_timer($slides_container); + }, + + _init_events: function ($slides_container) { + var self = this, + $container = $slides_container.parent(); + + $(window) + .on('load.fndtn.orbit', function() { + $slides_container.height(''); + $slides_container.height($slides_container.height($container.height())); + $slides_container.trigger('orbit:ready'); + }) + .on('resize.fndtn.orbit', function() { + $slides_container.height(''); + $slides_container.height($slides_container.height($container.height())); + }); + + $(document).on('click.fndtn.orbit', '[data-orbit-link]', function(e) { + e.preventDefault(); + var id = $(e.currentTarget).attr('data-orbit-link'), + $slide = $slides_container.find('[data-orbit-slide=' + id + ']').first(); + + if ($slide.length === 1) { + self._reset_timer($slides_container, true); + self._goto($slides_container, $slide.index(), function() {}); + } + }); + + $container.siblings('.' + self.settings.bullets_container_class) + .on('click.fndtn.orbit', '[data-orbit-slide-number]', function(e) { + e.preventDefault(); + self._reset_timer($slides_container, true); + self._goto($slides_container, $(e.currentTarget).data('orbit-slide-number'),function() {}); + }); + + $container + .on('orbit:after-slide-change.fndtn.orbit', function(e, orbit) { + var $slide_number = $container.find('.' + self.settings.slide_number_class); + + if ($slide_number.length === 1) { + $slide_number.replaceWith(self._slide_number_html(orbit.slide_number, orbit.total_slides)); + } + }) + .on('orbit:next-slide.fndtn.orbit click.fndtn.orbit', '.' + self.settings.next_class, function(e) { + e.preventDefault(); + self._reset_timer($slides_container, true); + self._goto($slides_container, 'next', function() {}); + }) + .on('orbit:prev-slide.fndtn.orbit click.fndtn.orbit', '.' + self.settings.prev_class, function(e) { + e.preventDefault(); + self._reset_timer($slides_container, true); + self._goto($slides_container, 'prev', function() {}); + }) + .on('orbit:toggle-play-pause.fndtn.orbit click.fndtn.orbit touchstart.fndtn.orbit', '.' + self.settings.timer_container_class, function(e) { + e.preventDefault(); + var $timer = $(e.currentTarget).toggleClass(self.settings.timer_paused_class), + $slides_container = $timer.closest('.' + self.settings.container_class) + .find('.' + self.settings.slides_container_class); + + if ($timer.hasClass(self.settings.timer_paused_class)) { + self._stop_timer($slides_container); + } else { + self._start_timer($slides_container); + } + }) + .on('touchstart.fndtn.orbit', function(e) { + if (!e.touches) { e = e.originalEvent; } + var data = { + start_page_x: e.touches[0].pageX, + start_page_y: e.touches[0].pageY, + start_time: (new Date()).getTime(), + delta_x: 0, + is_scrolling: undefined + }; + $container.data('swipe-transition', data); + e.stopPropagation(); + }) + .on('touchmove.fndtn.orbit', function(e) { + if (!e.touches) { e = e.originalEvent; } + // Ignore pinch/zoom events + if(e.touches.length > 1 || e.scale && e.scale !== 1) return; + + var data = $container.data('swipe-transition'); + if (typeof data === 'undefined') { + data = {}; + } + + data.delta_x = e.touches[0].pageX - data.start_page_x; + + if ( typeof data.is_scrolling === 'undefined') { + data.is_scrolling = !!( data.is_scrolling || Math.abs(data.delta_x) < Math.abs(e.touches[0].pageY - data.start_page_y) ); + } + + if (!data.is_scrolling && !data.active) { + e.preventDefault(); + self._stop_timer($slides_container); + var direction = (data.delta_x < 0) ? 'next' : 'prev'; + data.active = true; + self._goto($slides_container, direction, function() {}); + } + }) + .on('touchend.fndtn.orbit', function(e) { + $container.data('swipe-transition', {}); + e.stopPropagation(); + }); + }, + + _init_dimensions: function ($slides_container) { + var $container = $slides_container.parent(), + $slides = $slides_container.children(); + + $slides_container.css('width', $slides.length * 100 + '%'); + $slides.css('width', 100 / $slides.length + '%'); + $slides_container.height($container.height()); + $slides_container.css('width', $slides.length * 100 + '%'); + }, + + _start_timer: function ($slides_container) { + var self = this, + $container = $slides_container.parent(); + + var callback = function() { + self._reset_timer($slides_container, false); + self._goto($slides_container, 'next', function() { + self._start_timer($slides_container); + }); + }; + + var $timer = $container.find('.' + self.settings.timer_container_class), + $progress = $timer.find('.' + self.settings.timer_progress_class), + progress_pct = ($progress.width() / $timer.width()), + delay = self.settings.timer_speed - (progress_pct * self.settings.timer_speed); + + $progress.animate({'width': '100%'}, delay, 'linear', callback); + $slides_container.trigger('orbit:timer-started'); + }, + + _stop_timer: function ($slides_container) { + var self = this, + $container = $slides_container.parent(), + $timer = $container.find('.' + self.settings.timer_container_class), + $progress = $timer.find('.' + self.settings.timer_progress_class), + progress_pct = $progress.width() / $timer.width() + self._rebuild_timer($container, progress_pct * 100 + '%'); + // $progress.stop(); + $slides_container.trigger('orbit:timer-stopped'); + $timer = $container.find('.' + self.settings.timer_container_class); + $timer.addClass(self.settings.timer_paused_class); + }, + + _reset_timer: function($slides_container, is_paused) { + var self = this, + $container = $slides_container.parent(); + self._rebuild_timer($container, '0%'); + if (typeof is_paused === 'boolean' && is_paused) { + var $timer = $container.find('.' + self.settings.timer_container_class); + $timer.addClass(self.settings.timer_paused_class); + } + }, + + _rebuild_timer: function ($container, width_pct) { + // Zepto is unable to stop animations since they + // are css-based. This is a workaround for that + // limitation, which rebuilds the dom element + // thus stopping the animation + var self = this, + $timer = $container.find('.' + self.settings.timer_container_class), + $new_timer = $(self._timer_html()), + $new_timer_progress = $new_timer.find('.' + self.settings.timer_progress_class); + + if (typeof Zepto === 'function') { + $timer.remove(); + $container.append($new_timer); + $new_timer_progress.css('width', width_pct); + } else if (typeof jQuery === 'function') { + var $progress = $timer.find('.' + self.settings.timer_progress_class); + $progress.css('width', width_pct); + $progress.stop(); + } + }, + + _goto: function($slides_container, index_or_direction, callback) { + var self = this, + $container = $slides_container.parent(), + $slides = $slides_container.children(), + $active_slide = $slides_container.find('.' + self.settings.active_slide_class), + active_index = $active_slide.index(), + margin_position = Foundation.rtl ? 'marginRight' : 'marginLeft'; + + if ($container.hasClass(self.settings.orbit_transition_class)) { + return false; + } + + if (index_or_direction === 'prev') { + if (active_index === 0) { + active_index = $slides.length - 1; + } + else { + active_index--; + } + } + else if (index_or_direction === 'next') { + active_index = (active_index+1) % $slides.length; + } + else if (typeof index_or_direction === 'number') { + active_index = (index_or_direction % $slides.length); + } + if (active_index === ($slides.length - 1) && index_or_direction === 'next') { + $slides_container.css(margin_position, '0%'); + active_index = 1; + } + else if (active_index === 0 && index_or_direction === 'prev') { + $slides_container.css(margin_position, '-' + ($slides.length - 1) * 100 + '%'); + active_index = $slides.length - 2; + } + // Start transition, make next slide active + $container.addClass(self.settings.orbit_transition_class); + $active_slide.removeClass(self.settings.active_slide_class); + $($slides[active_index]).addClass(self.settings.active_slide_class); + // Make next bullet active + var $bullets = $container.siblings('.' + self.settings.bullets_container_class); + if ($bullets.length === 1) { + $bullets.children().removeClass(self.settings.bullets_active_class); + $($bullets.children()[active_index-1]).addClass(self.settings.bullets_active_class); + } + var new_margin_left = '-' + (active_index * 100) + '%'; + // Check to see if animation will occur, otherwise perform + // callbacks manually + $slides_container.trigger('orbit:before-slide-change'); + if ($slides_container.css(margin_position) === new_margin_left) { + $container.removeClass(self.settings.orbit_transition_class); + $slides_container.trigger('orbit:after-slide-change', [{slide_number: active_index, total_slides: $slides_container.children().length - 2}]); + callback(); + } else { + var properties = {}; + properties[margin_position] = new_margin_left; + + $slides_container.animate(properties, self.settings.animation_speed, 'linear', function() { + $container.removeClass(self.settings.orbit_transition_class); + $slides_container.trigger('orbit:after-slide-change', [{slide_number: active_index, total_slides: $slides_container.children().length - 2}]); + callback(); + }); + } + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.placeholder.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.placeholder.js new file mode 100644 index 00000000..65c18fc2 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.placeholder.js @@ -0,0 +1,159 @@ +/*! http://mths.be/placeholder v2.0.7 by @mathias + Modified to work with Zepto.js by ZURB +*/ +;(function(window, document, $) { + + var isInputSupported = 'placeholder' in document.createElement('input'), + isTextareaSupported = 'placeholder' in document.createElement('textarea'), + prototype = $.fn, + valHooks = $.valHooks, + hooks, + placeholder; + + if (isInputSupported && isTextareaSupported) { + + placeholder = prototype.placeholder = function() { + return this; + }; + + placeholder.input = placeholder.textarea = true; + + } else { + + placeholder = prototype.placeholder = function() { + var $this = this; + $this + .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') + .not('.placeholder') + .bind({ + 'focus.placeholder': clearPlaceholder, + 'blur.placeholder': setPlaceholder + }) + .data('placeholder-enabled', true) + .trigger('blur.placeholder'); + return $this; + }; + + placeholder.input = isInputSupported; + placeholder.textarea = isTextareaSupported; + + hooks = { + 'get': function(element) { + var $element = $(element); + return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; + }, + 'set': function(element, value) { + var $element = $(element); + if (!$element.data('placeholder-enabled')) { + return element.value = value; + } + if (value == '') { + element.value = value; + // Issue #56: Setting the placeholder causes problems if the element continues to have focus. + if (element != document.activeElement) { + // We can't use `triggerHandler` here because of dummy text/password inputs :( + setPlaceholder.call(element); + } + } else if ($element.hasClass('placeholder')) { + clearPlaceholder.call(element, true, value) || (element.value = value); + } else { + element.value = value; + } + // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363 + return $element; + } + }; + + isInputSupported || (valHooks.input = hooks); + isTextareaSupported || (valHooks.textarea = hooks); + + $(function() { + // Look for forms + $(document).delegate('form', 'submit.placeholder', function() { + // Clear the placeholder values so they don't get submitted + var $inputs = $('.placeholder', this).each(clearPlaceholder); + setTimeout(function() { + $inputs.each(setPlaceholder); + }, 10); + }); + }); + + // Clear placeholder values upon page reload + $(window).bind('beforeunload.placeholder', function() { + $('.placeholder').each(function() { + this.value = ''; + }); + }); + + } + + function args(elem) { + // Return an object of element attributes + var newAttrs = {}, + rinlinejQuery = /^jQuery\d+$/; + $.each(elem.attributes, function(i, attr) { + if (attr.specified && !rinlinejQuery.test(attr.name)) { + newAttrs[attr.name] = attr.value; + } + }); + return newAttrs; + } + + function clearPlaceholder(event, value) { + var input = this, + $input = $(input); + if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) { + if ($input.data('placeholder-password')) { + $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id')); + // If `clearPlaceholder` was called from `$.valHooks.input.set` + if (event === true) { + return $input[0].value = value; + } + $input.focus(); + } else { + input.value = ''; + $input.removeClass('placeholder'); + input == document.activeElement && input.select(); + } + } + } + + function setPlaceholder() { + var $replacement, + input = this, + $input = $(input), + $origInput = $input, + id = this.id; + if (input.value == '') { + if (input.type == 'password') { + if (!$input.data('placeholder-textinput')) { + try { + $replacement = $input.clone().attr({ 'type': 'text' }); + } catch(e) { + $replacement = $('').attr($.extend(args(this), { 'type': 'text' })); + } + $replacement + .removeAttr('name') + .data({ + 'placeholder-password': true, + 'placeholder-id': id + }) + .bind('focus.placeholder', clearPlaceholder); + $input + .data({ + 'placeholder-textinput': $replacement, + 'placeholder-id': id + }) + .before($replacement); + } + $input = $input.removeAttr('id').hide().prev().attr('id', id).show(); + // Note: `$input[0] != input` now! + } + $input.addClass('placeholder'); + $input[0].value = $input.attr('placeholder'); + } else { + $input.removeClass('placeholder'); + } + } + +}(this, document, Foundation.zj)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.reveal.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.reveal.js new file mode 100644 index 00000000..3ef6c605 --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.reveal.js @@ -0,0 +1,272 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.reveal = { + name: 'reveal', + + version : '4.1.2', + + locked : false, + + settings : { + animation: 'fadeAndPop', + animationSpeed: 250, + closeOnBackgroundClick: true, + dismissModalClass: 'close-reveal-modal', + bgClass: 'reveal-modal-bg', + open: function(){}, + opened: function(){}, + close: function(){}, + closed: function(){}, + bg : $('.reveal-modal-bg'), + css : { + open : { + 'opacity': 0, + 'visibility': 'visible', + 'display' : 'block' + }, + close : { + 'opacity': 1, + 'visibility': 'hidden', + 'display': 'none' + } + } + }, + + init : function (scope, method, options) { + this.scope = scope || this.scope; + Foundation.inherit(this, 'data_options delay'); + + if (typeof method === 'object') { + $.extend(true, this.settings, method); + } else if (typeof options !== 'undefined') { + $.extend(true, this.settings, options); + } + + if (typeof method != 'string') { + this.events(); + + return this.settings.init; + } else { + return this[method].call(this, options); + } + }, + + events : function () { + var self = this; + + $(this.scope) + .off('.fndtn.reveal') + .on('click.fndtn.reveal', '[data-reveal-id]', function (e) { + e.preventDefault(); + if (!self.locked) { + self.locked = true; + self.open.call(self, $(this)); + } + }) + .on('click.fndtn.reveal touchend.click.fndtn.reveal', this.close_targets(), function (e) { + e.preventDefault(); + if (!self.locked) { + self.locked = true; + self.close.call(self, $(this).closest('.reveal-modal')); + } + }) + .on('open.fndtn.reveal', '.reveal-modal', this.settings.open) + .on('opened.fndtn.reveal', '.reveal-modal', this.settings.opened) + .on('opened.fndtn.reveal', '.reveal-modal', this.open_video) + .on('close.fndtn.reveal', '.reveal-modal', this.settings.close) + .on('closed.fndtn.reveal', '.reveal-modal', this.settings.closed) + .on('closed.fndtn.reveal', '.reveal-modal', this.close_video); + + return true; + }, + + open : function (target) { + if (target) { + var modal = $('#' + target.data('reveal-id')); + } else { + var modal = $(this.scope); + } + + if (!modal.hasClass('open')) { + var open_modal = $('.reveal-modal.open'); + + if (typeof modal.data('css-top') === 'undefined') { + modal.data('css-top', parseInt(modal.css('top'), 10)) + .data('offset', this.cache_offset(modal)); + } + + modal.trigger('open'); + + if (open_modal.length < 1) { + this.toggle_bg(modal); + } + this.hide(open_modal, this.settings.css.open); + this.show(modal, this.settings.css.open); + } + }, + + close : function (modal) { + + var modal = modal || $(this.scope), + open_modals = $('.reveal-modal.open'); + + if (open_modals.length > 0) { + this.locked = true; + modal.trigger('close'); + this.toggle_bg(modal); + this.hide(open_modals, this.settings.css.close); + } + }, + + close_targets : function () { + var base = '.' + this.settings.dismissModalClass; + + if (this.settings.closeOnBackgroundClick) { + return base + ', .' + this.settings.bgClass; + } + + return base; + }, + + toggle_bg : function (modal) { + if ($('.reveal-modal-bg').length === 0) { + this.settings.bg = $('
          ', {'class': this.settings.bgClass}) + .appendTo('body'); + } + + if (this.settings.bg.filter(':visible').length > 0) { + this.hide(this.settings.bg); + } else { + this.show(this.settings.bg); + } + }, + + show : function (el, css) { + // is modal + if (css) { + if (/pop/i.test(this.settings.animation)) { + css.top = $(window).scrollTop() - el.data('offset') + 'px'; + var end_css = { + top: $(window).scrollTop() + el.data('css-top') + 'px', + opacity: 1 + } + + return this.delay(function () { + return el + .css(css) + .animate(end_css, this.settings.animationSpeed, 'linear', function () { + this.locked = false; + el.trigger('opened'); + }.bind(this)) + .addClass('open'); + }.bind(this), this.settings.animationSpeed / 2); + } + + if (/fade/i.test(this.settings.animation)) { + var end_css = {opacity: 1}; + + return this.delay(function () { + return el + .css(css) + .animate(end_css, this.settings.animationSpeed, 'linear', function () { + this.locked = false; + el.trigger('opened'); + }.bind(this)) + .addClass('open'); + }.bind(this), this.settings.animationSpeed / 2); + } + + return el.css(css).show().css({opacity: 1}).addClass('open').trigger('opened'); + } + + // should we animate the background? + if (/fade/i.test(this.settings.animation)) { + return el.fadeIn(this.settings.animationSpeed / 2); + } + + return el.show(); + }, + + hide : function (el, css) { + // is modal + if (css) { + if (/pop/i.test(this.settings.animation)) { + var end_css = { + top: - $(window).scrollTop() - el.data('offset') + 'px', + opacity: 0 + }; + + return this.delay(function () { + return el + .animate(end_css, this.settings.animationSpeed, 'linear', function () { + this.locked = false; + el.css(css).trigger('closed'); + }.bind(this)) + .removeClass('open'); + }.bind(this), this.settings.animationSpeed / 2); + } + + if (/fade/i.test(this.settings.animation)) { + var end_css = {opacity: 0}; + + return this.delay(function () { + return el + .animate(end_css, this.settings.animationSpeed, 'linear', function () { + this.locked = false; + el.css(css).trigger('closed'); + }.bind(this)) + .removeClass('open'); + }.bind(this), this.settings.animationSpeed / 2); + } + + return el.hide().css(css).removeClass('open').trigger('closed'); + } + + // should we animate the background? + if (/fade/i.test(this.settings.animation)) { + return el.fadeOut(this.settings.animationSpeed / 2); + } + + return el.hide(); + }, + + close_video : function (e) { + var video = $(this).find('.flex-video'), + iframe = video.find('iframe'); + + if (iframe.length > 0) { + iframe.attr('data-src', iframe[0].src); + iframe.attr('src', 'about:blank'); + video.fadeOut(100).hide(); + } + }, + + open_video : function (e) { + var video = $(this).find('.flex-video'), + iframe = video.find('iframe'); + + if (iframe.length > 0) { + var data_src = iframe.attr('data-src'); + if (typeof data_src === 'string') { + iframe[0].src = iframe.attr('data-src'); + } + video.show().fadeIn(100); + } + }, + + cache_offset : function (modal) { + var offset = modal.show().height() + parseInt(modal.css('top'), 10); + + modal.hide(); + + return offset; + }, + + off : function () { + $(this.scope).off('.fndtn.reveal'); + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.section.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.section.js new file mode 100644 index 00000000..17e17fed --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.section.js @@ -0,0 +1,291 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.section = { + name: 'section', + + version : '4.1.2', + + settings : { + deep_linking: false, + one_up: true, + callback: function (){} + }, + + init : function (scope, method, options) { + var self = this; + Foundation.inherit(this, 'throttle data_options position_right offset_right'); + + if (typeof method != 'string') { + this.set_active_from_hash(); + this.events(); + + return true; + } else { + return this[method].call(this, options); + } + }, + + events : function () { + var self = this; + + $(this.scope) + .on('click.fndtn.section', '[data-section] .title, [data-section] [data-section-title]', function (e) { + var $this = $(this), + section = $this.closest('[data-section]'); + + self.toggle_active.call(this, e, self); + }); + + $(window) + .on('resize.fndtn.section', self.throttle(function () { + self.resize.call(this); + }, 30)) + .on('hashchange', function () { + if (!self.settings.toggled){ + self.set_active_from_hash(); + $(this).trigger('resize'); + } + }).trigger('resize'); + + $(document) + .on('click.fndtn.section', function (e) { + if ($(e.target).closest('.title, [data-section-title]').length < 1) { + $('[data-section="vertical-nav"], [data-section="horizontal-nav"]') + .find('section, .section, [data-section-region]') + .removeClass('active') + .attr('style', ''); + } + }); + + }, + + toggle_active : function (e, self) { + var $this = $(this), + section = $this.closest('section, .section, [data-section-region]'), + content = section.find('.content, [data-section-content]'), + parent = section.closest('[data-section]'), + self = Foundation.libs.section, + settings = $.extend({}, self.settings, self.data_options(parent)); + + self.settings.toggled = true; + + if (!settings.deep_linking && content.length > 0) { + e.preventDefault(); + } + + if (section.hasClass('active')) { + if (self.small(parent) + || self.is_vertical(parent) + || self.is_horizontal(parent) + || self.is_accordion(parent)) { + section + .removeClass('active') + .attr('style', ''); + } + } else { + var prev_active_section = null, + title_height = self.outerHeight(section.find('.title, [data-section-title]')); + + if (self.small(parent) || settings.one_up) { + prev_active_section = $this.closest('[data-section]').find('section.active, .section.active, .active[data-section-region]'); + + if (self.small(parent)) { + prev_active_section.attr('style', ''); + } else { + prev_active_section.attr('style', 'visibility: hidden; padding-top: '+title_height+'px;'); + } + } + + if (self.small(parent)) { + section.attr('style', ''); + } else { + section.css('padding-top', title_height); + } + + section.addClass('active'); + + if (prev_active_section !== null) { + prev_active_section.removeClass('active').attr('style', ''); + } + } + + setTimeout(function () { + self.settings.toggled = false; + }, 300); + + settings.callback(); + }, + + resize : function () { + var sections = $('[data-section]'), + self = Foundation.libs.section; + + sections.each(function() { + var $this = $(this), + active_section = $this.find('section.active, .section.active, .active[data-section-region]'), + settings = $.extend({}, self.settings, self.data_options($this)); + + if (active_section.length > 1) { + active_section + .not(':first') + .removeClass('active') + .attr('style', ''); + } else if (active_section.length < 1 + && !self.is_vertical($this) + && !self.is_horizontal($this) + && !self.is_accordion($this)) { + + var first = $this.find('section, .section, [data-section-region]').first(); + + if (settings.one_up) { + first.addClass('active'); + } + + if (self.small($this)) { + first.attr('style', ''); + } else { + first.css('padding-top', self.outerHeight(first.find('.title, [data-section-title]'))); + } + } + + if (self.small($this)) { + active_section.attr('style', ''); + } else { + active_section.css('padding-top', self.outerHeight(active_section.find('.title, [data-section-title]'))); + } + + self.position_titles($this); + + if (self.is_horizontal($this) && !self.small($this)) { + self.position_content($this); + } else { + self.position_content($this, false); + } + }); + }, + + is_vertical : function (el) { + return /vertical-nav/i.test(el.data('section')); + }, + + is_horizontal : function (el) { + return /horizontal-nav/i.test(el.data('section')); + }, + + is_accordion : function (el) { + return /accordion/i.test(el.data('section')); + }, + + is_tabs : function (el) { + return /tabs/i.test(el.data('section')); + }, + + set_active_from_hash : function () { + var hash = window.location.hash.substring(1), + sections = $('[data-section]'), + self = this; + + sections.each(function () { + var section = $(this), + settings = $.extend({}, self.settings, self.data_options(section)); + + if (hash.length > 0 && settings.deep_linking) { + section + .find('section, .section, [data-section-region]') + .attr('style', '') + .removeClass('active'); + section + .find('.content[data-slug="' + hash + '"], [data-section-content][data-slug="' + hash + '"]') + .closest('section, .section, [data-section-region]') + .addClass('active'); + } + }); + }, + + position_titles : function (section, off) { + var titles = section.find('.title, [data-section-title]'), + previous_width = 0, + self = this; + + if (typeof off === 'boolean') { + titles.attr('style', ''); + + } else { + titles.each(function () { + if (!self.rtl) { + $(this).css('left', previous_width); + } else { + $(this).css('right', previous_width); + } + previous_width += self.outerWidth($(this)); + }); + } + }, + + position_content : function (section, off) { + var titles = section.find('.title, [data-section-title]'), + content = section.find('.content, [data-section-content]'), + self = this; + + if (typeof off === 'boolean') { + content.attr('style', ''); + section.attr('style', ''); + } else { + section.find('section, .section, [data-section-region]').each(function () { + var title = $(this).find('.title, [data-section-title]'), + content = $(this).find('.content, [data-section-content]'); + if (!self.rtl) { + content.css({left: title.position().left - 1, top: self.outerHeight(title) - 2}); + } else { + content.css({right: self.position_right(title) + 1, top: self.outerHeight(title) - 2}); + } + }); + + // temporary work around for Zepto outerheight calculation issues. + if (typeof Zepto === 'function') { + section.height(this.outerHeight(titles.first())); + } else { + section.height(this.outerHeight(titles.first()) - 2); + } + } + + }, + + position_right : function (el) { + var section = el.closest('[data-section]'), + section_width = el.closest('[data-section]').width(), + offset = section.find('.title, [data-section-title]').length; + return (section_width - el.position().left - el.width() * (el.index() + 1) - offset); + }, + + reflow : function () { + $('[data-section]').trigger('resize'); + }, + + small : function (el) { + var settings = $.extend({}, this.settings, this.data_options(el)); + if (this.is_tabs(el)) { + return false; + } + if (el && this.is_accordion(el)) { + return true; + } + if ($('html').hasClass('lt-ie9')) { + return true; + } + if ($('html').hasClass('ie8compat')) { + return true; + } + return $(this.scope).width() < 768; + }, + + off : function () { + $(this.scope).off('.fndtn.section'); + $(window).off('.fndtn.section'); + $(document).off('.fndtn.section') + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.tooltips.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.tooltips.js new file mode 100644 index 00000000..4e9cf7ec --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.tooltips.js @@ -0,0 +1,199 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.tooltips = { + name: 'tooltips', + + version : '4.1.0', + + settings : { + selector : '.has-tip', + additionalInheritableClasses : [], + tooltipClass : '.tooltip', + tipTemplate : function (selector, content) { + return '' + content + ''; + } + }, + + cache : {}, + + init : function (scope, method, options) { + var self = this; + this.scope = scope || this.scope; + + if (typeof method === 'object') { + $.extend(true, this.settings, method); + } + + if (typeof method != 'string') { + if (Modernizr.touch) { + $(this.scope) + .on('click.fndtn.tooltip touchstart.fndtn.tooltip touchend.fndtn.tooltip', + '[data-tooltip]', function (e) { + e.preventDefault(); + $(self.settings.tooltipClass).hide(); + self.showOrCreateTip($(this)); + }) + .on('click.fndtn.tooltip touchstart.fndtn.tooltip touchend.fndtn.tooltip', + this.settings.tooltipClass, function (e) { + e.preventDefault(); + $(this).fadeOut(150); + }); + } else { + $(this.scope) + .on('mouseenter.fndtn.tooltip mouseleave.fndtn.tooltip', + '[data-tooltip]', function (e) { + var $this = $(this); + + if (e.type === 'mouseover' || e.type === 'mouseenter') { + self.showOrCreateTip($this); + } else if (e.type === 'mouseout' || e.type === 'mouseleave') { + self.hide($this); + } + }); + } + + // $(this.scope).data('fndtn-tooltips', true); + } else { + return this[method].call(this, options); + } + + }, + + showOrCreateTip : function ($target) { + var $tip = this.getTip($target); + + if ($tip && $tip.length > 0) { + return this.show($target); + } + + return this.create($target); + }, + + getTip : function ($target) { + var selector = this.selector($target), + tip = null; + + if (selector) { + tip = $('span[data-selector=' + selector + ']' + this.settings.tooltipClass); + } + + return (typeof tip === 'object') ? tip : false; + }, + + selector : function ($target) { + var id = $target.attr('id'), + dataSelector = $target.attr('data-tooltip') || $target.attr('data-selector'); + + if ((id && id.length < 1 || !id) && typeof dataSelector != 'string') { + dataSelector = 'tooltip' + Math.random().toString(36).substring(7); + $target.attr('data-selector', dataSelector); + } + + return (id && id.length > 0) ? id : dataSelector; + }, + + create : function ($target) { + var $tip = $(this.settings.tipTemplate(this.selector($target), $('
          ').html($target.attr('title')).html())), + classes = this.inheritable_classes($target); + + $tip.addClass(classes).appendTo('body'); + if (Modernizr.touch) { + $tip.append('tap to close '); + } + $target.removeAttr('title').attr('title',''); + this.show($target); + }, + + reposition : function (target, tip, classes) { + var width, nub, nubHeight, nubWidth, column, objPos; + + tip.css('visibility', 'hidden').show(); + + width = target.data('width'); + nub = tip.children('.nub'); + nubHeight = this.outerHeight(nub); + nubWidth = this.outerHeight(nub); + + objPos = function (obj, top, right, bottom, left, width) { + return obj.css({ + 'top' : (top) ? top : 'auto', + 'bottom' : (bottom) ? bottom : 'auto', + 'left' : (left) ? left : 'auto', + 'right' : (right) ? right : 'auto', + 'width' : (width) ? width : 'auto' + }).end(); + }; + + objPos(tip, (target.offset().top + this.outerHeight(target) + 10), 'auto', 'auto', target.offset().left, width); + + if ($(window).width() < 767) { + objPos(tip, (target.offset().top + this.outerHeight(target) + 10), 'auto', 'auto', 12.5, $(this.scope).width()); + tip.addClass('tip-override'); + objPos(nub, -nubHeight, 'auto', 'auto', target.offset().left); + } else { + var left = target.offset().left; + if (Foundation.rtl) { + left = target.offset().left + target.offset().width - this.outerWidth(tip); + } + objPos(tip, (target.offset().top + this.outerHeight(target) + 10), 'auto', 'auto', left, width); + tip.removeClass('tip-override'); + if (classes && classes.indexOf('tip-top') > -1) { + objPos(tip, (target.offset().top - this.outerHeight(tip)), 'auto', 'auto', left, width) + .removeClass('tip-override'); + } else if (classes && classes.indexOf('tip-left') > -1) { + objPos(tip, (target.offset().top + (this.outerHeight(target) / 2) - nubHeight*2.5), 'auto', 'auto', (target.offset().left - this.outerWidth(tip) - nubHeight), width) + .removeClass('tip-override'); + } else if (classes && classes.indexOf('tip-right') > -1) { + objPos(tip, (target.offset().top + (this.outerHeight(target) / 2) - nubHeight*2.5), 'auto', 'auto', (target.offset().left + this.outerWidth(target) + nubHeight), width) + .removeClass('tip-override'); + } + } + + tip.css('visibility', 'visible').hide(); + }, + + inheritable_classes : function (target) { + var inheritables = ['tip-top', 'tip-left', 'tip-bottom', 'tip-right', 'noradius'].concat(this.settings.additionalInheritableClasses), + classes = target.attr('class'), + filtered = classes ? $.map(classes.split(' '), function (el, i) { + if ($.inArray(el, inheritables) !== -1) { + return el; + } + }).join(' ') : ''; + + return $.trim(filtered); + }, + + show : function ($target) { + var $tip = this.getTip($target); + + this.reposition($target, $tip, $target.attr('class')); + $tip.fadeIn(150); + }, + + hide : function ($target) { + var $tip = this.getTip($target); + + $tip.fadeOut(150); + }, + + // deprecate reload + reload : function () { + var $self = $(this); + + return ($self.data('fndtn-tooltips')) ? $self.foundationTooltips('destroy').foundationTooltips('init') : $self.foundationTooltips('init'); + }, + + off : function () { + $(this.scope).off('.fndtn.tooltip'); + $(this.settings.tooltipClass).each(function (i) { + $('[data-tooltip]').get(i).attr('title', $(this).text()); + }).remove(); + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.topbar.js b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.topbar.js new file mode 100644 index 00000000..c49992ce --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/foundation/foundation.topbar.js @@ -0,0 +1,242 @@ +/*jslint unparam: true, browser: true, indent: 2 */ + +;(function ($, window, document, undefined) { + 'use strict'; + + Foundation.libs.topbar = { + name : 'topbar', + + version : '4.1.2', + + settings : { + index : 0, + stickyClass : 'sticky', + custom_back_text: true, + back_text: 'Back', + init : false + }, + + init : function (section, method, options) { + var self = this; + + if (typeof method === 'object') { + $.extend(true, this.settings, method); + } + + if (typeof method != 'string') { + + $('.top-bar').each(function () { + self.settings.$w = $(window); + self.settings.$topbar = $(this); + self.settings.$section = self.settings.$topbar.find('section'); + self.settings.$titlebar = self.settings.$topbar.children('ul').first(); + + + self.settings.$topbar.data('index', 0); + + var breakpoint = $("
          ").insertAfter(self.settings.$topbar); + self.settings.breakPoint = breakpoint.width(); + breakpoint.remove(); + + self.assemble(); + + if (self.settings.$topbar.parent().hasClass('fixed')) { + $('body').css('padding-top', self.outerHeight(self.settings.$topbar)); + } + }); + + if (!self.settings.init) { + this.events(); + } + + return this.settings.init; + } else { + // fire method + return this[method].call(this, options); + } + }, + + events : function () { + var self = this; + var offst = this.outerHeight($('.top-bar')); + $(this.scope) + .on('click.fndtn.topbar', '.top-bar .toggle-topbar', function (e) { + var topbar = $(this).closest('.top-bar'), + section = topbar.find('section, .section'), + titlebar = topbar.children('ul').first(); + + if (!topbar.data('height')) self.largestUL(); + + e.preventDefault(); + + if (self.breakpoint()) { + topbar + .toggleClass('expanded') + .css('min-height', ''); + } + + if (!topbar.hasClass('expanded')) { + if (!self.rtl) { + section.css({left: '0%'}); + section.find('>.name').css({left: '100%'}); + } else { + section.css({right: '0%'}); + section.find('>.name').css({right: '100%'}); + } + section.find('li.moved').removeClass('moved'); + topbar.data('index', 0); + + if (topbar.hasClass('fixed')) { + topbar.parent().addClass('fixed'); + topbar.removeClass('fixed'); + $('body').css('padding-top',offst); + } + } else if (topbar.parent().hasClass('fixed')) { + topbar.parent().removeClass('fixed'); + topbar.addClass('fixed'); + $('body').css('padding-top','0'); + window.scrollTo(0,0); + } + }) + + .on('click.fndtn.topbar', '.top-bar .has-dropdown>a', function (e) { + var topbar = $(this).closest('.top-bar'), + section = topbar.find('section, .section'), + titlebar = topbar.children('ul').first(); + + if (Modernizr.touch || self.breakpoint()) { + e.preventDefault(); + } + + if (self.breakpoint()) { + var $this = $(this), + $selectedLi = $this.closest('li'); + + topbar.data('index', topbar.data('index') + 1); + $selectedLi.addClass('moved'); + if (!self.rtl) { + section.css({left: -(100 * topbar.data('index')) + '%'}); + section.find('>.name').css({left: 100 * topbar.data('index') + '%'}); + } else { + section.css({right: -(100 * topbar.data('index')) + '%'}); + section.find('>.name').css({right: 100 * topbar.data('index') + '%'}); + } + + $this.siblings('ul') + .height(topbar.data('height') + self.outerHeight(titlebar, true)); + topbar + .css('min-height', topbar.data('height') + self.outerHeight(titlebar, true) * 2) + } + }); + + $(window).on('resize.fndtn.topbar', function () { + if (!self.breakpoint()) { + $('.top-bar') + .css('min-height', '') + .removeClass('expanded'); + } + }.bind(this)); + + // Go up a level on Click + $(this.scope).on('click.fndtn', '.top-bar .has-dropdown .back', function (e) { + e.preventDefault(); + + var $this = $(this), + topbar = $this.closest('.top-bar'), + section = topbar.find('section, .section'), + $movedLi = $this.closest('li.moved'), + $previousLevelUl = $movedLi.parent(); + + topbar.data('index', topbar.data('index') - 1); + if (!self.rtl) { + section.css({left: -(100 * topbar.data('index')) + '%'}); + section.find('>.name').css({left: 100 * topbar.data('index') + '%'}); + } else { + section.css({right: -(100 * topbar.data('index')) + '%'}); + section.find('>.name').css({right: 100 * topbar.data('index') + '%'}); + } + + if (topbar.data('index') === 0) { + topbar.css('min-height', 0); + } + + setTimeout(function () { + $movedLi.removeClass('moved'); + }, 300); + }); + }, + + breakpoint : function () { + return $(window).width() <= this.settings.breakPoint || $('html').hasClass('lt-ie9'); + }, + + assemble : function () { + var self = this; + // Pull element out of the DOM for manipulation + this.settings.$section.detach(); + + this.settings.$section.find('.has-dropdown>a').each(function () { + var $link = $(this), + $dropdown = $link.siblings('.dropdown'), + $titleLi = $('
        2. '); + + // Copy link to subnav + if (self.settings.custom_back_text == true) { + $titleLi.find('h5>a').html('« ' + self.settings.back_text); + } else { + $titleLi.find('h5>a').html('« ' + $link.html()); + } + $dropdown.prepend($titleLi); + }); + + // Put element back in the DOM + this.settings.$section.appendTo(this.settings.$topbar); + + // check for sticky + this.sticky(); + }, + + largestUL : function () { + var uls = this.settings.$topbar.find('section ul ul'), + largest = uls.first(), + total = 0, + self = this; + + uls.each(function () { + if ($(this).children('li').length > largest.children('li').length) { + largest = $(this); + } + }); + + largest.children('li').each(function () { total += self.outerHeight($(this), true); }); + + this.settings.$topbar.data('height', total); + }, + + sticky : function () { + var klass = '.' + this.settings.stickyClass; + if ($(klass).length > 0) { + var distance = $(klass).length ? $(klass).offset().top: 0, + $window = $(window); + var offst = this.outerHeight($('.top-bar')); + + $window.scroll(function() { + if ($window.scrollTop() >= (distance)) { + $(klass).addClass("fixed"); + $('body').css('padding-top',offst); + } + + else if ($window.scrollTop() < distance) { + $(klass).removeClass("fixed"); + $('body').css('padding-top','0'); + } + }); + } + }, + + off : function () { + $(this.scope).off('.fndtn.topbar'); + $(window).off('.fndtn.topbar'); + } + }; +}(Foundation.zj, this, this.document)); diff --git a/engine/src/main/resources/org/archive/crawler/restlet/js/vendor/custom.modernizr.js b/engine/src/main/resources/org/archive/crawler/restlet/js/vendor/custom.modernizr.js new file mode 100644 index 00000000..e5afa6ca --- /dev/null +++ b/engine/src/main/resources/org/archive/crawler/restlet/js/vendor/custom.modernizr.js @@ -0,0 +1,4 @@ +/* Modernizr 2.6.2 (Custom Build) | MIT & BSD + * Build: http://modernizr.com/download/#-inlinesvg-svg-svgclippaths-touch-shiv-mq-cssclasses-teststyles-prefixes-ie8compat-load + */ +;window.Modernizr=function(a,b,c){function y(a){j.cssText=a}function z(a,b){return y(m.join(a+";")+(b||""))}function A(a,b){return typeof a===b}function B(a,b){return!!~(""+a).indexOf(b)}function C(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:A(f,"function")?f.bind(d||b):f}return!1}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n={svg:"http://www.w3.org/2000/svg"},o={},p={},q={},r=[],s=r.slice,t,u=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["­",'"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},v=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return u("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},w={}.hasOwnProperty,x;!A(w,"undefined")&&!A(w.call,"undefined")?x=function(a,b){return w.call(a,b)}:x=function(a,b){return b in a&&A(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=s.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(s.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(s.call(arguments)))};return e}),o.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:u(["@media (",m.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},o.svg=function(){return!!b.createElementNS&&!!b.createElementNS(n.svg,"svg").createSVGRect},o.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="",(a.firstChild&&a.firstChild.namespaceURI)==n.svg},o.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(l.call(b.createElementNS(n.svg,"clipPath")))};for(var D in o)x(o,D)&&(t=D.toLowerCase(),e[t]=o[D](),r.push((e[t]?"":"no-")+t));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)x(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},y(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=m,e.mq=v,e.testStyles=u,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+r.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f type pairs + class2type = {}, + + // List of deleted data cache ids, so we can reuse them + core_deletedIds = [], + + core_version = "1.9.1", + + // Save a reference to some core methods + core_concat = core_deletedIds.concat, + core_push = core_deletedIds.push, + core_slice = core_deletedIds.slice, + core_indexOf = core_deletedIds.indexOf, + core_toString = class2type.toString, + core_hasOwn = class2type.hasOwnProperty, + core_trim = core_version.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, + + // Used for splitting on whitespace + core_rnotwhite = /\S+/g, + + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }, + + // The ready event handler + completed = function( event ) { + + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } + }, + // Clean-up method for dom ready events + detach = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: core_version, + + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return core_slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + if ( obj == null ) { + return String( obj ); + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ core_toString.call(obj) ] || "object" : + typeof obj; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // keepScripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, keepScripts ) { + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + keepScripts = context; + context = false; + } + context = context || document; + + var parsed = rsingleTag.exec( data ), + scripts = !keepScripts && []; + + // Single tag + if ( parsed ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ); + if ( scripts ) { + jQuery( scripts ).remove(); + } + return jQuery.merge( [], parsed.childNodes ); + }, + + parseJSON: function( data ) { + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + if ( data === null ) { + return data; + } + + if ( typeof data === "string" ) { + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + if ( data ) { + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + } + } + } + + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Use native String.trim function wherever possible + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? + function( text ) { + return text == null ? + "" : + core_trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + core_push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return core_concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || type !== "function" && + ( length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj ); +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( list && ( !fired || stack ) ) { + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); +jQuery.support = (function() { + + var support, all, a, + input, select, fragment, + opt, eventName, isSupported, i, + div = document.createElement("div"); + + // Setup + div.setAttribute( "className", "t" ); + div.innerHTML = "
          a"; + + // Support tests won't run in some limited or non-browser environments + all = div.getElementsByTagName("*"); + a = div.getElementsByTagName("a")[ 0 ]; + if ( !all || !a || !all.length ) { + return {}; + } + + // First batch of tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + a.style.cssText = "top:1px;float:left;opacity:.5"; + support = { + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: div.firstChild.nodeType === 3, + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: a.getAttribute("href") === "/a", + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.5/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) + checkOn: !!input.value, + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Tests for enctype support on a form (#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode + boxModel: document.compatMode === "CSS1Compat", + + // Will be defined later + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true, + boxSizingReliable: true, + pixelPosition: false + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Support: IE<9 + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + // Check if we can trust getAttribute("value") + input = document.createElement("input"); + input.setAttribute( "value", "" ); + support.input = input.getAttribute( "value" ) === ""; + + // Check if an input maintains its value after becoming a radio + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "checked", "t" ); + input.setAttribute( "name", "t" ); + + fragment = document.createDocumentFragment(); + fragment.appendChild( input ); + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php + for ( i in { submit: true, change: true, focusin: true }) { + div.setAttribute( eventName = "on" + i, "t" ); + + support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; + } + + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, marginDiv, tds, + divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + + body.appendChild( container ).appendChild( div ); + + // Support: IE8 + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + div.innerHTML = "
          t
          "; + tds = div.getElementsByTagName("td"); + tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Support: IE8 + // Check if empty table cells still have offsetWidth/Height + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + support.boxSizing = ( div.offsetWidth === 4 ); + support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + + // Use window.getComputedStyle because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. (#3333) + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = div.appendChild( document.createElement("div") ); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== core_strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Support: IE6 + // Check if elements with layout shrink-wrap their children + div.style.display = "block"; + div.innerHTML = "
          "; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + if ( support.inlineBlockNeedsLayout ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); + + // Null elements to avoid leaks in IE + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + all = select = fragment = opt = a = input = null; + + return support; +})(); + +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; + +function internalData( elem, name, data, pvt /* Internal Use Only */ ){ + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var i, l, thisCache, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + // Do not set data on non-element because it will not be cleared (#8335). + if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { + return false; + } + + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var attrs, name, + elem = this[0], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attrs = elem.attributes; + for ( ; i < attrs.length; i++ ) { + name = attrs[i].name; + + if ( !name.indexOf( "data-" ) ) { + name = jQuery.camelCase( name.slice(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return jQuery.access( this, function( value ) { + + if ( value === undefined ) { + // Try to fetch any internally stored data first + return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; + } + + this.each(function() { + jQuery.data( this, key, value ); + }); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + hooks.cur = fn; + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, + rclass = /[\t\r\n]/g, + rreturn = /\r/g, + rfocusable = /^(?:input|select|textarea|button|object)$/i, + rclickable = /^(?:a|area)$/i, + rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, + ruseDefault = /^(?:checked|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + getSetInput = jQuery.support.input; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call( this, j, this.className ) ); + }); + } + + if ( proceed ) { + // The disjunction here is for better compressibility (see removeClass) + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + " " + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + elem.className = jQuery.trim( cur ); + + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = arguments.length === 0 || typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call( this, j, this.className ) ); + }); + } + if ( proceed ) { + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + "" + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + elem.className = value ? jQuery.trim( cur ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.match( core_rnotwhite ) || []; + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + // Toggle whole class name + } else if ( type === core_strundefined || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // If the element has a class name or if we're passed "false", + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var ret, hooks, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var val, + self = jQuery(this); + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attr: function( elem, name, value ) { + var hooks, notxml, ret, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === core_strundefined ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + + } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + // In IE9+, Flash objects don't have .getAttribute (#12945) + // Support: IE9+ + if ( typeof elem.getAttribute !== core_strundefined ) { + ret = elem.getAttribute( name ); + } + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var name, propName, + i = 0, + attrNames = value && value.match( core_rnotwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( (name = attrNames[i++]) ) { + propName = jQuery.propFix[ name ] || name; + + // Boolean attributes get special treatment (#10870) + if ( rboolean.test( name ) ) { + // Set corresponding property to false for boolean attributes + // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 + if ( !getSetAttribute && ruseDefault.test( name ) ) { + elem[ jQuery.camelCase( "default-" + name ) ] = + elem[ propName ] = false; + } else { + elem[ propName ] = false; + } + + // See #9699 for explanation of this approach (setting first, then removal) + } else { + jQuery.attr( elem, name, "" ); + } + + elem.removeAttribute( getSetAttribute ? name : propName ); + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to default in case type is set after value during creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + var + // Use .prop to determine if this attribute is understood as boolean + prop = jQuery.prop( elem, name ), + + // Fetch it accordingly + attr = typeof prop === "boolean" && elem.getAttribute( name ), + detail = typeof prop === "boolean" ? + + getSetInput && getSetAttribute ? + attr != null : + // oldIE fabricates an empty string for missing boolean attributes + // and conflates checked/selected into attroperties + ruseDefault.test( name ) ? + elem[ jQuery.camelCase( "default-" + name ) ] : + !!attr : + + // fetch an attribute node for properties not recognized as boolean + elem.getAttributeNode( name ); + + return detail && detail.value !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { + // IE<8 needs the *property* name + elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); + + // Use defaultChecked and defaultSelected for oldIE + } else { + elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; + } + + return name; + } +}; + +// fix oldIE value attroperty +if ( !getSetInput || !getSetAttribute ) { + jQuery.attrHooks.value = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return jQuery.nodeName( elem, "input" ) ? + + // Ignore the value *property* by using defaultValue + elem.defaultValue : + + ret && ret.specified ? ret.value : undefined; + }, + set: function( elem, value, name ) { + if ( jQuery.nodeName( elem, "input" ) ) { + // Does not return so that setAttribute is also used + elem.defaultValue = value; + } else { + // Use nodeHook if defined (#1954); otherwise setAttribute is fine + return nodeHook && nodeHook.set( elem, value, name ); + } + } + }; +} + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? + ret.value : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + elem.setAttributeNode( + (ret = elem.ownerDocument.createAttribute( name )) + ); + } + + ret.value = value += ""; + + // Break association with cloned elements by also using setAttribute (#9646) + return name === "value" || value === elem.getAttribute( name ) ? + value : + undefined; + } + }; + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + nodeHook.set( elem, value === "" ? false : value, name ); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); +} + + +// Some attributes require a special call on IE +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret == null ? undefined : ret; + } + }); + }); + + // href/src property should get the full normalized URL (#10299/#12915) + jQuery.each([ "href", "src" ], function( i, name ) { + jQuery.propHooks[ name ] = { + get: function( elem ) { + return elem.getAttribute( name, 4 ); + } + }; + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Note: IE uppercases css property names, but if we were to .toLowerCase() + // .cssText, that would destroy case senstitivity in URL's, like in "background" + return elem.style.cssText || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = core_hasOwn.call( event, "type" ) ? event.type : event, + namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + event.isTrigger = true; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = core_slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + for ( ; cur != this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + } + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== document.activeElement && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === document.activeElement && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + + beforeunload: { + postDispatch: function( event ) { + + // Even when returnValue equals to undefined Firefox will still show alert + if ( event.result !== undefined ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === core_strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ + */ +(function( window, undefined ) { + +var i, + cachedruns, + Expr, + getText, + isXML, + compile, + hasDuplicate, + outermostContext, + + // Local document vars + setDocument, + document, + docElem, + documentIsXML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + sortOrder, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + support = {}, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Array methods + arr = [], + pop = arr.pop, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + operators = "([*^$|!~]?=)", + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments quoted, + // then not containing pseudos/brackets, + // then attribute selectors/non-parenthetical expressions, + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rsibling = /[\x20\t\r\n\f]*[+~]/, + + rnative = /^[^{]+\{\s*\[native code/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rescape = /'|\\/g, + rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, + funescape = function( _, escaped ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + return high !== high ? + escaped : + // BMP codepoint + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Use a stripped-down slice if we can't use a native one +try { + slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, + results = []; + while ( (elem = this[i++]) ) { + results.push( elem ); + } + return results; + }; +} + +/** + * For feature detection + * @param {Function} fn The function to test for native support + */ +function isNative( fn ) { + return rnative.test( fn + "" ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var cache, + keys = []; + + return (cache = function( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key += " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key ] = value); + }); +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return fn( div ); + } catch (e) { + return false; + } finally { + // release memory in IE + div = null; + } +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( !documentIsXML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { + push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); + return results; + } + } + + // QSA path + if ( support.qsa && !rbuggyQSA.test(selector) ) { + old = true; + nid = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, slice.call( newContext.querySelectorAll( + newSelector + ), 0 ) ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Detect xml + * @param {Element|Object} elem An element or a document + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var doc = node ? node.ownerDocument || node : preferredDoc; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsXML = isXML( doc ); + + // Check if getElementsByTagName("*") returns only elements + support.tagNameNoComments = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if attributes should be retrieved by attribute nodes + support.attributes = assert(function( div ) { + div.innerHTML = ""; + var type = typeof div.lastChild.getAttribute("multiple"); + // IE8 returns a string for some attributes even when not present + return type !== "boolean" && type !== "string"; + }); + + // Check if getElementsByClassName can be trusted + support.getByClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { + return false; + } + + // Safari 3.2 caches class attributes and doesn't catch changes + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length === 2; + }); + + // Check if getElementById returns elements by name + // Check if getElementsByName privileges form controls or returns elements by ID + support.getByName = assert(function( div ) { + // Inject content + div.id = expando + 0; + div.innerHTML = "
          "; + docElem.insertBefore( div, docElem.firstChild ); + + // Test + var pass = doc.getElementsByName && + // buggy browsers will return fewer than the correct 2 + doc.getElementsByName( expando ).length === 2 + + // buggy browsers will return more than the correct 0 + doc.getElementsByName( expando + 0 ).length; + support.getIdNotName = !doc.getElementById( expando ); + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + + // IE6/7 return modified attributes + Expr.attrHandle = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }) ? + {} : + { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }; + + // ID find and filter + if ( support.getIdNotName ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && !documentIsXML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && !documentIsXML ) { + var m = context.getElementById( id ); + + return m ? + m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? + [m] : + undefined : + []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.tagNameNoComments ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Name + Expr.find["NAME"] = support.getByName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }; + + // Class + Expr.find["CLASS"] = support.getByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { + return context.getElementsByClassName( className ); + } + }; + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21), + // no need to also add to buggyMatches since matches checks buggyQSA + // A support test would require too much code (would include document ready) + rbuggyQSA = [ ":focus" ]; + + if ( (support.qsa = isNative(doc.querySelectorAll)) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explictly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // IE8 - Some boolean attributes are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Opera 10-12/IE8 - ^= $= *= and empty values + // Should not select anything + div.innerHTML = ""; + if ( div.querySelectorAll("[i^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || + docElem.mozMatchesSelector || + docElem.webkitMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + // Document order sorting + sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + var compare; + + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { + if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { + if ( a === doc || contains( preferredDoc, a ) ) { + return -1; + } + if ( b === doc || contains( preferredDoc, b ) ) { + return 1; + } + return 0; + } + return compare & 4 ? -1 : 1; + } + + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + // Always assume the presence of duplicates if sort doesn't + // pass them to our comparison function (as in Google Chrome). + hasDuplicate = false; + [0, 0].sort( sortOrder ); + support.detectDuplicates = hasDuplicate; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + // rbuggyQSA always contains :focus, so no need for an existence check + if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [elem] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + var val; + + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + if ( !documentIsXML ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( documentIsXML || support.attributes ) { + return elem.getAttribute( name ); + } + return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? + name : + val && val.specified ? val.value : null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +// Document sorting and removing duplicates +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + i = 1, + j = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +// Returns a function to use in pseudos for input types +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +// Returns a function to use in pseudos for buttons +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +// Returns a function to use in pseudos for positionals +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[5] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[4] ) { + match[2] = match[4]; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeName ) { + if ( nodeName === "*" ) { + return function() { return true; }; + } + + nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifider + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsXML ? + elem.getAttribute("xml:lang") || elem.getAttribute("lang") : + elem.lang) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push( { + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var data, cache, outerCache, + dirkey = dirruns + " " + doneName; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { + if ( (data = cache[1]) === true || data === cachedruns ) { + return data === true; + } + } else { + cache = outerCache[ dir ] = [ dirkey ]; + cache[1] = matcher( elem, context, xml ) || cachedruns; + if ( cache[1] === true ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + // A counter to specify which element is currently being matched + var matcherCachedRuns = 0, + bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && !documentIsXML && + Expr.relative[ tokens[1].type ] ) { + + context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, slice.call( seed, 0 ) ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + documentIsXML, + results, + rsibling.test( selector ) + ); + return results; +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Easy API for creating new setFilters +function setFilters() {} +Expr.filters = setFilters.prototype = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Initialize with the default document +setDocument(); + +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})( window ); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + isSimple = /^.[^:#\[\.,]*$/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, ret, self, + len = this.length; + + if ( typeof selector !== "string" ) { + self = this; + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + ret = []; + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, this[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; + return ret; + }, + + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false) ); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true) ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + rneedsContext.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + cur = this[i]; + + while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + } + cur = cur.parentNode; + } + } + + return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( jQuery.unique(all) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +jQuery.fn.andSelf = jQuery.fn.addBack; + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( this.length > 1 && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
          ", "
          " ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
          " ], + tr: [ 2, "", "
          " ], + col: [ 2, "", "
          " ], + td: [ 3, "", "
          " ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
          ", "
          " ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function(i) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, false, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, false, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return jQuery.access( this, function( value ) { + var elem = this[0] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function( value ) { + var isFunc = jQuery.isFunction( value ); + + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( !isFunc && typeof value !== "string" ) { + value = jQuery( value ).not( this ).detach(); + } + + return this.domManip( [ value ], true, function( elem ) { + var next = this.nextSibling, + parent = this.parentNode; + + if ( parent ) { + jQuery( this ).remove(); + parent.insertBefore( elem, next ); + } + }); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + + // Flatten any nested arrays + args = core_concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, table ? self.html() : undefined ); + } + self.domManip( args, table, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( + table && jQuery.nodeName( this[i], "table" ) ? + findOrAppend( this[i], "tbody" ) : + this[i], + node, + i + ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Hope ajax is available... + jQuery.ajax({ + url: node.src, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +function findOrAppend( elem, tag ) { + return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + var attr = elem.getAttributeNode("type"); + elem.type = ( attr && attr.specified ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + core_push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( manipulation_rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !jQuery.support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
          " && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== core_strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + core_deletedIds.push( id ); + } + } + } + } + } +}); +var iframe, getStyles, curCSS, + ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity\s*=\s*([^)]*)/, + rposition = /^(top|right|bottom|left)$/, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), + elemdisplay = { BODY: "block" }, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; + +// return a css property mapped to a potentially vendor prefixed property +function vendorPropName( style, name ) { + + // shortcut for names that are not vendor prefixed + if ( name in style ) { + return name; + } + + // check for vendor prefixed names + var capName = name.charAt(0).toUpperCase() + name.slice(1), + origName = name, + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in style ) { + return name; + } + } + + return origName; +} + +function isHidden( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var display, elem, hidden, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + values[ index ] = jQuery._data( elem, "olddisplay" ); + display = elem.style.display; + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else { + + if ( !values[ index ] ) { + hidden = isHidden( elem ); + + if ( display && display !== "none" || !hidden ) { + jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); + } + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + var len, styles, + map = {}, + i = 0; + + if ( jQuery.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + var bool = typeof state === "boolean"; + + return this.each(function() { + if ( bool ? state : isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "columnCount": true, + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, + // but it would mean to define eight (for every problematic property) identical functions + if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var num, val, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + //convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Return, converting to number if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +// NOTE: we've included the "window" in window.getComputedStyle +// because jsdom on node.js will break without it. +if ( window.getComputedStyle ) { + getStyles = function( elem ) { + return window.getComputedStyle( elem, null ); + }; + + curCSS = function( elem, name, _computed ) { + var width, minWidth, maxWidth, + computed = _computed || getStyles( elem ), + + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, + style = elem.style; + + if ( computed ) { + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right + // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels + // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values + if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + getStyles = function( elem ) { + return elem.currentStyle; + }; + + curCSS = function( elem, name, _computed ) { + var left, rs, rsLeft, + computed = _computed || getStyles( elem ), + ret = computed ? computed[ name ] : undefined, + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret == null && style && style[ name ] ) { + ret = style[ name ]; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // but not position css attributes, as those are proportional to the parent element instead + // and we can't measure the parent instead because it might trigger a "stacking dolls" problem + if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + + // Remember the original values + left = style.left; + rs = elem.runtimeStyle; + rsLeft = rs && rs.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + rs.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + rs.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + // If we already have the right measurement, avoid augmentation + 4 : + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + // both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + // at this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var valueIsBorderBox = true, + val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + styles = getStyles( elem ), + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, styles ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test(val) ) { + return val; + } + + // we need the check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + // Use the already-created iframe if possible + iframe = ( iframe || + jQuery("