code
stringlengths
3
1.18M
language
stringclasses
1 value
package pt.inesc.id.l2f.annotation.execution; /** * * @author Tiago Luis * */ public class LafFile extends File { public LafFile(String file) { super(file); } }
Java
package pt.inesc.id.l2f.annotation.execution; import java.util.Collections; import java.util.LinkedList; import java.util.List; import pt.inesc.id.l2f.annotation.document.laf.LinguisticAnnotationDocument; import pt.inesc.id.l2f.annotation.input.InputDocument; import pt.inesc.id.l2f.annotation.stage.Stage; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.unit.FinalProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; public abstract class ExecutionMode { protected LinkedList<Stage> _stages; protected LinkedList<Thread> _threads; public ExecutionMode() { _stages = new LinkedList<Stage>(); _threads = new LinkedList<Thread>(); } public ExecutionMode(Stage ... stages) { this(); for (Stage stage : stages) { _stages.add(stage); _threads.add(new Thread(stage)); } } public ExecutionMode(List<Stage> stages) { this(); for (Stage stage : stages) { _stages.add(stage); _threads.add(new Thread(stage)); } } public ExecutionMode(Tool ... tools) { this(); for (Tool tool : tools) { Stage stage = new Stage(tool); _stages.add(stage); _threads.add(new Thread(stage)); } } /** * * */ public void start() { // verify number of stages if (_stages.size() < 1) { System.err.println("..."); return; } for (int i = 0; i < _stages.size() - 1; i++) { Stage current = _stages.get(i); Stage next = _stages.get(i + 1); // link stages next.setInputQueue(current.getOutputQueue()); } for (Stage stage : _stages) { stage.getTool().init(); stage.getTool().start(); } for (Thread thread : _threads) { thread.start(); } } // TODO: dar um nome melhor a Text public abstract void annotateText(Text input, Path output); public abstract void annotateText(List<Text> input, Path output); public abstract void annotateFile(File input, Path output); public abstract void annotateFile(List<File> input, Path output); // TODO: mudar nome public abstract void annotateText(Directory input, Path output); public abstract void annotate(List<LinguisticAnnotationDocument> annotations, Path output); public abstract void annotate(LinguisticAnnotationProcessUnit annotation, Path output); public abstract void annotateInputDocuments(List<InputDocument> documents, Path output); /** * * */ public void close() { try { Stage first = _stages.getFirst(); // add final unit first.getInputQueue().put(new FinalProcessUnit()); for (Thread thread : _threads) { thread.join(); } for (Stage stage : _stages) { stage.getTool().close(); } } catch (InterruptedException e) { e.printStackTrace(); } } /** * @return the stages */ public List<Stage> getStages() { return Collections.unmodifiableList(_stages); } /** * * * @return */ public Stage getFirstStage() { return _stages.getFirst(); } /** * * * @return */ public Stage getFinalStage() { return _stages.getLast(); } /** * @param stages the stages to set */ public void setStages(LinkedList<Stage> stages) { _stages = stages; } public void addFinalStage(Stage stage) { Stage last = _stages.getLast(); stage.setInputQueue(last.getOutputQueue()); _stages.addLast(stage); _threads.addLast(new Thread(stage)); } /** * @return the threads */ public List<Thread> getThreads() { return Collections.unmodifiableList(_threads); } /** * @param threads the threads to set */ public void setThreads(LinkedList<Thread> threads) { _threads = threads; } }
Java
package pt.inesc.id.l2f.annotation.execution; /** * * @author Tiago Luis * */ public class TeiFile extends File { public TeiFile(String file) { super(file); } }
Java
package pt.inesc.id.l2f.annotation.execution; public class Path { protected String _path; public Path(String path) { _path = path; } /** * * @return the path */ public String getPath() { return _path; } /** * * @param path the path to set */ public void setPath(String path) { _path = path; } }
Java
package pt.inesc.id.l2f.annotation.execution; /** * * @author Tiago Luis * */ public class File extends Path { public File(String file) { super(file); } }
Java
package pt.inesc.id.l2f.annotation.execution; import pt.inesc.id.l2f.annotation.stage.Stage; import pt.inesc.id.l2f.annotation.tool.Tool; public abstract class ParallelExecutionMode extends ExecutionMode { public ParallelExecutionMode(Stage ... stages) { super(stages); } public ParallelExecutionMode(Tool ... tools) { super(tools); } }
Java
package pt.inesc.id.l2f.annotation.execution; public class Text { private String _text; public Text(String text) { _text = text; } /** * * @return the text */ public String getText() { return _text; } }
Java
package pt.inesc.id.l2f.annotation.execution; public class Directory extends Path { public Directory(String directory) { super(directory); } }
Java
package pt.inesc.id.l2f.annotation.document.util; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.apache.hadoop.io.Writable; import org.apache.hadoop.util.ReflectionUtils; /** * A Writable Map. */ public class ListWritable<K extends Writable> extends AbstractListWritable implements List<K> { private List<K> _list; /** Default constructor. */ public ListWritable() { super(); _list = new ArrayList<K>(); } @Override public void write(DataOutput out) throws IOException { super.write(out); // write out the number of entries in the map out.writeInt(_list.size()); // then write out each key/value pair for (Writable e: _list) { out.writeByte(getId(e.getClass())); e.write(out); } } @Override @SuppressWarnings("unchecked") public void readFields(DataInput in) throws IOException { super.readFields(in); // first clear the map (otherwise we will just accumulate entries every time this method is called) this._list.clear(); // read the number of entries in the map int entries = in.readInt(); // then read each key/value pair for (int i = 0; i < entries; i++) { K value = (K) ReflectionUtils.newInstance(getClass(in.readByte()), getConf()); value.readFields(in); _list.add(value); } } public void add(int index, K element) { super.addToList(element.getClass()); _list.add(index, element); } public boolean contains(Object o) { return _list.contains(o); } public boolean containsAll(Collection<?> c) { return _list.containsAll(c); } public K get(int index) { return _list.get(index); } public int indexOf(Object o) { return _list.indexOf(o); } public Iterator<K> iterator() { return _list.iterator(); } public int lastIndexOf(Object o) { return _list.lastIndexOf(o); } public ListIterator<K> listIterator() { return _list.listIterator(); } public ListIterator<K> listIterator(int index) { return _list.listIterator(index); } public K remove(int index) { return _list.remove(index); } public boolean removeAll(Collection<?> c) { return _list.removeAll(c); } public boolean retainAll(Collection<?> c) { return _list.retainAll(c); } public K set(int index, K element) { return _list.set(index, element); } public List<K> subList(int fromIndex, int toIndex) { return _list.subList(fromIndex, toIndex); } public Object[] toArray() { return _list.toArray(); } public <T> T[] toArray(T[] a) { return _list.toArray(a); } public boolean add(K e) { super.addToList(e.getClass()); return _list.add(e); } public void clear() { _list.clear(); } public boolean isEmpty() { return _list.isEmpty(); } public boolean remove(Object o) { return _list.remove(o); } public int size() { return _list.size(); } public boolean addAll(Collection<? extends K> c) { throw new RuntimeException("Not implemented"); } public boolean addAll(int index, Collection<? extends K> c) { throw new RuntimeException("Not implemented"); } }
Java
package pt.inesc.id.l2f.annotation.document.util; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Writable; /** * Abstract base class for MapWritable. * * * @author Tiago Luis * */ public abstract class AbstractListWritable implements Writable, Configurable { private Configuration _conf; // class to id mappings @SuppressWarnings("unchecked") private Map<Class, Byte> classToIdMap = new HashMap<Class, Byte>(); // id to class mappings @SuppressWarnings("unchecked") private Map<Byte, Class> idToClassMap = new HashMap<Byte, Class>(); // the number of new classes (those not established by the constructor) private volatile byte newClasses = 0; public AbstractListWritable() { _conf = new Configuration(); } /** * * * @return the number of known classes */ byte getNewClasses() { return newClasses; } /** * Used to add "predefined" classes and by Writable to copy "new" classes. * * @param clazz * @param id */ @SuppressWarnings("unchecked") private synchronized void addToList(Class clazz, byte id) { if (classToIdMap.containsKey(clazz)) { byte b = classToIdMap.get(clazz); if (b != id) { throw new IllegalArgumentException ("Class " + clazz.getName() + " already registered but maps to " + b + " and not " + id); } } if (idToClassMap.containsKey(id)) { Class c = idToClassMap.get(id); if (!c.equals(clazz)) { throw new IllegalArgumentException("Id " + id + " exists but maps to " + c.getName() + " and not " + clazz.getName()); } } classToIdMap.put(clazz, id); idToClassMap.put(id, clazz); } /** * Add a Class to the maps if it is not already present. * * @param clazz */ @SuppressWarnings("unchecked") protected synchronized void addToList(Class clazz) { if (classToIdMap.containsKey(clazz)) { return; } if (newClasses + 1 > Byte.MAX_VALUE) { throw new IndexOutOfBoundsException("adding an additional class would" + " exceed the maximum number allowed"); } byte id = ++newClasses; this.addToList(clazz, id); } /** * * * @param id * @return the Class class for the specified id */ @SuppressWarnings("unchecked") protected Class getClass(byte id) { return idToClassMap.get(id); } /** * * * @param clazz * @return the id for the specified Class */ @SuppressWarnings("unchecked") protected byte getId(Class clazz) { return classToIdMap.containsKey(clazz) ? classToIdMap.get(clazz) : -1; } public Configuration getConf() { return _conf; } public void setConf(Configuration conf) { _conf = conf; } public void write(DataOutput out) throws IOException { // first write out the size of the class table and any classes that are "unknown" classes out.writeByte(newClasses); for (byte i = 1; i <= newClasses; i++) { out.writeByte(i); out.writeUTF(getClass(i).getName()); } } public void readFields(DataInput in) throws IOException { // get the number of "unknown" classes newClasses = in.readByte(); // then read in the class names and add them to our tables for (int i = 0; i < newClasses; i++) { byte id = in.readByte(); String className = in.readUTF(); try { this.addToList(Class.forName(className), id); } catch (ClassNotFoundException e) { throw new IOException("can't find class: " + className + " because "+ e.getMessage()); } } } }
Java
package pt.inesc.id.l2f.annotation.document.util; public class Pair<F, S> { // ... private F _first; // ... private S _second; public Pair(F first, S second) { _first = first; _second = second; } /** * * * @return the first */ public F getFirst() { return _first; } /** * * * @return the second */ public S getSecond() { return _second; } }
Java
package pt.inesc.id.l2f.annotation.document.util; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.hadoop.io.Writable; import org.apache.hadoop.util.ReflectionUtils; /** * A Writable Map. */ public class MapWritable<K extends Writable, V extends Writable> extends AbstractMapWritable implements Map<K, V> { private Map<K, V> _map; /** Default constructor. */ public MapWritable() { super(); _map = new HashMap<K, V>(); } /** {@inheritDoc} */ public void clear() { _map.clear(); } /** {@inheritDoc} */ public boolean containsKey(Object key) { return _map.containsKey(key); } /** {@inheritDoc} */ public boolean containsValue(Object value) { return _map.containsValue(value); } /** {@inheritDoc} */ public Set<Map.Entry<K, V>> entrySet() { return _map.entrySet(); } /** {@inheritDoc} */ public V get(Object key) { return _map.get(key); } /** {@inheritDoc} */ public boolean isEmpty() { return _map.isEmpty(); } /** {@inheritDoc} */ public Set<K> keySet() { return _map.keySet(); } /** {@inheritDoc} */ public V put(K key, V value) { addToMap(key.getClass()); addToMap(value.getClass()); return _map.put(key, value); } /** {@inheritDoc} */ public void putAll(Map<? extends K, ? extends V> t) { for (Map.Entry<? extends K, ? extends V> e: t.entrySet()) { _map.put(e.getKey(), e.getValue()); } } /** {@inheritDoc} */ public V remove(Object key) { return _map.remove(key); } /** {@inheritDoc} */ public int size() { return _map.size(); } /** {@inheritDoc} */ public Collection<V> values() { return _map.values(); } @Override public void write(DataOutput out) throws IOException { super.write(out); // Write out the number of entries in the map out.writeInt(_map.size()); // Then write out each key/value pair for (Map.Entry<K, V> e: _map.entrySet()) { out.writeByte(getId(e.getKey().getClass())); e.getKey().write(out); out.writeByte(getId(e.getValue().getClass())); e.getValue().write(out); } } @Override @SuppressWarnings("unchecked") public void readFields(DataInput in) throws IOException { super.readFields(in); // first clear the map (otherwise we will just accumulate entries every time this method is called) this._map.clear(); // read the number of entries in the map int entries = in.readInt(); // then read each key/value pair for (int i = 0; i < entries; i++) { K key = (K) ReflectionUtils.newInstance(getClass(in.readByte()), getConf()); key.readFields(in); V value = (V) ReflectionUtils.newInstance(getClass(in.readByte()), getConf()); value.readFields(in); _map.put(key, value); } } }
Java
package pt.inesc.id.l2f.annotation.document.util; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Writable; /** * Abstract base class for MapWritable. * * * @author Tiago Luis * */ public abstract class AbstractMapWritable implements Writable, Configurable { private Configuration _conf; // class to id mappings @SuppressWarnings("unchecked") private Map<Class, Byte> classToIdMap = new HashMap<Class, Byte>(); // id to class mappings @SuppressWarnings("unchecked") private Map<Byte, Class> idToClassMap = new HashMap<Byte, Class>(); // the number of new classes (those not established by the constructor) private volatile byte newClasses = 0; public AbstractMapWritable() { this._conf = new Configuration(); } /** * * * @return the number of known classes */ byte getNewClasses() { return newClasses; } /** * Used to add "predefined" classes and by Writable to copy "new" classes. * * @param clazz * @param id */ @SuppressWarnings("unchecked") private synchronized void addToMap(Class clazz, byte id) { if (classToIdMap.containsKey(clazz)) { byte b = classToIdMap.get(clazz); if (b != id) { throw new IllegalArgumentException ("Class " + clazz.getName() + " already registered but maps to " + b + " and not " + id); } } if (idToClassMap.containsKey(id)) { Class c = idToClassMap.get(id); if (!c.equals(clazz)) { throw new IllegalArgumentException("Id " + id + " exists but maps to " + c.getName() + " and not " + clazz.getName()); } } classToIdMap.put(clazz, id); idToClassMap.put(id, clazz); } /** * Add a Class to the maps if it is not already present. * * @param clazz */ @SuppressWarnings("unchecked") protected synchronized void addToMap(Class clazz) { if (classToIdMap.containsKey(clazz)) { return; } if (newClasses + 1 > Byte.MAX_VALUE) { throw new IndexOutOfBoundsException("adding an additional class would" + " exceed the maximum number allowed"); } byte id = ++newClasses; this.addToMap(clazz, id); } /** * * * @param id * @return the Class class for the specified id */ @SuppressWarnings("unchecked") protected Class getClass(byte id) { return idToClassMap.get(id); } /** * * * @param clazz * @return the id for the specified Class */ @SuppressWarnings("unchecked") protected byte getId(Class clazz) { return classToIdMap.containsKey(clazz) ? classToIdMap.get(clazz) : -1; } public Configuration getConf() { return _conf; } public void setConf(Configuration conf) { _conf = conf; } public void write(DataOutput out) throws IOException { // first write out the size of the class table and any classes that are "unknown" classes out.writeByte(newClasses); for (byte i = 1; i <= newClasses; i++) { out.writeByte(i); out.writeUTF(getClass(i).getName()); } } public void readFields(DataInput in) throws IOException { // get the number of "unknown" classes newClasses = in.readByte(); // then read in the class names and add them to our tables for (int i = 0; i < newClasses; i++) { byte id = in.readByte(); String className = in.readUTF(); try { addToMap(Class.forName(className), id); } catch (ClassNotFoundException e) { throw new IOException("can't find class: " + className + " because "+ e.getMessage()); } } } }
Java
package pt.inesc.id.l2f.annotation.document.xml; import java.io.InputStream; import java.io.Reader; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; public class XMLReader { // ... private static XMLInputFactory _xmlif; // ... private XMLStreamReader _xmlr; static { _xmlif = XMLInputFactory.newInstance(); } public XMLReader(Reader reader) { try { _xmlr = _xmlif.createXMLStreamReader(reader); } catch (XMLStreamException e) { e.printStackTrace(); } } public XMLReader(InputStream input) { try { _xmlr = _xmlif.createXMLStreamReader(input); } catch (XMLStreamException e) { e.printStackTrace(); } } public XMLReader(InputStream input, String encoding) { try { _xmlr = _xmlif.createXMLStreamReader(input, encoding); } catch (XMLStreamException e) { e.printStackTrace(); } } /** * * * @return */ public boolean hasNext() { try { return _xmlr.hasNext(); } catch (XMLStreamException e) { e.printStackTrace(); } return false; } /** * * * @return */ public int next() { try { return _xmlr.next(); } catch (XMLStreamException e) { e.printStackTrace(); } return -1; } /** * * * @return */ public Map<String, String> getAttributes() { Map<String, String> attributes = new HashMap<String, String>(); for (int i = 0; i < _xmlr.getAttributeCount(); i++) { String name = _xmlr.getAttributeName(i).toString(); String value = _xmlr.getAttributeValue(i); attributes.put(name, value); } return Collections.unmodifiableMap(attributes); } public String getcharacters() { int start = _xmlr.getTextStart(); int length = _xmlr.getTextLength(); return new String(_xmlr.getTextCharacters(), start, length); } /** * * * @param event * @param name element name * @return */ public boolean isElementEnd(int event, String name) { return event == XMLStreamConstants.END_ELEMENT && name.equals(_xmlr.getLocalName().toString()); } /** * * * @param event * @return */ public boolean isCharacters(int event) { return event == XMLStreamConstants.CHARACTERS; } /** * * * @param event * @return */ public boolean isElementStart(int event) { return event == XMLStreamConstants.START_ELEMENT; } /** * * * @param event * @return */ public boolean isDocumentEnd(int event) { return event == XMLStreamConstants.END_DOCUMENT; } /** * * * @return */ public String getElementName() { return _xmlr.getLocalName().toString(); } // public void next() { // Element current = _current; // // // get next element // _current = this.getNextElement(); // // return current; // } // private Element getNextElement() { // Element element = null; // // try { // while (_xmlr.hasNext()) { // _xmlr.next(); // // if (_xmlr.getEventType() == XMLStreamConstants.START_ELEMENT) { // element = new Element(_xmlr.getLocalName()); // // System.out.println("DEBUG: " + element.getName()); // // // get element attributes // for (int i = 0; i < _xmlr.getAttributeCount(); i++) { // String name = _xmlr.getAttributeName(i).toString(); // String value = _xmlr.getAttributeValue(i); // // element.addAttribute(name, value); // } // // break; // } // } // } catch (XMLStreamException e) { // e.printStackTrace(); // } // // return element; // } // // public Element getCurrentElement() { // return _current; // } // public Map<String, String> getCurrentElementAttributes() { // Map<String, String> attributes = new HashMap<String, String>(); // // for (int i = 0; i < _xmlr.getAttributeCount(); i++) { // QName name = _xmlr.getAttributeName(i); // String value = _xmlr.getAttributeValue(i); // // attributes.put(name.toString(), value); // } // // return attributes; // } }
Java
package pt.inesc.id.l2f.annotation.document.xml; import java.io.OutputStream; import java.io.Writer; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; public class XMLWriter { private static XMLOutputFactory _xmlof; private XMLStreamWriter _xmlw; static { _xmlof = XMLOutputFactory.newInstance(); } public XMLWriter(Writer writer) { try { _xmlw = _xmlof.createXMLStreamWriter(writer); } catch (XMLStreamException e) { e.printStackTrace(); } } public XMLWriter(OutputStream output) { try { _xmlw = _xmlof.createXMLStreamWriter(output); } catch (XMLStreamException e) { e.printStackTrace(); } } public void writeAttribute(String localName, String value) { try { _xmlw.writeAttribute(localName, value); } catch (XMLStreamException e) { e.printStackTrace(); } } public void writeStartElement(String localName) { try { _xmlw.writeStartElement(localName); } catch (XMLStreamException e) { e.printStackTrace(); } } public void writeEndElement() { try { _xmlw.writeEndElement(); } catch (XMLStreamException e) { e.printStackTrace(); } } public void writeCharacters(String text) { try { _xmlw.writeCharacters(text); } catch (XMLStreamException e) { e.printStackTrace(); } } public void writeStartDocument(String encoding, String version) { try { _xmlw.writeStartDocument(encoding, version); } catch (XMLStreamException e) { e.printStackTrace(); } } public void writeDTD(String dtd) { try { _xmlw.writeDTD(dtd); } catch (XMLStreamException e) { e.printStackTrace(); } } public void writeEndDocument() { try { _xmlw.writeEndDocument(); } catch (XMLStreamException e) { e.printStackTrace(); } } }
Java
package pt.inesc.id.l2f.annotation.document; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public interface DocumentElement { /** * * * @param xmlw */ public void writeTo(XMLWriter xmlw); /** * * * @param xmlr */ public void readFrom(XMLReader xmlr); }
Java
package pt.inesc.id.l2f.annotation.document.laf; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Collections; import java.util.Map; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.DocumentElement; import pt.inesc.id.l2f.annotation.document.util.MapWritable; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class FeatureStructure implements DocumentElement, Writable { private MapWritable<Text, Feature> _features; public FeatureStructure() { _features = new MapWritable<Text, Feature>(); } /** * * @return */ public Map<Text, Feature> getFeatures() { return Collections.unmodifiableMap(_features); } /** * * @param name * @return */ public Feature getFeature(String name) { return _features.get(new Text(name)); } /** * * @param name * @param feature */ public void addFeature(String name, Feature feature) { _features.put(new Text(name), feature); } public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("fs"); // write features for (Feature feature : _features.values()) { feature.writeTo(xmlw); } xmlw.writeEndElement(); } public void readFrom(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isElementEnd(event, "fs")) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("f")) { Feature f = new Feature(); f.readFrom(xmlr); _features.put(new Text(f.getName()), f); } } } } public void readFields(DataInput in) throws IOException { _features = new MapWritable<Text, Feature>(); _features.readFields(in); } public void write(DataOutput out) throws IOException { _features.write(out); } }
Java
package pt.inesc.id.l2f.annotation.document.laf; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Map; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.DocumentElement; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class Feature implements DocumentElement, Writable { // ... private Text _name; // ... private Text _value; public Feature() {} public Feature(String name, String value) { _name = new Text(name); _value = new Text(value); } /** * @return the name */ public String getName() { return _name.toString(); } /** * @param name the name to set */ public void setName(String name) { _name = new Text(name); } /** * * @return */ public String getValue() { return _value.toString(); } /** * * @param value */ public void setValue(String value) { _value = new Text(value); } public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("f"); xmlw.writeAttribute("name", _name.toString()); xmlw.writeAttribute("value", _value.toString()); xmlw.writeEndElement(); } public void readFrom(XMLReader xmlr) { Map<String, String> feature = xmlr.getAttributes(); _name = new Text(feature.get("name")); _value = new Text(feature.get("value")); } public void readFields(DataInput in) throws IOException { _name = new Text(); _name.readFields(in); _value = new Text(); _value.readFields(in); } public void write(DataOutput out) throws IOException { _name.write(out); _value.write(out); } }
Java
package pt.inesc.id.l2f.annotation.document.laf; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.DocumentElement; import pt.inesc.id.l2f.annotation.document.util.ListWritable; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class MorphoSyntacticAnnotation implements DocumentElement, Writable { private ListWritable<Classification> _classifications; public MorphoSyntacticAnnotation() { _classifications = new ListWritable<Classification>(); } public List<Classification> getClassifications() { return _classifications; } public void addClassification(Classification classification) { _classifications.add(classification); } public void setClassifications(List<Classification> classifications) { _classifications = new ListWritable<Classification>(); for (Classification classification : classifications) { _classifications.add(classification); } } public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("nodeSet"); for (Classification classification : _classifications) { classification.writeTo(xmlw); } xmlw.writeEndElement(); } public void readFrom(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isElementEnd(event, "nodeSet")) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("node")) { Classification classification = new Classification(); // get segments (edgesTo) attribute String attribute = xmlr.getAttributes().get("edgesTo"); // parse attribute String[] segments = attribute.split(" "); for (String segment : segments) { classification.addSegment(segment); } classification.readFrom(xmlr); _classifications.add(classification); } } } } public void readFields(DataInput in) throws IOException { _classifications = new ListWritable<Classification>(); _classifications.readFields(in); } public void write(DataOutput out) throws IOException { _classifications.write(out); } }
Java
package pt.inesc.id.l2f.annotation.document.laf; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.Document; import pt.inesc.id.l2f.annotation.document.util.ListWritable; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class LinguisticAnnotationDocument implements Document, Writable { // ... private ListWritable<Segmentation> _segmentations; // ... private ListWritable<MorphoSyntacticAnnotation> _annotations; public LinguisticAnnotationDocument() { _segmentations = new ListWritable<Segmentation>(); _annotations = new ListWritable<MorphoSyntacticAnnotation>(); } /** * * * @return */ public List<Segmentation> getSegmentations() { return Collections.unmodifiableList(_segmentations); } public Segment getSegment(String id) { for (Segmentation segmentation : _segmentations) { if (segmentation.getSegment(id) != null) { return segmentation.getSegment(id); } } return null; } /** * * * @return * @throws NoSuchElementException */ public Segmentation getSegmentation() throws NoSuchElementException { return _segmentations.get(_segmentations.size() - 1); } /** * * * @param segmentations */ public void setSegmentations(List<Segmentation> segmentations) { _segmentations = new ListWritable<Segmentation>(); for (Segmentation segmentation : segmentations) { _segmentations.add(segmentation); } } /** * * * @param segmentation */ public void addSegmentation(Segmentation segmentation) { _segmentations.add(segmentation); } /** * * * @param annotation */ public void addMorphoSyntacticAnnotation(MorphoSyntacticAnnotation annotation) { _annotations.add(annotation); } /** * * * @return * @throws NoSuchElementException */ public MorphoSyntacticAnnotation getLastMorphoSyntacticAnnotation() throws NoSuchElementException { return _annotations.get(_annotations.size() - 1); } /** * * * @return */ public List<MorphoSyntacticAnnotation> getMorphoSyntacticAnnotations() { return Collections.unmodifiableList(_annotations); } public void merge(LinguisticAnnotationDocument doc) { for (Segmentation segmentation : doc.getSegmentations()) { _segmentations.add(segmentation); } for (MorphoSyntacticAnnotation annotation : doc.getMorphoSyntacticAnnotations()) { _annotations.add(annotation); } } // public void writeTo(Writer writer) { // XMLWriter xmlw = new XMLWriter(writer); // this.writeTo(xmlw); // } public void writeTo(XMLWriter xmlw) { // write root element start xmlw.writeStartElement("laf"); // write segmentations if (_segmentations.size() > 0) { for (Segmentation segmentation : _segmentations) { segmentation.writeTo(xmlw); } } // write classifications of segments if (_annotations.size() > 0) { for (MorphoSyntacticAnnotation annotation : _annotations) { annotation.writeTo(xmlw); } } // write root element end xmlw.writeEndElement(); } // public void readFrom(Reader reader) { // XMLReader xmlr = new XMLReader(reader); // this.readFrom(xmlr); // } public void readFrom(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isElementEnd(event, "laf")) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("edgeSet")) { Segmentation segmentation = new Segmentation(); segmentation.readFrom(xmlr); _segmentations.add(segmentation); } if (name.equals("nodeSet")) { MorphoSyntacticAnnotation annotation = new MorphoSyntacticAnnotation(); annotation.readFrom(xmlr); _annotations.add(annotation); } } } } public void readFields(DataInput in) throws IOException { _segmentations = new ListWritable<Segmentation>(); _segmentations.readFields(in); _annotations = new ListWritable<MorphoSyntacticAnnotation>(); _annotations.readFields(in); } public void write(DataOutput out) throws IOException { _segmentations.write(out); _annotations.write(out); } }
Java
package pt.inesc.id.l2f.annotation.document.laf; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Map; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.DocumentElement; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class Segment implements DocumentElement, Writable { // ... private Text _id; // ... private Text _from; // ... private Text _to; // ... private Text _word; public Segment() {} public Segment(String id, String from, String to, String word) { _id = new Text(id); _from = new Text(from); _to = new Text(to); _word = new Text(word); } /** * * * @return */ public String getId() { return _id.toString(); } /** * * * @param id */ public void setId(String id) { _id = new Text(id); } /** * * * @return */ public String getFrom() { return _from.toString(); } /** * * * @param from */ public void setFrom(String from) { _from = new Text(from); } /** * * * @return */ public String getTo() { return _to.toString(); } /** * * * @param to */ public void setTo(String to) { _to = new Text(to); } /** * * * @return */ public String getWord() { return _word.toString(); } /** * * * @param word */ public void setWord(String word) { _word = new Text(word); } public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("edge"); xmlw.writeAttribute("id", _id.toString()); xmlw.writeAttribute("from", _from.toString()); xmlw.writeAttribute("to", _to.toString()); xmlw.writeAttribute("word", _word.toString()); xmlw.writeEndElement(); } public void readFrom(XMLReader xmlr) { Map<String, String> attributes = xmlr.getAttributes(); _id = new Text(attributes.get("id")); _from = new Text(attributes.get("from")); _to = new Text(attributes.get("to")); _word = new Text(attributes.get("word")); } public void readFields(DataInput in) throws IOException { _id = new Text(); _id.readFields(in); _from = new Text(); _from.readFields(in); _to = new Text(); _to.readFields(in); _word = new Text(); _word.readFields(in); } public void write(DataOutput out) throws IOException { _id.write(out); _from.write(out); _to.write(out); _word.write(out); } }
Java
package pt.inesc.id.l2f.annotation.document.laf; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.util.ListWritable; import pt.inesc.id.l2f.annotation.document.util.MapWritable; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; import pt.inesc.id.l2f.annotation.document.DocumentElement; public class Segmentation implements DocumentElement, Writable { // ... private ListWritable<Segment> _segmentsList; // ... private MapWritable<Text, Segment> _segmentsMap; public Segmentation() { _segmentsList = new ListWritable<Segment>(); _segmentsMap = new MapWritable<Text, Segment>(); } /** * * * @return */ public List<Segment> getSegments() { return _segmentsList; } /** * * * @param id * @return */ public Segment getSegment(String id) { return (Segment) _segmentsMap.get(new Text(id)); } /** * * * @param segment */ public void addSegment(Segment segment) { _segmentsList.add(segment); _segmentsMap.put(new Text(segment.getId()), segment); } public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("edgeSet"); for (Segment segment : _segmentsList) { segment.writeTo(xmlw); } xmlw.writeEndElement(); } public void readFrom(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isElementEnd(event, "edgeSet")) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("edge")) { Segment segment = new Segment(); segment.readFrom(xmlr); _segmentsList.add(segment); _segmentsMap.put(new Text(segment.getId()), segment); } } } } public void readFields(DataInput in) throws IOException { _segmentsList = new ListWritable<Segment>(); _segmentsList.readFields(in); _segmentsMap = new MapWritable<Text, Segment>(); _segmentsMap.readFields(in); } public void write(DataOutput out) throws IOException { _segmentsList.write(out); _segmentsMap.write(out); } }
Java
package pt.inesc.id.l2f.annotation.document.laf; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.DocumentElement; import pt.inesc.id.l2f.annotation.document.util.ListWritable; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class Classification implements DocumentElement, Writable { private ListWritable<Text> _segments; private ListWritable<FeatureStructure> _fs; public Classification() { _segments = new ListWritable<Text>(); _fs = new ListWritable<FeatureStructure>(); } public Classification(FeatureStructure fs) { this(); // add feature structure _fs.add(fs); } public Classification(List<FeatureStructure> fs) { this(); // add feature structure list _fs.addAll(fs); } /** * * * @return */ public List<FeatureStructure> getFeatureStructures() { return _fs; } /** * * * @return * @throws NoSuchElementException */ public FeatureStructure getFirstFeatureStructure() throws NoSuchElementException { return _fs.get(0); } /** * * * @param fs */ public void addFeatureStructure(FeatureStructure fs) { _fs.add(fs); } // /** // * // * // * @param fs // */ // public void setFeatureStructures(List<FeatureStructure> fs) { // _fs = fs; // } /** * * * @return the segments */ public List<String> getSegments() { List<String> segments = new ArrayList<String>(); for (Text segment : _segments) { segments.add(segment.toString()); } return segments; } /** * * * @param segment */ public void addSegment(String segment) { _segments.add(new Text(segment)); } /** * * * @param segments the segments to set */ public void setSegments(List<String> segments) { _segments = new ListWritable<Text>(); for (String segment : segments) { _segments.add(new Text(segment)); } } public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("node"); // create edgesTo string from segment id's String edgesTo = ""; for (Text segment : _segments) { edgesTo += segment + " "; } if (edgesTo.length() > 0) { // remove last character (blank space) edgesTo = edgesTo.substring(0, edgesTo.length() - 1); } xmlw.writeAttribute("edgesTo", edgesTo); for (FeatureStructure fs : _fs) { fs.writeTo(xmlw); } xmlw.writeEndElement(); } public void readFrom(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isElementEnd(event, "node")) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("fs")) { FeatureStructure fs = new FeatureStructure(); fs.readFrom(xmlr); _fs.add(fs); } } } } public void readFields(DataInput in) throws IOException { _segments = new ListWritable<Text>(); _segments.readFields(in); _fs = new ListWritable<FeatureStructure>(); _fs.readFields(in); } public void write(DataOutput out) throws IOException { _segments.write(out); _fs.write(out); } }
Java
package pt.inesc.id.l2f.annotation.document; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public interface Document { /** * * * @param xmlw */ public void writeTo(XMLWriter xmlw); /** * * * @param xmlr */ public void readFrom(XMLReader xmlr); }
Java
package pt.inesc.id.l2f.annotation.unit; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; import pt.inesc.id.l2f.annotation.input.InputDocument; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.tool.ToolVisitor; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; public class InputDocumentProcessUnit extends ProcessUnit { private InputDocument _idoc; public InputDocumentProcessUnit(InputDocument idoc) { _idoc = idoc; } @Override public void accept(ToolVisitor visitor) { visitor.visit(this); } @Override public void execute(Tool tool, ToolExecutionModeUnit unit) { tool.process(this, unit); } /** * * * @return the input document */ public InputDocument getInputDocument() { return _idoc; } // @Override // public void writeTo(Writer writer) {} @Override public void writeTo(XMLWriter xmlw) {} @Override public void readFrom(XMLReader xmlr) { } public void readFields(DataInput in) throws IOException {} public void write(DataOutput out) throws IOException {} // @Override // public void writeTo(String filename) {} }
Java
package pt.inesc.id.l2f.annotation.unit; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.UUID; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.tool.ToolVisitor; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; import pt.inesc.id.l2f.annotation.document.laf.LinguisticAnnotationDocument; import pt.inesc.id.l2f.annotation.document.laf.MorphoSyntacticAnnotation; import pt.inesc.id.l2f.annotation.document.laf.Segmentation; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class LinguisticAnnotationProcessUnit extends ProcessUnit implements Comparable<LinguisticAnnotationProcessUnit> { // id generated by UUID class private Text _id; // annotation commond id (generated by UUID class) private Text _annotation; // stage counter private IntWritable _stage; // unit annotation dependencies private Dependencies _dependencies; // ... private LinguisticAnnotationDocument _input; // ... private LinguisticAnnotationDocument _output; // ... (result of documents merge) private LinguisticAnnotationDocument _document; public LinguisticAnnotationProcessUnit() { _dependencies = new Dependencies(); _input = new LinguisticAnnotationDocument(); _output = new LinguisticAnnotationDocument(); _document = new LinguisticAnnotationDocument(); // generate unique identifier _id = new Text(UUID.randomUUID().toString()); _annotation = new Text(UUID.randomUUID().toString()); _stage = new IntWritable(1); } public LinguisticAnnotationProcessUnit(String id, String annotation, int stage) { _dependencies = new Dependencies(); _input = new LinguisticAnnotationDocument(); _output = new LinguisticAnnotationDocument(); _document = new LinguisticAnnotationDocument(); _id = new Text(id); _annotation = new Text(annotation); _stage = new IntWritable(stage); } public LinguisticAnnotationProcessUnit(LinguisticAnnotationDocument input, LinguisticAnnotationDocument output, Dependencies dependencies, String annotation, int stage) { _input = input; _output = output; _dependencies = dependencies; _annotation = new Text(annotation); _stage = new IntWritable(stage); // merge input and output document _document = new LinguisticAnnotationDocument(); _document.merge(input); _document.merge(output); // generate unique identifier _id = new Text(UUID.randomUUID().toString()); } public LinguisticAnnotationProcessUnit(LinguisticAnnotationDocument input, LinguisticAnnotationDocument output) { this(input, output, new Dependencies(), UUID.randomUUID().toString(), 1); } @Override public void accept(ToolVisitor visitor) { visitor.visit(this); } @Override public void execute(Tool tool, ToolExecutionModeUnit unit) { tool.process(this, unit); } /** * * * @param segmentation */ public void addSegmentation(Segmentation segmentation) { _output.addSegmentation(segmentation); _document.addSegmentation(segmentation); } /** * * * @param annotation */ public void addMorphoSyntacticAnnotation(MorphoSyntacticAnnotation annotation) { _output.addMorphoSyntacticAnnotation(annotation); _document.addMorphoSyntacticAnnotation(annotation); } /** * * * @return */ public List<Segmentation> getOutputDocumentSegmentations() { return Collections.unmodifiableList(_output.getSegmentations()); } /** * * * @return */ public List<MorphoSyntacticAnnotation> getOutputDocumentMorphoSyntacticAnnotations() { return Collections.unmodifiableList(_output.getMorphoSyntacticAnnotations()); } /** * * * @return */ public LinguisticAnnotationDocument getInputDocument() { return _input; } /** * * * @return */ public LinguisticAnnotationDocument getDocument() { return _document; } /** * * * @param odoc */ public void setDocument(LinguisticAnnotationDocument odoc) { _input = odoc; } /** * * * @param output */ public void mergeOutput(LinguisticAnnotationDocument output) { _output.merge(output); } /** * * * @param id */ public void addDependency(String id) { _dependencies.addDependency(id); } /** * * * @return the dependencies */ public List<String> getDependencies() { return _dependencies.getDependencies(); } /** * * * @return the _annotation */ public String getAnnotationId() { return _annotation.toString(); } /** * * * @return the stage */ public int getStageNumber() { return _stage.get(); } /** * * * @return the id */ public String getId() { return _id.toString(); } @Override public void readFrom(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isElementEnd(event, "unit")) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("dependencies")) { Dependencies dependencies = new Dependencies(); dependencies.readFrom(xmlr); _dependencies = dependencies; } if (name.equals("laf")) { LinguisticAnnotationDocument doc = new LinguisticAnnotationDocument(); doc.readFrom(xmlr); _input = doc; _document = doc; } } } } @Override public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("unit"); xmlw.writeAttribute("id", _id.toString()); xmlw.writeAttribute("annotation", _annotation.toString()); xmlw.writeAttribute("stage", _stage.toString()); xmlw.writeStartElement("header"); _dependencies.writeTo(xmlw); xmlw.writeEndElement(); // write annotation _output.writeTo(xmlw); xmlw.writeEndElement(); } public void readFields(DataInput in) throws IOException { _id = new Text(); _id.readFields(in); _annotation = new Text(); _annotation.readFields(in); _stage = new IntWritable(); _stage.readFields(in); _dependencies = new Dependencies(); _dependencies.readFields(in); _input = new LinguisticAnnotationDocument(); _input.readFields(in); _output = new LinguisticAnnotationDocument(); _output.readFields(in); _document = new LinguisticAnnotationDocument(); _document.merge(_input); _document.merge(_output); } public void write(DataOutput out) throws IOException { _id.write(out); _annotation.write(out); _stage.write(out); _dependencies.write(out); _input.write(out); _output.write(out); } public int compareTo(LinguisticAnnotationProcessUnit unit) { return new Integer(_stage.get()).compareTo(unit.getStageNumber()); } }
Java
package pt.inesc.id.l2f.annotation.unit; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.tool.ToolVisitor; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; public class FinalProcessUnit extends ProcessUnit { public FinalProcessUnit() { super(true); } @Override public void accept(ToolVisitor visitor) { // TODO: ver isto..................... } @Override public void execute(Tool tool, ToolExecutionModeUnit unit) { // TODO: ver isto..................... } @Override public void writeTo(XMLWriter xmlw) {} @Override public void readFrom(XMLReader xmlr) {} public void readFields(DataInput in) throws IOException {} public void write(DataOutput out) throws IOException {} }
Java
package pt.inesc.id.l2f.annotation.unit; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.DocumentElement; import pt.inesc.id.l2f.annotation.document.util.ListWritable; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; public class Dependencies implements DocumentElement, Writable { // list annotation document dependencies private ListWritable<Text> _dependencies; public Dependencies() { _dependencies = new ListWritable<Text>(); } public void readFields(DataInput in) throws IOException { _dependencies = new ListWritable<Text>(); _dependencies.readFields(in); } public void write(DataOutput out) throws IOException { _dependencies.write(out); } /** * * * @return the dependencies */ public List<String> getDependencies() { List<String> dependencies = new ArrayList<String>(); for (Text dependency : _dependencies) { dependencies.add(dependency.toString()); } return dependencies; } /** * * * @param id */ public void addDependency(String id) { _dependencies.add(new Text(id)); } public void readFrom(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isElementEnd(event, "dependencies")) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("annotation")) { Map<String, String> feature = xmlr.getAttributes(); _dependencies.add(new Text(feature.get("id"))); } } } } public void writeTo(XMLWriter xmlw) { xmlw.writeStartElement("dependencies"); for (Text dependency : _dependencies) { xmlw.writeStartElement("annotation"); xmlw.writeAttribute("id", dependency.toString()); xmlw.writeEndElement(); } xmlw.writeEndElement(); } }
Java
package pt.inesc.id.l2f.annotation.unit; import org.apache.hadoop.io.Writable; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.document.xml.XMLWriter; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.tool.ToolVisitor; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; /** * * * @author Tiago Luis * */ public abstract class ProcessUnit implements Writable { // true if this is the last unit private boolean _last; public ProcessUnit() { _last = false; } public ProcessUnit(boolean last) { _last = last; } /** * * * @param visitor * @return */ public abstract void accept(ToolVisitor visitor); /** * * * @param visitor */ public abstract void execute(Tool tool, ToolExecutionModeUnit unit); /** * * * @param xmlw */ public abstract void writeTo(XMLWriter xmlw); /** * * * @param xmlr */ public abstract void readFrom(XMLReader xmlr); /** * * * @return true if this unit is the last one */ public boolean isLast() { return _last; } /** * * */ public void setLast() { _last = true; } }
Java
package pt.inesc.id.l2f.annotation.tool; import pt.inesc.id.l2f.annotation.document.laf.LinguisticAnnotationDocument; import pt.inesc.id.l2f.annotation.document.laf.Segmentation; import pt.inesc.id.l2f.annotation.input.InputDocument; import pt.inesc.id.l2f.annotation.input.TextElement; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionMode; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; /** * * * @author Tiago Luis * */ public abstract class Tokenizer extends Tool { public Tokenizer(ToolExecutionMode mode) { super(mode); } public void visit(InputDocumentProcessUnit unit) { _mode.input(this, unit); } public void visit(LinguisticAnnotationProcessUnit unit) { // TODO: criar excepção throw new RuntimeException("..."); } // public void visit(SyntacticProcessUnit unit) { // // TODO: criar excepção // throw new RuntimeException("..."); // } public void process(InputDocumentProcessUnit unit, ToolExecutionModeUnit result) { InputDocument idoc = unit.getInputDocument(); LinguisticAnnotationDocument odoc = new LinguisticAnnotationDocument(); // TODO: retirar esta dependência do DOM (Node) TextElement node = null; while ((node = idoc.next()) != null) { @SuppressWarnings("unused") String id = "none"; String text = node.getText(); if (text.matches("\\s+")) { continue; } // TODO: colocar id como atributo no text node // if ((node.getAttributes() != null) && (node.getAttributes().getNamedItem("id") != null)) { // id = node.getAttributes().getNamedItem("id").getNodeValue(); // } this.tokenize(text, odoc); } this.getStage().collect(new LinguisticAnnotationProcessUnit()); } @Override public void process(LinguisticAnnotationProcessUnit unit, ToolExecutionModeUnit result) { // TODO: criar excepção throw new RuntimeException("..."); } private void tokenize(String input, LinguisticAnnotationDocument odoc) { String id = "none"; // if (inode.getAttributes().getNamedItem("id") != null) { // id = inode.getAttributes().getNamedItem("id").getNodeValue(); // } // get tokens from input string Segmentation segmentation = this.tokenize(input, id); // add tokens to output document odoc.addSegmentation(segmentation); } /** * ... * * @param input * @param id * * @return */ protected abstract Segmentation tokenize(String input, String id); }
Java
package pt.inesc.id.l2f.annotation.tool; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; /** * * * @author Tiago Luis * */ public interface ToolVisitor { /** * */ public abstract void start(); /** * * * @param unit * @return */ public void visit(InputDocumentProcessUnit unit); /** * * * @param unit * @return */ public void visit(LinguisticAnnotationProcessUnit unit); /** * */ public abstract void close(); }
Java
package pt.inesc.id.l2f.annotation.tool.execution; import java.io.IOException; import java.net.ServerSocket; import java.util.Arrays; import com.facebook.thrift.transport.TSocket; import com.facebook.thrift.transport.TTransport; import com.facebook.thrift.transport.TTransportException; import com.facebook.thrift.protocol.TBinaryProtocol; import com.facebook.thrift.protocol.TProtocol; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; public abstract class ThriftExecutionMode extends ToolExecutionMode { // ... protected TTransport _transport; // ... protected TProtocol _protocol; // ... protected int _port; // ... protected String _hostname; // ... protected ProcessBuilder _processBuilder; // ... protected Process _process; // ... protected String[] _command; // ... protected String[][] _environment; public ThriftExecutionMode(String hostname, int port) { _hostname = hostname; _port = port; } public ThriftExecutionMode(String[] command, int port, String[][] environment) { _hostname = "localhost"; _port = port; _command = command; _environment = environment; } public ThriftExecutionMode(Tool tool, String hostname, int port) { super(tool); _hostname = hostname; _port = port; } public abstract void createClient(); @Override public void init() { if (_command != null) { // create process command with command _processBuilder = new ProcessBuilder(Arrays.asList(_command)); if (_environment != null) { // set environment for (String[] pair : _environment) { String key = pair[0]; String value = pair[1]; _processBuilder.environment().put(key, value); } } } } @Override @SuppressWarnings("static-access") public void start() { if (_command != null) { try { _process = _processBuilder.start(); // Thread t = new Thread(this); // t.start(); // // wait for server initialization Thread.currentThread().sleep(2000); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } try { _transport = new TSocket(_hostname, _port); _protocol = new TBinaryProtocol(_transport); _transport.open(); } catch (TTransportException e) { e.printStackTrace(); } this.createClient(); } // @Override // public void run() { // BufferedReader br1 = new BufferedReader(new InputStreamReader(_process.getErrorStream())); // BufferedReader br2 = new BufferedReader(new InputStreamReader(_process.getInputStream())); // // String line = ""; // // try { // while ((line = br1.readLine()) != null) { // System.out.println("DEBUG (Error): " + line); // } // //// while ((line = br2.readLine()) != null) { //// System.out.println("DEBUG (Input): " + line); //// } // } catch (IOException e) { // e.printStackTrace(); // } // } @Override public void input(Tool tool, InputDocumentProcessUnit unit) { unit.execute(tool, this.getOutput(unit)); } @Override public void input(Tool tool, LinguisticAnnotationProcessUnit unit) { unit.execute(tool, this.getOutput(unit)); } // @Override // public void input(Tool tool, SyntacticProcessUnit unit) { // unit.execute(tool, this.getOutput(unit)); // } public abstract ToolExecutionModeUnit getOutput(InputDocumentProcessUnit unit); public abstract ToolExecutionModeUnit getOutput(LinguisticAnnotationProcessUnit unit); // public abstract ToolExecutionModeUnit getOutput(SyntacticProcessUnit unit); @Override public void close() { _transport.close(); if (_process != null) { _process.destroy(); } } /** * @return the transport */ public TTransport getTransport() { return _transport; } /** * @return the protocol */ public TProtocol getProtocol() { return _protocol; } public static int findFreePort() { int port = -1; try { ServerSocket server; server = new ServerSocket(0); port = server.getLocalPort(); server.close(); } catch (IOException e) { e.printStackTrace(); } return port; } }
Java
package pt.inesc.id.l2f.annotation.tool.execution; import java.util.List; import pt.inesc.id.l2f.annotation.unit.ProcessUnit; /** * * * @author Tiago Luis * */ public class ToolExecutionModeUnit extends Thread { // ... protected List<String> _input; // ... protected List<String> _output; // ... protected ProcessUnit _unit; // ... private boolean _last; public ToolExecutionModeUnit(boolean last) { _last = last; } public ToolExecutionModeUnit(List<String> input, ProcessUnit unit) { _input = input; _unit = unit; _last = false; } /** * @return the input */ public List<String> getInput() { return _input; } /** * @param input the input to set */ public void setInput(List<String> input) { _input = input; } /** * @return the unit */ public ProcessUnit getUnit() { return _unit; } /** * * * @param unit the unit to set */ public void setUnit(ProcessUnit unit) { _unit = unit; } /** * * * @return the output */ public List<String> getOutput() { return _output; } /** * * * @param output the output to set */ public void setOutput(List<String> output) { _output = output; } /** * * @return true if it is the last unit */ public boolean isLast() { return _last; } /** * * @param last the boolean value to set */ public void setLast(boolean last) { _last = last; } }
Java
package pt.inesc.id.l2f.annotation.tool.execution; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; /** * * * @author Tiago Luis * */ public abstract class ToolExecutionMode extends Thread { // ... protected Tool _tool; public ToolExecutionMode() {} public ToolExecutionMode(Tool tool) { _tool = tool; } /** * * * @param tool * @param unit */ public abstract void input(Tool tool, InputDocumentProcessUnit unit); /** * * * @param tool * @param unit */ public abstract void input(Tool tool, LinguisticAnnotationProcessUnit unit); // /** // * // * // * @param tool // * @param unit // */ // public abstract void input(Tool tool, SyntacticProcessUnit unit); /** * * */ public abstract void init(); /** * * */ public abstract void start(); /** * * */ public abstract void close(); /** * * * @return */ public Tool getTool() { return _tool; } /** * * * @param tool */ public void setTool(Tool tool) { _tool = tool; } }
Java
package pt.inesc.id.l2f.annotation.tool.execution; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import pt.inesc.id.l2f.annotation.input.TextDocument; import pt.inesc.id.l2f.annotation.input.TextElement; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; /** * * * @author Tiago Luis * */ public abstract class ExternalProcessExecutionMode extends ToolExecutionMode { // ... private ProcessBuilder _processBuilder; // ... protected Thread _outputCollectorThread; // ... protected OutputStreamWriter _osr; // ... protected Process _process; // ... protected String[] _command; // ... protected String[][] _environment; // ... protected String _charset; // ... protected BlockingQueue<ToolExecutionModeUnit> _in = new LinkedBlockingQueue<ToolExecutionModeUnit>(); public ExternalProcessExecutionMode(String[] command, String[][] environment, String charset) { _command = command; _environment = environment; _charset = charset; } /** * * */ public void init() { // create process command with command _processBuilder = new ProcessBuilder(Arrays.asList(_command)); if (_environment != null) { // set environment for (String[] pair : _environment) { String key = pair[0]; String value = pair[1]; _processBuilder.environment().put(key, value); } } } /** * * */ public void start() { try { _process = _processBuilder.start(); // get process output stream writer _osr = new OutputStreamWriter(_process.getOutputStream(), _charset); // start output collector _outputCollectorThread = new Thread(this); _outputCollectorThread.start(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { // TODO: ver isto BufferedReader br = new BufferedReader(new InputStreamReader(_process.getInputStream(), _charset)); InputStream is = _process.getInputStream(); while (true) { ToolExecutionModeUnit unit = _in.take(); // stop if it finds final unit if (unit.isLast()) { break; } // get process output this.setOutput(unit, is, br); unit.getUnit().execute(_tool, unit); } } catch (InterruptedException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void input(Tool tool, InputDocumentProcessUnit unit) { try { TextElement node = null; while ((node = unit.getInputDocument().next()) != null) { List<String> list = new ArrayList<String>(); list.add(node.getText()); // TODO: parameterizar for (int i = 0; i < 0; i++) { node = unit.getInputDocument().next(); if (node != null) { list.add(node.getText()); } else { break; } } TextDocument doc = new TextDocument(list); ToolExecutionModeUnit eunit = this.setInput(new InputDocumentProcessUnit(doc)); for (String input : eunit.getInput()) { _osr.write(input); } _in.put(eunit); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void input(Tool tool, LinguisticAnnotationProcessUnit unit) { try { ToolExecutionModeUnit eunit = this.setInput(unit); for (String input : eunit.getInput()) { _osr.write(input); } _in.put(eunit); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * * * @param unit * @return */ public abstract ToolExecutionModeUnit setInput(InputDocumentProcessUnit unit); /** * * * @param unit * @return */ public abstract ToolExecutionModeUnit setInput(LinguisticAnnotationProcessUnit unit); /** * * * @param unit * @param is * @param reader * @return */ public abstract ToolExecutionModeUnit setOutput(ToolExecutionModeUnit unit, InputStream is, Reader reader); /** * * */ public void close() { try { _osr.close(); _in.put(new ToolExecutionModeUnit(true)); _outputCollectorThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * * * @return */ public boolean isRunning() { try { // try to get process exit value _process.exitValue(); // the process is running return false; } catch (IllegalThreadStateException itse) { return true; } } /** * @return the process */ public Process getProcess() { return _process; } }
Java
package pt.inesc.id.l2f.annotation.tool.execution; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; /** * * * @author Tiago Luis * */ public class JavaExecutionMode extends ToolExecutionMode { public JavaExecutionMode() {} public JavaExecutionMode(Tool tool) { super(tool); } @Override public void init() {} @Override public void start() {} @Override public void input(Tool tool, InputDocumentProcessUnit unit) { unit.execute(tool, null); } @Override public void input(Tool tool, LinguisticAnnotationProcessUnit unit) { unit.execute(tool, null); } @Override public void close() {} }
Java
package pt.inesc.id.l2f.annotation.tool.execution; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; public abstract class JNIExecutionMode extends ToolExecutionMode { public JNIExecutionMode() {} @Override public void start() {} @Override public void input(Tool tool, InputDocumentProcessUnit unit) { unit.execute(tool, this.getOutput(unit)); } @Override public void input(Tool tool, LinguisticAnnotationProcessUnit unit) { unit.execute(tool, this.getOutput(unit)); } public abstract ToolExecutionModeUnit getOutput(InputDocumentProcessUnit unit); public abstract ToolExecutionModeUnit getOutput(LinguisticAnnotationProcessUnit unit); @Override public void close() {} }
Java
package pt.inesc.id.l2f.annotation.tool; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionMode; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; import pt.inesc.id.l2f.annotation.stage.Stage; /** * * * @author Tiago Luis * */ public abstract class Tool implements ToolVisitor { // ... protected Stage _stage; // ... protected ToolExecutionMode _mode; public Tool(ToolExecutionMode mode) { _mode = mode; } /** * * * @param unit * @param result */ public abstract void process(InputDocumentProcessUnit unit, ToolExecutionModeUnit result); /** * * * @param unit * @param result */ public abstract void process(LinguisticAnnotationProcessUnit unit, ToolExecutionModeUnit result); /** * */ public void init() { _mode.init(); } /** * */ public void start() { _mode.close(); } /** * */ public void close() { _mode.close(); } /** * * * @return the stage */ public Stage getStage() { return _stage; } /** * * * @param stage the stage to set */ public void setStage(Stage stage) { _stage = stage; } /** * * * @return execution mode of tool */ public ToolExecutionMode getExecutionMode() { return _mode; } /** * * * @param mode execution mode of tool */ public void setExecutionMode(ToolExecutionMode mode) { _mode = mode; } }
Java
package pt.inesc.id.l2f.annotation.tool; import java.util.ArrayList; import java.util.List; import pt.inesc.id.l2f.annotation.document.laf.MorphoSyntacticAnnotation; import pt.inesc.id.l2f.annotation.document.laf.Segment; import pt.inesc.id.l2f.annotation.document.laf.Segmentation; import pt.inesc.id.l2f.annotation.input.TextElement; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionMode; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; /** * * * @author Tiago Luis * */ public abstract class Classifier extends Tool { // current unit private LinguisticAnnotationProcessUnit _unit; public Classifier(ToolExecutionMode mode) { super(mode); } public void visit(InputDocumentProcessUnit unit) { _mode.input(this, unit); } public void visit(LinguisticAnnotationProcessUnit unit) { _mode.input(this, unit); } public void process(InputDocumentProcessUnit unit, ToolExecutionModeUnit result) { if (result != null) { // set current unit _unit = new LinguisticAnnotationProcessUnit(); this.tagg(null, result.getInput(), result.getOutput()); // put unit into next stage _stage.collect(_unit); } else { TextElement node = null; while ((node = unit.getInputDocument().next()) != null) { // set current unit _unit = new LinguisticAnnotationProcessUnit(); List<String> input = new ArrayList<String>(); String s = node.getText(); if (s.matches("\\s+")) { continue; } input.add(s); this.tagg(null, input, null); // put unit into next stage _stage.collect(_unit); } } } @Override public void process(LinguisticAnnotationProcessUnit unit, ToolExecutionModeUnit result) { // if (result != null) { List<String> input = null; List<String> output = null; if (result != null) { input = result.getInput(); output = result.getOutput(); } // set current unit _unit = unit; MorphoSyntacticAnnotation morphoSyntacticAnnotation = unit.getDocument().getLastMorphoSyntacticAnnotation(); this.tagg(morphoSyntacticAnnotation, input, output); // unit.merge(_unit.getDocument()); _stage.collect(unit); // } else { // // TODO: lançar excepção própria // throw new RuntimeException("Operation not supported"); // } } /** * * * @param segmentation */ protected void addSegmentation(Segmentation segmentation) { _unit.addSegmentation(segmentation); } /** * * * @param id * @return */ protected Segment getSegment(String id) { return _unit.getDocument().getSegment(id); } /** * * * @param morphoSyntacticAnnotation */ protected void addMorphoSyntacticAnnotation(MorphoSyntacticAnnotation morphoSyntacticAnnotation) { _unit.addMorphoSyntacticAnnotation(morphoSyntacticAnnotation); } /** * * * @param input * @param output */ protected abstract void tagg(MorphoSyntacticAnnotation morphoSyntacticAnnotation, List<String> input, List<String> output); }
Java
package pt.inesc.id.l2f.annotation.tool; import pt.inesc.id.l2f.annotation.tool.execution.JavaExecutionMode; import pt.inesc.id.l2f.annotation.tool.execution.ToolExecutionModeUnit; import pt.inesc.id.l2f.annotation.unit.InputDocumentProcessUnit; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; public class IdentityTool extends Tool { public IdentityTool() { super(new JavaExecutionMode()); } @Override public void start() { } public void visit(InputDocumentProcessUnit unit) { _mode.input(this, unit); } public void visit(LinguisticAnnotationProcessUnit unit) { _mode.input(this, unit); } // public void visit(SyntacticProcessUnit unit) { // _mode.input(this, unit); // } @Override public void process(InputDocumentProcessUnit unit, ToolExecutionModeUnit result) {} @Override public void process(LinguisticAnnotationProcessUnit unit, ToolExecutionModeUnit result) {} // @Override // public void process(SyntacticProcessUnit unit, ToolExecutionModeUnit result) {} @Override public void close() {} }
Java
/************************************************************************ * * Copyright (c) 2008 L2F (INESC-ID LISBOA) * All Rights Reserved. * * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF L2F (INESC-ID LISBOA) * The copyright notice above does not evidence any * actual or intended publication of such source code. * ************************************************************************/ package pt.inesc.id.l2f.annotation.main; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import pt.inesc.id.l2f.annotation.document.laf.LinguisticAnnotationDocument; import pt.inesc.id.l2f.annotation.document.xml.XMLReader; import pt.inesc.id.l2f.annotation.execution.Directory; import pt.inesc.id.l2f.annotation.execution.ExecutionMode; import pt.inesc.id.l2f.annotation.execution.File; import pt.inesc.id.l2f.annotation.execution.LafFile; import pt.inesc.id.l2f.annotation.execution.LocalExecutionMode; import pt.inesc.id.l2f.annotation.execution.RawFile; import pt.inesc.id.l2f.annotation.execution.TeiFile; import pt.inesc.id.l2f.annotation.execution.hadoop.HadoopExecutionMode; import pt.inesc.id.l2f.annotation.input.InputDocument; import pt.inesc.id.l2f.annotation.input.RawDocument; import pt.inesc.id.l2f.annotation.input.TEIDocument; import pt.inesc.id.l2f.annotation.stage.FinalStage; import pt.inesc.id.l2f.annotation.tool.Tool; import pt.inesc.id.l2f.annotation.tools.ar.ArabicPOSTagger; import pt.inesc.id.l2f.annotation.tools.cn.ChinesePOSTagger; import pt.inesc.id.l2f.annotation.tools.en.StanfordEnglishPOSTagger; import pt.inesc.id.l2f.annotation.tools.jp.JapanesePOSTagger; import pt.inesc.id.l2f.annotation.tools.pt.jmarv.JMARv; import pt.inesc.id.l2f.annotation.tools.pt.palavroso.Palavroso; import pt.inesc.id.l2f.annotation.tools.pt.rudrico.Rudrico; import pt.inesc.id.l2f.annotation.unit.Dependencies; import pt.inesc.id.l2f.annotation.unit.LinguisticAnnotationProcessUnit; /** * * * * @author Tiago Luis * */ public class Main { public static void main(String[] args) { ExecutionMode mode = null; // input option Option tinput = new Option("tei", true, "TEI document filename"); tinput.setArgs(Option.UNLIMITED_VALUES); Option rinput = new Option("raw", true, "RAW document filename (one sentence per line)"); rinput.setArgs(Option.UNLIMITED_VALUES); Option linput = new Option("laf", true, "LAF annotation filename"); linput.setArgs(Option.UNLIMITED_VALUES); Option dependencies = new Option("dependencies", false, "LAF annotation dependencies"); dependencies.setArgs(Option.UNLIMITED_VALUES); OptionGroup inputGroup = new OptionGroup(); inputGroup.addOption(tinput); inputGroup.addOption(rinput); inputGroup.addOption(linput); inputGroup.setRequired(true); // output option Option output = new Option("output", true, "LAF annotation filename"); output.setArgs(Option.UNLIMITED_VALUES); OptionGroup outputGroup = new OptionGroup(); outputGroup.addOption(output); outputGroup.setRequired(true); // execution mode Option local = new Option("local", false, "local execution mode"); Option parallel = new Option("parallel", false, "parallel execution mode"); OptionGroup executionGroup = new OptionGroup(); executionGroup.addOption(local); executionGroup.addOption(parallel); executionGroup.setRequired(true); // parallel execution mode options Option mappers = new Option("mappers", true, "mappers number"); Option reducers = new Option("reducers", true, "reducers number"); Option compressall = new Option("compressall", false, "compress intermediate and output"); Option compressoutput = new Option("compressoutput", false, "compress output"); Option compressintermediate = new Option("compressintermediate", false, "compress intermediate"); // tools options Option english = new Option("english", false, "Stanford English POS Tagger"); Option arabic = new Option("arabic", false, "Arabic POS Tagger"); Option japanese = new Option("japanese", false, "Japanese POS Tagger"); Option chinese = new Option("chinese", false, "Chinese POS Tagger"); Option palavroso = new Option("palavroso", false, "Portuguese POS Tagger"); Option rudrico = new Option("rudrico", false, "Portuguese Post...."); Option jmarv = new Option("jmarv", false, "Portuguese Disambiguator"); Option xip = new Option("xip", false, "Portuguese XIP Chain"); OptionGroup toolsGroup = new OptionGroup(); toolsGroup.addOption(english); toolsGroup.addOption(arabic); toolsGroup.addOption(japanese); toolsGroup.addOption(chinese); toolsGroup.addOption(palavroso); toolsGroup.addOption(rudrico); toolsGroup.addOption(jmarv); toolsGroup.addOption(xip); toolsGroup.setRequired(true); Options options = new Options(); options.addOptionGroup(inputGroup); options.addOption(dependencies); options.addOptionGroup(outputGroup); options.addOptionGroup(executionGroup); options.addOption(mappers); options.addOption(reducers); options.addOption(compressall); options.addOption(compressoutput); options.addOption(compressintermediate); options.addOptionGroup(toolsGroup); // help printer HelpFormatter formatter = new HelpFormatter(); Parser parser = new GnuParser(); List<Tool> tools = new ArrayList<Tool>(); try { CommandLine cl = parser.parse(options, args); if (cl.hasOption("palavroso")) { tools.add(new Palavroso()); } else if (cl.hasOption("rudrico")) { tools.add(new Rudrico()); } else if (cl.hasOption("jmarv")) { tools.add(new JMARv()); } else if (cl.hasOption("xip")) { tools.add(new Palavroso()); tools.add(new JMARv()); } else if (cl.hasOption("english")) { tools.add(new StanfordEnglishPOSTagger()); } else if (cl.hasOption("arabic")) { tools.add(new ArabicPOSTagger()); } else if (cl.hasOption("japanese")) { tools.add(new JapanesePOSTagger()); } else if (cl.hasOption("chinese")) { tools.add(new ChinesePOSTagger()); } if (cl.hasOption("local")) { mode = new LocalExecutionMode(tools.toArray(new Tool[tools.size()])); // add final stage mode.addFinalStage(new FinalStage(cl.getOptionValue("output"), cl.hasOption("compress"))); // start execution mode mode.start(); Map<String, LinguisticAnnotationProcessUnit> units = new HashMap<String, LinguisticAnnotationProcessUnit>(); if (cl.hasOption("laf")) { if (cl.hasOption("dependencies")) { for (Object value : cl.getOptionValues("dependencies")) { XMLReader xmlr = new XMLReader(new FileReader(value.toString())); while (true) { LinguisticAnnotationProcessUnit unit = readLinguisticAnnotationUnit(xmlr); if (unit == null) { break; } units.put(unit.getId(), unit); } } } XMLReader xmlr = new XMLReader(new FileReader(cl.getOptionValue("laf"))); while (true) { LinguisticAnnotationProcessUnit unit = readLinguisticAnnotationUnit(xmlr); if (unit == null) { break; } LinguisticAnnotationDocument annotation = new LinguisticAnnotationDocument(); Dependencies dep = new Dependencies(); for (String dependency : unit.getDependencies()) { if (units.get(dependency) != null) { LinguisticAnnotationDocument doc = units.get(dependency).getDocument(); annotation.merge(doc); dep.addDependency(dependency); } else { System.err.println("Dependency with id " + dependency + " does not exist."); System.exit(1); } } dep.addDependency(unit.getId()); annotation.merge(unit.getDocument()); mode.annotate(new LinguisticAnnotationProcessUnit(annotation, new LinguisticAnnotationDocument(), dep, unit.getAnnotationId(), unit.getStageNumber() + 1), null); } } else if (cl.hasOption("raw")) { List<InputDocument> list = new ArrayList<InputDocument>(); for (Object value : cl.getOptionValues("raw")) { RawDocument doc = new RawDocument(value.toString()); // add annotation document (after processing) list.add(doc); } mode.annotateInputDocuments(list, null); } else if (cl.hasOption("tei")) { List<InputDocument> list = new ArrayList<InputDocument>(); for (Object value : cl.getOptionValues("tei")) { TEIDocument doc = new TEIDocument(value.toString()); // add annotation document (after processing) list.add(doc); } mode.annotateInputDocuments(list, null); } mode.close(); } else if (cl.hasOption("parallel")) { mode = new HadoopExecutionMode(tools.toArray(new Tool[tools.size()])); mode.start(); ((HadoopExecutionMode) mode).setMappers(Integer.valueOf(cl.getOptionValue("mappers", "2"))); ((HadoopExecutionMode) mode).setReducers(Integer.valueOf(cl.getOptionValue("reducers", "1"))); if (cl.hasOption("compressall")) { ((HadoopExecutionMode) mode).compressMapOutput(); ((HadoopExecutionMode) mode).compressFinalOutput(); } if (cl.hasOption("compressintermediate")) { ((HadoopExecutionMode) mode).compressMapOutput(); } if (cl.hasOption("compressoutput")) { ((HadoopExecutionMode) mode).compressFinalOutput(); } if (cl.hasOption("raw")) { mode.annotateFile(new RawFile(cl.getOptionValue("raw")), new Directory(cl.getOptionValue("output"))); } else if (cl.hasOption("tei")) { mode.annotateFile(new TeiFile(cl.getOptionValue("tei")), new Directory(cl.getOptionValue("output"))); } else if (cl.hasOption("laf")) { List<File> files = new ArrayList<File>(); for (Object value : cl.getOptionValues("laf")) { files.add(new LafFile(value.toString())); } mode.annotateFile(files, new Directory(cl.getOptionValue("output"))); } mode.close(); } } catch (ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("split", options); } catch (FileNotFoundException e) { e.printStackTrace(); } } // TODO: remover private static LinguisticAnnotationProcessUnit readLinguisticAnnotationUnit(XMLReader xmlr) { int event = -1; while (true) { event = xmlr.next(); if (xmlr.isDocumentEnd(event)) { break; } if (xmlr.isElementStart(event)) { String name = xmlr.getElementName(); if (name.equals("unit")) { Map<String, String> feature = xmlr.getAttributes(); LinguisticAnnotationProcessUnit unit = new LinguisticAnnotationProcessUnit(feature.get("id"), feature.get("annotation"), Integer.valueOf(feature.get("stage"))); unit.readFrom(xmlr); return unit; } } } return null; } }
Java
package pl.polidea.treeview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; /** * Tree view, expandable multi-level. * * <pre> * attr ref pl.polidea.treeview.R.styleable#TreeViewList_collapsible * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_expanded * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_collapsed * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indent_width * attr ref pl.polidea.treeview.R.styleable#TreeViewList_handle_trackball_press * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_gravity * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_background * attr ref pl.polidea.treeview.R.styleable#TreeViewList_row_background * </pre> */ public class TreeViewList extends ListView { private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed; private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded; private static final int DEFAULT_INDENT = 0; private static final int DEFAULT_GRAVITY = Gravity.LEFT | Gravity.CENTER_VERTICAL; private Drawable expandedDrawable; private Drawable collapsedDrawable; private Drawable rowBackgroundDrawable; private Drawable indicatorBackgroundDrawable; private int indentWidth = 0; private int indicatorGravity = 0; private AbstractTreeViewAdapter< ? > treeAdapter; private boolean collapsible; private boolean handleTrackballPress; public TreeViewList(final Context context, final AttributeSet attrs) { this(context, attrs, R.style.treeViewListStyle); } public TreeViewList(final Context context) { this(context, null); } public TreeViewList(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); parseAttributes(context, attrs); } private void parseAttributes(final Context context, final AttributeSet attrs) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TreeViewList); expandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded); if (expandedDrawable == null) { expandedDrawable = context.getResources().getDrawable( DEFAULT_EXPANDED_RESOURCE); } collapsedDrawable = a .getDrawable(R.styleable.TreeViewList_src_collapsed); if (collapsedDrawable == null) { collapsedDrawable = context.getResources().getDrawable( DEFAULT_COLLAPSED_RESOURCE); } indentWidth = a.getDimensionPixelSize( R.styleable.TreeViewList_indent_width, DEFAULT_INDENT); indicatorGravity = a.getInteger( R.styleable.TreeViewList_indicator_gravity, DEFAULT_GRAVITY); indicatorBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_indicator_background); rowBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_row_background); collapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true); handleTrackballPress = a.getBoolean( R.styleable.TreeViewList_handle_trackball_press, true); } @Override public void setAdapter(final ListAdapter adapter) { if (!(adapter instanceof AbstractTreeViewAdapter)) { throw new TreeConfigurationException( "The adapter is not of TreeViewAdapter type"); } treeAdapter = (AbstractTreeViewAdapter< ? >) adapter; syncAdapter(); super.setAdapter(treeAdapter); } private void syncAdapter() { treeAdapter.setCollapsedDrawable(collapsedDrawable); treeAdapter.setExpandedDrawable(expandedDrawable); treeAdapter.setIndicatorGravity(indicatorGravity); treeAdapter.setIndentWidth(indentWidth); treeAdapter.setIndicatorBackgroundDrawable(indicatorBackgroundDrawable); treeAdapter.setRowBackgroundDrawable(rowBackgroundDrawable); treeAdapter.setCollapsible(collapsible); if (handleTrackballPress) { setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView< ? > parent, final View view, final int position, final long id) { treeAdapter.handleItemClick(view, view.getTag()); } }); } else { setOnClickListener(null); } } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; syncAdapter(); treeAdapter.refresh(); } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; syncAdapter(); treeAdapter.refresh(); } public void setHandleTrackballPress(final boolean handleTrackballPress) { this.handleTrackballPress = handleTrackballPress; syncAdapter(); treeAdapter.refresh(); } public Drawable getExpandedDrawable() { return expandedDrawable; } public Drawable getCollapsedDrawable() { return collapsedDrawable; } public Drawable getRowBackgroundDrawable() { return rowBackgroundDrawable; } public Drawable getIndicatorBackgroundDrawable() { return indicatorBackgroundDrawable; } public int getIndentWidth() { return indentWidth; } public int getIndicatorGravity() { return indicatorGravity; } public boolean isCollapsible() { return collapsible; } public boolean isHandleTrackballPress() { return handleTrackballPress; } }
Java
package pl.polidea.treeview; import android.app.Activity; import android.content.Context; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.ListAdapter; /** * Adapter used to feed the table view. * * @param <T> * class for ID of the tree */ public abstract class AbstractTreeViewAdapter<T> extends BaseAdapter implements ListAdapter { private final TreeStateManager<T> treeStateManager; private final int numberOfLevels; private final LayoutInflater layoutInflater; private int indentWidth = 0; private int indicatorGravity = 0; private Drawable collapsedDrawable; private Drawable expandedDrawable; private Drawable indicatorBackgroundDrawable; private Drawable rowBackgroundDrawable; private final OnClickListener indicatorClickListener = new OnClickListener() { @Override public void onClick(final View v) { @SuppressWarnings("unchecked") final T id = (T) v.getTag(); expandCollapse(id); } }; private boolean collapsible; private final Activity activity; public Activity getActivity() { return activity; } protected TreeStateManager<T> getManager() { return treeStateManager; } protected void expandCollapse(final T id) { final TreeNodeInfo<T> info = treeStateManager.getNodeInfo(id); if (!info.isWithChildren()) { // ignore - no default action return; } if (info.isExpanded()) { treeStateManager.collapseChildren(id); } else { treeStateManager.expandDirectChildren(id); } } private void calculateIndentWidth() { if (expandedDrawable != null) { indentWidth = Math.max(getIndentWidth(), expandedDrawable.getIntrinsicWidth()); } if (collapsedDrawable != null) { indentWidth = Math.max(getIndentWidth(), collapsedDrawable.getIntrinsicWidth()); } } public AbstractTreeViewAdapter(final Activity activity, final TreeStateManager<T> treeStateManager, final int numberOfLevels) { this.activity = activity; this.treeStateManager = treeStateManager; this.layoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.numberOfLevels = numberOfLevels; this.collapsedDrawable = null; this.expandedDrawable = null; this.rowBackgroundDrawable = null; this.indicatorBackgroundDrawable = null; } @Override public void registerDataSetObserver(final DataSetObserver observer) { treeStateManager.registerDataSetObserver(observer); } @Override public void unregisterDataSetObserver(final DataSetObserver observer) { treeStateManager.unregisterDataSetObserver(observer); } @Override public int getCount() { return treeStateManager.getVisibleCount(); } @Override public Object getItem(final int position) { return getItemId(position); } public T getTreeId(final int position) { return treeStateManager.getVisibleList().get(position); } public TreeNodeInfo<T> getTreeNodeInfo(final int position) { return treeStateManager.getNodeInfo(getTreeId(position)); } @Override public boolean hasStableIds() { // NOPMD return true; } @Override public int getItemViewType(final int position) { return getTreeNodeInfo(position).getLevel(); } @Override public int getViewTypeCount() { return numberOfLevels; } @Override public boolean isEmpty() { return getCount() == 0; } @Override public boolean areAllItemsEnabled() { // NOPMD return true; } @Override public boolean isEnabled(final int position) { // NOPMD return true; } protected int getTreeListItemWrapperId() { return R.layout.tree_list_item_wrapper; } @Override public final View getView(final int position, final View convertView, final ViewGroup parent) { final TreeNodeInfo<T> nodeInfo = getTreeNodeInfo(position); if (convertView == null) { final LinearLayout layout = (LinearLayout) layoutInflater.inflate( getTreeListItemWrapperId(), null); return populateTreeItem(layout, getNewChildView(nodeInfo), nodeInfo, true); } else { final LinearLayout linear = (LinearLayout) convertView; final FrameLayout frameLayout = (FrameLayout) linear .findViewById(R.id.treeview_list_item_frame); final View childView = frameLayout.getChildAt(0); updateView(childView, nodeInfo); return populateTreeItem(linear, childView, nodeInfo, false); } } /** * Called when new view is to be created. * * @param treeNodeInfo * node info * @return view that should be displayed as tree content */ public abstract View getNewChildView(TreeNodeInfo<T> treeNodeInfo); /** * Called when new view is going to be reused. You should update the view * and fill it in with the data required to display the new information. You * can also create a new view, which will mean that the old view will not be * reused. * * @param view * view that should be updated with the new values * @param treeNodeInfo * node info used to populate the view * @return view to used as row indented content */ public abstract View updateView(View view, TreeNodeInfo<T> treeNodeInfo); /** * Retrieves background drawable for the node. * * @param treeNodeInfo * node info * @return drawable returned as background for the whole row. Might be null, * then default background is used */ public Drawable getBackgroundDrawable(final TreeNodeInfo<T> treeNodeInfo) { // NOPMD return null; } private Drawable getDrawableOrDefaultBackground(final Drawable r) { if (r == null) { return activity.getResources() .getDrawable(R.drawable.list_selector_background).mutate(); } else { return r; } } public final LinearLayout populateTreeItem(final LinearLayout layout, final View childView, final TreeNodeInfo<T> nodeInfo, final boolean newChildView) { final Drawable individualRowDrawable = getBackgroundDrawable(nodeInfo); layout.setBackgroundDrawable(individualRowDrawable == null ? getDrawableOrDefaultBackground(rowBackgroundDrawable) : individualRowDrawable); final LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( calculateIndentation(nodeInfo), LayoutParams.FILL_PARENT); final LinearLayout indicatorLayout = (LinearLayout) layout .findViewById(R.id.treeview_list_item_image_layout); indicatorLayout.setGravity(indicatorGravity); indicatorLayout.setLayoutParams(indicatorLayoutParams); final ImageView image = (ImageView) layout .findViewById(R.id.treeview_list_item_image); image.setImageDrawable(getDrawable(nodeInfo)); image.setBackgroundDrawable(getDrawableOrDefaultBackground(indicatorBackgroundDrawable)); image.setScaleType(ScaleType.CENTER); image.setTag(nodeInfo.getId()); if (nodeInfo.isWithChildren() && collapsible) { image.setOnClickListener(indicatorClickListener); } else { image.setOnClickListener(null); } layout.setTag(nodeInfo.getId()); final FrameLayout frameLayout = (FrameLayout) layout .findViewById(R.id.treeview_list_item_frame); final FrameLayout.LayoutParams childParams = new FrameLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); if (newChildView) { frameLayout.addView(childView, childParams); } frameLayout.setTag(nodeInfo.getId()); return layout; } protected int calculateIndentation(final TreeNodeInfo<T> nodeInfo) { return getIndentWidth() * (nodeInfo.getLevel() + (collapsible ? 1 : 0)); } private Drawable getDrawable(final TreeNodeInfo<T> nodeInfo) { if (!nodeInfo.isWithChildren() || !collapsible) { return getDrawableOrDefaultBackground(indicatorBackgroundDrawable); } if (nodeInfo.isExpanded()) { return expandedDrawable; } else { return collapsedDrawable; } } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; calculateIndentWidth(); } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; calculateIndentWidth(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; calculateIndentWidth(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; } public void refresh() { treeStateManager.refresh(); } private int getIndentWidth() { return indentWidth; } @SuppressWarnings("unchecked") public void handleItemClick(final View view, final Object id) { expandCollapse((T) id); } }
Java
package pl.polidea.treeview; /** * This exception is thrown when the tree does not contain node requested. * */ public class NodeNotInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeNotInTreeException(final String id) { super("The tree does not contain the node specified: " + id); } }
Java
/** * Provides expandable Tree View implementation. */ package pl.polidea.treeview;
Java
package pl.polidea.treeview; import android.util.Log; /** * Allows to build tree easily in sequential mode (you have to know levels of * all the tree elements upfront). You should rather use this class rather than * manager if you build initial tree from some external data source. * * @param <T> */ public class TreeBuilder<T> { private static final String TAG = TreeBuilder.class.getSimpleName(); private final TreeStateManager<T> manager; private T lastAddedId = null; private int lastLevel = -1; public TreeBuilder(final TreeStateManager<T> manager) { this.manager = manager; } public void clear() { manager.clear(); } /** * Adds new relation to existing tree. Child is set as the last child of the * parent node. Parent has to already exist in the tree, child cannot yet * exist. This method is mostly useful in case you add entries layer by * layer - i.e. first top level entries, then children for all parents, then * grand-children and so on. * * @param parent * parent id * @param child * child id */ public synchronized void addRelation(final T parent, final T child) { Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child); manager.addAfterChild(parent, child, null); lastAddedId = child; lastLevel = manager.getLevel(child); } /** * Adds sequentially new node. Using this method is the simplest way of * building tree - if you have all the elements in the sequence as they * should be displayed in fully-expanded tree. You can combine it with add * relation - for example you can add information about few levels using * {@link addRelation} and then after the right level is added as parent, * you can continue adding them using sequential operation. * * @param id * id of the node * @param level * its level */ public synchronized void sequentiallyAddNextNode(final T id, final int level) { Log.d(TAG, "Adding sequentiall node " + id + " at level " + level); if (lastAddedId == null) { addNodeToParentOneLevelDown(null, id, level); } else { if (level <= lastLevel) { final T parent = findParentAtLevel(lastAddedId, level - 1); addNodeToParentOneLevelDown(parent, id, level); } else { addNodeToParentOneLevelDown(lastAddedId, id, level); } } } /** * Find parent of the node at the level specified. * * @param node * node from which we start * @param levelToFind * level which we are looking for * @return the node found (null if it is topmost node). */ private T findParentAtLevel(final T node, final int levelToFind) { T parent = manager.getParent(node); while (parent != null) { if (manager.getLevel(parent) == levelToFind) { break; } parent = manager.getParent(parent); } return parent; } /** * Adds note to parent at the level specified. But it verifies that the * level is one level down than the parent! * * @param parent * parent parent * @param id * new node id * @param level * should always be parent's level + 1 */ private void addNodeToParentOneLevelDown(final T parent, final T id, final int level) { if (parent == null && level != 0) { throw new TreeConfigurationException("Trying to add new id " + id + " to top level with level != 0 (" + level + ")"); } if (parent != null && manager.getLevel(parent) != level - 1) { throw new TreeConfigurationException("Trying to add new id " + id + " <" + level + "> to " + parent + " <" + manager.getLevel(parent) + ">. The difference in levels up is bigger than 1."); } manager.addAfterChild(parent, id, null); setLastAdded(id, level); } private void setLastAdded(final T id, final int level) { lastAddedId = id; lastLevel = level; } }
Java
package pl.polidea.treeview; /** * Exception thrown when there is a problem with configuring tree. * */ public class TreeConfigurationException extends RuntimeException { private static final long serialVersionUID = 1L; public TreeConfigurationException(final String detailMessage) { super(detailMessage); } }
Java
package pl.polidea.treeview; /** * The node being added is already in the tree. * */ public class NodeAlreadyInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeAlreadyInTreeException(final String id, final String oldNode) { super("The node has already been added to the tree: " + id + ". Old node is:" + oldNode); } }
Java
package pl.polidea.treeview; /** * Information about the node. * * @param <T> * type of the id for the tree */ public class TreeNodeInfo<T> { private final T id; private final int level; private final boolean withChildren; private final boolean visible; private final boolean expanded; /** * Creates the node information. * * @param id * id of the node * @param level * level of the node * @param withChildren * whether the node has children. * @param visible * whether the tree node is visible. * @param expanded * whether the tree node is expanded * */ public TreeNodeInfo(final T id, final int level, final boolean withChildren, final boolean visible, final boolean expanded) { super(); this.id = id; this.level = level; this.withChildren = withChildren; this.visible = visible; this.expanded = expanded; } public T getId() { return id; } public boolean isWithChildren() { return withChildren; } public boolean isVisible() { return visible; } public boolean isExpanded() { return expanded; } public int getLevel() { return level; } @Override public String toString() { return "TreeNodeInfo [id=" + id + ", level=" + level + ", withChildren=" + withChildren + ", visible=" + visible + ", expanded=" + expanded + "]"; } }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.List; import android.database.DataSetObserver; /** * Manages information about state of the tree. It only keeps information about * tree elements, not the elements themselves. * * @param <T> * type of the identifier for nodes in the tree */ public interface TreeStateManager<T> extends Serializable { /** * Returns array of integers showing the location of the node in hierarchy. * It corresponds to heading numbering. {0,0,0} in 3 level node is the first * node {0,0,1} is second leaf (assuming that there are two leaves in first * subnode of the first node). * * @param id * id of the node * @return textual description of the hierarchy in tree for the node. */ Integer[] getHierarchyDescription(T id); /** * Returns level of the node. * * @param id * id of the node * @return level in the tree */ int getLevel(T id); /** * Returns information about the node. * * @param id * node id * @return node info */ TreeNodeInfo<T> getNodeInfo(T id); /** * Returns children of the node. * * @param id * id of the node or null if asking for top nodes * @return children of the node */ List<T> getChildren(T id); /** * Returns parent of the node. * * @param id * id of the node * @return parent id or null if no parent */ T getParent(T id); /** * Adds the node before child or at the beginning. * * @param parent * id of the parent node. If null - adds at the top level * @param newChild * new child to add if null - adds at the beginning. * @param beforeChild * child before which to add the new child */ void addBeforeChild(T parent, T newChild, T beforeChild); /** * Adds the node after child or at the end. * * @param parent * id of the parent node. If null - adds at the top level. * @param newChild * new child to add. If null - adds at the end. * @param afterChild * child after which to add the new child */ void addAfterChild(T parent, T newChild, T afterChild); /** * Removes the node and all children from the tree. * * @param id * id of the node to remove or null if all nodes are to be * removed. */ void removeNodeRecursively(T id); /** * Expands all children of the node. * * @param id * node which children should be expanded. cannot be null (top * nodes are always expanded!). */ void expandDirectChildren(T id); /** * Expands everything below the node specified. Might be null - then expands * all. * * @param id * node which children should be expanded or null if all nodes * are to be expanded. */ void expandEverythingBelow(T id); /** * Collapse children. * * @param id * id collapses everything below node specified. If null, * collapses everything but top-level nodes. */ void collapseChildren(T id); /** * Returns next sibling of the node (or null if no further sibling). * * @param id * node id * @return the sibling (or null if no next) */ T getNextSibling(T id); /** * Returns previous sibling of the node (or null if no previous sibling). * * @param id * node id * @return the sibling (or null if no previous) */ T getPreviousSibling(T id); /** * Checks if given node is already in tree. * * @param id * id of the node * @return true if node is already in tree. */ boolean isInTree(T id); /** * Count visible elements. * * @return number of currently visible elements. */ int getVisibleCount(); /** * Returns visible node list. * * @return return the list of all visible nodes in the right sequence */ List<T> getVisibleList(); /** * Registers observers with the manager. * * @param observer * observer */ void registerDataSetObserver(final DataSetObserver observer); /** * Unregisters observers with the manager. * * @param observer * observer */ void unregisterDataSetObserver(final DataSetObserver observer); /** * Cleans tree stored in manager. After this operation the tree is empty. * */ void clear(); /** * Refreshes views connected to the manager. */ void refresh(); }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * Node. It is package protected so that it cannot be used outside. * * @param <T> * type of the identifier used by the tree */ class InMemoryTreeNode<T> implements Serializable { private static final long serialVersionUID = 1L; private final T id; private final T parent; private final int level; private boolean visible = true; private final List<InMemoryTreeNode<T>> children = new LinkedList<InMemoryTreeNode<T>>(); private List<T> childIdListCache = null; public InMemoryTreeNode(final T id, final T parent, final int level, final boolean visible) { super(); this.id = id; this.parent = parent; this.level = level; this.visible = visible; } public int indexOf(final T id) { return getChildIdList().indexOf(id); } /** * Cache is built lasily only if needed. The cache is cleaned on any * structure change for that node!). * * @return list of ids of children */ public synchronized List<T> getChildIdList() { if (childIdListCache == null) { childIdListCache = new LinkedList<T>(); for (final InMemoryTreeNode<T> n : children) { childIdListCache.add(n.getId()); } } return childIdListCache; } public boolean isVisible() { return visible; } public void setVisible(final boolean visible) { this.visible = visible; } public int getChildrenListSize() { return children.size(); } public synchronized InMemoryTreeNode<T> add(final int index, final T child, final boolean visible) { childIdListCache = null; // Note! top levell children are always visible (!) final InMemoryTreeNode<T> newNode = new InMemoryTreeNode<T>(child, getId(), getLevel() + 1, getId() == null ? true : visible); children.add(index, newNode); return newNode; } /** * Note. This method should technically return unmodifiable collection, but * for performance reason on small devices we do not do it. * * @return children list */ public List<InMemoryTreeNode<T>> getChildren() { return children; } public synchronized void clearChildren() { children.clear(); childIdListCache = null; } public synchronized void removeChild(final T child) { final int childIndex = indexOf(child); if (childIndex != -1) { children.remove(childIndex); childIdListCache = null; } } @Override public String toString() { return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent() + ", level=" + getLevel() + ", visible=" + visible + ", children=" + children + ", childIdListCache=" + childIdListCache + "]"; } T getId() { return id; } T getParent() { return parent; } int getLevel() { return level; } }
Java
package pl.polidea.treeview; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import android.database.DataSetObserver; /** * In-memory manager of tree state. * * @param <T> * type of identifier */ public class InMemoryTreeStateManager<T> implements TreeStateManager<T> { private static final long serialVersionUID = 1L; private final Map<T, InMemoryTreeNode<T>> allNodes = new HashMap<T, InMemoryTreeNode<T>>(); private final InMemoryTreeNode<T> topSentinel = new InMemoryTreeNode<T>( null, null, -1, true); private transient List<T> visibleListCache = null; // lasy initialised private transient List<T> unmodifiableVisibleList = null; private boolean visibleByDefault = true; private final transient Set<DataSetObserver> observers = new HashSet<DataSetObserver>(); private synchronized void internalDataSetChanged() { visibleListCache = null; unmodifiableVisibleList = null; for (final DataSetObserver observer : observers) { observer.onChanged(); } } /** * If true new nodes are visible by default. * * @param visibleByDefault * if true, then newly added nodes are expanded by default */ public void setVisibleByDefault(final boolean visibleByDefault) { this.visibleByDefault = visibleByDefault; } private InMemoryTreeNode<T> getNodeFromTreeOrThrow(final T id) { if (id == null) { throw new NodeNotInTreeException("(null)"); } final InMemoryTreeNode<T> node = allNodes.get(id); if (node == null) { throw new NodeNotInTreeException(id.toString()); } return node; } private InMemoryTreeNode<T> getNodeFromTreeOrThrowAllowRoot(final T id) { if (id == null) { return topSentinel; } return getNodeFromTreeOrThrow(id); } private void expectNodeNotInTreeYet(final T id) { final InMemoryTreeNode<T> node = allNodes.get(id); if (node != null) { throw new NodeAlreadyInTreeException(id.toString(), node.toString()); } } @Override public synchronized TreeNodeInfo<T> getNodeInfo(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrow(id); final List<InMemoryTreeNode<T>> children = node.getChildren(); boolean expanded = false; if (!children.isEmpty() && children.get(0).isVisible()) { expanded = true; } return new TreeNodeInfo<T>(id, node.getLevel(), !children.isEmpty(), node.isVisible(), expanded); } @Override public synchronized List<T> getChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getChildIdList(); } @Override public synchronized T getParent(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getParent(); } private boolean getChildrenVisibility(final InMemoryTreeNode<T> node) { boolean visibility; final List<InMemoryTreeNode<T>> children = node.getChildren(); if (children.isEmpty()) { visibility = visibleByDefault; } else { visibility = children.get(0).isVisible(); } return visibility; } @Override public synchronized void addBeforeChild(final T parent, final T newChild, final T beforeChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); // top nodes are always expanded. if (beforeChild == null) { final InMemoryTreeNode<T> added = node.add(0, newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(beforeChild); final InMemoryTreeNode<T> added = node.add(index == -1 ? 0 : index, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void addAfterChild(final T parent, final T newChild, final T afterChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); if (afterChild == null) { final InMemoryTreeNode<T> added = node.add( node.getChildrenListSize(), newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(afterChild); final InMemoryTreeNode<T> added = node.add( index == -1 ? node.getChildrenListSize() : index, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void removeNodeRecursively(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); final boolean visibleNodeChanged = removeNodeRecursively(node); final T parent = node.getParent(); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); parentNode.removeChild(id); if (visibleNodeChanged) { internalDataSetChanged(); } } private boolean removeNodeRecursively(final InMemoryTreeNode<T> node) { boolean visibleNodeChanged = false; for (final InMemoryTreeNode<T> child : node.getChildren()) { if (removeNodeRecursively(child)) { visibleNodeChanged = true; } } node.clearChildren(); if (node.getId() != null) { allNodes.remove(node.getId()); if (node.isVisible()) { visibleNodeChanged = true; } } return visibleNodeChanged; } private void setChildrenVisibility(final InMemoryTreeNode<T> node, final boolean visible, final boolean recursive) { for (final InMemoryTreeNode<T> child : node.getChildren()) { child.setVisible(visible); if (recursive) { setChildrenVisibility(child, visible, true); } } } @Override public synchronized void expandDirectChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, false); internalDataSetChanged(); } @Override public synchronized void expandEverythingBelow(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, true); internalDataSetChanged(); } @Override public synchronized void collapseChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (node == topSentinel) { for (final InMemoryTreeNode<T> n : topSentinel.getChildren()) { setChildrenVisibility(n, false, true); } } else { setChildrenVisibility(node, false, true); } internalDataSetChanged(); } @Override public synchronized T getNextSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); boolean returnNext = false; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (returnNext) { return child.getId(); } if (child.getId().equals(id)) { returnNext = true; } } return null; } @Override public synchronized T getPreviousSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); final T previousSibling = null; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (child.getId().equals(id)) { return previousSibling; } } return null; } @Override public synchronized boolean isInTree(final T id) { return allNodes.containsKey(id); } @Override public synchronized int getVisibleCount() { return getVisibleList().size(); } @Override public synchronized List<T> getVisibleList() { T currentId = null; if (visibleListCache == null) { visibleListCache = new ArrayList<T>(allNodes.size()); do { currentId = getNextVisible(currentId); if (currentId == null) { break; } else { visibleListCache.add(currentId); } } while (true); } if (unmodifiableVisibleList == null) { unmodifiableVisibleList = Collections .unmodifiableList(visibleListCache); } return unmodifiableVisibleList; } public synchronized T getNextVisible(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (!node.isVisible()) { return null; } final List<InMemoryTreeNode<T>> children = node.getChildren(); if (!children.isEmpty()) { final InMemoryTreeNode<T> firstChild = children.get(0); if (firstChild.isVisible()) { return firstChild.getId(); } } final T sibl = getNextSibling(id); if (sibl != null) { return sibl; } T parent = node.getParent(); do { if (parent == null) { return null; } final T parentSibling = getNextSibling(parent); if (parentSibling != null) { return parentSibling; } parent = getNodeFromTreeOrThrow(parent).getParent(); } while (true); } @Override public synchronized void registerDataSetObserver( final DataSetObserver observer) { observers.add(observer); } @Override public synchronized void unregisterDataSetObserver( final DataSetObserver observer) { observers.remove(observer); } @Override public int getLevel(final T id) { return getNodeFromTreeOrThrow(id).getLevel(); } @Override public Integer[] getHierarchyDescription(final T id) { final int level = getLevel(id); final Integer[] hierarchy = new Integer[level + 1]; int currentLevel = level; T currentId = id; T parent = getParent(currentId); while (currentLevel >= 0) { hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId); currentId = parent; parent = getParent(parent); } return hierarchy; } private void appendToSb(final StringBuilder sb, final T id) { if (id != null) { final TreeNodeInfo<T> node = getNodeInfo(id); final int indent = node.getLevel() * 4; final char[] indentString = new char[indent]; Arrays.fill(indentString, ' '); sb.append(indentString); sb.append(node.toString()); sb.append(Arrays.asList(getHierarchyDescription(id)).toString()); sb.append("\n"); } final List<T> children = getChildren(id); for (final T child : children) { appendToSb(sb, child); } } @Override public synchronized String toString() { final StringBuilder sb = new StringBuilder(); appendToSb(sb, null); return sb.toString(); } @Override public synchronized void clear() { allNodes.clear(); topSentinel.clearChildren(); internalDataSetChanged(); } @Override public void refresh() { internalDataSetChanged(); } }
Java
package pl.polidea.treeview.demo; import java.util.Arrays; import java.util.Set; import pl.polidea.treeview.AbstractTreeViewAdapter; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.TextView; /** * This is a very simple adapter that provides very basic tree view with a * checkboxes and simple item description. * */ class SimpleStandardAdapter extends AbstractTreeViewAdapter<Long> { private final Set<Long> selected; private final OnCheckedChangeListener onCheckedChange = new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { final Long id = (Long) buttonView.getTag(); changeSelected(isChecked, id); } }; private void changeSelected(final boolean isChecked, final Long id) { if (isChecked) { selected.add(id); } else { selected.remove(id); } } public SimpleStandardAdapter(final TreeViewListDemo treeViewListDemo, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(treeViewListDemo, treeStateManager, numberOfLevels); this.selected = selected; } private String getDescription(final long id) { final Integer[] hierarchy = getManager().getHierarchyDescription(id); return "Node " + id + Arrays.asList(hierarchy); } @Override public View getNewChildView(final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) getActivity() .getLayoutInflater().inflate(R.layout.demo_list_item, null); return updateView(viewLayout, treeNodeInfo); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) view; final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setText(getDescription(treeNodeInfo.getId())); levelView.setText(Integer.toString(treeNodeInfo.getLevel())); final CheckBox box = (CheckBox) viewLayout .findViewById(R.id.demo_list_checkbox); box.setTag(treeNodeInfo.getId()); if (treeNodeInfo.isWithChildren()) { box.setVisibility(View.GONE); } else { box.setVisibility(View.VISIBLE); box.setChecked(selected.contains(treeNodeInfo.getId())); } box.setOnCheckedChangeListener(onCheckedChange); return viewLayout; } @Override public void handleItemClick(final View view, final Object id) { final Long longId = (Long) id; final TreeNodeInfo<Long> info = getManager().getNodeInfo(longId); if (info.isWithChildren()) { super.handleItemClick(view, id); } else { final ViewGroup vg = (ViewGroup) view; final CheckBox cb = (CheckBox) vg .findViewById(R.id.demo_list_checkbox); cb.performClick(); } } @Override public long getItemId(final int position) { return getTreeId(position); } }
Java
package pl.polidea.treeview.demo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import pl.polidea.treeview.InMemoryTreeStateManager; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeBuilder; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import pl.polidea.treeview.TreeViewList; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; /** * Demo activity showing how the tree view can be used. * */ public class TreeViewListDemo extends Activity { private enum TreeType implements Serializable { SIMPLE, FANCY } private final Set<Long> selected = new HashSet<Long>(); private static final String TAG = TreeViewListDemo.class.getSimpleName(); private TreeViewList treeView; private static final int[] DEMO_NODES = new int[] { 0, 0, 1, 1, 1, 2, 2, 1, 1, 2, 1, 0, 0, 0, 1, 2, 3, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1 }; private static final int LEVEL_NUMBER = 4; private TreeStateManager<Long> manager = null; private FancyColouredVariousSizesAdapter fancyAdapter; private SimpleStandardAdapter simpleAdapter; private TreeType treeType; private boolean collapsible; @SuppressWarnings("unchecked") @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); TreeType newTreeType = null; boolean newCollapsible; if (savedInstanceState == null) { manager = new InMemoryTreeStateManager<Long>(); final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager); for (int i = 0; i < DEMO_NODES.length; i++) { treeBuilder.sequentiallyAddNextNode((long) i, DEMO_NODES[i]); } Log.d(TAG, manager.toString()); newTreeType = TreeType.SIMPLE; newCollapsible = true; } else { manager = (TreeStateManager<Long>) savedInstanceState .getSerializable("treeManager"); newTreeType = (TreeType) savedInstanceState .getSerializable("treeType"); newCollapsible = savedInstanceState.getBoolean("collapsible"); } setContentView(R.layout.main_demo); treeView = (TreeViewList) findViewById(R.id.mainTreeView); fancyAdapter = new FancyColouredVariousSizesAdapter(this, selected, manager, LEVEL_NUMBER); simpleAdapter = new SimpleStandardAdapter(this, selected, manager, LEVEL_NUMBER); setTreeAdapter(newTreeType); setCollapsible(newCollapsible); registerForContextMenu(treeView); } @Override protected void onSaveInstanceState(final Bundle outState) { outState.putSerializable("treeManager", manager); outState.putSerializable("treeType", treeType); outState.putBoolean("collapsible", this.collapsible); super.onSaveInstanceState(outState); } protected final void setTreeAdapter(final TreeType newTreeType) { this.treeType = newTreeType; switch (newTreeType) { case SIMPLE: treeView.setAdapter(simpleAdapter); break; case FANCY: treeView.setAdapter(fancyAdapter); break; default: treeView.setAdapter(simpleAdapter); } } protected final void setCollapsible(final boolean newCollapsible) { this.collapsible = newCollapsible; treeView.setCollapsible(this.collapsible); } @Override public boolean onCreateOptionsMenu(final Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { final MenuItem collapsibleMenu = menu .findItem(R.id.collapsible_menu_item); if (collapsible) { collapsibleMenu.setTitle(R.string.collapsible_menu_disable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_disable)); } else { collapsibleMenu.setTitle(R.string.collapsible_menu_enable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_enable)); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == R.id.simple_menu_item) { setTreeAdapter(TreeType.SIMPLE); } else if (item.getItemId() == R.id.fancy_menu_item) { setTreeAdapter(TreeType.FANCY); } else if (item.getItemId() == R.id.collapsible_menu_item) { setCollapsible(!this.collapsible); } else if (item.getItemId() == R.id.expand_all_menu_item) { manager.expandEverythingBelow(null); } else if (item.getItemId() == R.id.collapse_all_menu_item) { manager.collapseChildren(null); } else { return false; } return true; } @Override public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { final AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo; final long id = adapterInfo.id; final TreeNodeInfo<Long> info = manager.getNodeInfo(id); final MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.context_menu, menu); if (info.isWithChildren()) { if (info.isExpanded()) { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); } else { menu.findItem(R.id.context_menu_collapse).setVisible(false); } } else { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); menu.findItem(R.id.context_menu_collapse).setVisible(false); } super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(final MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); final long id = info.id; if (item.getItemId() == R.id.context_menu_collapse) { manager.collapseChildren(id); return true; } else if (item.getItemId() == R.id.context_menu_expand_all) { manager.expandEverythingBelow(id); return true; } else if (item.getItemId() == R.id.context_menu_expand_item) { manager.expandDirectChildren(id); return true; } else if (item.getItemId() == R.id.context_menu_delete) { manager.removeNodeRecursively(id); return true; } else { return super.onContextItemSelected(item); } } }
Java
/** * Provides just demo of the TreeView widget. */ package pl.polidea.treeview.demo;
Java
package pl.polidea.treeview.demo; import java.util.Set; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; final class FancyColouredVariousSizesAdapter extends SimpleStandardAdapter { public FancyColouredVariousSizesAdapter(final TreeViewListDemo activity, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(activity, selected, treeStateManager, numberOfLevels); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = super.updateView(view, treeNodeInfo); final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); levelView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); return viewLayout; } @Override public Drawable getBackgroundDrawable(final TreeNodeInfo<Long> treeNodeInfo) { switch (treeNodeInfo.getLevel()) { case 0: return new ColorDrawable(Color.WHITE); case 1: return new ColorDrawable(Color.GRAY); case 2: return new ColorDrawable(Color.YELLOW); default: return null; } } }
Java
/*___Generated_by_IDEA___*/ package com.birdorg.anpr.sdk.simple.camera.example; /* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */ public final class Manifest { }
Java
/*___Generated_by_IDEA___*/ package com.birdorg.anpr.sdk.simple.camera.example; /* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */ public final class BuildConfig { public final static boolean DEBUG = Boolean.parseBoolean(null); }
Java
package com.example.mymodule.app; public class ftp4j { }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * This interface describes how to build objects used to intercept any * communication between the client and the server. It is useful to catch what * happens behind. A FTPCommunicationListener can be added to any FTPClient * object by calling its addCommunicationListener() method. * * @author Carlo Pelliccia * @see FTPClient#addCommunicationListener(it.sauronsoftware.ftp4j.FTPCommunicationListener) */ public interface FTPCommunicationListener { /** * Called every time a telnet statement has been sent over the network to * the remote FTP server. * * @param statement * The statement that has been sent. */ public void sent(String statement); /** * Called every time a telnet statement is received by the client. * * @param statement * The received statement. */ public void received(String statement); }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import java.util.Date; /** * The instances of this class represents the files in a remote FTP directory. * * @author Carlo Pelliccia */ public class FTPFile { /** * The value for the type "file". */ public static final int TYPE_FILE = 0; /** * The value for the type "directory". */ public static final int TYPE_DIRECTORY = 1; /** * The value for the type "link". */ public static final int TYPE_LINK = 2; /** * The name of the file. */ private String name = null; /** * The path of the linked file, if this one is a link. */ private String link = null; /** * The last modified date of the file. */ private Date modifiedDate = null; /** * The size of the file (bytes). */ private long size = -1; /** * The type of the entry represented. It must be {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_FILE}, * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_DIRECTORY} or {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_LINK}. */ private int type; /** * Returns the last modified date of the file. Pay attention: it could be * null if the information is not supplied by the server. * * @return The last modified date of the file, or null if the information is * not supplied. */ public Date getModifiedDate() { return modifiedDate; } /** * Sets the last modified date of the file. * * @param modifiedDate * The last modified date of the file. */ public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } /** * Returns the name of the file. * * @return The name of the file. */ public String getName() { return name; } /** * Sets the name of the file. * * @param name * The name of the file. */ public void setName(String name) { this.name = name; } /** * Returns the type of the entry represented. It must be * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_FILE}, {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_DIRECTORY} or * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_LINK}. * * @return The type of the entry represented. It must be * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_FILE}, {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_DIRECTORY} or * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_LINK}. */ public int getType() { return type; } /** * Sets the type of the entry represented. It can be * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_FILE}, {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_DIRECTORY} or * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_LINK}. * * @param type * The type of the entry represented. It can be * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_FILE}, {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_DIRECTORY} or * {@link it.sauronsoftware.ftp4j.FTPFile#TYPE_LINK}. */ public void setType(int type) { this.type = type; } /** * Returns the size of the file (bytes). A negative value is returned if the * information is not available. * * @return The size of the file (bytes). A negative value is returned if the * information is not available. */ public long getSize() { return size; } /** * Sets the size of the file (bytes). * * @param size * The size of the file (bytes). */ public void setSize(long size) { this.size = size; } /** * This method returns the path of the linked file, if this one is a link. * If this is not a link, or if the information is not available, it returns * null. * * @return The path of the linked file, if this one is a link. If this is * not a link, or if the information is not available, it returns * null. */ public String getLink() { return link; } /** * This method sets the path of the linked file, if this one is a link. * * @param link * The path of the linked file, if this one is a link. */ public void setLink(String link) { this.link = link; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()); buffer.append(" [name="); buffer.append(name); buffer.append(", type="); if (type == TYPE_FILE) { buffer.append("FILE"); } else if (type == TYPE_DIRECTORY) { buffer.append("DIRECTORY"); } else if (type == TYPE_LINK) { buffer.append("LINK"); buffer.append(", link="); buffer.append(link); } else { buffer.append("UNKNOWN"); } buffer.append(", size="); buffer.append(size); buffer.append(", modifiedDate="); buffer.append(modifiedDate); buffer.append("]"); return buffer.toString(); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * This interface describes how to implement a textual extension recognizer, * which can be plugged into a FTPClient object calling its * setTextualExtensionsRecognizer() method. * * @author Carlo Pelliccia * @see FTPClient#setTextualExtensionRecognizer(it.sauronsoftware.ftp4j.FTPTextualExtensionRecognizer) */ public interface FTPTextualExtensionRecognizer { /** * This method returns true if the given file extension is recognized to be * a textual one. * * @param ext * The file extension, always in lower-case. * @return true if the given file extension is recognized to be a textual * one. */ public boolean isTextualExt(String ext); }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * Static property keys used by the library. * * @author Carlo Pelliccia * @since 1.3 */ interface FTPKeys { /** * The key used to retrieve the system property with the port range for * active data transfers. The value has to be in the * <em>startPort-endPort</em> form. */ public String ACTIVE_DT_PORT_RANGE = "ftp4j.activeDataTransfer.portRange"; /** * The key used to retrieve the system property with the host IPv4 address * for active data transfers. The value has to be in the <em>x.x.x.x</em> * form. */ public String ACTIVE_DT_HOST_ADDRESS = "ftp4j.activeDataTransfer.hostAddress"; /** * The key used to retrieve the system property with the accept timeout for * active data transfars. The value should be ms. Default value is 30000. A * 0 value stands for infinite. */ public String ACTIVE_DT_ACCEPT_TIMEOUT = "ftp4j.activeDataTransfer.acceptTimeout"; /** * The key used to retrieve the system property that can force the client to * exchange data by connecting to the IP address suggested by the server * after a PASV command. To avoid frequently reported NAT problems, ftp4j * connects always to the host supplied in the * {@link FTPClient#connect(String)} or * {@link FTPClient#connect(String, int)} methods. The response of a PASV * command is used only to decode the port for the connection. By using the * value &quot;true&quot;, &quot;yes&quot; or &quot;1&quot; on this system * property, ftp4j will change its behaviour and it will connect to the IP * address returned from the server. * * @since 1.5 */ public String PASSIVE_DT_USE_SUGGESTED_ADDRESS = "ftp4j.passiveDataTransfer.useSuggestedAddress"; }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.extrecognizers; import java.util.ArrayList; import it.sauronsoftware.ftp4j.FTPClient; import it.sauronsoftware.ftp4j.FTPTextualExtensionRecognizer; /** * A textual extension recognizer with parametric extensions, which can be added * or removed at runtime. * * @author Carlo Pelliccia * @see FTPClient#setTextualExtensionRecognizer(FTPTextualExtensionRecognizer) */ public class ParametricTextualExtensionRecognizer implements FTPTextualExtensionRecognizer { /** * Extension list. */ private ArrayList exts = new ArrayList(); /** * It builds the recognizer with an empty extension list. */ public ParametricTextualExtensionRecognizer() { ; } /** * It builds the recognizer with an initial extension list. * * @param exts * The initial extension list. */ public ParametricTextualExtensionRecognizer(String[] exts) { for (int i = 0; i < exts.length; i++) { addExtension(exts[i]); } } /** * It builds the recognizer with an initial extension list. * * @param exts * The initial extension list. */ public ParametricTextualExtensionRecognizer(ArrayList exts) { int size = exts.size(); for (int i = 0; i < size; i++) { Object aux = exts.get(i); if (aux instanceof String) { String ext = (String) aux; addExtension(ext); } } } /** * This method adds an extension to the recognizer. * * @param ext * The extension. */ public void addExtension(String ext) { synchronized (exts) { ext = ext.toLowerCase(); exts.add(ext); } } /** * This method removes an extension to the recognizer. * * @param ext * The extension to be removed. */ public void removeExtension(String ext) { synchronized (exts) { ext = ext.toLowerCase(); exts.remove(ext); } } /** * This method returns the recognized extension list. * * @return The list with all the extensions recognized to be for textual * files. */ public String[] getExtensions() { synchronized (exts) { int size = exts.size(); String[] ret = new String[size]; for (int i = 0; i < size; i++) { ret[i] = (String) exts.get(i); } return ret; } } public boolean isTextualExt(String ext) { synchronized (exts) { return exts.contains(ext); } } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.extrecognizers; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * <p> * This is the default FTPTextualExtensionRecognizer for every new FTPClient * object. It recognizes as textual these extensions: * </p> * * <pre> * abc acgi aip asm asp c c cc cc com conf cpp csh css cxx def el etx f f f77 * f90 f90 flx for for g h h hh hh hlb htc htm html htmls htt htx idc jav jav * java java js ksh list log lsp lst lsx m m mar mcf p pas php pl pl pm py rexx * rt rt rtf rtx s scm scm sdml sgm sgm sgml sgml sh shtml shtml spc ssi talk * tcl tcsh text tsv txt uil uni unis uri uris uu uue vcs wml wmls wsc xml zsh * </pre> * * <p> * These extensions are loaded from the file textualexts within the package. The * file can be manipulated to add or remove extensions, but it's more convenient * to plug a ParametricTextualExtensionRecognizer instance in the client. * </p> * * @author Carlo Pelliccia */ public class DefaultTextualExtensionRecognizer extends ParametricTextualExtensionRecognizer { /** * Lock object. */ private static final Object lock = new Object(); /** * The singleton instance. */ private static DefaultTextualExtensionRecognizer instance = null; /** * This one returns the default instance of the class. * * @return An instance of the class. */ public static DefaultTextualExtensionRecognizer getInstance() { synchronized (lock) { if (instance == null) { instance = new DefaultTextualExtensionRecognizer(); } } return instance; } /** * It builds the instance. */ private DefaultTextualExtensionRecognizer() { BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(getClass() .getResourceAsStream("textualexts"))); String line; while ((line = r.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { addExtension(st.nextToken()); } } } catch (Exception e) { ; } finally { if (r != null) { try { r.close(); } catch (Throwable t) { ; } } } } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * This exception is thrown to announce the abort of a ongoing data transfer * operation. * * @author Carlo Pelliccia */ public class FTPAbortedException extends Exception { private static final long serialVersionUID = 1L; }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import javax.net.ssl.SSLSocketFactory; /** * This class is used to represent a communication channel with a FTP server. * * @author Carlo Pelliccia * @version 1.1 */ public class FTPCommunicationChannel { /** * The FTPCommunicationListener objects registered on the channel. */ private ArrayList communicationListeners = new ArrayList(); /** * The connection. */ private Socket connection = null; /** * The name of the charset that has to be used to encode and decode the * communication. */ private String charsetName = null; /** * The stream-reader channel established with the remote server. */ private NVTASCIIReader reader = null; /** * The stream-writer channel established with the remote server. */ private NVTASCIIWriter writer = null; /** * It builds a FTP communication channel. * * @param connection * The underlying connection. * @param charsetName * The name of the charset that has to be used to encode and * decode the communication. * @throws java.io.IOException * If a I/O error occurs. */ public FTPCommunicationChannel(Socket connection, String charsetName) throws IOException { this.connection = connection; this.charsetName = charsetName; InputStream inStream = connection.getInputStream(); OutputStream outStream = connection.getOutputStream(); // Wrap the streams into reader and writer objects. reader = new NVTASCIIReader(inStream, charsetName); writer = new NVTASCIIWriter(outStream, charsetName); } /** * This method adds a FTPCommunicationListener to the object. * * @param listener * The listener. */ public void addCommunicationListener(FTPCommunicationListener listener) { communicationListeners.add(listener); } /** * This method removes a FTPCommunicationListener previously added to the * object. * * @param listener * The listener to be removed. */ public void removeCommunicationListener(FTPCommunicationListener listener) { communicationListeners.remove(listener); } /** * Closes the channel. */ public void close() { try { connection.close(); } catch (Exception e) { ; } } /** * This method returns a list with all the FTPCommunicationListener used by * the client. * * @return A list with all the FTPCommunicationListener used by the client. */ public FTPCommunicationListener[] getCommunicationListeners() { int size = communicationListeners.size(); FTPCommunicationListener[] ret = new FTPCommunicationListener[size]; for (int i = 0; i < size; i++) { ret[i] = (FTPCommunicationListener) communicationListeners.get(i); } return ret; } /** * This method reads a line from the remote server. * * @return The string read. * @throws java.io.IOException * If an I/O error occurs during the operation. */ private String read() throws IOException { // Read the line from the server. String line = reader.readLine(); if (line == null) { throw new IOException("FTPConnection closed"); } // Call received() method on every communication listener // registered. for (Iterator iter = communicationListeners.iterator(); iter.hasNext();) { FTPCommunicationListener l = (FTPCommunicationListener) iter.next(); l.received(line); } // Return the line read. return line; } /** * This method sends a command line to the server. * * @param command * The command to be sent. * @throws java.io.IOException * If an I/O error occurs. */ public void sendFTPCommand(String command) throws IOException { writer.writeLine(command); for (Iterator iter = communicationListeners.iterator(); iter.hasNext();) { FTPCommunicationListener l = (FTPCommunicationListener) iter.next(); l.sent(command); } } /** * This method reads and parses a FTP reply statement from the server. * * @return The reply from the server. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server doesn't reply in a FTP-compliant way. */ public FTPReply readFTPReply() throws IOException, FTPIllegalReplyException { int code = 0; ArrayList messages = new ArrayList(); do { String statement; do { statement = read(); } while (statement.trim().length() == 0); if (statement.startsWith("\n")) { statement = statement.substring(1); } int l = statement.length(); if (code == 0 && l < 3) { throw new FTPIllegalReplyException(); } int aux; try { aux = Integer.parseInt(statement.substring(0, 3)); } catch (Exception e) { if (code == 0) { throw new FTPIllegalReplyException(); } else { aux = 0; } } if (code != 0 && aux != 0 && aux != code) { throw new FTPIllegalReplyException(); } if (code == 0) { code = aux; } if (aux > 0) { if (l > 3) { char s = statement.charAt(3); String message = statement.substring(4, l); messages.add(message); if (s == ' ') { break; } else if (s == '-') { continue; } else { throw new FTPIllegalReplyException(); } } else if (l == 3) { break; } else { messages.add(statement); } } else { messages.add(statement); } } while (true); int size = messages.size(); String[] m = new String[size]; for (int i = 0; i < size; i++) { m[i] = (String) messages.get(i); } return new FTPReply(code, m); } /** * Changes the current charset. * * @param charsetName * The new charset. * @throws java.io.IOException * If I/O error occurs. * @since 1.1 */ public void changeCharset(String charsetName) throws IOException { this.charsetName = charsetName; reader.changeCharset(charsetName); writer.changeCharset(charsetName); } /** * Applies SSL encryption to the communication channel. * * @param sslSocketFactory * The SSLSocketFactory used to produce the SSL connection. * @throws java.io.IOException * If a I/O error occurs. * @since 1.4 */ public void ssl(SSLSocketFactory sslSocketFactory) throws IOException { String host = connection.getInetAddress().getHostName(); int port = connection.getPort(); connection = sslSocketFactory.createSocket(connection, host, port, true); InputStream inStream = connection.getInputStream(); OutputStream outStream = connection.getOutputStream(); reader = new NVTASCIIReader(inStream, charsetName); writer = new NVTASCIIWriter(outStream, charsetName); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import java.net.Socket; /** * A package reserved {@link FTPConnection} provider, used internally by the * client to obtain connections for data transfer purposes. * * @author cpelliccia * */ interface FTPDataTransferConnectionProvider { /** * Returns the connection. * * @return The connection. * @throws FTPException * If an unexpected error occurs. */ public Socket openDataTransferConnection() throws FTPDataTransferException; /** * Terminates the provider. */ public void dispose(); }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; /** * This is an NVT-ASCII character stream reader. * * @author Carlo Pelliccia * @version 1.1 */ class NVTASCIIReader extends Reader { /** * This system line separator chars sequence. */ private static final String SYSTEM_LINE_SEPARATOR = System .getProperty("line.separator"); /** * The wrapped stream. */ private InputStream stream; /** * The underlying reader. */ private Reader reader; /** * Builds the reader. * * @param stream * The underlying stream. * @param charsetName * The name of a supported charset. * @throws java.io.IOException * If an I/O error occurs. */ public NVTASCIIReader(InputStream stream, String charsetName) throws IOException { this.stream = stream; reader = new InputStreamReader(stream, charsetName); } public void close() throws IOException { synchronized (this) { reader.close(); } } public int read(char[] cbuf, int off, int len) throws IOException { synchronized (this) { return reader.read(cbuf, off, len); } } /** * Changes the current charset. * * @param charsetName * The new charset. * @throws java.io.IOException * If I/O error occurs. * @since 1.1 */ public void changeCharset(String charsetName) throws IOException { synchronized (this) { reader = new InputStreamReader(stream, charsetName); } } /** * Reads a line from the stream. * * @return The line read, or null if the end of the stream is reached. * @throws java.io.IOException * If an I/O error occurs. */ public String readLine() throws IOException { StringBuffer buffer = new StringBuffer(); int previous = -1; int current = -1; do { int i = reader.read(); if (i == -1) { if (buffer.length() == 0) { return null; } else { return buffer.toString(); } } previous = current; current = i; if (/* previous == '\r' && */current == '\n') { // End of line. return buffer.toString(); } else if (previous == '\r' && current == 0) { // Literal new line. buffer.append(SYSTEM_LINE_SEPARATOR); } else if (current != 0 && current != '\r') { buffer.append((char) current); } } while (true); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * Exception thrown every time the remote FTP server replies to the client in an * unexpected way, breaking the rules of the FTP protocol. * * @author Carlo Pelliccia */ public class FTPIllegalReplyException extends Exception { private static final long serialVersionUID = 1L; }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * This class helps in represent FTP error codes and messages. * * @author Carlo Pelliccia */ public class FTPException extends Exception { private static final long serialVersionUID = 1L; private int code; private String message; public FTPException(int code) { this.code = code; } public FTPException(int code, String message) { this.code = code; this.message = message; } public FTPException(FTPReply reply) { StringBuffer message = new StringBuffer(); String[] lines = reply.getMessages(); for (int i = 0; i < lines.length; i++) { if (i > 0) { message.append(System.getProperty("line.separator")); } message.append(lines[i]); } this.code = reply.getCode(); this.message = message.toString(); } /** * Returns the code of the occurred FTP error. * * @return The code of the occurred FTP error. */ public int getCode() { return code; } /** * Returns the message of the occurred FTP error. * * @return The message of the occurred FTP error. */ public String getMessage() { return message; } public String toString() { return getClass().getName() + " [code=" + code + ", message= " + message + "]"; } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * Exception thrown by the list() method in FTPClient objects when the response * sent by the server to a FTP list command is not parseable through the known * parsers. * * @author Carlo Pelliccia * */ public class FTPListParseException extends Exception { private static final long serialVersionUID = 1L; }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * This interface describes the methods requested by an object that can listen * data transfer operations. You can supply an object implementing this * interface to any upload/download method of the client. * * @author Carlo Pelliccia */ public interface FTPDataTransferListener { /** * Called to notify the listener that the transfer operation has been * initialized. */ public void started(); /** * Called to notify the listener that some bytes have been transmitted. * * @param length * The number of the bytes transmitted since the last time the * method was called (or since the begin of the operation, at the * first call received). */ public void transferred(int length); /** * Called to notify the listener that the transfer operation has been * successfully complete. */ public void completed(); /** * Called to notify the listener that the transfer operation has been * aborted. */ public void aborted(); /** * Called to notify the listener that the transfer operation has failed due * to an error. */ public void failed(); }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * This interface is a constants container, each one representing a common FTP * response code. * * @author Carlo Pelliccia */ public interface FTPCodes { public int SYNTAX_ERROR = 500; public int SYNTAX_ERROR_IN_PARAMETERS = 501; public int COMMAND_NOT_IMPLEMENTED = 502; public int BAD_SEQUENCE_OF_COMMANDS = 503; public int COMMAND_PARAMETER_NOT_IMPLEMENTED = 504; public int NOT_LOGGED_IN = 530; public int FILE_NOT_FOUND = 550; public int PAGE_TYPE_UNKNOWN = 551; public int EXCEEDED_STORAGE_ALLOCATION = 552; public int FILE_NAME_NOT_ALLOWED = 553; public int SERVICE_NOT_AVAILABLE = 421; public int CANNOT_OPEN_DATA_CONNECTION = 425; public int CONNECTION_CLOSED = 426; public int FILE_ACTION_NOT_TAKEN = 450; public int LOCAL_ERROR_IN_PROCESSING = 451; public int FILE_UNAVAILABLE = 452; public int USERNAME_OK = 331; public int NEED_ACCOUNT = 332; public int PENDING_FURTHER_INFORMATION = 350; public int COMMAND_OK = 200; public int SUPERFLOUS_COMMAND = 202; public int STATUS_MESSAGE = 211; public int DIRECTORY_STATUS = 212; public int FILE_STATUS = 213; public int HELP_MESSAGE = 214; public int NAME_SYSTEM_TIME = 215; public int SERVICE_READY_FOR_NEW_USER = 220; public int SERVICE_CLOSING_CONTROL_CONNECTION = 221; public int DATA_CONNECTION_OPEN = 225; public int DATA_CONNECTION_CLOSING = 226; public int ENTER_PASSIVE_MODE = 227; public int USER_LOGGED_IN = 230; public int FILE_ACTION_COMPLETED = 250; public int PATHNAME_CREATED = 257; public int RESTART_MARKER = 110; public int SERVICE_NOT_READY = 120; public int DATA_CONNECTION_ALREADY_OPEN = 125; public int FILE_STATUS_OK = 150; }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import it.sauronsoftware.ftp4j.FTPConnector; import java.io.IOException; import java.net.Socket; /** * The DirectConnector connects the remote host with a straight socket * connection, using no proxy. * * The connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag is <em>false</em>. * * @author Carlo Pelliccia */ public class DirectConnector extends FTPConnector { public Socket connectForCommunicationChannel(String host, int port) throws IOException { return tcpConnectForCommunicationChannel(host, port); } public Socket connectForDataTransferChannel(String host, int port) throws IOException { return tcpConnectForDataTransferChannel(host, port); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import it.sauronsoftware.ftp4j.FTPConnector; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; /** * This one connects a remote ftp host via a HTTP 1.1 proxy which allows * tunneling through the HTTP CONNECT method. * * The connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag is <em>false</em>. * * @author Carlo Pelliccia */ public class HTTPTunnelConnector extends FTPConnector { /** * The proxy host name. */ private String proxyHost; /** * The proxy port. */ private int proxyPort; /** * The proxyUser for proxy authentication. */ private String proxyUser; /** * The proxyPass for proxy authentication. */ private String proxyPass; /** * Builds the connector. * * @param proxyHost * The proxy host name. * @param proxyPort * The proxy port. * @param proxyUser * The username for proxy authentication. * @param proxyPass * The password for proxy authentication. */ public HTTPTunnelConnector(String proxyHost, int proxyPort, String proxyUser, String proxyPass) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.proxyUser = proxyUser; this.proxyPass = proxyPass; } /** * Builds the connector. * * @param proxyHost * The proxy host name. * @param proxyPort * The proxy port. */ public HTTPTunnelConnector(String proxyHost, int proxyPort) { this(proxyHost, proxyPort, null, null); } private Socket httpConnect(String host, int port, boolean forDataTransfer) throws IOException { // The CRLF sequence. byte[] CRLF = "\r\n".getBytes("UTF-8"); // The connect command line. String connect = "CONNECT " + host + ":" + port + " HTTP/1.1"; String hostHeader = "Host: " + host + ":" + port; // A connection status flag. boolean connected = false; // The socket for the connection with the proxy. Socket socket = null; InputStream in = null; OutputStream out = null; // FTPConnection routine. try { if (forDataTransfer) { socket = tcpConnectForDataTransferChannel(proxyHost, proxyPort); } else { socket = tcpConnectForCommunicationChannel(proxyHost, proxyPort); } in = socket.getInputStream(); out = socket.getOutputStream(); // Send the CONNECT request. out.write(connect.getBytes("UTF-8")); out.write(CRLF); out.write(hostHeader.getBytes("UTF-8")); out.write(CRLF); // Auth headers if (proxyUser != null && proxyPass != null) { String header = "Proxy-Authorization: Basic " + Base64.encode(proxyUser + ":" + proxyPass); out.write(header.getBytes("UTF-8")); out.write(CRLF); } out.write(CRLF); out.flush(); // Get the proxy response. ArrayList responseLines = new ArrayList(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); for (String line = reader.readLine(); line != null && line.length() > 0; line = reader.readLine()) { responseLines.add(line); } // Parse the response. int size = responseLines.size(); if (size < 1) { throw new IOException( "HTTPTunnelConnector: invalid proxy response"); } String code = null; String response = (String) responseLines.get(0); if (response.startsWith("HTTP/") && response.length() >= 12) { code = response.substring(9, 12); } else { throw new IOException( "HTTPTunnelConnector: invalid proxy response"); } if (!"200".equals(code)) { StringBuffer msg = new StringBuffer(); msg.append("HTTPTunnelConnector: connection failed\r\n"); msg.append("Response received from the proxy:\r\n"); for (int i = 0; i < size; i++) { String line = (String) responseLines.get(i); msg.append(line); msg.append("\r\n"); } throw new IOException(msg.toString()); } connected = true; } catch (IOException e) { throw e; } finally { if (!connected) { if (out != null) { try { out.close(); } catch (Throwable t) { ; } } if (in != null) { try { in.close(); } catch (Throwable t) { ; } } if (socket != null) { try { socket.close(); } catch (Throwable t) { ; } } } } return socket; } public Socket connectForCommunicationChannel(String host, int port) throws IOException { return httpConnect(host, port, false); } public Socket connectForDataTransferChannel(String host, int port) throws IOException { return httpConnect(host, port, true); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import it.sauronsoftware.ftp4j.FTPCommunicationChannel; import it.sauronsoftware.ftp4j.FTPConnector; import it.sauronsoftware.ftp4j.FTPIllegalReplyException; import it.sauronsoftware.ftp4j.FTPReply; import java.io.IOException; import java.net.Socket; /** * This one connects a remote host via a FTP proxy which supports the SITE or * the OPEN proxy method. * * The connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag is <em>true</em>. * * @author Carlo Pelliccia */ public class FTPProxyConnector extends FTPConnector { /** * Requires the connection to the remote host through a SITE command after * proxy authentication. Default one. */ public static int STYLE_SITE_COMMAND = 0; /** * Requires the connection to the remote host through a OPEN command without * proxy authentication. */ public static int STYLE_OPEN_COMMAND = 1; /** * The proxy host name. */ private String proxyHost; /** * The proxy port. */ private int proxyPort; /** * The proxyUser for proxy authentication. */ private String proxyUser; /** * The proxyPass for proxy authentication. */ private String proxyPass; /** * The style used by the proxy. */ public int style = STYLE_SITE_COMMAND; /** * Builds the connector. * * Default value for the style is STYLE_SITE_COMMAND. * * @param proxyHost * The proxy host name. * @param proxyPort * The proxy port. * @param proxyUser * The username for proxy authentication. * @param proxyPass * The password for proxy authentication. */ public FTPProxyConnector(String proxyHost, int proxyPort, String proxyUser, String proxyPass) { super(true); this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.proxyUser = proxyUser; this.proxyPass = proxyPass; } /** * Builds the connector. * * Default value for the style is STYLE_SITE_COMMAND. * * @param proxyHost * The proxy host name. * @param proxyPort * The proxy port. */ public FTPProxyConnector(String proxyHost, int proxyPort) { this(proxyHost, proxyPort, "anonymous", "ftp4j"); } /** * Sets the style used by the proxy. * * {@link it.sauronsoftware.ftp4j.connectors.FTPProxyConnector#STYLE_SITE_COMMAND} - Requires the connection to * the remote host through a SITE command after proxy authentication. * * {@link it.sauronsoftware.ftp4j.connectors.FTPProxyConnector#STYLE_OPEN_COMMAND} - Requires the connection to * the remote host through a OPEN command without proxy authentication. * * Default value for the style is STYLE_SITE_COMMAND. * * @param style * The style. * @see it.sauronsoftware.ftp4j.connectors.FTPProxyConnector#STYLE_SITE_COMMAND * @see it.sauronsoftware.ftp4j.connectors.FTPProxyConnector#STYLE_OPEN_COMMAND */ public void setStyle(int style) { if (style != STYLE_OPEN_COMMAND && style != STYLE_SITE_COMMAND) { throw new IllegalArgumentException("Invalid style"); } this.style = style; } public Socket connectForCommunicationChannel(String host, int port) throws IOException { Socket socket = tcpConnectForCommunicationChannel(proxyHost, proxyPort); FTPCommunicationChannel communication = new FTPCommunicationChannel( socket, "ASCII"); // Welcome message. FTPReply r; try { r = communication.readFTPReply(); } catch (FTPIllegalReplyException e) { throw new IOException("Invalid proxy response"); } // Does this reply mean "ok"? if (r.getCode() != 220) { // Mmmmm... it seems no! throw new IOException("Invalid proxy response"); } if (style == STYLE_SITE_COMMAND) { // Usefull flags. boolean passwordRequired; // Send the user and read the reply. communication.sendFTPCommand("USER " + proxyUser); try { r = communication.readFTPReply(); } catch (FTPIllegalReplyException e) { throw new IOException("Invalid proxy response"); } switch (r.getCode()) { case 230: // Password isn't required. passwordRequired = false; break; case 331: // Password is required. passwordRequired = true; break; default: // User validation failed. throw new IOException("Proxy authentication failed"); } // Password. if (passwordRequired) { // Send the password. communication.sendFTPCommand("PASS " + proxyPass); try { r = communication.readFTPReply(); } catch (FTPIllegalReplyException e) { throw new IOException("Invalid proxy response"); } if (r.getCode() != 230) { // Authentication failed. throw new IOException("Proxy authentication failed"); } } communication.sendFTPCommand("SITE " + host + ":" + port); } else if (style == STYLE_OPEN_COMMAND) { communication.sendFTPCommand("OPEN " + host + ":" + port); } return socket; } public Socket connectForDataTransferChannel(String host, int port) throws IOException { return tcpConnectForDataTransferChannel(host, port); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import it.sauronsoftware.ftp4j.FTPConnector; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; /** * This one connects a remote ftp host through a SOCKS4/4a proxy server. * * The connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag is <em>false</em>. * * @author Carlo Pelliccia */ public class SOCKS4Connector extends FTPConnector { /** * The socks4 proxy host name. */ private String socks4host; /** * The socks4 proxy port. */ private int socks4port; /** * The socks4 proxy user (optional). */ private String socks4user; /** * It builds the connector. * * @param socks4host * The socks4 proxy host name. * @param socks4port * The socks4 proxy port. * @param socks4user * The socks4 proxy user (optional, can be set to null). */ public SOCKS4Connector(String socks4host, int socks4port, String socks4user) { this.socks4host = socks4host; this.socks4port = socks4port; this.socks4user = socks4user; } /** * It builds the connector. * * @param socks4host * The socks4 proxy host name. * @param socks4port * The socks4 proxy port. */ public SOCKS4Connector(String socks4host, int socks4port) { this(socks4host, socks4port, null); } private Socket socksConnect(String host, int port, boolean forDataTransfer) throws IOException { // Socks 4 or 4a? boolean socks4a = false; byte[] address; try { address = InetAddress.getByName(host).getAddress(); } catch (Exception e) { // Cannot resolve host, switch to version 4a. socks4a = true; address = new byte[] { 0x00, 0x00, 0x00, 0x01 }; } // A connection status flag. boolean connected = false; // The socket for the connection with the proxy. Socket socket = null; InputStream in = null; OutputStream out = null; // FTPConnection routine. try { if (forDataTransfer) { socket = tcpConnectForDataTransferChannel(socks4host, socks4port); } else { socket = tcpConnectForCommunicationChannel(socks4host, socks4port); } in = socket.getInputStream(); out = socket.getOutputStream(); // Send the request. // Version 4. out.write(0x04); // CONNECT method. out.write(0x01); // Remote port number. out.write(port >> 8); out.write(port); // Remote host address. out.write(address); // The user. if (socks4user != null) { out.write(socks4user.getBytes("UTF-8")); } // End of user. out.write(0x00); // Version 4a? if (socks4a) { out.write(host.getBytes("UTF-8")); out.write(0x00); } // Get and parse the response. int aux = read(in); if (aux != 0x00) { throw new IOException("SOCKS4Connector: invalid proxy response"); } aux = read(in); switch (aux) { case 0x5a: in.skip(6); connected = true; break; case 0x5b: throw new IOException( "SOCKS4Connector: connection refused/failed"); case 0x5c: throw new IOException( "SOCKS4Connector: cannot validate the user"); case 0x5d: throw new IOException("SOCKS4Connector: invalid user"); default: throw new IOException("SOCKS4Connector: invalid proxy response"); } } catch (IOException e) { throw e; } finally { if (!connected) { if (out != null) { try { out.close(); } catch (Throwable t) { ; } } if (in != null) { try { in.close(); } catch (Throwable t) { ; } } if (socket != null) { try { socket.close(); } catch (Throwable t) { ; } } } } return socket; } private int read(InputStream in) throws IOException { int aux = in.read(); if (aux < 0) { throw new IOException( "SOCKS4Connector: connection closed by the proxy"); } return aux; } public Socket connectForCommunicationChannel(String host, int port) throws IOException { return socksConnect(host, port, false); } public Socket connectForDataTransferChannel(String host, int port) throws IOException { return socksConnect(host, port, true); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import java.io.IOException; import java.io.InputStream; /** * <p> * A base64 encoding input stream. * </p> * * <p> * A <em>Base64InputStream</em> reads from an underlying stream which is * supposed to be a base64 encoded stream. <em>Base64InputStream</em> decodes * the data read from the underlying stream and returns the decoded bytes to the * caller. * </p> * * @author Carlo Pelliccia */ class Base64InputStream extends InputStream { /** * The underlying stream. */ private InputStream inputStream; /** * The buffer. */ private int[] buffer; /** * A counter for values in the buffer. */ private int bufferCounter = 0; /** * End-of-stream flag. */ private boolean eof = false; /** * <p> * It builds a base64 decoding input stream. * </p> * * @param inputStream * The underlying stream, from which the encoded data is read. */ public Base64InputStream(InputStream inputStream) { this.inputStream = inputStream; } public int read() throws IOException { if (buffer == null || bufferCounter == buffer.length) { if (eof) { return -1; } acquire(); if (buffer.length == 0) { buffer = null; return -1; } bufferCounter = 0; } return buffer[bufferCounter++]; } /** * Reads from the underlying stream, decodes the data and puts the decoded * bytes into the buffer. */ private void acquire() throws IOException { char[] four = new char[4]; int i = 0; do { int b = inputStream.read(); if (b == -1) { if (i != 0) { throw new IOException("Bad base64 stream"); } else { buffer = new int[0]; eof = true; return; } } char c = (char) b; if (Base64.chars.indexOf(c) != -1 || c == Base64.pad) { four[i++] = c; } else if (c != '\r' && c != '\n') { throw new IOException("Bad base64 stream"); } } while (i < 4); boolean padded = false; for (i = 0; i < 4; i++) { if (four[i] != Base64.pad) { if (padded) { throw new IOException("Bad base64 stream"); } } else { if (!padded) { padded = true; } } } int l; if (four[3] == Base64.pad) { if (inputStream.read() != -1) { throw new IOException("Bad base64 stream"); } eof = true; if (four[2] == Base64.pad) { l = 1; } else { l = 2; } } else { l = 3; } int aux = 0; for (i = 0; i < 4; i++) { if (four[i] != Base64.pad) { aux = aux | (Base64.chars.indexOf(four[i]) << (6 * (3 - i))); } } buffer = new int[l]; for (i = 0; i < l; i++) { buffer[i] = (aux >>> (8 * (2 - i))) & 0xFF; } } public void close() throws IOException { inputStream.close(); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import it.sauronsoftware.ftp4j.FTPConnector; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /** * This one connects a remote ftp host through a SOCKS5 proxy server. * * The connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag is <em>false</em>. * * @author Carlo Pelliccia */ public class SOCKS5Connector extends FTPConnector { /** * The socks5 proxy host name. */ private String socks5host; /** * The socks5 proxy port. */ private int socks5port; /** * The socks5 proxy user (optional). */ private String socks5user; /** * The socks5 proxy password (optional). */ private String socks5pass; /** * It builds the connector. * * @param socks5host * The socks5 proxy host name. * @param socks5port * The socks5 proxy port. * @param socks5user * The socks5 proxy user (optional, can be set to null). * @param socks5pass * The socks5 proxy password (optional, can be set to null if * also socks5user is null). */ public SOCKS5Connector(String socks5host, int socks5port, String socks5user, String socks5pass) { this.socks5host = socks5host; this.socks5port = socks5port; this.socks5user = socks5user; this.socks5pass = socks5pass; } /** * It builds the connector. * * @param socks5host * The socks5 proxy host name. * @param socks5port * The socks5 proxy port. */ public SOCKS5Connector(String socks5host, int socks5port) { this(socks5host, socks5port, null, null); } private Socket socksConnect(String host, int port, boolean forDataTransfer) throws IOException { // Authentication flag boolean authentication = socks5user != null && socks5pass != null; // A connection status flag. boolean connected = false; // The socket for the connection with the proxy. Socket socket = null; InputStream in = null; OutputStream out = null; // FTPConnection routine. try { if (forDataTransfer) { socket = tcpConnectForDataTransferChannel(socks5host, socks5port); } else { socket = tcpConnectForCommunicationChannel(socks5host, socks5port); } in = socket.getInputStream(); out = socket.getOutputStream(); int aux; // Version 5. out.write(0x05); // Authentication? if (authentication) { // Authentication with username/password. out.write(0x01); out.write(0x02); } else { // No authentication. out.write(0x01); out.write(0x00); } // Get the response. aux = read(in); if (aux != 0x05) { throw new IOException("SOCKS5Connector: invalid proxy response"); } aux = read(in); if (authentication) { if (aux != 0x02) { throw new IOException( "SOCKS5Connector: proxy doesn't support " + "username/password authentication method"); } // Authentication with username/password. byte[] user = socks5user.getBytes("UTF-8"); byte[] pass = socks5pass.getBytes("UTF-8"); int userLength = user.length; int passLength = pass.length; // Check sizes. if (userLength > 0xff) { throw new IOException("SOCKS5Connector: username too long"); } if (passLength > 0xff) { throw new IOException("SOCKS5Connector: password too long"); } // Version 1. out.write(0x01); // Username. out.write(userLength); out.write(user); // Password. out.write(passLength); out.write(pass); // Check the response. aux = read(in); if (aux != 0x01) { throw new IOException( "SOCKS5Connector: invalid proxy response"); } aux = read(in); if (aux != 0x00) { throw new IOException( "SOCKS5Connector: authentication failed"); } } else { if (aux != 0x00) { throw new IOException( "SOCKS5Connector: proxy requires authentication"); } } // FTPConnection request. // Version 5. out.write(0x05); // CONNECT method out.write(0x01); // Reserved. out.write(0x00); // Address type -> domain. out.write(0x03); // Domain. byte[] domain = host.getBytes("UTF-8"); if (domain.length > 0xff) { throw new IOException("SOCKS5Connector: domain name too long"); } out.write(domain.length); out.write(domain); // Port number. out.write(port >> 8); out.write(port); // FTPConnection response // Version? aux = read(in); if (aux != 0x05) { throw new IOException("SOCKS5Connector: invalid proxy response"); } // Status? aux = read(in); switch (aux) { case 0x00: // Connected! break; case 0x01: throw new IOException("SOCKS5Connector: general failure"); case 0x02: throw new IOException( "SOCKS5Connector: connection not allowed by ruleset"); case 0x03: throw new IOException("SOCKS5Connector: network unreachable"); case 0x04: throw new IOException("SOCKS5Connector: host unreachable"); case 0x05: throw new IOException( "SOCKS5Connector: connection refused by destination host"); case 0x06: throw new IOException("SOCKS5Connector: TTL expired"); case 0x07: throw new IOException( "SOCKS5Connector: command not supported / protocol error"); case 0x08: throw new IOException( "SOCKS5Connector: address type not supported"); default: throw new IOException("SOCKS5Connector: invalid proxy response"); } // Reserved. in.skip(1); // Address type. aux = read(in); if (aux == 0x01) { // IPv4. in.skip(4); } else if (aux == 0x03) { // Domain name. aux = read(in); in.skip(aux); } else if (aux == 0x04) { // IPv6. in.skip(16); } else { throw new IOException("SOCKS5Connector: invalid proxy response"); } // Port number. in.skip(2); // Well done! connected = true; } catch (IOException e) { throw e; } finally { if (!connected) { if (out != null) { try { out.close(); } catch (Throwable t) { ; } } if (in != null) { try { in.close(); } catch (Throwable t) { ; } } if (socket != null) { try { socket.close(); } catch (Throwable t) { ; } } } } return socket; } private int read(InputStream in) throws IOException { int aux = in.read(); if (aux < 0) { throw new IOException( "SOCKS5Connector: connection closed by the proxy"); } return aux; } public Socket connectForCommunicationChannel(String host, int port) throws IOException { return socksConnect(host, port, false); } public Socket connectForDataTransferChannel(String host, int port) throws IOException { return socksConnect(host, port, true); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; /** * <p> * Base64 encoding and decoding utility methods, both for binary and textual * informations. * </p> * * @author Carlo Pelliccia * @since 1.1 * @version 1.3 */ class Base64 { static String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static char pad = '='; /** * <p> * Encodes a string. * </p> * <p> * Before the string is encoded in Base64, it is converted in a binary * sequence using the system default charset. * </p> * * @param str * The source string. * @return The encoded string. * @throws RuntimeException * If an unexpected error occurs. */ public static String encode(String str) throws RuntimeException { byte[] bytes = str.getBytes(); byte[] encoded = encode(bytes); try { return new String(encoded, "ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("ASCII is not supported!", e); } } /** * <p> * Encodes a string. * </p> * <p> * Before the string is encoded in Base64, it is converted in a binary * sequence using the supplied charset. * </p> * * @param str * The source string * @param charset * The charset name. * @return The encoded string. * @throws RuntimeException * If an unexpected error occurs. * @since 1.2 */ public static String encode(String str, String charset) throws RuntimeException { byte[] bytes; try { bytes = str.getBytes(charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported charset: " + charset, e); } byte[] encoded = encode(bytes); try { return new String(encoded, "ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("ASCII is not supported!", e); } } /** * <p> * Decodes the supplied string. * </p> * <p> * The supplied string is decoded into a binary sequence, and then the * sequence is encoded with the system default charset and returned. * </p> * * @param str * The encoded string. * @return The decoded string. * @throws RuntimeException * If an unexpected error occurs. */ public static String decode(String str) throws RuntimeException { byte[] bytes; try { bytes = str.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("ASCII is not supported!", e); } byte[] decoded = decode(bytes); return new String(decoded); } /** * <p> * Decodes the supplied string. * </p> * <p> * The supplied string is decoded into a binary sequence, and then the * sequence is encoded with the supplied charset and returned. * </p> * * @param str * The encoded string. * @param charset * The charset name. * @return The decoded string. * @throws RuntimeException * If an unexpected error occurs. * @since 1.2 */ public static String decode(String str, String charset) throws RuntimeException { byte[] bytes; try { bytes = str.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("ASCII is not supported!", e); } byte[] decoded = decode(bytes); try { return new String(decoded, charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported charset: " + charset, e); } } /** * <p> * Encodes a binary sequence. * </p> * <p> * If data are large, i.e. if you are working with large binary files, * consider to use a {@link Base64OutputStream} instead of loading too much * data in memory. * </p> * * @param bytes * The source sequence. * @return The encoded sequence. * @throws RuntimeException * If an unexpected error occurs. * @since 1.2 */ public static byte[] encode(byte[] bytes) throws RuntimeException { return encode(bytes, 0); } /** * <p> * Encodes a binary sequence, wrapping every encoded line every * <em>wrapAt</em> characters. A <em>wrapAt</em> value less than 1 disables * wrapping. * </p> * <p> * If data are large, i.e. if you are working with large binary files, * consider to use a {@link Base64OutputStream} instead of loading too much * data in memory. * </p> * * @param bytes * The source sequence. * @param wrapAt * The max line length for encoded data. If less than 1 no wrap * is applied. * @return The encoded sequence. * @throws RuntimeException * If an unexpected error occurs. * @since 1.2 */ public static byte[] encode(byte[] bytes, int wrapAt) throws RuntimeException { ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { encode(inputStream, outputStream, wrapAt); } catch (IOException e) { throw new RuntimeException("Unexpected I/O error", e); } finally { try { inputStream.close(); } catch (Throwable t) { ; } try { outputStream.close(); } catch (Throwable t) { ; } } return outputStream.toByteArray(); } /** * <p> * Decodes a binary sequence. * </p> * <p> * If data are large, i.e. if you are working with large binary files, * consider to use a {@link Base64InputStream} instead of loading too much * data in memory. * </p> * * @param bytes * The encoded sequence. * @return The decoded sequence. * @throws RuntimeException * If an unexpected error occurs. * @since 1.2 */ public static byte[] decode(byte[] bytes) throws RuntimeException { ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { decode(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Unexpected I/O error", e); } finally { try { inputStream.close(); } catch (Throwable t) { ; } try { outputStream.close(); } catch (Throwable t) { ; } } return outputStream.toByteArray(); } /** * <p> * Encodes data from the given input stream and writes them in the given * output stream. * </p> * <p> * The supplied input stream is read until its end is reached, but it's not * closed by this method. * </p> * <p> * The supplied output stream is nor flushed neither closed by this method. * </p> * * @param inputStream * The input stream. * @param outputStream * The output stream. * @throws java.io.IOException * If an I/O error occurs. */ public static void encode(InputStream inputStream, OutputStream outputStream) throws IOException { encode(inputStream, outputStream, 0); } /** * <p> * Encodes data from the given input stream and writes them in the given * output stream, wrapping every encoded line every <em>wrapAt</em> * characters. A <em>wrapAt</em> value less than 1 disables wrapping. * </p> * <p> * The supplied input stream is read until its end is reached, but it's not * closed by this method. * </p> * <p> * The supplied output stream is nor flushed neither closed by this method. * </p> * * @param inputStream * The input stream from which clear data are read. * @param outputStream * The output stream in which encoded data are written. * @param wrapAt * The max line length for encoded data. If less than 1 no wrap * is applied. * @throws java.io.IOException * If an I/O error occurs. */ public static void encode(InputStream inputStream, OutputStream outputStream, int wrapAt) throws IOException { Base64OutputStream aux = new Base64OutputStream(outputStream, wrapAt); copy(inputStream, aux); aux.commit(); } /** * <p> * Decodes data from the given input stream and writes them in the given * output stream. * </p> * <p> * The supplied input stream is read until its end is reached, but it's not * closed by this method. * </p> * <p> * The supplied output stream is nor flushed neither closed by this method. * </p> * * @param inputStream * The input stream from which encoded data are read. * @param outputStream * The output stream in which decoded data are written. * @throws java.io.IOException * If an I/O error occurs. */ public static void decode(InputStream inputStream, OutputStream outputStream) throws IOException { copy(new Base64InputStream(inputStream), outputStream); } /** * <p> * Encodes data from the given source file contents and writes them in the * given target file, wrapping every encoded line every <em>wrapAt</em> * characters. A <em>wrapAt</em> value less than 1 disables wrapping. * </p> * * @param source * The source file, from which decoded data are read. * @param target * The target file, in which encoded data are written. * @param wrapAt * The max line length for encoded data. If less than 1 no wrap * is applied. * @throws java.io.IOException * If an I/O error occurs. * @since 1.3 */ public static void encode(File source, File target, int wrapAt) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new FileInputStream(source); outputStream = new FileOutputStream(target); Base64.encode(inputStream, outputStream, wrapAt); } finally { if (outputStream != null) { try { outputStream.close(); } catch (Throwable t) { ; } } if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ; } } } } /** * <p> * Encodes data from the given source file contents and writes them in the * given target file. * </p> * * @param source * The source file, from which decoded data are read. * @param target * The target file, in which encoded data are written. * @throws java.io.IOException * If an I/O error occurs. * @since 1.3 */ public static void encode(File source, File target) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new FileInputStream(source); outputStream = new FileOutputStream(target); Base64.encode(inputStream, outputStream); } finally { if (outputStream != null) { try { outputStream.close(); } catch (Throwable t) { ; } } if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ; } } } } /** * <p> * Decodes data from the given source file contents and writes them in the * given target file. * </p> * * @param source * The source file, from which encoded data are read. * @param target * The target file, in which decoded data are written. * @throws java.io.IOException * If an I/O error occurs. * @since 1.3 */ public static void decode(File source, File target) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new FileInputStream(source); outputStream = new FileOutputStream(target); decode(inputStream, outputStream); } finally { if (outputStream != null) { try { outputStream.close(); } catch (Throwable t) { ; } } if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ; } } } } /** * Copies data from a stream to another. * * @param inputStream * The input stream. * @param outputStream * The output stream. * @throws java.io.IOException * If a unexpected I/O error occurs. */ private static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { // 1KB buffer byte[] b = new byte[1024]; int len; while ((len = inputStream.read(b)) != -1) { outputStream.write(b, 0, len); } } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import java.io.IOException; import java.io.OutputStream; /** * <p> * A base64 decoding output stream. * </p> * * <p> * It encodes in base64 everything passed to the stream, and it puts the encoded * data into the underlying stream. * </p> * * @author Carlo Pelliccia */ class Base64OutputStream extends OutputStream { /** * The underlying stream. */ private OutputStream outputStream = null; /** * A value buffer. */ private int buffer = 0; /** * How many bytes are currently in the value buffer? */ private int bytecounter = 0; /** * A counter for the current line length. */ private int linecounter = 0; /** * The requested line length. */ private int linelength = 0; /** * <p> * It builds a base64 encoding output stream writing the encoded data in the * given underlying stream. * </p> * * <p> * The encoded data is wrapped to a new line (with a CRLF sequence) every 76 * bytes sent to the underlying stream. * </p> * * @param outputStream * The underlying stream. */ public Base64OutputStream(OutputStream outputStream) { this(outputStream, 76); } /** * <p> * It builds a base64 encoding output stream writing the encoded data in the * given underlying stream. * </p> * * <p> * The encoded data is wrapped to a new line (with a CRLF sequence) every * <em>wrapAt</em> bytes sent to the underlying stream. If the * <em>wrapAt</em> supplied value is less than 1 the encoded data will not * be wrapped. * </p> * * @param outputStream * The underlying stream. * @param wrapAt * The max line length for encoded data. If less than 1 no wrap * is applied. */ public Base64OutputStream(OutputStream outputStream, int wrapAt) { this.outputStream = outputStream; this.linelength = wrapAt; } public void write(int b) throws IOException { int value = (b & 0xFF) << (16 - (bytecounter * 8)); buffer = buffer | value; bytecounter++; if (bytecounter == 3) { commit(); } } public void close() throws IOException { commit(); outputStream.close(); } /** * <p> * It commits 4 bytes to the underlying stream. * </p> */ protected void commit() throws IOException { if (bytecounter > 0) { if (linelength > 0 && linecounter == linelength) { outputStream.write("\r\n".getBytes()); linecounter = 0; } char b1 = Base64.chars.charAt((buffer << 8) >>> 26); char b2 = Base64.chars.charAt((buffer << 14) >>> 26); char b3 = (bytecounter < 2) ? Base64.pad : Base64.chars.charAt((buffer << 20) >>> 26); char b4 = (bytecounter < 3) ? Base64.pad : Base64.chars.charAt((buffer << 26) >>> 26); outputStream.write(b1); outputStream.write(b2); outputStream.write(b3); outputStream.write(b4); linecounter += 4; bytecounter = 0; buffer = 0; } } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * This class represents FTP server replies in a manageable object oriented way. * * @author Carlo Pelliccia */ public class FTPReply { /** * The reply code. */ private int code = 0; /** * The reply message(s). */ private String[] messages; /** * Build the reply. * * @param code * The code of the reply. * @param message * The textual message(s) in the reply. */ FTPReply(int code, String[] messages) { this.code = code; this.messages = messages; } /** * Returns the code of the reply. * * @return The code of the reply. */ public int getCode() { return code; } /** * Returns true if the code of the reply is in the range of success codes * (2**). * * @return true if the code of the reply is in the range of success codes * (2**). */ public boolean isSuccessCode() { int aux = code - 200; return aux >= 0 && aux < 100; } /** * Returns the textual message(s) of the reply. * * @return The textual message(s) of the reply. */ public String[] getMessages() { return messages; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()); buffer.append(" [code="); buffer.append(code); buffer.append(", message="); for (int i = 0; i < messages.length; i++) { if (i > 0) { buffer.append(" "); } buffer.append(messages[i]); } buffer.append("]"); return buffer.toString(); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * Implement this interface to build a new LIST parser. List parsers are called * to parse the result of a FTP LIST command send to the server in the list() * method. You can add a custom parser to your instance of FTPClient calling on * it the method addListParser. * * @author Carlo Pelliccia * @see FTPClient#addListParser(it.sauronsoftware.ftp4j.FTPListParser) */ public interface FTPListParser { /** * Parses a LIST command response and builds an array of FTPFile objects. * * @param lines * The response to parse, splitted by line. * @return An array of FTPFile objects representing the result of the * operation. * @throws FTPListParseException * If this parser cannot parse the given response. */ public FTPFile[] parse(String[] lines) throws FTPListParseException; }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.listparsers; import it.sauronsoftware.ftp4j.FTPFile; import it.sauronsoftware.ftp4j.FTPListParseException; import it.sauronsoftware.ftp4j.FTPListParser; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This parser can handle NetWare list responses. * * @author Carlo Pelliccia */ public class NetWareListParser implements FTPListParser { private static final Pattern PATTERN = Pattern .compile("^(d|-)\\s+\\[.{8}\\]\\s+\\S+\\s+(\\d+)\\s+" + "(?:(\\w{3})\\s+(\\d{1,2}))\\s+(?:(\\d{4})|(?:(\\d{1,2}):(\\d{1,2})))\\s+" + "([^\\\\/*?\"<>|]+)$"); private static final DateFormat DATE_FORMAT = new SimpleDateFormat( "MMM dd yyyy HH:mm", Locale.US); public FTPFile[] parse(String[] lines) throws FTPListParseException { int size = lines.length; // What's the date today? Calendar now = Calendar.getInstance(); // Ok, starts parsing. int currentYear = now.get(Calendar.YEAR); FTPFile[] ret = new FTPFile[size]; for (int i = 0; i < size; i++) { Matcher m = PATTERN.matcher(lines[i]); if (m.matches()) { String typeString = m.group(1); String sizeString = m.group(2); String monthString = m.group(3); String dayString = m.group(4); String yearString = m.group(5); String hourString = m.group(6); String minuteString = m.group(7); String nameString = m.group(8); // Parse the data. ret[i] = new FTPFile(); if (typeString.equals("-")) { ret[i].setType(FTPFile.TYPE_FILE); } else if (typeString.equals("d")) { ret[i].setType(FTPFile.TYPE_DIRECTORY); } else { throw new FTPListParseException(); } long fileSize; try { fileSize = Long.parseLong(sizeString); } catch (Throwable t) { throw new FTPListParseException(); } ret[i].setSize(fileSize); if (dayString.length() == 1) { dayString = "0" + dayString; } StringBuffer mdString = new StringBuffer(); mdString.append(monthString); mdString.append(' '); mdString.append(dayString); mdString.append(' '); boolean checkYear = false; if (yearString == null) { mdString.append(currentYear); checkYear = true; } else { mdString.append(yearString); checkYear = false; } mdString.append(' '); if (hourString != null && minuteString != null) { if (hourString.length() == 1) { hourString = "0" + hourString; } if (minuteString.length() == 1) { minuteString = "0" + minuteString; } mdString.append(hourString); mdString.append(':'); mdString.append(minuteString); } else { mdString.append("00:00"); } Date md; try { synchronized (DATE_FORMAT) { md = DATE_FORMAT.parse(mdString.toString()); } } catch (ParseException e) { throw new FTPListParseException(); } if (checkYear) { Calendar mc = Calendar.getInstance(); mc.setTime(md); if (mc.after(now) && mc.getTimeInMillis() - now.getTimeInMillis() > 24L * 60L * 60L * 1000L) { mc.set(Calendar.YEAR, currentYear - 1); md = mc.getTime(); } } ret[i].setModifiedDate(md); ret[i].setName(nameString); } else { throw new FTPListParseException(); } } return ret; } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.listparsers; import it.sauronsoftware.ftp4j.FTPFile; import it.sauronsoftware.ftp4j.FTPListParseException; import it.sauronsoftware.ftp4j.FTPListParser; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This parser can handle the result of a list ftp command as it is a UNIX "ls * -l" command response. * * @author Carlo Pelliccia */ public class UnixListParser implements FTPListParser { private static final Pattern PATTERN = Pattern .compile("^([dl\\-])[r\\-][w\\-][xSs\\-][r\\-][w\\-][xSs\\-][r\\-][w\\-][xTt\\-]\\s+" + "(?:\\d+\\s+)?\\S+\\s*\\S+\\s+(\\d+)\\s+(?:(\\w{3})\\s+(\\d{1,2}))\\s+" + "(?:(\\d{4})|(?:(\\d{1,2}):(\\d{1,2})))\\s+" + "([^\\\\*?\"<>|]+)(?: -> ([^\\\\*?\"<>|]+))?$"); private static final DateFormat DATE_FORMAT = new SimpleDateFormat( "MMM dd yyyy HH:mm", Locale.US); public FTPFile[] parse(String[] lines) throws FTPListParseException { int size = lines.length; if (size == 0) { return new FTPFile[0]; } // Removes the "total" line used in MAC style. if (lines[0].startsWith("total")) { size--; String[] lines2 = new String[size]; for (int i = 0; i < size; i++) { lines2[i] = lines[i + 1]; } lines = lines2; } // What's the date today? Calendar now = Calendar.getInstance(); // Ok, starts parsing. int currentYear = now.get(Calendar.YEAR); FTPFile[] ret = new FTPFile[size]; for (int i = 0; i < size; i++) { Matcher m = PATTERN.matcher(lines[i]); if (m.matches()) { ret[i] = new FTPFile(); // Retrieve the data. String typeString = m.group(1); String sizeString = m.group(2); String monthString = m.group(3); String dayString = m.group(4); String yearString = m.group(5); String hourString = m.group(6); String minuteString = m.group(7); String nameString = m.group(8); String linkedString = m.group(9); // Parse the data. if (typeString.equals("-")) { ret[i].setType(FTPFile.TYPE_FILE); } else if (typeString.equals("d")) { ret[i].setType(FTPFile.TYPE_DIRECTORY); } else if (typeString.equals("l")) { ret[i].setType(FTPFile.TYPE_LINK); ret[i].setLink(linkedString); } else { throw new FTPListParseException(); } long fileSize; try { fileSize = Long.parseLong(sizeString); } catch (Throwable t) { throw new FTPListParseException(); } ret[i].setSize(fileSize); if (dayString.length() == 1) { dayString = "0" + dayString; } StringBuffer mdString = new StringBuffer(); mdString.append(monthString); mdString.append(' '); mdString.append(dayString); mdString.append(' '); boolean checkYear = false; if (yearString == null) { mdString.append(currentYear); checkYear = true; } else { mdString.append(yearString); checkYear = false; } mdString.append(' '); if (hourString != null && minuteString != null) { if (hourString.length() == 1) { hourString = "0" + hourString; } if (minuteString.length() == 1) { minuteString = "0" + minuteString; } mdString.append(hourString); mdString.append(':'); mdString.append(minuteString); } else { mdString.append("00:00"); } Date md; try { synchronized (DATE_FORMAT) { md = DATE_FORMAT.parse(mdString.toString()); } } catch (ParseException e) { throw new FTPListParseException(); } if (checkYear) { Calendar mc = Calendar.getInstance(); mc.setTime(md); if (mc.after(now) && mc.getTimeInMillis() - now.getTimeInMillis() > 24L * 60L * 60L * 1000L) { mc.set(Calendar.YEAR, currentYear - 1); md = mc.getTime(); } } ret[i].setModifiedDate(md); ret[i].setName(nameString); } else { throw new FTPListParseException(); } } return ret; } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.listparsers; import java.util.Date; import java.util.StringTokenizer; import it.sauronsoftware.ftp4j.FTPFile; import it.sauronsoftware.ftp4j.FTPListParseException; import it.sauronsoftware.ftp4j.FTPListParser; /** * This parser can handle the EPLF format. * * @author Carlo Pelliccia */ public class EPLFListParser implements FTPListParser { public FTPFile[] parse(String[] lines) throws FTPListParseException { int size = lines.length; FTPFile[] ret = null; for (int i = 0; i < size; i++) { String l = lines[i]; // Validate the plus sign. if (l.charAt(0) != '+') { throw new FTPListParseException(); } // Split the facts from the filename. int a = l.indexOf('\t'); if (a == -1) { throw new FTPListParseException(); } String facts = l.substring(1, a); String name = l.substring(a + 1, l.length()); // Parse the facts. Date md = null; boolean dir = false; long fileSize = 0; StringTokenizer st = new StringTokenizer(facts, ","); while (st.hasMoreTokens()) { String f = st.nextToken(); int s = f.length(); if (s > 0) { if (s == 1) { if (f.equals("/")) { // This is a directory. dir = true; } } else { char c = f.charAt(0); String value = f.substring(1, s); if (c == 's') { // Size parameter. try { fileSize = Long.parseLong(value); } catch (Throwable t) { ; } } else if (c == 'm') { // Modified date. try { long m = Long.parseLong(value); md = new Date(m * 1000); } catch (Throwable t) { ; } } } } } // Create the related FTPFile object. if (ret == null) { ret = new FTPFile[size]; } ret[i] = new FTPFile(); ret[i].setName(name); ret[i].setModifiedDate(md); ret[i].setSize(fileSize); ret[i].setType(dir ? FTPFile.TYPE_DIRECTORY : FTPFile.TYPE_FILE); } return ret; } public static void main(String[] args) throws Throwable { String[] test = { "+i8388621.29609,m824255902,/,\tdev", "+i8388621.44468,m839956783,r,s10376,\tRFCEPLF" }; EPLFListParser parser = new EPLFListParser(); FTPFile[] f = parser.parse(test); for (int i = 0; i < f.length; i++) { System.out.println(f[i]); } } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.listparsers; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import it.sauronsoftware.ftp4j.FTPFile; import it.sauronsoftware.ftp4j.FTPListParseException; import it.sauronsoftware.ftp4j.FTPListParser; /** * This parser can handle the MSDOS-style LIST responses. * * @author Carlo Pelliccia */ public class DOSListParser implements FTPListParser { private static final Pattern PATTERN = Pattern .compile("^(\\d{2})-(\\d{2})-(\\d{2})\\s+(\\d{2}):(\\d{2})(AM|PM)\\s+" + "(<DIR>|\\d+)\\s+([^\\\\/*?\"<>|]+)$"); private static final DateFormat DATE_FORMAT = new SimpleDateFormat( "MM/dd/yy hh:mm a"); public FTPFile[] parse(String[] lines) throws FTPListParseException { int size = lines.length; FTPFile[] ret = new FTPFile[size]; for (int i = 0; i < size; i++) { Matcher m = PATTERN.matcher(lines[i]); if (m.matches()) { String month = m.group(1); String day = m.group(2); String year = m.group(3); String hour = m.group(4); String minute = m.group(5); String ampm = m.group(6); String dirOrSize = m.group(7); String name = m.group(8); ret[i] = new FTPFile(); ret[i].setName(name); if (dirOrSize.equalsIgnoreCase("<DIR>")) { ret[i].setType(FTPFile.TYPE_DIRECTORY); ret[i].setSize(0); } else { long fileSize; try { fileSize = Long.parseLong(dirOrSize); } catch (Throwable t) { throw new FTPListParseException(); } ret[i].setType(FTPFile.TYPE_FILE); ret[i].setSize(fileSize); } String mdString = month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + ampm; Date md; try { synchronized (DATE_FORMAT) { md = DATE_FORMAT.parse(mdString); } } catch (ParseException e) { throw new FTPListParseException(); } ret[i].setModifiedDate(md); } else { throw new FTPListParseException(); } } return ret; } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.listparsers; import it.sauronsoftware.ftp4j.FTPFile; import it.sauronsoftware.ftp4j.FTPListParseException; import it.sauronsoftware.ftp4j.FTPListParser; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; /** * This parser can handle the standard MLST/MLSD responses (RFC 3659). * * @author Carlo Pelliccia * @since 1.5 */ public class MLSDListParser implements FTPListParser { /** * Date format 1 for MLSD date facts (supports millis). */ private static final DateFormat MLSD_DATE_FORMAT_1 = new SimpleDateFormat("yyyyMMddhhmmss.SSS Z"); /** * Date format 2 for MLSD date facts (doesn't support millis). */ private static final DateFormat MLSD_DATE_FORMAT_2 = new SimpleDateFormat("yyyyMMddhhmmss Z"); public FTPFile[] parse(String[] lines) throws FTPListParseException { ArrayList list = new ArrayList(); for (int i = 0; i < lines.length; i++) { FTPFile file = parseLine(lines[i]); if (file != null) { list.add(file); } } int size = list.size(); FTPFile[] ret = new FTPFile[size]; for (int i = 0; i < size; i++) { ret[i] = (FTPFile) list.get(i); } return ret; } /** * Parses a line ad a MLSD response element. * * @param line * The line. * @return The file, or null if the line has to be ignored. * @throws FTPListParseException * If the line is not a valid MLSD entry. */ private FTPFile parseLine(String line) throws FTPListParseException { // Divides facts and name. ArrayList list = new ArrayList(); StringTokenizer st = new StringTokenizer(line, ";"); while (st.hasMoreElements()) { String aux = st.nextToken().trim(); if (aux.length() > 0) { list.add(aux); } } if (list.size() == 0) { throw new FTPListParseException(); } // Extracts the file name. String name = (String) list.remove(list.size() - 1); // Parses the facts. Properties facts = new Properties(); for (Iterator i = list.iterator(); i.hasNext();) { String aux = (String) i.next(); int sep = aux.indexOf('='); if (sep == -1) { throw new FTPListParseException(); } String key = aux.substring(0, sep).trim(); String value = aux.substring(sep + 1, aux.length()).trim(); if (key.length() == 0 || value.length() == 0) { throw new FTPListParseException(); } facts.setProperty(key, value); } // Type. int type; String typeString = facts.getProperty("type"); if (typeString == null) { throw new FTPListParseException(); } else if ("file".equalsIgnoreCase(typeString)) { type = FTPFile.TYPE_FILE; } else if ("dir".equalsIgnoreCase(typeString)) { type = FTPFile.TYPE_DIRECTORY; } else if ("cdir".equalsIgnoreCase(typeString)) { // Current directory. Skips... return null; } else if ("pdir".equalsIgnoreCase(typeString)) { // Parent directory. Skips... return null; } else { // Unknown... (link?)... Skips... return null; } // Last modification date. Date modifiedDate = null; String modifyString = facts.getProperty("modify"); if (modifyString != null) { modifyString += " +0000"; try { synchronized (MLSD_DATE_FORMAT_1) { modifiedDate = MLSD_DATE_FORMAT_1.parse(modifyString); } } catch (ParseException e1) { try { synchronized (MLSD_DATE_FORMAT_2) { modifiedDate = MLSD_DATE_FORMAT_2.parse(modifyString); } } catch (ParseException e2) { ; } } } // Size. long size = 0; String sizeString = facts.getProperty("size"); if (sizeString != null) { try { size = Long.parseLong(sizeString); } catch (NumberFormatException e) { ; } if (size < 0) { size = 0; } } // Done! FTPFile ret = new FTPFile(); ret.setType(type); ret.setModifiedDate(modifiedDate); ret.setSize(size); ret.setName(name); return ret; } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import it.sauronsoftware.ftp4j.connectors.DirectConnector; import it.sauronsoftware.ftp4j.extrecognizers.DefaultTextualExtensionRecognizer; import it.sauronsoftware.ftp4j.extrecognizers.ParametricTextualExtensionRecognizer; import it.sauronsoftware.ftp4j.listparsers.DOSListParser; import it.sauronsoftware.ftp4j.listparsers.EPLFListParser; import it.sauronsoftware.ftp4j.listparsers.MLSDListParser; import it.sauronsoftware.ftp4j.listparsers.NetWareListParser; import it.sauronsoftware.ftp4j.listparsers.UnixListParser; 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.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.InetAddress; import java.net.Socket; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import javax.net.ssl.SSLSocketFactory; /** * This class implements a FTP client. * * You can use an instance of this class to connect to a remote FTP site and do * FTP operations like directory listing, file upload and download, resume a * broken upload/download and so on. * * The common flow is: create the object, connect to a remote FTP site with the * connect() method, authenticate with login(), do anything you need with the * contents of the remote site, quit the site with disconnect(). * * A FTPClient object can handle a connection per time. Once you have used and * disconnected a FTPClient object you can use it again to connect another FTP * server. * * @author Carlo Pelliccia * @version 1.7.1 */ public class FTPClient { /** * The constant for the FTP security level. * * @since 1.4 */ public static final int SECURITY_FTP = 0; /** * The constant for the FTPS (FTP over implicit TLS/SSL) security level. * * @since 1.4 */ public static final int SECURITY_FTPS = 1; /** * The constant for the FTPES (FTP over explicit TLS/SSL) security level. * * @since 1.4 */ public static final int SECURITY_FTPES = 2; /** * The constant for the AUTO file transfer type. It lets the client pick * between textual and binary types, depending on the extension of the file * exchanged through a textual extension recognizer. */ public static final int TYPE_AUTO = 0; /** * The constant for the TEXTUAL file transfer type. It means that the data * sent or received is treated as textual information. This implies charset * conversion during the transfer. */ public static final int TYPE_TEXTUAL = 1; /** * The constant for the BINARY file transfer type. It means that the data * sent or received is treated as a binary stream. The data is taken "as * is", without any charset conversion. */ public static final int TYPE_BINARY = 2; /** * The constant for the MLSD policy that causes the client to use the MLSD * command instead of LIST, but only if the MLSD command is explicitly * supported by the server (the support is tested with the FEAT command). * * @since 1.5 */ public static final int MLSD_IF_SUPPORTED = 0; /** * The constant for the MLSD policy that causes the client to use always the * MLSD command instead of LIST, also if the MLSD command is not explicitly * supported by the server (the support is tested with the FEAT command). * * @since 1.5 */ public static final int MLSD_ALWAYS = 1; /** * The constant for the MLSD policy that causes the client to use always the * LIST command, also if the MLSD command is explicitly supported by the * server (the support is tested with the FEAT command). * * @since 1.5 */ public static final int MLSD_NEVER = 2; /** * The size of the buffer used when sending or receiving data. * * @since 1.6 */ private static final int SEND_AND_RECEIVE_BUFFER_SIZE = 64 * 1024; /** * The DateFormat object used to parse the reply to a MDTM command. */ private static final DateFormat MDTM_DATE_FORMAT = new SimpleDateFormat( "yyyyMMddHHmmss"); /** * The RegExp Pattern object used to parse the reply to a PASV command. */ private static final Pattern PASV_PATTERN = Pattern .compile("\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3}"); /** * The RegExp Pattern object used to parse the reply to a PWD command. */ private static final Pattern PWD_PATTERN = Pattern.compile("\"/.*\""); /** * The connector used to connect the remote host. */ private FTPConnector connector = new DirectConnector(); /** * The SSL socket factory used to negotiate SSL connections. */ private SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory .getDefault(); /** * The FTPCommunicationListener objects registered on the client. */ private ArrayList communicationListeners = new ArrayList(); /** * The FTPListParser objects registered on the client. */ private ArrayList listParsers = new ArrayList(); /** * The textual extension recognizer used by the client. */ private FTPTextualExtensionRecognizer textualExtensionRecognizer = DefaultTextualExtensionRecognizer.getInstance(); /** * The FTPListParser used successfully during previous connection-scope list * operations. */ private FTPListParser parser = null; /** * If the client is connected, it reports the remote host name or address. */ private String host = null; /** * If the client is connected, it reports the remote port number. */ private int port = 0; /** * The security level. The value should be one of SECURITY_FTP, * SECURITY_FTPS and SECURITY_FTPES constants. Default value is * SECURITY_FTP. */ private int security = SECURITY_FTP; /** * If the client is authenticated, it reports the authentication username. */ private String username; /** * If the client is authenticated, it reports the authentication password. */ private String password; /** * The flag reporting the connection status. */ private boolean connected = false; /** * The flag reporting the authentication status. */ private boolean authenticated = false; /** * The flag for the passive FTP data transfer mode. Default value is true, * cause it's usually the preferred FTP operating mode. */ private boolean passive = true; /** * The type of the data transfer contents (auto, textual, binary). The value * should be one of {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_AUTO}, * {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_TEXTUAL} and {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_BINARY} * constants. Default value is TYPE_AUTO. */ private int type = TYPE_AUTO; /** * The MLSD command policy. The value should be one of * {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_IF_SUPPORTED}, {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_ALWAYS} and * {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_NEVER} constants. Default value is * MLSD_IF_SUPPORTED. */ private int mlsdPolicy = MLSD_IF_SUPPORTED; /** * If this value is greater than 0, the auto-noop feature is enabled. If * positive, the field is used as a timeout value (expressed in * milliseconds). If autoNoopDelay milliseconds has passed without any * communication between the client and the server, a NOOP command is * automaticaly sent to the server by the client. */ private long autoNoopTimeout = 0; /** * The auto noop timer thread. */ private AutoNoopTimer autoNoopTimer; /** * The system time (in millis) of the moment when the next auto noop command * should be issued. */ private long nextAutoNoopTime; /** * A flag used to mark whether the connected server supports the resume of * broken transfers. */ private boolean restSupported = false; /** * The name of the charset used to establish textual communications. If not * null the client will use always the given charset. If null the client * tries to auto-detect the server charset. If this attempt fails the client * will use the machine current charset. */ private String charset = null; /** * This flag enables and disables the use of compression (ZLIB) during data * transfers. Compression is enabled when both this flag is true and the * server supports compressed transfers. */ private boolean compressionEnabled = false; /** * A flag used to mark whether the connected server supports UTF-8 pathnames * encoding. */ private boolean utf8Supported = false; /** * A flag used to mark whether the connected server supports the MLSD * command (RFC 3659). */ private boolean mlsdSupported = false; /** * A flag used to mark whether the connected server supports the MODE Z * command. */ private boolean modezSupported = false; /** * A flag used to mark whether MODE Z is enabled. */ private boolean modezEnabled = false; /** * This flag indicates whether the data channel is encrypted. */ private boolean dataChannelEncrypted = false; /** * This flag reports if there's any ongoing abortable data transfer * operation. Its value should be accessed only under the eye of the * abortLock synchronization object. */ private boolean ongoingDataTransfer = false; /** * The InputStream used for data transfer operations. */ private InputStream dataTransferInputStream = null; /** * The OutputStream used for data transfer operations. */ private OutputStream dataTransferOutputStream = null; /** * This flag turns to true when any data transfer stream is closed due to an * abort request. */ private boolean aborted = false; /** * This flags tells if the reply to an ABOR command waits to be consumed. */ private boolean consumeAborCommandReply = false; /** * Lock object used for synchronization. */ private Object lock = new Object(); /** * Lock object used for synchronization in abort operations. */ private Object abortLock = new Object(); /** * The communication channel established with the server. */ private FTPCommunicationChannel communication = null; /** * Builds and initializes the client. */ public FTPClient() { // The built-in parsers. addListParser(new UnixListParser()); addListParser(new DOSListParser()); addListParser(new EPLFListParser()); addListParser(new NetWareListParser()); addListParser(new MLSDListParser()); } /** * This method returns the connector used to connect the remote host. * * @return The connector used to connect the remote host. */ public FTPConnector getConnector() { synchronized (lock) { return connector; } } /** * This method sets the connector used to connect the remote host. * * Default one is a * it.sauronsoftware.ftp4j.connectors.direct.DirectConnector instance. * * @param connector * The connector used to connect the remote host. * @see DirectConnector */ public void setConnector(FTPConnector connector) { synchronized (lock) { this.connector = connector; } } /** * Sets the SSL socket factory used to negotiate SSL connections. * * @param sslSocketFactory * The SSL socket factory used to negotiate SSL connections. * * @since 1.4 */ public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { synchronized (lock) { this.sslSocketFactory = sslSocketFactory; } } /** * Returns the SSL socket factory used to negotiate SSL connections. * * @return The SSL socket factory used to negotiate SSL connections. * * @since 1.4 */ public SSLSocketFactory getSSLSocketFactory() { synchronized (lock) { return sslSocketFactory; } } /** * Sets the security level for the connection. This method should be called * before starting a connection with a server. The security level must be * expressed using one of the SECURITY_FTP, SECURITY_FTPS and SECURITY_FTPES * costants. * * SECURITY_FTP, which is the default value, applies the basic FTP security * level. * * SECURITY_FTPS applies the FTPS security level, which is FTP over implicit * TLS/SSL. * * SECURITY_FTPES applies the FTPES security level, which is FTP over * explicit TLS/SSL. * * @param security * The security level. * @throws IllegalStateException * If the client is already connected to a server. * @throws IllegalArgumentException * If the supplied security level is not valid. * @since 1.4 */ public void setSecurity(int security) throws IllegalStateException, IllegalArgumentException { if (security != SECURITY_FTP && security != SECURITY_FTPS && security != SECURITY_FTPES) { throw new IllegalArgumentException("Invalid security"); } synchronized (lock) { if (connected) { throw new IllegalStateException( "The security level of the connection can't be " + "changed while the client is connected"); } this.security = security; } } /** * Returns the security level used by the client in the connection. * * @return The security level, which could be one of the SECURITY_FTP, * SECURITY_FTPS and SECURITY_FTPES costants. * * @since 1.4 */ public int getSecurity() { return security; } /** * Applies SSL encryption to an already open socket. * * @param socket * The already established socket. * @param host * The logical destination host. * @param port * The logical destination port. * @return The SSL socket. * @throws java.io.IOException * If the SSL negotiation fails. */ private Socket ssl(Socket socket, String host, int port) throws IOException { return sslSocketFactory.createSocket(socket, host, port, true); } /** * This method enables/disables the use of the passive mode. * * @param passive * If true the passive mode is enabled. */ public void setPassive(boolean passive) { synchronized (lock) { this.passive = passive; } } /** * This methods sets how to treat the contents during a file transfer. * * The type supplied should be one of TYPE_AUTO, TYPE_TEXTUAL or TYPE_BINARY * constants. Default value is TYPE_AUTO. * * {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_TEXTUAL} means that the data sent or received is * treated as textual information. This implies charset conversion during * the transfer. * * {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_BINARY} means that the data sent or received is * treated as a binary stream. The data is taken "as is", without any * charset conversion. * * {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_AUTO} lets the client pick between textual and * binary types, depending on the extension of the file exchanged, using a * FTPTextualExtensionRecognizer instance, which could be set through the * setTextualExtensionRecognizer method. The default recognizer is an * instance of {@link DefaultTextualExtensionRecognizer}. * * @param type * The type. * @throws IllegalArgumentException * If the supplied type is not valid. * @see it.sauronsoftware.ftp4j.FTPClient#setTextualExtensionRecognizer(FTPTextualExtensionRecognizer) * @see DefaultTextualExtensionRecognizer */ public void setType(int type) throws IllegalArgumentException { if (type != TYPE_AUTO && type != TYPE_BINARY && type != TYPE_TEXTUAL) { throw new IllegalArgumentException("Invalid type"); } synchronized (lock) { this.type = type; } } /** * This method returns the value suggesting how the client encode and decode * the contents during a data transfer. * * @return The type as a numeric value. The value could be compared to the * constants {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_AUTO}, * {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_BINARY} and {@link it.sauronsoftware.ftp4j.FTPClient#TYPE_TEXTUAL}. */ public int getType() { synchronized (lock) { return type; } } /** * This method lets the user control how the client chooses whether to use * or not the MLSD command (RFC 3659) instead of the base LIST command. * * The type supplied should be one of MLSD_IF_SUPPORTED, MLSD_ALWAYS or * MLSD_NEVER constants. Default value is MLSD_IF_SUPPORTED. * * {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_IF_SUPPORTED} means that the client should use the * MLSD command only if it is explicitly supported by the server. * * {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_ALWAYS} means that the client should use always the * MLSD command, also if the MLSD command is not explicitly supported by the * server * * {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_NEVER} means that the client should use always only * the LIST command, also if the MLSD command is explicitly supported by the * server. * * The support for the MLSD command is tested by the client after the * connection to the remote server, with the FEAT command. * * @param mlsdPolicy * The MLSD policy. * @throws IllegalArgumentException * If the supplied MLSD policy value is not valid. * @since 1.5 */ public void setMLSDPolicy(int mlsdPolicy) throws IllegalArgumentException { if (type != MLSD_IF_SUPPORTED && type != MLSD_ALWAYS && type != MLSD_NEVER) { throw new IllegalArgumentException("Invalid MLSD policy"); } synchronized (lock) { this.mlsdPolicy = mlsdPolicy; } } /** * This method returns the value suggesting how the client chooses whether * to use or not the MLSD command (RFC 3659) instead of the base LIST * command. * * @return The MLSD policy as a numeric value. The value could be compared * to the constants {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_IF_SUPPORTED}, * {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_ALWAYS} and {@link it.sauronsoftware.ftp4j.FTPClient#MLSD_NEVER}. * @since 1.5 */ public int getMLSDPolicy() { synchronized (lock) { return mlsdPolicy; } } /** * Returns the name of the charset used to establish textual communications. * If not null the client will use always the given charset. If null the * client tries to auto-detect the server charset. If this attempt fails the * client will use the machine current charset. * * @return The name of the charset used to establish textual communications. * @since 1.1 */ public String getCharset() { synchronized (lock) { return charset; } } /** * Sets the name of the charset used to establish textual communications. If * not null the client will use always the given charset. If null the client * tries to auto-detect the server charset. If this attempt fails the client * will use the machine current charset. * * @param charset * The name of the charset used to establish textual * communications. * @since 1.1 */ public void setCharset(String charset) { synchronized (lock) { this.charset = charset; if (connected) { try { communication.changeCharset(pickCharset()); } catch (IOException e) { e.printStackTrace(); } } } } /** * Checks whether the connected server explicitly supports resuming of * broken data transfers. * * @return true if the server supports resuming, false otherwise. * @since 1.5.1 */ public boolean isResumeSupported() { synchronized (lock) { return restSupported; } } /** * Checks whether the connected remote FTP server supports compressed data * transfers (uploads, downloads, list operations etc.). If so, the * compression of any subsequent data transfer (upload, download, list etc.) * can be compressed, saving bandwidth. To enable compression call * {@link it.sauronsoftware.ftp4j.FTPClient#setCompressionEnabled(boolean)} . * * The returned value is not significant if the client is not connected and * authenticated. * * @return <em>true</em> if compression of data transfers is supported on * the server-side, <em>false</em> otherwise. * @see it.sauronsoftware.ftp4j.FTPClient#isCompressionEnabled() * @since 1.5 */ public boolean isCompressionSupported() { return modezSupported; } /** * Enables or disables the use of compression during any subsequent data * transfer. Compression is enabled when both the supplied value and the * {@link it.sauronsoftware.ftp4j.FTPClient#isCompressionSupported()}) returned value are * <em>true</em>. * * The default value is <em>false</em>. * * @param compressionEnabled * <em>true</em> to enable the use of compression during any * subsequent file transfer, <em>false</em> to disable the * feature. * @see it.sauronsoftware.ftp4j.FTPClient#isCompressionSupported() * @since 1.5 */ public void setCompressionEnabled(boolean compressionEnabled) { this.compressionEnabled = compressionEnabled; } /** * Checks whether the use of compression is enabled on the client-side. * * Please note that compressed transfers are actually enabled only if both * this method and {@link it.sauronsoftware.ftp4j.FTPClient#isCompressionSupported()} return * <em>true</em>. * * @return <em>true</em> if compression is enabled, <em>false</em> * otherwise. * @see it.sauronsoftware.ftp4j.FTPClient#isCompressionSupported() * @since 1.5 */ public boolean isCompressionEnabled() { return compressionEnabled; } /** * This method returns the textual extension recognizer used by the client. * * Default one is {@link DefaultTextualExtensionRecognizer}. * * @return The textual extension recognizer used by the client. * @see DefaultTextualExtensionRecognizer */ public FTPTextualExtensionRecognizer getTextualExtensionRecognizer() { synchronized (lock) { return textualExtensionRecognizer; } } /** * This method sets the textual extension recognizer used by the client. * * The default one is {@link DefaultTextualExtensionRecognizer}. * * You can plug your own by implementing the * {@link FTPTextualExtensionRecognizer} interface. For your convenience the * ftp4j gives you another FTPTextualExtensionRecognizer implementation, * which is {@link ParametricTextualExtensionRecognizer}. * * @param textualExtensionRecognizer * The textual extension recognizer used by the client. * @see DefaultTextualExtensionRecognizer * @see ParametricTextualExtensionRecognizer */ public void setTextualExtensionRecognizer(FTPTextualExtensionRecognizer textualExtensionRecognizer) { synchronized (lock) { this.textualExtensionRecognizer = textualExtensionRecognizer; } } /** * This method tests if this client is authenticated. * * @return true if this client is authenticated, false otherwise. */ public boolean isAuthenticated() { synchronized (lock) { return authenticated; } } /** * This method tests if this client is connected to a remote FTP server. * * @return true if this client is connected to a remote FTP server, false * otherwise. */ public boolean isConnected() { synchronized (lock) { return connected; } } /** * This method tests if this client works in passive FTP mode. * * @return true if this client is configured to work in passive FTP mode. */ public boolean isPassive() { synchronized (lock) { return passive; } } /** * If the client is connected, it reports the remote host name or address. * * @return The remote host name or address. */ public String getHost() { synchronized (lock) { return host; } } /** * If the client is connected, it reports the remote port number. * * @return The remote port number. */ public int getPort() { synchronized (lock) { return port; } } /** * If the client is authenticated, it reports the authentication password. * * @return The authentication password. */ public String getPassword() { synchronized (lock) { return password; } } /** * If the client is authenticated, it reports the authentication username. * * @return The authentication username. */ public String getUsername() { synchronized (lock) { return username; } } /** * Enable and disable the auto-noop feature. * * If the supplied value is greater than 0, the auto-noop feature is * enabled, otherwise it is disabled. If positive, the field is used as a * timeout value (expressed in milliseconds). If autoNoopDelay milliseconds * has passed without any communication between the client and the server, a * NOOP command is automaticaly sent to the server by the client. * * The default value for the auto noop delay is 0 (disabled). * * @param autoNoopTimeout * The duration of the auto-noop timeout, in milliseconds. If 0 * or less, the auto-noop feature is disabled. * * @since 1.5 */ public void setAutoNoopTimeout(long autoNoopTimeout) { synchronized (lock) { if (connected && authenticated) { stopAutoNoopTimer(); } long oldValue = this.autoNoopTimeout; long newValue = autoNoopTimeout; this.autoNoopTimeout = autoNoopTimeout; if (oldValue != 0 && newValue != 0 && nextAutoNoopTime > 0) { nextAutoNoopTime = nextAutoNoopTime - (oldValue - newValue); } if (connected && authenticated) { startAutoNoopTimer(); } } } /** * Returns the duration of the auto-noop timeout, in milliseconds. If 0 or * less, the auto-noop feature is disabled. * * @return The duration of the auto-noop timeout, in milliseconds. If 0 or * less, the auto-noop feature is disabled. * * @since 1.5 */ public long getAutoNoopTimeout() { synchronized (lock) { return autoNoopTimeout; } } /** * This method adds a FTPCommunicationListener to the object. * * @param listener * The listener. */ public void addCommunicationListener(FTPCommunicationListener listener) { synchronized (lock) { communicationListeners.add(listener); if (communication != null) { communication.addCommunicationListener(listener); } } } /** * This method removes a FTPCommunicationListener previously added to the * object. * * @param listener * The listener to be removed. */ public void removeCommunicationListener(FTPCommunicationListener listener) { synchronized (lock) { communicationListeners.remove(listener); if (communication != null) { communication.removeCommunicationListener(listener); } } } /** * This method returns a list with all the {@link FTPCommunicationListener} * used by the client. * * @return A list with all the FTPCommunicationListener used by the client. */ public FTPCommunicationListener[] getCommunicationListeners() { synchronized (lock) { int size = communicationListeners.size(); FTPCommunicationListener[] ret = new FTPCommunicationListener[size]; for (int i = 0; i < size; i++) { ret[i] = (FTPCommunicationListener) communicationListeners.get(i); } return ret; } } /** * This method adds a {@link FTPListParser} to the object. * * @param listParser * The list parser. */ public void addListParser(FTPListParser listParser) { synchronized (lock) { listParsers.add(listParser); } } /** * This method removes a {@link FTPListParser} previously added to the * object. * * @param listParser * The list parser to be removed. */ public void removeListParser(FTPListParser listParser) { synchronized (lock) { listParsers.remove(listParser); } } /** * This method returns a list with all the {@link FTPListParser} used by the * client. * * @return A list with all the FTPListParsers used by the client. */ public FTPListParser[] getListParsers() { synchronized (lock) { int size = listParsers.size(); FTPListParser[] ret = new FTPListParser[size]; for (int i = 0; i < size; i++) { ret[i] = (FTPListParser) listParsers.get(i); } return ret; } } /** * This method connects the client to the remote FTP host, using the default * port value 21 (990 if security level is set to FTPS, see * {@link it.sauronsoftware.ftp4j.FTPClient#setSecurity(int)}). * * @param host * The hostname of the remote server. * @return The server welcome message, one line per array element. * @throws IllegalStateException * If the client is already connected to a remote host. * @throws java.io.IOException * If an I/O occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the server refuses the connection. */ public String[] connect(String host) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { int def; if (security == SECURITY_FTPS) { def = 990; } else { def = 21; } return connect(host, def); } /** * This method connects the client to the remote FTP host. * * @param host * The host name or address of the remote server. * @param port * The port listened by the remote server. * @return The server welcome message, one line per array element. * @throws IllegalStateException * If the client is already connected to a remote host. * @throws java.io.IOException * If an I/O occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the server refuses the connection. */ public String[] connect(String host, int port) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client already connected to any host? if (connected) { throw new IllegalStateException("Client already connected to " + host + " on port " + port); } // Ok, it's connection time. Let's try! Socket connection = null; try { // Open the connection. connection = connector.connectForCommunicationChannel(host, port); if (security == SECURITY_FTPS) { connection = ssl(connection, host, port); } // Open the communication channel. communication = new FTPCommunicationChannel(connection, pickCharset()); for (Iterator i = communicationListeners.iterator(); i.hasNext();) { communication.addCommunicationListener((FTPCommunicationListener) i.next()); } // Welcome message. FTPReply wm = communication.readFTPReply(); // Does this reply mean "ok"? if (!wm.isSuccessCode()) { // Mmmmm... it seems no! throw new FTPException(wm); } // Flag this object as connected to the remote host. this.connected = true; this.authenticated = false; this.parser = null; this.host = host; this.port = port; this.username = null; this.password = null; this.utf8Supported = false; this.restSupported = false; this.mlsdSupported = false; this.modezSupported = false; this.dataChannelEncrypted = false; // Returns the welcome message. return wm.getMessages(); } catch (IOException e) { // D'oh! throw e; } finally { // If connection has failed... if (!connected) { if (connection != null) { // Close the connection, 'cause it should be open. try { connection.close(); } catch (Throwable t) { ; } } } } } } /** * Aborts the current connection attempt. It can be called by a secondary * thread while the client is blocked in a <em>connect()</em> call. The * connect() method will exit with an {@link java.io.IOException}. * * @since 1.7 */ public void abortCurrentConnectionAttempt() { connector.abortConnectForCommunicationChannel(); } /** * This method disconnects from the remote server, optionally performing the * QUIT procedure. * * @param sendQuitCommand * If true the QUIT procedure with the server will be performed, * otherwise the connection is abruptly closed by the client * without sending any advice to the server. * @throws IllegalStateException * If the client is not connected to a remote host. * @throws java.io.IOException * If an I/O occurs (can be thrown only if sendQuitCommand is * true). * @throws FTPIllegalReplyException * If the server replies in an illegal way (can be thrown only * if sendQuitCommand is true). * @throws FTPException * If the server refuses the QUIT command (can be thrown only if * sendQuitCommand is true). */ public void disconnect(boolean sendQuitCommand) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Stops the auto noop timer (if started). if (authenticated) { stopAutoNoopTimer(); } // Send QUIT? if (sendQuitCommand) { // Call the QUIT command. communication.sendFTPCommand("QUIT"); FTPReply r = communication.readFTPReply(); if (!r.isSuccessCode()) { throw new FTPException(r); } } // Close the communication. communication.close(); communication = null; // Reset the connection flag. connected = false; } } /** * This method causes the communication channel to be abruptly closed. Use * it carefully, since this one is not thread-safe. It is given as an * "emergency brake" to close the control connection when it is blocked. A * thread-safe solution for the same purpose is a call to disconnect(false). * * @see it.sauronsoftware.ftp4j.FTPClient#disconnect(boolean) */ public void abruptlyCloseCommunication() { // Close the communication. if (communication != null) { communication.close(); communication = null; } // Reset the connection flag. connected = false; // Stops the auto noop timer. stopAutoNoopTimer(); } /** * This method authenticates the user against the server. * * @param username * The username. * @param password * The password (if none set it to null). * @throws IllegalStateException * If the client is not connected. Call the connect() method * before! * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If login fails. */ public void login(String username, String password) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { login(username, password, null); } /** * This method authenticates the user against the server. * * @param username * The username. * @param password * The password (if none set it to null). * @param account * The account (if none set it to null). Be careful: some servers * don't implement this feature. * @throws IllegalStateException * If the client is not connected. Call the connect() method * before! * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If login fails. */ public void login(String username, String password, String account) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // AUTH TLS command if security is FTPES if (security == SECURITY_FTPES) { communication.sendFTPCommand("AUTH TLS"); FTPReply r = communication.readFTPReply(); if (r.isSuccessCode()) { communication.ssl(sslSocketFactory); } else { communication.sendFTPCommand("AUTH SSL"); r = communication.readFTPReply(); if (r.isSuccessCode()) { communication.ssl(sslSocketFactory); } else { throw new FTPException(r.getCode(), "SECURITY_FTPES cannot be applied: " + "the server refused both AUTH TLS and AUTH SSL commands"); } } } // Reset the authentication flag. authenticated = false; // Usefull flags. boolean passwordRequired; boolean accountRequired; // Send the user and read the reply. communication.sendFTPCommand("USER " + username); FTPReply r = communication.readFTPReply(); switch (r.getCode()) { case 230: // Password and account aren't required. passwordRequired = false; accountRequired = false; break; case 331: // Password is required. passwordRequired = true; // Account... maybe! More information later... accountRequired = false; break; case 332: // Password is not required, but account is required. passwordRequired = false; accountRequired = true; default: // User validation failed. throw new FTPException(r); } // Password. if (passwordRequired) { if (password == null) { throw new FTPException(331); } // Send the password. communication.sendFTPCommand("PASS " + password); r = communication.readFTPReply(); switch (r.getCode()) { case 230: // Account is not required. accountRequired = false; break; case 332: // Account is required. accountRequired = true; break; default: // Authentication failed. throw new FTPException(r); } } // Account. if (accountRequired) { if (account == null) { throw new FTPException(332); } // Send the account. communication.sendFTPCommand("ACCT " + account); r = communication.readFTPReply(); switch (r.getCode()) { case 230: // Well done! break; default: // Something goes wrong. throw new FTPException(r); } } // Well, if this point is reached the client could consider itself // as authenticated. this.authenticated = true; this.username = username; this.password = password; } // Post-login operations. postLoginOperations(); // Starts the auto noop timer. startAutoNoopTimer(); } /** * Performs some post-login operations, such trying to detect server support * for utf8. * * @throws IllegalStateException * If the client is not connected. Call the connect() method * before! * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If login fails. */ private void postLoginOperations() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { utf8Supported = false; restSupported = false; mlsdSupported = false; modezSupported = false; dataChannelEncrypted = false; communication.sendFTPCommand("FEAT"); FTPReply r = communication.readFTPReply(); if (r.getCode() == 211) { String[] lines = r.getMessages(); for (int i = 1; i < lines.length - 1; i++) { String feat = lines[i].trim().toUpperCase(); // REST STREAM supported? if ("REST STREAM".equalsIgnoreCase(feat)) { restSupported = true; continue; } // UTF8 supported? if ("UTF8".equalsIgnoreCase(feat)) { utf8Supported = true; communication.changeCharset("UTF-8"); continue; } // MLSD supported? if ("MLSD".equalsIgnoreCase(feat)) { mlsdSupported = true; continue; } // MODE Z supported? if ("MODE Z".equalsIgnoreCase(feat) || feat.startsWith("MODE Z ")) { modezSupported = true; continue; } } } // Turn UTF 8 on (if supported). if (utf8Supported) { communication.sendFTPCommand("OPTS UTF8 ON"); communication.readFTPReply(); } // Data channel security. if (security == SECURITY_FTPS || security == SECURITY_FTPES) { communication.sendFTPCommand("PBSZ 0"); communication.readFTPReply(); communication.sendFTPCommand("PROT P"); FTPReply reply = communication.readFTPReply(); if (reply.isSuccessCode()) { dataChannelEncrypted = true; } } } } /** * This method performs a logout operation for the current user, leaving the * connection open, thus it can be used to start a new user session. Be * careful with this: some FTP servers don't implement this feature, even * though it is a standard FTP one. * * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public void logout() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Send the REIN command. communication.sendFTPCommand("REIN"); FTPReply r = communication.readFTPReply(); if (!r.isSuccessCode()) { throw new FTPException(r); } else { // Stops the auto noop timer. stopAutoNoopTimer(); // Ok. Not authenticated, now. authenticated = false; username = null; password = null; } } } /** * This method performs a "noop" operation with the server. * * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If login fails. */ public void noop() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Safe code try { // Send the noop. communication.sendFTPCommand("NOOP"); FTPReply r = communication.readFTPReply(); if (!r.isSuccessCode()) { throw new FTPException(r); } } finally { // Resets auto noop timer. touchAutoNoopTimer(); } } } /** * This method sends a custom command to the server. Don't use this method * to send standard commands already supported by the client: this should * cause unexpected results. * * @param command * The command line. * @return The reply supplied by the server, parsed and served in an object * way mode. * @throws IllegalStateException * If this client is not connected. * @throws java.io.IOException * If a I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. */ public FTPReply sendCustomCommand(String command) throws IllegalStateException, IOException, FTPIllegalReplyException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Sends the command. communication.sendFTPCommand(command); // Resets auto noop timer. touchAutoNoopTimer(); // Returns the reply. return communication.readFTPReply(); } } /** * This method sends a SITE specific command to the server. * * @param command * The site command. * @return The reply supplied by the server, parsed and served in an object * way mode. * @throws IllegalStateException * If this client is not connected. * @throws java.io.IOException * If a I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. */ public FTPReply sendSiteCommand(String command) throws IllegalStateException, IOException, FTPIllegalReplyException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Sends the command. communication.sendFTPCommand("SITE " + command); // Resets auto noop timer. touchAutoNoopTimer(); // Returns the reply. return communication.readFTPReply(); } } /** * Call this method to switch the user current account. Be careful with * this: some FTP servers don't implement this feature, even though it is a * standard FTP one. * * @param account * The account. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If login fails. */ public void changeAccount(String account) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Send the ACCT command. communication.sendFTPCommand("ACCT " + account); // Gets the reply. FTPReply r = communication.readFTPReply(); // Resets auto noop timer. touchAutoNoopTimer(); // Evaluates the response. if (!r.isSuccessCode()) { throw new FTPException(r); } } } /** * This method asks and returns the current working directory. * * @return path The path to the current working directory. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public String currentDirectory() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Send the PWD command. communication.sendFTPCommand("PWD"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Parse the response. String[] messages = r.getMessages(); if (messages.length != 1) { throw new FTPIllegalReplyException(); } Matcher m = PWD_PATTERN.matcher(messages[0]); if (m.find()) { return messages[0].substring(m.start() + 1, m.end() - 1); } else { throw new FTPIllegalReplyException(); } } } /** * This method changes the current working directory. * * @param path * The path to the new working directory. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public void changeDirectory(String path) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Send the CWD command. communication.sendFTPCommand("CWD " + path); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } } } /** * This method changes the current working directory to the parent one. * * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public void changeDirectoryUp() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the CWD command. communication.sendFTPCommand("CDUP"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } } } /** * This method asks and returns the last modification date of a file or * directory. * * @param path * The path to the file or the directory. * @return The file/directory last modification date. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public Date modifiedDate(String path) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the MDTM command. communication.sendFTPCommand("MDTM " + path); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } String[] messages = r.getMessages(); if (messages.length != 1) { throw new FTPIllegalReplyException(); } else { try { return MDTM_DATE_FORMAT.parse(messages[0]); } catch (ParseException e) { throw new FTPIllegalReplyException(); } } } } /** * This method asks and returns a file size in bytes. * * @param path * The path to the file. * @return The file size in bytes. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public long fileSize(String path) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the TYPE I command. communication.sendFTPCommand("TYPE I"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Sends the SIZE command. communication.sendFTPCommand("SIZE " + path); r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } String[] messages = r.getMessages(); if (messages.length != 1) { throw new FTPIllegalReplyException(); } else { try { return Long.parseLong(messages[0]); } catch (Throwable t) { throw new FTPIllegalReplyException(); } } } } /** * This method renames a remote file or directory. It can also be used to * move a file or a directory. * * In example: * * <pre> * client.rename(&quot;oldname&quot;, &quot;newname&quot;); // This one renames * </pre> * * <pre> * client.rename(&quot;the/old/path/oldname&quot;, &quot;/a/new/path/newname&quot;); // This one moves * </pre> * * @param oldPath * The current path of the file (or directory). * @param newPath * The new path for the file (or directory). * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public void rename(String oldPath, String newPath) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the RNFR command. communication.sendFTPCommand("RNFR " + oldPath); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.getCode() != 350) { throw new FTPException(r); } // Sends the RNFR command. communication.sendFTPCommand("RNTO " + newPath); r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } } } /** * This method deletes a remote file. * * @param path * The path to the file. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public void deleteFile(String path) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the DELE command. communication.sendFTPCommand("DELE " + path); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } } } /** * This method deletes a remote directory. * * @param path * The path to the directory. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public void deleteDirectory(String path) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the RMD command. communication.sendFTPCommand("RMD " + path); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } } } /** * This method creates a new remote directory in the current working one. * * @param directoryName * The name of the new directory. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public void createDirectory(String directoryName) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the MKD command. communication.sendFTPCommand("MKD " + directoryName); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } } } /** * This method calls the HELP command on the remote server, returning a list * of lines with the help contents. * * @return The help contents, splitted by line. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public String[] help() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the HELP command. communication.sendFTPCommand("HELP"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } return r.getMessages(); } } /** * This method returns the remote server status, as the result of a FTP STAT * command. * * @return The remote server status, splitted by line. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. */ public String[] serverStatus() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Sends the STAT command. communication.sendFTPCommand("STAT"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } return r.getMessages(); } } /** * This method lists the entries of the current working directory parsing * the reply to a FTP LIST command. * * The response to the LIST command is parsed through the FTPListParser * objects registered on the client. The distribution of ftp4j contains some * standard parsers already registered on every FTPClient object created. If * they don't work in your case (a FTPListParseException is thrown), you can * build your own parser implementing the FTPListParser interface and add it * to the client by calling its addListParser() method. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The list() method will break with a * FTPAbortedException. * * @param fileSpec * A file filter string. Depending on the server implementation, * wildcard characters could be accepted. * @return The list of the files (and directories) in the current working * directory. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @throws FTPListParseException * If none of the registered parsers can handle the response * sent by the server. * @see FTPListParser * @see it.sauronsoftware.ftp4j.FTPClient#addListParser(FTPListParser) * @see it.sauronsoftware.ftp4j.FTPClient#getListParsers() * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) * @see it.sauronsoftware.ftp4j.FTPClient#listNames() * @since 1.2 */ public FTPFile[] list(String fileSpec) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException, FTPListParseException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // ASCII, please! communication.sendFTPCommand("TYPE A"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Prepares the connection for the data transfer. FTPDataTransferConnectionProvider provider = openDataTransferChannel(); // MLSD or LIST command? boolean mlsdCommand; if (mlsdPolicy == MLSD_IF_SUPPORTED) { mlsdCommand = mlsdSupported; } else if (mlsdPolicy == MLSD_ALWAYS) { mlsdCommand = true; } else { mlsdCommand = false; } String command = mlsdCommand ? "MLSD" : "LIST"; // Adds the file/directory selector. if (fileSpec != null && fileSpec.length() > 0) { command += " " + fileSpec; } // Prepares the lines array. ArrayList lines = new ArrayList(); // Local abort state. boolean wasAborted = false; // Sends the command. communication.sendFTPCommand(command); try { Socket dtConnection; try { dtConnection = provider.openDataTransferConnection(); } finally { provider.dispose(); } // Change the operation status. synchronized (abortLock) { ongoingDataTransfer = true; aborted = false; consumeAborCommandReply = false; } // Fetch the list from the data transfer connection. NVTASCIIReader dataReader = null; try { // Opens the data transfer connection. dataTransferInputStream = dtConnection.getInputStream(); // MODE Z enabled? if (modezEnabled) { dataTransferInputStream = new InflaterInputStream(dataTransferInputStream); } // Let's do it! dataReader = new NVTASCIIReader(dataTransferInputStream, mlsdCommand ? "UTF-8" : pickCharset()); String line; while ((line = dataReader.readLine()) != null) { if (line.length() > 0) { lines.add(line); } } } catch (IOException e) { synchronized (abortLock) { if (aborted) { throw new FTPAbortedException(); } else { throw new FTPDataTransferException( "I/O error in data transfer", e); } } } finally { if (dataReader != null) { try { dataReader.close(); } catch (Throwable t) { ; } } try { dtConnection.close(); } catch (Throwable t) { ; } // Set to null the instance-level input stream. dataTransferInputStream = null; // Change the operation status. synchronized (abortLock) { wasAborted = aborted; ongoingDataTransfer = false; aborted = false; } } } finally { r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.getCode() != 150 && r.getCode() != 125) { throw new FTPException(r); } // Consumes the result reply of the transfer. r = communication.readFTPReply(); if (!wasAborted && r.getCode() != 226) { throw new FTPException(r); } // ABOR command response (if needed). if (consumeAborCommandReply) { communication.readFTPReply(); consumeAborCommandReply = false; } } // Build an array of lines. int size = lines.size(); String[] list = new String[size]; for (int i = 0; i < size; i++) { list[i] = (String) lines.get(i); } // Parse the list. FTPFile[] ret = null; if (mlsdCommand) { // Forces the MLSDListParser. MLSDListParser parser = new MLSDListParser(); ret = parser.parse(list); } else { // Is there any already successful parser? if (parser != null) { // Yes, let's try with it. try { ret = parser.parse(list); } catch (FTPListParseException e) { // That parser doesn't work anymore. parser = null; } } // Is there an available result? if (ret == null) { // Try to parse the list with every available parser. for (Iterator i = listParsers.iterator(); i.hasNext();) { FTPListParser aux = (FTPListParser) i.next(); try { // Let's try! ret = aux.parse(list); // This parser smells good! parser = aux; // Leave the loop. break; } catch (FTPListParseException e) { // Let's try the next one. continue; } } } } if (ret == null) { // None of the parsers can handle the list response. throw new FTPListParseException(); } else { // Return the parsed list. return ret; } } } /** * This method lists the entries of the current working directory parsing * the reply to a FTP LIST command. * * The response to the LIST command is parsed through the FTPListParser * objects registered on the client. The distribution of ftp4j contains some * standard parsers already registered on every FTPClient object created. If * they don't work in your case (a FTPListParseException is thrown), you can * build your own parser implementing the FTPListParser interface and add it * to the client by calling its addListParser() method. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The list() method will break with a * FTPAbortedException. * * @return The list of the files (and directories) in the current working * directory. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @throws FTPListParseException * If none of the registered parsers can handle the response * sent by the server. * @see FTPListParser * @see it.sauronsoftware.ftp4j.FTPClient#addListParser(FTPListParser) * @see it.sauronsoftware.ftp4j.FTPClient#getListParsers() * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) * @see it.sauronsoftware.ftp4j.FTPClient#listNames() */ public FTPFile[] list() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException, FTPListParseException { return list(null); } /** * This method lists the entries of the current working directory with a FTP * NLST command. * * The response consists in an array of string, each one reporting the name * of a file or a directory placed in the current working directory. For a * more detailed directory listing procedure look at the list() method. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The listNames() method will break with a * FTPAbortedException. * * @return The list of the files (and directories) in the current working * directory. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @throws FTPListParseException * If none of the registered parsers can handle the response * sent by the server. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) * @see it.sauronsoftware.ftp4j.FTPClient#list() */ public String[] listNames() throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException, FTPListParseException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // ASCII, please! communication.sendFTPCommand("TYPE A"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Prepares the lines array. ArrayList lines = new ArrayList(); // Local abort state. boolean wasAborted = false; // Prepares the connection for the data transfer. FTPDataTransferConnectionProvider provider = openDataTransferChannel(); // Send the NLST command. communication.sendFTPCommand("NLST"); try { Socket dtConnection; try { dtConnection = provider.openDataTransferConnection(); } finally { provider.dispose(); } // Change the operation status. synchronized (abortLock) { ongoingDataTransfer = true; aborted = false; consumeAborCommandReply = false; } // Fetch the list from the data transfer connection. NVTASCIIReader dataReader = null; try { // Opens the data transfer connection. dataTransferInputStream = dtConnection.getInputStream(); // MODE Z enabled? if (modezEnabled) { dataTransferInputStream = new InflaterInputStream(dataTransferInputStream); } // Let's do it! dataReader = new NVTASCIIReader(dataTransferInputStream, pickCharset()); String line; while ((line = dataReader.readLine()) != null) { if (line.length() > 0) { lines.add(line); } } } catch (IOException e) { synchronized (abortLock) { if (aborted) { throw new FTPAbortedException(); } else { throw new FTPDataTransferException( "I/O error in data transfer", e); } } } finally { if (dataReader != null) { try { dataReader.close(); } catch (Throwable t) { ; } } try { dtConnection.close(); } catch (Throwable t) { ; } // Set to null the instance-level input stream. dataTransferInputStream = null; // Change the operation status. synchronized (abortLock) { wasAborted = aborted; ongoingDataTransfer = false; aborted = false; } } } finally { r = communication.readFTPReply(); if (r.getCode() != 150 && r.getCode() != 125) { throw new FTPException(r); } // Consumes the result reply of the transfer. r = communication.readFTPReply(); if (!wasAborted && r.getCode() != 226) { throw new FTPException(r); } // ABOR command response (if needed). if (consumeAborCommandReply) { communication.readFTPReply(); consumeAborCommandReply = false; } } // Build an array. int size = lines.size(); String[] list = new String[size]; for (int i = 0; i < size; i++) { list[i] = (String) lines.get(i); } return list; } } /** * This method uploads a file to the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param file * The file to upload. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void upload(File file) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { upload(file, 0, null); } /** * This method uploads a file to the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param file * The file to upload. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void upload(File file, FTPDataTransferListener listener) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { upload(file, 0, listener); } /** * This method uploads a file to the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param file * The file to upload. * @param restartAt * The restart point (number of bytes already uploaded). Use * {@link it.sauronsoftware.ftp4j.FTPClient#isResumeSupported()} to check if the server * supports resuming of broken data transfers. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void upload(File file, long restartAt) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { upload(file, restartAt, null); } /** * This method uploads a file to the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param file * The file to upload. * @param restartAt * The restart point (number of bytes already uploaded). Use * {@link it.sauronsoftware.ftp4j.FTPClient#isResumeSupported()} to check if the server * supports resuming of broken data transfers. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void upload(File file, long restartAt, FTPDataTransferListener listener) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (IOException e) { throw new FTPDataTransferException(e); } try { upload(file.getName(), inputStream, restartAt, restartAt, listener); } catch (IllegalStateException e) { throw e; } catch (IOException e) { throw e; } catch (FTPIllegalReplyException e) { throw e; } catch (FTPException e) { throw e; } catch (FTPDataTransferException e) { throw e; } catch (FTPAbortedException e) { throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ; } } } } /** * This method uploads a content to the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param fileName * The name of the remote file. * @param inputStream * The source of data. * @param restartAt * The restart point (number of bytes already uploaded). Use * {@link it.sauronsoftware.ftp4j.FTPClient#isResumeSupported()} to check if the server * supports resuming of broken data transfers. * @param streamOffset * The offset to skip in the stream. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void upload(String fileName, InputStream inputStream, long restartAt, long streamOffset, FTPDataTransferListener listener) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Select the type of contents. int tp = type; if (tp == TYPE_AUTO) { tp = detectType(fileName); } if (tp == TYPE_TEXTUAL) { communication.sendFTPCommand("TYPE A"); } else if (tp == TYPE_BINARY) { communication.sendFTPCommand("TYPE I"); } FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Prepares the connection for the data transfer. FTPDataTransferConnectionProvider provider = openDataTransferChannel(); // REST command (if supported and/or requested). if (restSupported || restartAt > 0) { boolean done = false; try { communication.sendFTPCommand("REST " + restartAt); r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.getCode() != 350 && ((r.getCode() != 501 && r.getCode() != 502) || restartAt > 0)) { throw new FTPException(r); } done = true; } finally { if (!done) { provider.dispose(); } } } // Local abort state. boolean wasAborted = false; // Send the STOR command. communication.sendFTPCommand("STOR " + fileName); try { Socket dtConnection; try { dtConnection = provider.openDataTransferConnection(); } finally { provider.dispose(); } // Change the operation status. synchronized (abortLock) { ongoingDataTransfer = true; aborted = false; consumeAborCommandReply = false; } // Upload the stream. try { // Skips. inputStream.skip(streamOffset); // Opens the data transfer connection. dataTransferOutputStream = dtConnection.getOutputStream(); // MODE Z enabled? if (modezEnabled) { dataTransferOutputStream = new DeflaterOutputStream(dataTransferOutputStream); } // Listeners. if (listener != null) { listener.started(); } // Let's do it! if (tp == TYPE_TEXTUAL) { Reader reader = new InputStreamReader(inputStream); Writer writer = new OutputStreamWriter( dataTransferOutputStream, pickCharset()); char[] buffer = new char[SEND_AND_RECEIVE_BUFFER_SIZE]; int l; while ((l = reader.read(buffer)) != -1) { writer.write(buffer, 0, l); writer.flush(); if (listener != null) { listener.transferred(l); } } } else if (tp == TYPE_BINARY) { byte[] buffer = new byte[SEND_AND_RECEIVE_BUFFER_SIZE]; int l; while ((l = inputStream.read(buffer)) != -1) { dataTransferOutputStream.write(buffer, 0, l); dataTransferOutputStream.flush(); if (listener != null) { listener.transferred(l); } } } } catch (IOException e) { synchronized (abortLock) { if (aborted) { if (listener != null) { listener.aborted(); } throw new FTPAbortedException(); } else { if (listener != null) { listener.failed(); } throw new FTPDataTransferException( "I/O error in data transfer", e); } } } finally { // Closing stream and data connection. if (dataTransferOutputStream != null) { try { dataTransferOutputStream.close(); } catch (Throwable t) { ; } } try { dtConnection.close(); } catch (Throwable t) { ; } // Set to null the instance-level input stream. dataTransferOutputStream = null; // Change the operation status. synchronized (abortLock) { wasAborted = aborted; ongoingDataTransfer = false; aborted = false; } } } finally { // Data transfer command reply. r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.getCode() != 150 && r.getCode() != 125) { throw new FTPException(r); } // Consumes the result reply of the transfer. r = communication.readFTPReply(); if (!wasAborted && r.getCode() != 226) { throw new FTPException(r); } // ABOR command response (if needed). if (consumeAborCommandReply) { communication.readFTPReply(); consumeAborCommandReply = false; } } // Listener notification. if (listener != null) { listener.completed(); } } } /** * This method appends the contents of a local file to an existing file on * the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param file * The local file whose contents will be appended to the remote * file. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) * @since 1.6 */ public void append(File file) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { append(file, null); } /** * This method uploads a file to the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param file * The local file whose contents will be appended to the remote * file. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) * @since 1.6 */ public void append(File file, FTPDataTransferListener listener) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (IOException e) { throw new FTPDataTransferException(e); } try { append(file.getName(), inputStream, 0, listener); } catch (IllegalStateException e) { throw e; } catch (IOException e) { throw e; } catch (FTPIllegalReplyException e) { throw e; } catch (FTPException e) { throw e; } catch (FTPDataTransferException e) { throw e; } catch (FTPAbortedException e) { throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ; } } } } /** * This method appends data to an existing file on the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param fileName * The name of the remote file. * @param inputStream * The source of data. * @param streamOffset * The offset to skip in the stream. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) * @since 1.6 */ public void append(String fileName, InputStream inputStream, long streamOffset, FTPDataTransferListener listener) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Select the type of contents. int tp = type; if (tp == TYPE_AUTO) { tp = detectType(fileName); } if (tp == TYPE_TEXTUAL) { communication.sendFTPCommand("TYPE A"); } else if (tp == TYPE_BINARY) { communication.sendFTPCommand("TYPE I"); } FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Local abort state. boolean wasAborted = false; // Prepares the connection for the data transfer. FTPDataTransferConnectionProvider provider = openDataTransferChannel(); // Send the STOR command. communication.sendFTPCommand("APPE " + fileName); try { Socket dtConnection; try { dtConnection = provider.openDataTransferConnection(); } finally { provider.dispose(); } // Change the operation status. synchronized (abortLock) { ongoingDataTransfer = true; aborted = false; consumeAborCommandReply = false; } // Upload the stream. try { // Skips. inputStream.skip(streamOffset); // Opens the data transfer connection. dataTransferOutputStream = dtConnection.getOutputStream(); // MODE Z enabled? if (modezEnabled) { dataTransferOutputStream = new DeflaterOutputStream(dataTransferOutputStream); } // Listeners. if (listener != null) { listener.started(); } // Let's do it! if (tp == TYPE_TEXTUAL) { Reader reader = new InputStreamReader(inputStream); Writer writer = new OutputStreamWriter( dataTransferOutputStream, pickCharset()); char[] buffer = new char[SEND_AND_RECEIVE_BUFFER_SIZE]; int l; while ((l = reader.read(buffer)) != -1) { writer.write(buffer, 0, l); writer.flush(); if (listener != null) { listener.transferred(l); } } } else if (tp == TYPE_BINARY) { byte[] buffer = new byte[SEND_AND_RECEIVE_BUFFER_SIZE]; int l; while ((l = inputStream.read(buffer)) != -1) { dataTransferOutputStream.write(buffer, 0, l); dataTransferOutputStream.flush(); if (listener != null) { listener.transferred(l); } } } } catch (IOException e) { synchronized (abortLock) { if (aborted) { if (listener != null) { listener.aborted(); } throw new FTPAbortedException(); } else { if (listener != null) { listener.failed(); } throw new FTPDataTransferException( "I/O error in data transfer", e); } } } finally { // Closing stream and data connection. if (dataTransferOutputStream != null) { try { dataTransferOutputStream.close(); } catch (Throwable t) { ; } } try { dtConnection.close(); } catch (Throwable t) { ; } // Set to null the instance-level input stream. dataTransferOutputStream = null; // Change the operation status. synchronized (abortLock) { wasAborted = aborted; ongoingDataTransfer = false; aborted = false; } } } finally { r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.getCode() != 150 && r.getCode() != 125) { throw new FTPException(r); } // Consumes the result reply of the transfer. r = communication.readFTPReply(); if (!wasAborted && r.getCode() != 226) { throw new FTPException(r); } // ABOR command response (if needed). if (consumeAborCommandReply) { communication.readFTPReply(); consumeAborCommandReply = false; } } // Notifies the listener. if (listener != null) { listener.completed(); } } } /** * This method downloads a remote file from the server to a local file. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param remoteFileName * The name of the file to download. * @param localFile * The local file. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void download(String remoteFileName, File localFile) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { download(remoteFileName, localFile, 0, null); } /** * This method downloads a remote file from the server to a local file. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param remoteFileName * The name of the file to download. * @param localFile * The local file. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void download(String remoteFileName, File localFile, FTPDataTransferListener listener) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { download(remoteFileName, localFile, 0, listener); } /** * This method resumes a download operation from the remote server to a * local file. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param remoteFileName * The name of the file to download. * @param localFile * The local file. * @param restartAt * The restart point (number of bytes already downloaded). Use * {@link it.sauronsoftware.ftp4j.FTPClient#isResumeSupported()} to check if the server * supports resuming of broken data transfers. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void download(String remoteFileName, File localFile, long restartAt) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { download(remoteFileName, localFile, restartAt, null); } /** * This method resumes a download operation from the remote server to a * local file. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param remoteFileName * The name of the file to download. * @param localFile * The local file. * @param restartAt * The restart point (number of bytes already downloaded). Use * {@link it.sauronsoftware.ftp4j.FTPClient#isResumeSupported()} to check if the server * supports resuming of broken data transfers. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.FileNotFoundException * If the supplied file cannot be found. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void download(String remoteFileName, File localFile, long restartAt, FTPDataTransferListener listener) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { OutputStream outputStream = null; try { outputStream = new FileOutputStream(localFile, restartAt > 0); } catch (IOException e) { throw new FTPDataTransferException(e); } try { download(remoteFileName, outputStream, restartAt, listener); } catch (IllegalStateException e) { throw e; } catch (IOException e) { throw e; } catch (FTPIllegalReplyException e) { throw e; } catch (FTPException e) { throw e; } catch (FTPDataTransferException e) { throw e; } catch (FTPAbortedException e) { throw e; } finally { if (outputStream != null) { try { outputStream.close(); } catch (Throwable t) { ; } } } } /** * This method resumes a download operation from the remote server. * * Calling this method blocks the current thread until the operation is * completed. The operation could be interrupted by another thread calling * abortCurrentDataTransfer(). The method will break with a * FTPAbortedException. * * @param fileName * The name of the remote file. * @param outputStream * The destination stream of data read during the download. * @param restartAt * The restart point (number of bytes already downloaded). Use * {@link it.sauronsoftware.ftp4j.FTPClient#isResumeSupported()} to check if the server * supports resuming of broken data transfers. * @param listener * The listener for the operation. Could be null. * @throws IllegalStateException * If the client is not connected or not authenticated. * @throws java.io.IOException * If an I/O error occurs. * @throws FTPIllegalReplyException * If the server replies in an illegal way. * @throws FTPException * If the operation fails. * @throws FTPDataTransferException * If a I/O occurs in the data transfer connection. If you * receive this exception the transfer failed, but the main * connection with the remote FTP server is in theory still * working. * @throws FTPAbortedException * If operation is aborted by another thread. * @see it.sauronsoftware.ftp4j.FTPClient#abortCurrentDataTransfer(boolean) */ public void download(String fileName, OutputStream outputStream, long restartAt, FTPDataTransferListener listener) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException { synchronized (lock) { // Is this client connected? if (!connected) { throw new IllegalStateException("Client not connected"); } // Is this client authenticated? if (!authenticated) { throw new IllegalStateException("Client not authenticated"); } // Select the type of contents. int tp = type; if (tp == TYPE_AUTO) { tp = detectType(fileName); } if (tp == TYPE_TEXTUAL) { communication.sendFTPCommand("TYPE A"); } else if (tp == TYPE_BINARY) { communication.sendFTPCommand("TYPE I"); } FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Prepares the connection for the data transfer. FTPDataTransferConnectionProvider provider = openDataTransferChannel(); // REST command (if supported and/or requested). if (restSupported || restartAt > 0) { boolean done = false; try { communication.sendFTPCommand("REST " + restartAt); r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.getCode() != 350 && ((r.getCode() != 501 && r.getCode() != 502) || restartAt > 0)) { throw new FTPException(r); } done = true; } finally { if (!done) { provider.dispose(); } } } // Local abort state. boolean wasAborted = false; // Send the RETR command. communication.sendFTPCommand("RETR " + fileName); try { Socket dtConnection; try { dtConnection = provider.openDataTransferConnection(); } finally { provider.dispose(); } // Change the operation status. synchronized (abortLock) { ongoingDataTransfer = true; aborted = false; consumeAborCommandReply = false; } // Download the stream. try { // Opens the data transfer connection. dataTransferInputStream = dtConnection.getInputStream(); // MODE Z enabled? if (modezEnabled) { dataTransferInputStream = new InflaterInputStream(dataTransferInputStream); } // Listeners. if (listener != null) { listener.started(); } // Let's do it! if (tp == TYPE_TEXTUAL) { Reader reader = new InputStreamReader( dataTransferInputStream, pickCharset()); Writer writer = new OutputStreamWriter(outputStream); char[] buffer = new char[SEND_AND_RECEIVE_BUFFER_SIZE]; int l; while ((l = reader.read(buffer, 0, buffer.length)) != -1) { writer.write(buffer, 0, l); writer.flush(); if (listener != null) { listener.transferred(l); } } } else if (tp == TYPE_BINARY) { byte[] buffer = new byte[SEND_AND_RECEIVE_BUFFER_SIZE]; int l; while ((l = dataTransferInputStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, l); if (listener != null) { listener.transferred(l); } } } } catch (IOException e) { synchronized (abortLock) { if (aborted) { if (listener != null) { listener.aborted(); } throw new FTPAbortedException(); } else { if (listener != null) { listener.failed(); } throw new FTPDataTransferException( "I/O error in data transfer", e); } } } finally { // Closing stream and data connection. if (dataTransferInputStream != null) { try { dataTransferInputStream.close(); } catch (Throwable t) { ; } } try { dtConnection.close(); } catch (Throwable t) { ; } // Set to null the instance-level input stream. dataTransferInputStream = null; // Change the operation status. synchronized (abortLock) { wasAborted = aborted; ongoingDataTransfer = false; aborted = false; } } } finally { r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.getCode() != 150 && r.getCode() != 125) { throw new FTPException(r); } // Consumes the result reply of the transfer. r = communication.readFTPReply(); if (!wasAborted && r.getCode() != 226) { throw new FTPException(r); } // ABOR command response (if needed). if (consumeAborCommandReply) { communication.readFTPReply(); consumeAborCommandReply = false; } } // Notifies the listener. if (listener != null) { listener.completed(); } } } /** * This method detects the type for a file transfer. */ private int detectType(String fileName) throws IOException, FTPIllegalReplyException, FTPException { int start = fileName.lastIndexOf('.') + 1; int stop = fileName.length(); if (start > 0 && start < stop - 1) { String ext = fileName.substring(start, stop); ext = ext.toLowerCase(); if (textualExtensionRecognizer.isTextualExt(ext)) { return TYPE_TEXTUAL; } else { return TYPE_BINARY; } } else { return TYPE_BINARY; } } /** * This method opens a data transfer channel. */ private FTPDataTransferConnectionProvider openDataTransferChannel() throws IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException { // MODE Z? if (modezSupported && compressionEnabled) { if (!modezEnabled) { // Sends the MODE Z command. communication.sendFTPCommand("MODE Z"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.isSuccessCode()) { modezEnabled = true; } } } else { if (modezEnabled) { // Sends the MODE S command. communication.sendFTPCommand("MODE S"); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (r.isSuccessCode()) { modezEnabled = false; } } } // Active or passive? if (passive) { return openPassiveDataTransferChannel(); } else { return openActiveDataTransferChannel(); } } /** * This method opens a data transfer channel in active mode. */ private FTPDataTransferConnectionProvider openActiveDataTransferChannel() throws IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException { // Create a FTPDataTransferServer object. FTPDataTransferServer server = new FTPDataTransferServer() { public Socket openDataTransferConnection() throws FTPDataTransferException { Socket socket = super.openDataTransferConnection(); if (dataChannelEncrypted) { try { socket = ssl(socket, socket.getInetAddress().getHostName(), socket.getPort()); } catch (IOException e) { try { socket.close(); } catch (Throwable t) { } throw new FTPDataTransferException(e); } } return socket; } }; int port = server.getPort(); int p1 = port >>> 8; int p2 = port & 0xff; int[] addr = pickLocalAddress(); // Send the port command. communication.sendFTPCommand("PORT " + addr[0] + "," + addr[1] + "," + addr[2] + "," + addr[3] + "," + p1 + "," + p2); FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { // Disposes. server.dispose(); // Closes the already open connection (if any). try { Socket aux = server.openDataTransferConnection(); aux.close(); } catch (Throwable t) { ; } // Throws the exception. throw new FTPException(r); } return server; } /** * This method opens a data transfer channel in passive mode. */ private FTPDataTransferConnectionProvider openPassiveDataTransferChannel() throws IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException { // Send the PASV command. communication.sendFTPCommand("PASV"); // Read the reply. FTPReply r = communication.readFTPReply(); touchAutoNoopTimer(); if (!r.isSuccessCode()) { throw new FTPException(r); } // Use a regexp to extract the remote address and port. String addressAndPort = null; String[] messages = r.getMessages(); for (int i = 0; i < messages.length; i++) { Matcher m = PASV_PATTERN.matcher(messages[i]); if (m.find()) { int start = m.start(); int end = m.end(); addressAndPort = messages[i].substring(start, end); break; } } if (addressAndPort == null) { // The remote server has not sent the coordinates for the // data transfer connection. throw new FTPIllegalReplyException(); } // Parse the string extracted from the reply. StringTokenizer st = new StringTokenizer(addressAndPort, ","); int b1 = Integer.parseInt(st.nextToken()); int b2 = Integer.parseInt(st.nextToken()); int b3 = Integer.parseInt(st.nextToken()); int b4 = Integer.parseInt(st.nextToken()); int p1 = Integer.parseInt(st.nextToken()); int p2 = Integer.parseInt(st.nextToken()); final String pasvHost = b1 + "." + b2 + "." + b3 + "." + b4; final int pasvPort = (p1 << 8) | p2; FTPDataTransferConnectionProvider provider = new FTPDataTransferConnectionProvider() { public Socket openDataTransferConnection() throws FTPDataTransferException { // Establish the connection. Socket dtConnection; try { String selectedHost = connector.getUseSuggestedAddressForDataConnections() ? pasvHost : host; dtConnection = connector.connectForDataTransferChannel(selectedHost, pasvPort); if (dataChannelEncrypted) { dtConnection = ssl(dtConnection, selectedHost, pasvPort); } } catch (IOException e) { throw new FTPDataTransferException("Cannot connect to the remote server", e); } return dtConnection; } public void dispose() { // nothing to do } }; return provider; } /** * If there's any ongoing data transfer operation, this method aborts it. * * @param sendAborCommand * If true the client will negotiate the abort procedure with the * server, through the standard FTP ABOR command. Otherwise the * open data transfer connection will be closed without any * advise has sent to the server. * @throws java.io.IOException * If the ABOR command cannot be sent due to any I/O error. This * could happen only if force is false. * @throws FTPIllegalReplyException * If the server reply to the ABOR command is illegal. This * could happen only if force is false. */ public void abortCurrentDataTransfer(boolean sendAborCommand) throws IOException, FTPIllegalReplyException { synchronized (abortLock) { if (ongoingDataTransfer && !aborted) { if (sendAborCommand) { communication.sendFTPCommand("ABOR"); touchAutoNoopTimer(); consumeAborCommandReply = true; } if (dataTransferInputStream != null) { try { dataTransferInputStream.close(); } catch (Throwable t) { ; } } if (dataTransferOutputStream != null) { try { dataTransferOutputStream.close(); } catch (Throwable t) { ; } } aborted = true; } } } /** * Returns the name of the charset that should be used in textual * transmissions. * * @return The name of the charset that should be used in textual * transmissions. */ private String pickCharset() { if (charset != null) { return charset; } else if (utf8Supported) { return "UTF-8"; } else { return System.getProperty("file.encoding"); } } /** * Picks the local address for an active data transfer operation. * * @return The local address as a 4 integer values array. * @throws java.io.IOException * If an unexpected I/O error occurs while trying to resolve the * local address. */ private int[] pickLocalAddress() throws IOException { // Forced address? int[] ret = pickForcedLocalAddress(); // Auto-detect? if (ret == null) { ret = pickAutoDetectedLocalAddress(); } // Returns. return ret; } /** * If a local address for active data transfers has been supplied through * the {@link FTPKeys#ACTIVE_DT_HOST_ADDRESS}, it returns it as a 4 elements * integer array; otherwise it returns null. * * @return The forced local address, or null. */ private int[] pickForcedLocalAddress() { int[] ret = null; String aux = System.getProperty(FTPKeys.ACTIVE_DT_HOST_ADDRESS); if (aux != null) { boolean valid = false; StringTokenizer st = new StringTokenizer(aux, "."); if (st.countTokens() == 4) { valid = true; int[] arr = new int[4]; for (int i = 0; i < 4; i++) { String tk = st.nextToken(); try { arr[i] = Integer.parseInt(tk); } catch (NumberFormatException e) { arr[i] = -1; } if (arr[i] < 0 || arr[i] > 255) { valid = false; break; } } if (valid) { ret = arr; } } if (!valid) { // warning to the developer System.err.println("WARNING: invalid value \"" + aux + "\" for the " + FTPKeys.ACTIVE_DT_HOST_ADDRESS + " system property. The value should " + "be in the x.x.x.x form."); } } return ret; } /** * Auto-detects the local network address, and returns it in the form of a 4 * elements integer array. * * @return The detected local address. * @throws java.io.IOException * If an unexpected I/O error occurs while trying to resolve the * local address. */ private int[] pickAutoDetectedLocalAddress() throws IOException { InetAddress addressObj = InetAddress.getLocalHost(); byte[] addr = addressObj.getAddress(); int b1 = addr[0] & 0xff; int b2 = addr[1] & 0xff; int b3 = addr[2] & 0xff; int b4 = addr[3] & 0xff; int[] ret = { b1, b2, b3, b4 }; return ret; } public String toString() { synchronized (lock) { StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()); buffer.append(" [connected="); buffer.append(connected); if (connected) { buffer.append(", host="); buffer.append(host); buffer.append(", port="); buffer.append(port); } buffer.append(", connector="); buffer.append(connector); buffer.append(", security="); switch (security) { case SECURITY_FTP: buffer.append("SECURITY_FTP"); break; case SECURITY_FTPS: buffer.append("SECURITY_FTPS"); break; case SECURITY_FTPES: buffer.append("SECURITY_FTPES"); break; } buffer.append(", authenticated="); buffer.append(authenticated); if (authenticated) { buffer.append(", username="); buffer.append(username); buffer.append(", password="); StringBuffer buffer2 = new StringBuffer(); for (int i = 0; i < password.length(); i++) { buffer2.append('*'); } buffer.append(buffer2); buffer.append(", restSupported="); buffer.append(restSupported); buffer.append(", utf8supported="); buffer.append(utf8Supported); buffer.append(", mlsdSupported="); buffer.append(mlsdSupported); buffer.append(", mode=modezSupported"); buffer.append(modezSupported); buffer.append(", mode=modezEnabled"); buffer.append(modezEnabled); } buffer.append(", transfer mode="); buffer.append(passive ? "passive" : "active"); buffer.append(", transfer type="); switch (type) { case TYPE_AUTO: buffer.append("TYPE_AUTO"); break; case TYPE_BINARY: buffer.append("TYPE_BINARY"); break; case TYPE_TEXTUAL: buffer.append("TYPE_TEXTUAL"); break; } buffer.append(", textualExtensionRecognizer="); buffer.append(textualExtensionRecognizer); FTPListParser[] listParsers = getListParsers(); if (listParsers.length > 0) { buffer.append(", listParsers="); for (int i = 0; i < listParsers.length; i++) { if (i > 0) { buffer.append(", "); } buffer.append(listParsers[i]); } } FTPCommunicationListener[] communicationListeners = getCommunicationListeners(); if (communicationListeners.length > 0) { buffer.append(", communicationListeners="); for (int i = 0; i < communicationListeners.length; i++) { if (i > 0) { buffer.append(", "); } buffer.append(communicationListeners[i]); } } buffer.append(", autoNoopTimeout="); buffer.append(autoNoopTimeout); buffer.append("]"); return buffer.toString(); } } /** * Starts the auto-noop timer thread. */ private void startAutoNoopTimer() { if (autoNoopTimeout > 0) { autoNoopTimer = new AutoNoopTimer(); autoNoopTimer.start(); } } /** * Stops the auto-noop timer thread. * * @since 1.5 */ private void stopAutoNoopTimer() { if (autoNoopTimer != null) { autoNoopTimer.interrupt(); autoNoopTimer = null; } } /** * Resets the auto noop timer. */ private void touchAutoNoopTimer() { if (autoNoopTimer != null) { nextAutoNoopTime = System.currentTimeMillis() + autoNoopTimeout; } } /** * The auto noop timer thread. */ private class AutoNoopTimer extends Thread { public void run() { synchronized (lock) { if (nextAutoNoopTime <= 0 && autoNoopTimeout > 0) { nextAutoNoopTime = System.currentTimeMillis() + autoNoopTimeout; } while (!Thread.interrupted() && autoNoopTimeout > 0) { // Sleep till the next NOOP. long delay = nextAutoNoopTime - System.currentTimeMillis(); if (delay > 0) { try { lock.wait(delay); } catch (InterruptedException e) { break; } } // Is it really time to NOOP? if (System.currentTimeMillis() >= nextAutoNoopTime) { // Yes! try { noop(); } catch (Throwable t) { ; // ignore... } } } } } } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; /** * Exception thrown if any I/O error occurs during a data transfer attempt. * * @author Carlo Pelliccia */ public class FTPDataTransferException extends Exception { private static final long serialVersionUID = 1L; public FTPDataTransferException() { super(); } public FTPDataTransferException(String message, Throwable cause) { super(message, cause); } public FTPDataTransferException(String message) { super(message); } public FTPDataTransferException(Throwable cause) { super(cause); } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.StringTokenizer; /** * This class implements a local server to make data transfer with the remote * FTP server. * * @author Carlo Pelliccia */ class FTPDataTransferServer implements FTPDataTransferConnectionProvider, Runnable { /** * The ServerSocket object waiting for the incoming connection. */ private ServerSocket serverSocket = null; /** * The socket to be established with the remote host. */ private Socket socket; /** * The exception thrown during the wait for a connection (if any!). */ private IOException exception; /** * The thread executing the listening for incoming connection routine. */ private Thread thread; /** * Build the object. * * @throws FTPDataTransferException * If a I/O error occurs. */ public FTPDataTransferServer() throws FTPDataTransferException { boolean useRange = false; String aux = System.getProperty(FTPKeys.ACTIVE_DT_PORT_RANGE); int start = 0; int stop = 0; if (aux != null) { boolean valid = false; StringTokenizer st = new StringTokenizer(aux, "-"); if (st.countTokens() == 2) { String s1 = st.nextToken(); String s2 = st.nextToken(); int v1; try { v1 = Integer.parseInt(s1); } catch (NumberFormatException e) { v1 = 0; } int v2; try { v2 = Integer.parseInt(s2); } catch (NumberFormatException e) { v2 = 0; } if (v1 > 0 && v2 > 0 && v2 >= v1) { start = v1; stop = v2; valid = true; useRange = true; } } if (!valid) { // warning to the developer System.err.println("WARNING: invalid value \"" + aux + "\" for the " + FTPKeys.ACTIVE_DT_PORT_RANGE + " system property. The value should " + "be in the start-stop form, with " + "start > 0, stop > 0 and start <= stop."); } } if (useRange) { ArrayList availables = new ArrayList(); for (int i = start; i <= stop; i++) { availables.add(new Integer(i)); } int size; boolean done = false; while (!done && (size = availables.size()) > 0) { int rand = (int) Math.floor(Math.random() * size); int port = ((Integer) availables.remove(rand)).intValue(); // Tries with the obtained value; try { serverSocket = new ServerSocket(); serverSocket.setReceiveBufferSize(512 * 1024); serverSocket.bind(new InetSocketAddress(port)); done = true; } catch (IOException e) { // Port not available. } } if (!done) { throw new FTPDataTransferException( "Cannot open the ServerSocket. " + "No available port found in range " + aux); } } else { // Don't use a port range. try { serverSocket = new ServerSocket(); serverSocket.setReceiveBufferSize(512 * 1024); serverSocket.bind(new InetSocketAddress(0)); } catch (IOException e) { throw new FTPDataTransferException( "Cannot open the ServerSocket", e); } } // Starts the server thread. thread = new Thread(this); thread.start(); } /** * Returns the local port the server socket is bounded. * * @return The local port. */ public int getPort() { return serverSocket.getLocalPort(); } public void run() { int timeout = 30000; String aux = System.getProperty(FTPKeys.ACTIVE_DT_ACCEPT_TIMEOUT); if (aux != null) { boolean valid = false; int value; try { value = Integer.parseInt(aux); } catch (NumberFormatException e) { value = -1; } if (value >= 0) { timeout = value; valid = true; } if (!valid) { // warning to the developer System.err.println("WARNING: invalid value \"" + aux + "\" for the " + FTPKeys.ACTIVE_DT_ACCEPT_TIMEOUT + " system property. The value should " + "be an integer greater or equal to 0."); } } try { // Set the socket timeout. serverSocket.setSoTimeout(timeout); // Wait for the incoming connection. socket = serverSocket.accept(); socket.setSendBufferSize(512 * 1024); } catch (IOException e) { exception = e; } finally { // Close the server socket. try { serverSocket.close(); } catch (IOException e) { ; } } } /** * Disposes the server and interrupts every operating stream. */ public void dispose() { // Close the server socket (if open). if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { ; } } } public Socket openDataTransferConnection() throws FTPDataTransferException { if (socket == null && exception == null) { try { thread.join(); } catch (Exception e) { ; } } if (exception != null) { throw new FTPDataTransferException( "Cannot receive the incoming connection", exception); } if (socket == null) { throw new FTPDataTransferException("No socket available"); } return socket; } }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; /** * This abstract class is the base for creating a connector. Connectors are used * by the client to establish connections with remote servers. * * @author Carlo Pelliccia */ public abstract class FTPConnector { /** * Timeout in seconds for connection enstablishing. * * @since 1.7 */ protected int connectionTimeout = 10; /** * Timeout in seconds for read operations. * * @since 1.7 */ protected int readTimeout = 10; /** * Timeout in seconds for connection regular closing. * * @since 1.7 */ protected int closeTimeout = 10; /** * This flag determines the behavior of the connector when it has to open a * connection toward the server to perform a passive data transfer. * * @see it.sauronsoftware.ftp4j.FTPConnector#setUseSuggestedAddressForDataConnections(boolean) * @since 1.7.1 */ private boolean useSuggestedAddressForDataConnections; /** * The socket of an ongoing connection attempt for a communication channel. * * @since 1.7 */ private Socket connectingCommunicationChannelSocket; /** * Builds the connector. * * @param useSuggestedAddressForDataConnectionsDefValue * The connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag. * * @see it.sauronsoftware.ftp4j.FTPConnector#setUseSuggestedAddressForDataConnections(boolean) */ protected FTPConnector(boolean useSuggestedAddressForDataConnectionsDefValue) { String sysprop = System.getProperty(FTPKeys.PASSIVE_DT_USE_SUGGESTED_ADDRESS); if ("true".equalsIgnoreCase(sysprop) || "yes".equalsIgnoreCase(sysprop) || "1".equals(sysprop)) { useSuggestedAddressForDataConnections = true; } else if ("false".equalsIgnoreCase(sysprop) || "no".equalsIgnoreCase(sysprop) || "0".equals(sysprop)) { useSuggestedAddressForDataConnections = false; } else { useSuggestedAddressForDataConnections = useSuggestedAddressForDataConnectionsDefValue; } } /** * Builds the connector. * * By calling this constructor, the connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag is <em>false</em>. */ protected FTPConnector() { this(false); } /** * Sets the timeout for connection operations. * * @param connectionTimeout * The timeout value in seconds. * @since 1.7 */ public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } /** * Sets the timeout for read operations. * * @param readTimeout * The timeout value in seconds. * @since 1.7 */ public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } /** * Sets the timeout for close operations. * * @param closeTimeout * The timeout value in seconds. * @since 1.7 */ public void setCloseTimeout(int closeTimeout) { this.closeTimeout = closeTimeout; } /** * This flag determines the behavior of the connector when it has to open a * connection toward the server to perform a passive data transfer. * * If the flag is <em>true</em>, the client connects to the IP address * returned as a reply of the PASV command. * * If the flag is <em>false</em>, the client ignores the IP address * suggested by the server, and it connects to the same host used for the * communication connection (the same host supplied in the * {@link FTPClient#connect(String)} and * {@link FTPClient#connect(String, int)} methods). In this case, the * response to the PASV command is used only to determinate the port for the * connection. * * The default value for this flag (the one used if you never the method is * never called) depends on: * <ul> * <li>The specific FTPConnector implementation. Every FTPConnector could * choose a different default value for the property. It should declare the * default value in its own documentation.</li> * <li>The value of the * &quot;ftp4j.passiveDataTransfer.useSuggestedAddress&quot; system * property. Regardless the connector's default value, the flag will be * <em>true</em> if the system property value is &quot;true&quot;, * &quot;yes&quot; or &quot;1&quot;. Viceversa, it is <em>false</em> if the * system property value is &quot;false&quot;, &quot;no&quot; or * &quot;0&quot;.</li> * </ul> * * @param value * The value for the flag. */ public void setUseSuggestedAddressForDataConnections(boolean value) { this.useSuggestedAddressForDataConnections = value; } /** * Returns the value for the <em>useSuggestedAddressForDataConnections</em> * flag. * * @return The value for the <em>useSuggestedAddressForDataConnections</em> * flag. */ boolean getUseSuggestedAddressForDataConnections() { return useSuggestedAddressForDataConnections; } /** * Creates a socket and connects it to the given host for a communication * channel. Socket timeouts are automatically set according to the values of * {@link it.sauronsoftware.ftp4j.FTPConnector#connectionTimeout}, {@link it.sauronsoftware.ftp4j.FTPConnector#readTimeout} * and {@link it.sauronsoftware.ftp4j.FTPConnector#closeTimeout}. * * If you are extending FTPConnector, consider using this method to * establish your socket connection for the communication channel, instead * of creating Socket objects, since it is already aware of the timeout * values possibly given by the caller. Moreover the caller can abort * connection calling {@link FTPClient#abortCurrentConnectionAttempt()}. * * @param host * The host for the connection. * @param port * The port for the connection. * @return The connected socket. * @throws java.io.IOException * If connection fails. * @since 1.7 */ protected Socket tcpConnectForCommunicationChannel(String host, int port) throws IOException { try { connectingCommunicationChannelSocket = new Socket(); connectingCommunicationChannelSocket.setKeepAlive(true); connectingCommunicationChannelSocket.setSoTimeout(readTimeout * 1000); connectingCommunicationChannelSocket.setSoLinger(true, closeTimeout); connectingCommunicationChannelSocket.connect(new InetSocketAddress(host, port), connectionTimeout * 1000); return connectingCommunicationChannelSocket; } finally { connectingCommunicationChannelSocket = null; } } /** * Creates a socket and connects it to the given host for a data transfer * channel. Socket timeouts are automatically set according to the values of * {@link it.sauronsoftware.ftp4j.FTPConnector#connectionTimeout}, {@link it.sauronsoftware.ftp4j.FTPConnector#readTimeout} * and {@link it.sauronsoftware.ftp4j.FTPConnector#closeTimeout}. * * If you are extending FTPConnector, consider using this method to * establish your socket connection for the communication channel, instead * of creating Socket objects, since it is already aware of the timeout * values possibly given by the caller. * * @param host * The host for the connection. * @param port * The port for the connection. * @return The connected socket. * @throws java.io.IOException * If connection fails. * @since 1.7 */ protected Socket tcpConnectForDataTransferChannel(String host, int port) throws IOException { Socket socket = new Socket(); socket.setSoTimeout(readTimeout * 1000); socket.setSoLinger(true, closeTimeout); socket.setReceiveBufferSize(512 * 1024); socket.setSendBufferSize(512 * 1024); socket.connect(new InetSocketAddress(host, port), connectionTimeout * 1000); return socket; } /** * Aborts an ongoing connection attempt for a communication channel. * * @since 1.7 */ public void abortConnectForCommunicationChannel() { if (connectingCommunicationChannelSocket != null) { try { connectingCommunicationChannelSocket.close(); } catch (Throwable t) { } } } /** * This methods returns an established connection to a remote host, suitable * for a FTP communication channel. * * @param host * The remote host name or address. * @param port * The remote port. * @return The connection with the remote host. * @throws java.io.IOException * If the connection cannot be established. */ public abstract Socket connectForCommunicationChannel(String host, int port) throws IOException; /** * This methods returns an established connection to a remote host, suitable * for a FTP data transfer channel. * * @param host * The remote host name or address. * @param port * The remote port. * @return The connection with the remote host. * @throws java.io.IOException * If the connection cannot be established. */ public abstract Socket connectForDataTransferChannel(String host, int port) throws IOException; }
Java
/* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 Carlo Pelliccia (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.StringTokenizer; /** * This is an NVT-ASCII character stream writer. * * @author Carlo Pelliccia * @version 1.1 */ class NVTASCIIWriter extends Writer { /** * NTV line separator. */ private static final String LINE_SEPARATOR = "\r\n"; /** * The wrapped stream. */ private OutputStream stream; /** * The underlying writer. */ private Writer writer; /** * Builds the writer. * * @param stream * The underlying stream. * @param charsetName * The name of a supported charset. * @throws java.io.IOException * If an I/O error occurs. */ public NVTASCIIWriter(OutputStream stream, String charsetName) throws IOException { this.stream = stream; this.writer = new OutputStreamWriter(stream, charsetName); } /** * Causes this writer to be closed. * * @throws java.io.IOException */ public void close() throws IOException { synchronized (this) { writer.close(); } } public void flush() throws IOException { synchronized (this) { writer.flush(); } } public void write(char[] cbuf, int off, int len) throws IOException { synchronized (this) { writer.write(cbuf, off, len); } } /** * Changes the current charset. * * @param charsetName * The new charset. * @throws java.io.IOException * If I/O error occurs. * @since 1.1 */ public void changeCharset(String charsetName) throws IOException { synchronized (this) { writer = new OutputStreamWriter(stream, charsetName); } } /** * Writes a line in the stream. * * @param str * The line. * @throws java.io.IOException * If an I/O error occurs. */ public void writeLine(String str) throws IOException { StringBuffer buffer = new StringBuffer(); boolean atLeastOne = false; StringTokenizer st = new StringTokenizer(str, LINE_SEPARATOR); int count = st.countTokens(); for (int i = 0; i < count; i++) { String line = st.nextToken(); if (line.length() > 0) { if (atLeastOne) { buffer.append('\r'); buffer.append((char) 0); } buffer.append(line); atLeastOne = true; } } if (buffer.length() > 0) { String statement = buffer.toString(); // Sends the statement to the server. writer.write(statement); writer.write(LINE_SEPARATOR); writer.flush(); } } }
Java
package com.birdorg.anpr.sdk.simple.camera.example; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.AsyncPlayer; import android.media.AudioManager; import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.widget.TextView; import android.widget.Toast; public class AnprSdkExampleCheckingService extends Service { static AsyncPlayer asp; Context context; class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { Bundle b = msg.getData(); String numberPlate = b.getString("NumberPlate"); // NumberPlate data numberPlate = numberPlate.substring(2); String plate = "AA "+numberPlate; // boolean r = CheckCar(numberPlate); // check the car String res = ""; if (numberPlate != null) { res = " OK"; // car is OK } else { res = " Kujdes! Kjo makine ka Gjoba"; //car is not OK //int sound = context.getResources().getIdentifier("alert", "raw", context.getPackageName()); //asp.play(context, Uri.parse("android.resource://" + context.getPackageName() + "/" + sound), false, AudioManager.STREAM_MUSIC); } // Toast.makeText(getApplicationContext(), numberPlate + res, Toast.LENGTH_SHORT).show(); // show the checking result // return (numberPlate+"->"+res); Toast.makeText(getApplicationContext(), plate, Toast.LENGTH_SHORT).show(); // show the checking result } } final Messenger mMessenger = new Messenger(new IncomingHandler()); @Override public IBinder onBind(Intent arg0) { return mMessenger.getBinder(); } private boolean CheckCar(String aNumberPlate) // car checking function { boolean ret = false; char c = aNumberPlate.charAt(aNumberPlate.length() - 1); if (c == 2 * (int)(c / 2)) { ret = true; } return ret; } @Override public void onCreate() { context = getApplicationContext(); asp = new AsyncPlayer("t"); } }
Java
package com.birdorg.anpr.sdk.simple.camera.example; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.widget.ListView; import android.widget.Toast; import android.view.View; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import it.sauronsoftware.ftp4j.FTPClient; public class AnprSdkMenu extends ListActivity { static final String[] MOBILE_OS = new String[] { "Kontrollo", "Lista", "Kontrollet e Sotme", "Penalizimet e Sotme", "Konfigurimet", "FtpUpload"}; public static String SDK_PATH; public static String SDK_TEMP_PATH; /********* work only for Dedicated IP ***********/ static final String FTP_HOST= "comport.first.al"; /********* FTP USERNAME ***********/ static final String FTP_USER = "androidfirst"; /********* FTP PASSWORD ***********/ static final String FTP_PASS ="MNXjqJET"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createDir(); setListAdapter(new MenuArrayAdapter(this, MOBILE_OS)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); String cheese = MOBILE_OS[position]; if (position == 2) { cheese = "KontrolletSotme"; }else if (position == 3) { cheese = "PenalizimetSotme"; } try { String username = getIntent().getExtras().getString("Username"); Class ourClass = Class.forName("com.birdorg.anpr.sdk.simple.camera.example."+cheese); Intent ourIntent = new Intent(AnprSdkMenu.this, ourClass); ourIntent.putExtra("Username",username); startActivity(ourIntent); }catch (ClassNotFoundException e) { e.printStackTrace(); } } public void createDir(){ FTPClient client = new FTPClient(); try { client.connect(FTP_HOST,21); client.login(FTP_USER, FTP_PASS); client.setType(FTPClient.TYPE_BINARY); client.changeDirectory("/comport.first.al/anpr/uploads/"); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); //get current date time with Date() Date date = new Date(); client.createDirectory(dateFormat.format(date)); } catch (Exception e) { e.printStackTrace(); try { client.disconnect(true); } catch (Exception e2) { e2.printStackTrace(); } } } }
Java
package com.birdorg.anpr.sdk.simple.camera.example; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Vector; import static com.birdorg.anpr.sdk.simple.camera.example.R.drawable.cam; import static com.birdorg.anpr.sdk.simple.camera.example.R.drawable.cap; /** * Created by john on 7/22/2014. */ public class PenalizimetSotme extends ListActivity{ private ProgressDialog pDialog; private static final String TARGA_PENALIZIMET_SOTME_URL = "http://www.comport.first.al/anpr/penalizimet_sotme.php"; /* $post["gjoba"] = $row["gjoba"]; $post["shuma"] = $row["shuma"]; $post["targa"] = $row["targa"]; $post["data"] = $row["data"]; $post["pajisje_id"] = $row["pajisje_id"]; $post["user_id"] = $row["user_id"]; $post["imazhi"] = $row["imazhi"];*/ private static final String TAG_GJOBA = "gjoba"; private static final String TAG_SHUME = "shuma"; private static final String TAG_DATA = "data"; private static final String TAG_PAJISJE_ID= "pajisje_id"; private static final String TAG_USER_ID= "user_id"; private static final String TAG_CAPTURE_ID= "imazhi"; private static final String TAG_TARGA= "targa"; private static final String TAG_POSTS = "posts"; private JSONArray mPlates = null; // manages all of our comments in a list. private ArrayList<HashMap<String, String>> mPlatesList; ItemKontrollo item; private Vector<ItemKontrollo> VECITEM = new Vector<ItemKontrollo>(); private Vector<ItemKontrollo> VECITEM2 = new Vector<ItemKontrollo>(); // gets the content of each tag String gjoba; String shuma; String targa; String data; String pajisje_id; String user_id; String capture_image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // loading the comments via AsyncTask new LoadComments().execute(); } public void updateJSONdata() { mPlatesList = new ArrayList<HashMap<String, String>>(); JSONParser jParser = new JSONParser(); JSONObject json = jParser.getJSONFromUrl(TARGA_PENALIZIMET_SOTME_URL); item = new ItemKontrollo(); try { mPlates = json.getJSONArray(TAG_POSTS); // looping through all posts according to the json object returned for (int i = 0; i < mPlates.length(); i++) { JSONObject c = mPlates.getJSONObject(i); // gets the content of each tag gjoba = c.getString(TAG_GJOBA); shuma = c.getString(TAG_SHUME); targa = c.getString(TAG_TARGA); data = c.getString(TAG_DATA); pajisje_id = c.getString(TAG_PAJISJE_ID); user_id = c.getString(TAG_USER_ID); capture_image = c.getString(TAG_CAPTURE_ID); item.setGjoba(gjoba); item.setShuma(shuma); item.setTarga(targa); item.setData(data); item.setUser(user_id); item.setImgpath(capture_image); VECITEM.add(item); item = new ItemKontrollo(); } } catch (JSONException e) { e.printStackTrace(); } } private void updateKontrollo() { int length = VECITEM.size(); Collections.reverse(VECITEM); //Collections.copy(VECITEM2, VECITEM); for(int index=0; index < 5; index++){ ItemKontrollo item = VECITEM.get(index); VECITEM2.add(item); } setListAdapter(new PenalizimetSotemAdapter(this, VECITEM2)); ListView goclick= getListView(); goclick.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ItemKontrollo item = VECITEM2.get(position); String plate = item.getTarga(); String platepath = item.getImgpath(); String gjobaplate = item.getGjoba(); String shumaplate = item.getShuma(); Intent intent = new Intent(PenalizimetSotme.this,Printo.class); String ss = plate.substring(3, plate.length()); String sm = ss.substring(0, 1); int some = Integer.parseInt(sm); if (some == 1) { intent.putExtra("Ngjyra","Bardhe"); intent.putExtra("Marka","Peageut"); intent.putExtra("Pronar","Altin Gjokaj"); }else if (some == 2 ){ intent.putExtra("Ngjyra","Kuqe"); intent.putExtra("Marka","BMW"); intent.putExtra("Pronar","Manushaqe Veli"); }else if (some == 3) { intent.putExtra("Ngjyra","Zeze"); intent.putExtra("Marka","Fiat"); intent.putExtra("Pronar","Maria Mari"); }else if (some == 4) { intent.putExtra("Ngjyra","Gri"); intent.putExtra("Marka","Alfa Romeo"); intent.putExtra("Pronar","Albert Beri"); }else if (some == 5) { intent.putExtra("Ngjyra","Zeze"); intent.putExtra("Marka","Suzuki"); intent.putExtra("Pronar","Mario Shabani"); }else if (some == 6) { intent.putExtra("Ngjyra","Blu"); intent.putExtra("Marka","Subaru"); intent.putExtra("Pronar","Elton Anori"); }else if (some == 7){ intent.putExtra("Ngjyra","Gri"); intent.putExtra("Marka","Ford"); intent.putExtra("Pronar","Anxhela Katrin"); } else if (some == 8) { intent.putExtra("Ngjyra", "Bardh"); intent.putExtra("Marka", "Fiat"); intent.putExtra("Pronar", "Qemal Rexhepaj"); }else if (some == 9){ intent.putExtra("Ngjyra","Kuqe"); intent.putExtra("Marka","Benz"); intent.putExtra("Pronar","Vaso Balla"); }else{ intent.putExtra("Ngjyra","Zez"); intent.putExtra("Marka","Toyota"); intent.putExtra("Pronar","Taulant Tano"); } intent.putExtra("Targa",plate); intent.putExtra("Gjoba",gjobaplate); intent.putExtra("Shuma",shumaplate); intent.putExtra("Gjoba2"," "); intent.putExtra("Shuma2"," "); intent.putExtra("Shuma3"," "); intent.putExtra("FotoPath", platepath); intent.putExtra("Username", getIntent().getExtras().getString("Username")); startActivity(intent); } }); } public class LoadComments extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(PenalizimetSotme.this); pDialog.setMessage("Targat po ngarkohen..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected Boolean doInBackground(Void... arg0) { updateJSONdata(); return null; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); pDialog.dismiss(); updateKontrollo(); } } }
Java
package com.birdorg.anpr.sdk.simple.camera.example; /** * Created by john on 7/20/2014. */ public class DefaultMessages{ public String color1="Ngjyra: E Zeze"; public String color2="Ngjyra: E Bardhe"; public String color3="Ngjyra: E Kuqe"; public String color4="Ngjyra: Gri"; public String color5="Ngjyra: Blu"; public String color6="Ngjyra: E Kuqe"; public String type1="Tipi: Smart"; public String type2="Tipi: Ford"; public String type3="Tipi: Benz"; public String type4="Tipi: Fiat"; public String type5="Tipi: Mercedes"; public String type6="Tipi: Peugeot"; public String po="Po"; public String jo="Jo"; }
Java
package com.birdorg.anpr.sdk.simple.camera.example; import android.app.Activity; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.ImageView; public class Konfigurimet extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.konfigurimet); } }
Java
package com.birdorg.anpr.sdk.simple.camera.example; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Vector; import static com.birdorg.anpr.sdk.simple.camera.example.R.drawable.cam; import static com.birdorg.anpr.sdk.simple.camera.example.R.drawable.cap; /** * Created by john on 7/22/2014. */ public class KontrolletSotme extends ListActivity{ private ProgressDialog pDialog; private static final String TARGA_KONTROLLET_SOTME_URL = "http://www.comport.first.al/anpr/kontrollet_sotme.php"; private static final String TAG_DATA = "data"; private static final String TAG_PAJISJE_ID= "pajisje_id"; private static final String TAG_USER_ID= "user_id"; private static final String TAG_CAPTURE_ID= "capture_image"; private static final String TAG_TARGA= "targa"; private static final String TAG_POSTS = "posts"; String ftarga; String fpath; private JSONArray mPlates = null; // manages all of our comments in a list. private ArrayList<HashMap<String, String>> mPlatesList; ItemKontrollo item; private Vector<ItemKontrollo> VECITEM = new Vector<ItemKontrollo>(); private Vector<ItemKontrollo> VECITEM2 = new Vector<ItemKontrollo>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // loading the comments via AsyncTask new LoadComments().execute(); } public void updateJSONdata() { mPlatesList = new ArrayList<HashMap<String, String>>(); JSONParser jParser = new JSONParser(); JSONObject json = jParser.getJSONFromUrl(TARGA_KONTROLLET_SOTME_URL); item = new ItemKontrollo(); try { mPlates = json.getJSONArray(TAG_POSTS); // looping through all posts according to the json object returned for (int i = 0; i < mPlates.length(); i++) { JSONObject c = mPlates.getJSONObject(i); // gets the content of each tag String targa = c.getString(TAG_TARGA); ftarga = targa; String data = c.getString(TAG_DATA); String pajisje_id = c.getString(TAG_PAJISJE_ID); String user_id = c.getString(TAG_USER_ID); String capture_image = c.getString(TAG_CAPTURE_ID); fpath = capture_image; item.setTarga(targa); item.setData(data); item.setUser(user_id); item.setImgpath(capture_image); VECITEM.add(item); item = new ItemKontrollo(); } } catch (JSONException e) { e.printStackTrace(); } } private void updateKontrollo() { int length = VECITEM.size(); Collections.reverse(VECITEM); //Collections.copy(VECITEM2, VECITEM); for(int index=0; index < 5; index++){ ItemKontrollo item = VECITEM.get(index); VECITEM2.add(item); } setListAdapter(new KontrolletSotmeAdapter(this, VECITEM2)); ListView goclick= getListView(); goclick.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ItemKontrollo item = VECITEM2.get(position); String plate = item.getTarga(); String platepath = item.getImgpath(); Intent intent = new Intent(KontrolletSotme.this,Info.class); String ss = plate.substring(3, plate.length()); String sm = ss.substring(0, 1); int some = Integer.parseInt(sm); if (some == 1) { intent.putExtra("Ngjyra","Bardhe"); intent.putExtra("Marka","Peageut"); intent.putExtra("Gjoba","jo"); intent.putExtra("Siguracion","2014-06-11"); intent.putExtra("Sgs","2014-08-01"); intent.putExtra("Pronar","Altin Gjokaj"); }else if (some == 2 ){ intent.putExtra("Ngjyra","Kuqe"); intent.putExtra("Marka","BMW"); intent.putExtra("Gjoba","po"); intent.putExtra("Siguracion","2014-09-30"); intent.putExtra("Sgs","2014-10-01"); intent.putExtra("Pronar","Manushaqe Veli"); }else if (some == 3) { intent.putExtra("Ngjyra","Zeze"); intent.putExtra("Marka","Fiat"); intent.putExtra("Gjoba","jo"); intent.putExtra("Siguracion","2014-11-01"); intent.putExtra("Sgs","2014-10-30"); intent.putExtra("Pronar","Maria Mari"); }else if (some == 4) { intent.putExtra("Ngjyra","Gri"); intent.putExtra("Marka","Alfa Romeo"); intent.putExtra("Gjoba","po"); intent.putExtra("Siguracion","2014-12-31"); intent.putExtra("Sgs","2014-11-30"); intent.putExtra("Pronar","Albert Beri"); }else if (some == 5) { intent.putExtra("Ngjyra","Zeze"); intent.putExtra("Marka","Suzuki"); intent.putExtra("Gjoba","po"); intent.putExtra("Siguracion","2014-11-01"); intent.putExtra("Sgs","2014-10-30"); intent.putExtra("Pronar","Mario Shabani"); }else if (some == 6) { intent.putExtra("Ngjyra","Blu"); intent.putExtra("Marka","Subaru"); intent.putExtra("Gjoba","jo"); intent.putExtra("Siguracion","2014-11-01"); intent.putExtra("Sgs","2014-10-30"); intent.putExtra("Pronar","Elton Anori"); }else if (some == 7){ intent.putExtra("Ngjyra","Gri"); intent.putExtra("Marka","Ford"); intent.putExtra("Gjoba","po"); intent.putExtra("Siguracion","2014-11-01"); intent.putExtra("Sgs","2014-10-30"); intent.putExtra("Pronar","Anxhela Katrin"); } else if (some == 8) { intent.putExtra("Ngjyra", "Bardh"); intent.putExtra("Marka", "Fiat"); intent.putExtra("Gjoba", "jo"); intent.putExtra("Siguracion", "2014-09-01"); intent.putExtra("Sgs", "2014-08-30"); intent.putExtra("Pronar", "Qemal Rexhepaj"); }else if (some == 9){ intent.putExtra("Ngjyra","Kuqe"); intent.putExtra("Marka","Benz"); intent.putExtra("Gjoba","po"); intent.putExtra("Siguracion","2014-09-20"); intent.putExtra("Sgs","2014-08-10"); intent.putExtra("Pronar","Vaso Balla"); }else{ intent.putExtra("Ngjyra","Zez"); intent.putExtra("Marka","Toyota"); intent.putExtra("Gjoba","jo"); intent.putExtra("Siguracion","2014-11-01"); intent.putExtra("Sgs","2014-11-30"); intent.putExtra("Pronar","Taulant Tano"); } intent.putExtra("Targa",plate); intent.putExtra("FotoPath", platepath); intent.putExtra("Username", getIntent().getExtras().getString("Username")); startActivity(intent); } }); } public class LoadComments extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(KontrolletSotme.this); pDialog.setMessage("Targat po ngarkohen..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected Boolean doInBackground(Void... arg0) { updateJSONdata(); return null; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); pDialog.dismiss(); updateKontrollo(); } } }
Java