answer
stringlengths
17
10.2M
package org.eigenbase.enki.test; import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.junit.*; import org.xml.sax.*; import org.xml.sax.helpers.*; /** * XmiFileComparator performs an order-insensitive comparison of two XMI files * or strings. In addition to ignoring the order of model element instances * as well as the order of XML attributes, it does not require identical XMI * ID values and ignores the timestamp value in the XMI header. * * @author Stephan Zuercher */ public class XmiFileComparator { private static final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); private static boolean writeSortedElements = false; public static void main(String[] args) { File f1; File f2; if (args.length >= 2) { f1 = new File(args[0]); f2 = new File(args[1]); if (args.length >= 3) { setWriteSortedElements(args[2].equals("true")); } } else { // Default are the output files of ExportImportTest f1 = new File("test/results/ExportImportTest.xmi"); f2 = new File("test/results/ExportImportTest2.xmi"); } assertEqual(f1, f2); } public static void setWriteSortedElements(boolean enable) { writeSortedElements = enable; } public static void assertEqual(File expectedFile, File actualFile) { Element expected = load(expectedFile, new ExpectedElementFactory()); Element actual = load(actualFile, new ActualElementFactory()); compare(expected, actual); } public static void assertEqual(String expectedXmi, String actualXmi) { Element expected = load(expectedXmi, new ExpectedElementFactory()); Element actual = load(actualXmi, new ActualElementFactory()); compare(expected, actual); } private static Element load( Reader in, ElementFactory elementFactory, File sortedElementsDump) { try { SAXParser parser = saxParserFactory.newSAXParser(); InputSource source = new InputSource(in); Handler handler = new Handler(elementFactory); parser.parse(source, handler); Element element = handler.getRootElement(); if (writeSortedElements) { write(element, sortedElementsDump); } return element; } catch(Exception e) { ModelTestBase.fail(e); return null; // unreachable } } private static Element load(String xmi, ElementFactory elementFactory) { return load(new StringReader(xmi), elementFactory, null); } private static Element load(File file, ElementFactory elementFactory) { File dumpFile = null; if (writeSortedElements) { dumpFile = new File(file.getPath() + ".sorted"); } FileReader in; try { in = new FileReader(file); } catch (FileNotFoundException e) { ModelTestBase.fail(e); return null; // unreachable } return load(in, elementFactory, dumpFile); } private static void compare(Element expected, Element actual) { compare(expected, actual, true); } private static void compare( Element expected, Element actual, boolean recurse) { check( "element name mismatch", expected, actual, expected.name, actual.name); check( "attrib count mismatch", expected, actual, expected.attributes.size(), actual.attributes.size()); for(Map.Entry<String, String> entry: expected.attributes.entrySet()) { String attribName = entry.getKey(); StringBuffer expectedAttrib = new StringBuffer() .append(attribName) .append("=") .append(entry.getValue()); StringBuffer actualAttrib = new StringBuffer() .append(attribName) .append("=") .append(actual.attributes.get(attribName)); check( "attrib value mismatch", expected, actual, expectedAttrib.toString(), actualAttrib.toString()); } check( "reference mismatch", expected, actual, expected.isReference, actual.isReference); if (expected.isReference) { Element expectedRef = expected.getReferencedElement(); Element actualRef = actual.getReferencedElement(); compare(expectedRef, actualRef, false); } check( "child element count mismatch", expected, actual, expected.children.size(), actual.children.size()); if (recurse) { for(int i = 0; i < expected.children.size(); i++) { Element expectedChild = expected.children.get(i); Element actualChild = actual.children.get(i); compare(expectedChild, actualChild); } } } private static void check( String msg, Element expectedSrc, Element actualSrc, Object expected, Object actual) { StringBuffer m = new StringBuffer(msg) .append(" (Expected Line: ") .append(expectedSrc.lineNumber) .append("; Acutal Line: ") .append(actualSrc.lineNumber) .append(")"); Assert.assertEquals(m.toString(), expected, actual); } private static void write(Element element, File file) throws IOException { IdRemapper idRemapper = new IdRemapper(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); write(element, writer, 0, idRemapper); } private static void write( Element element, BufferedWriter writer, int indent, IdRemapper idRemapper) throws IOException { indent(writer, indent); writer.write("<"); writer.write(element.name); if (element.xmiId != null) { String id = idRemapper.remap(element.xmiId); if (element.isReference) { writer.write(" xmi.idref='"); } else { writer.write(" xmi.id='"); } writer.write(id); writer.write("'"); } for(Map.Entry<String, String> entry: element.attributes.entrySet()) { writer.write(" "); writer.write(entry.getKey()); writer.write("='"); writer.write(entry.getValue()); writer.write("'"); } if (element.characters.length() == 0 && element.children.isEmpty()) { // empty elem writer.write(" />"); writer.newLine(); return; } writer.write(">"); if (element.children.isEmpty()) { writer.write(element.characters.toString()); } else { writer.newLine(); if (element.characters.length() > 0) { indent(writer, indent + 1); writer.write(element.characters.toString()); writer.newLine(); } for(Element child: element.children) { write(child, writer, indent + 1, idRemapper); } indent(writer, indent); } writer.write("</"); writer.write(element.name); writer.write(">"); writer.newLine(); } private static void indent(BufferedWriter writer, int indent) throws IOException { for(int i = 0; i < indent; i++) { writer.write(" "); } } private abstract static class Element { private final String name; private final SortedMap<String, String> attributes; private final String xmiId; private final boolean isReference; private final int lineNumber; private final List<Element> children; private final StringBuffer characters; private Element(String name, Attributes xmlAttributes, Locator locator) { assert(name != null); this.name = name; this.attributes = new TreeMap<String, String>(); String xmiId = null; boolean isReference = false; for(int i = 0; i < xmlAttributes.getLength(); i++) { String attribName = xmlAttributes.getQName(i); String attribValue = xmlAttributes.getValue(i); if (attribName.equals("xmi.id")) { assert(xmiId == null); xmiId = attribValue; } else if (attribName.equals("xmi.idref")) { assert(xmiId == null); xmiId = attribValue; isReference = true; } else if (name.equals("XMI") && attribName.equals("timestamp")) { this.attributes.put(attribName, "<timestamp-ignored>"); } else { this.attributes.put(attribName, attribValue); } } this.xmiId = xmiId; this.isReference = isReference; this.lineNumber = locator.getLineNumber(); this.children = new ArrayList<Element>(); this.characters = new StringBuffer(); if (!isReference && xmiId != null) { getXmiIdElemMap().put(xmiId, this); } } public Element getReferencedElement() { assert(isReference); Element element = getXmiIdElemMap().get(xmiId); return element; } public void finish() { String chars = characters.toString().trim(); characters.setLength(0); characters.append(chars); } public void sort() { for(Element childElement: children) { childElement.sort(); } Collections.sort(children, ElementComparator.instance); } public void addChild(Element child) { this.children.add(child); } protected abstract Map<String, Element> getXmiIdElemMap(); } private static class ExpectedElement extends Element { private static Map<String, Element> xmiIdElemMap = new HashMap<String, Element>(); public ExpectedElement( String name, Attributes xmlAttributes, Locator locator) { super(name, xmlAttributes, locator); } @Override protected Map<String, Element> getXmiIdElemMap() { return xmiIdElemMap; } } private static class ActualElement extends Element { private static Map<String, Element> xmiIdElemMap = new HashMap<String, Element>(); public ActualElement( String name, Attributes xmlAttributes, Locator locator) { super(name, xmlAttributes, locator); } @Override protected Map<String, Element> getXmiIdElemMap() { return xmiIdElemMap; } } private static class ElementComparator implements Comparator<Element> { private static final ElementComparator instance = new ElementComparator(); public int compare(Element o1, Element o2) { int c = o1.name.compareTo(o2.name); if (c != 0) { return c; } if (!o1.attributes.isEmpty() || !o2.attributes.isEmpty()) { Iterator<Map.Entry<String, String>> iter1 = o1.attributes.entrySet().iterator(); Iterator<Map.Entry<String, String>> iter2 = o2.attributes.entrySet().iterator(); while(iter1.hasNext() && iter2.hasNext()) { Map.Entry<String, String> e1 = iter1.next(); Map.Entry<String, String> e2 = iter2.next(); c = e1.getKey().compareTo(e2.getKey()); if (c != 0) { return c; } c = e1.getValue().compareTo(e2.getValue()); if (c != 0) { return c; } } if (iter1.hasNext()) { return 1; } else if (iter2.hasNext()) { return -1; } } if (o1.isReference || o2.isReference) { Element subst1 = o1.isReference ? o1.getReferencedElement() : o1; Element subst2 = o2.isReference ? o2.getReferencedElement() : o2; c = compare(subst1, subst2); if (c != 0) { return c; } } if (o1.characters.length() > 0 || o2.characters.length() > 0) { c = o1.characters.toString().compareTo( o2.characters.toString()); if (c != 0) { return c; } } c = compare(o1.children, o2.children); if (c != 0) { return c; } if (o1.xmiId != null && o2.xmiId != null) { if (o1.isReference == o2.isReference) { c = o1.xmiId.compareTo(o2.xmiId); if (c != 0) { return c; } } } return 0; } private int compare(List<Element> o1children, List<Element> o2children) { Iterator<Element> o1iter = o1children.iterator(); Iterator<Element> o2iter = o2children.iterator(); while(o1iter.hasNext() && o2iter.hasNext()) { Element o1child = o1iter.next(); Element o2child = o2iter.next(); int c = compare(o1child, o2child); if (c != 0) { return c; } } if (o1iter.hasNext()) { return 1; } else if (o2iter.hasNext()) { return -1; } return 0; } } private static class Handler extends DefaultHandler { private final ElementFactory elementFactory; private Element root; private Stack<Element> elementStack; private Locator locator; private Handler(ElementFactory elementFactory) { this.elementFactory = elementFactory; this.elementStack = new Stack<Element>(); } public Element getRootElement() { return root; } @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } @Override public void startElement( String uri, String localName, String name, Attributes attributes) throws SAXException { Element element = elementFactory.createElement(name, attributes, locator); if (!elementStack.empty()) { elementStack.peek().addChild(element); } elementStack.push(element); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (!elementStack.empty()) { elementStack.peek().characters.append(ch, start, length); } } @Override public void endElement(String uri, String localName, String name) throws SAXException { Element element = elementStack.pop(); element.finish(); if (elementStack.empty()) { root = element; root.sort(); } } } private static abstract class ElementFactory { public abstract Element createElement( String name, Attributes xmlAttributes, Locator locator); } private static class ExpectedElementFactory extends ElementFactory { @Override public Element createElement( String name, Attributes xmlAttributes, Locator locator) { return new ExpectedElement(name, xmlAttributes, locator); } } private static class ActualElementFactory extends ElementFactory { @Override public Element createElement( String name, Attributes xmlAttributes, Locator locator) { return new ActualElement(name, xmlAttributes, locator); } } private static class IdRemapper { private Map<String, String> cache; private int nextId; IdRemapper() { this.cache = new HashMap<String, String>(); this.nextId = 1; } public String remap(String id) { String remappedId = cache.get(id); if (remappedId == null) { remappedId = "a" + nextId++; cache.put(id, remappedId); } return remappedId; } } } // End XmiFileComparator.java
package org.exist.xquery.functions.util; import org.exist.dom.DocumentSet; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.storage.Indexable; import org.exist.util.ValueOccurrences; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionCall; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.FunctionReference; import org.exist.xquery.value.IntegerValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; /** * @author wolf * */ public class IndexKeys extends BasicFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("index-keys", UtilModule.NAMESPACE_URI, UtilModule.PREFIX), "Can be used to query existing range indexes defined on a set of nodes. " + "All index keys defined for the given node set are reported to a callback function. " + "The node set is specified in the first argument. The second argument specifies a start " + "value. Only index keys of the same type but being greater than $b will be reported. " + "The third arguments is a function reference as created by the util:function function. " + "It can be an arbitrary user-defined function, but it should take exactly 2 arguments: " + "1) the current index key as found in the range index as an atomic value, 2) a sequence " + "containing three int values: a) the overall frequency of the key within the node set, " + "b) the number of distinct documents in the node set the key occurs in, " + "c) the current position of the key in the whole list of keys returned.", new SequenceType[] { new SequenceType(Type.NODE, Cardinality.ZERO_OR_MORE), new SequenceType(Type.ATOMIC, Cardinality.EXACTLY_ONE), new SequenceType(Type.FUNCTION_REFERENCE, Cardinality.EXACTLY_ONE), new SequenceType(Type.INT, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE)); /** * @param context * @param signature */ public IndexKeys(XQueryContext context) { super(context, signature); } /* * (non-Javadoc) * * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], * org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { if (args[0].getLength() == 0) return Sequence.EMPTY_SEQUENCE; NodeSet nodes = args[0].toNodeSet(); DocumentSet docs = nodes.getDocumentSet(); FunctionReference ref = (FunctionReference) args[2].itemAt(0); int max = ((IntegerValue) args[3].itemAt(0)).getInt(); FunctionCall call = ref.getFunctionCall(); Sequence result = new ValueSequence(); ValueOccurrences occur[] = context.getBroker().getValueIndex() .scanIndexKeys(docs, nodes, (Indexable) args[1]); int len = (occur.length > max ? max : occur.length); Sequence params[] = new Sequence[2]; ValueSequence data = new ValueSequence(); for (int j = 0; j < len; j++) { params[0] = occur[j].getValue(); data.add(new IntegerValue(occur[j].getOccurrences(), Type.UNSIGNED_INT)); data.add(new IntegerValue(occur[j].getDocuments(), Type.UNSIGNED_INT)); data.add(new IntegerValue(j + 1, Type.UNSIGNED_INT)); params[1] = data; result.addAll(call.evalFunction(contextSequence, null, params)); data.clear(); } LOG.debug("Returning: " + result.getLength()); return result; } }
package com.lightcrafts.image.metadata.makernotes; import java.awt.image.RenderedImage; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import com.lightcrafts.image.BadImageFileException; import com.lightcrafts.image.ImageInfo; import com.lightcrafts.image.UnknownImageTypeException; import com.lightcrafts.image.metadata.*; import com.lightcrafts.image.metadata.providers.*; import com.lightcrafts.image.metadata.values.ImageMetaValue; import com.lightcrafts.image.metadata.values.LongMetaValue; import com.lightcrafts.image.metadata.values.ShortMetaValue; import com.lightcrafts.image.types.JPEGImageType; import com.lightcrafts.utils.TextUtil; import static com.lightcrafts.image.metadata.EXIFConstants.*; import static com.lightcrafts.image.metadata.ImageMetaType.*; import static com.lightcrafts.image.metadata.ImageOrientation.*; import static com.lightcrafts.image.metadata.makernotes.CanonTags.*; import static com.lightcrafts.image.metadata.TIFFTags.*; import static com.lightcrafts.image.types.CIFFConstants.*; /** * A <code>CanonDirectory</code> is-an {@link ImageMetadataDirectory} for * holding Canon-specific maker-note metadata. * * @author Paul J. Lucas [paul@lightcrafts.com] */ @SuppressWarnings({"CloneableClassWithoutClone"}) public final class CanonDirectory extends MakerNotesDirectory implements ApertureProvider, ArtistProvider, ColorTemperatureProvider, FocalLengthProvider, ISOProvider, LensProvider, OrientationProvider, PreviewImageProvider, ShutterSpeedProvider, ThumbnailImageProvider, WidthHeightProvider { ////////// public ///////////////////////////////////////////////////////// /** * {@inheritDoc} */ public float getAperture() { final ImageMetaValue value = getValue( CANON_SI_FNUMBER ); return value != null ? (float)MetadataUtil.convertFStopFromAPEX( value.getIntValue() ) : 0; } /** * {@inheritDoc} */ public String getArtist() { final ImageMetaValue value = getValue( CANON_OWNER_NAME ); return value != null ? value.getStringValue() : null; } /** * {@inheritDoc} */ public int getColorTemperature() { ImageMetaValue value = getValue( CANON_PI_COLOR_TEMPERATURE ); if ( value == null ) value = getValue( CANON_CI_D30_COLOR_TEMPERATURE ); if ( value == null ) value = getValue( CANON_COLOR_TEMPERATURE ); return value != null ? value.getIntValue() : 0; } /** * {@inheritDoc} */ public float getFocalLength() { final ImageMetaValue value = getValue( CANON_FL_FOCAL_LENGTH ); return value != null ? value.getFloatValue() : 0; } /** * {@inheritDoc} */ public int getImageHeight() { final ImageMetaValue value = getValue( CANON_PI_IMAGE_HEIGHT ); return value != null ? value.getIntValue() : 0; } /** * {@inheritDoc} */ public int getImageWidth() { final ImageMetaValue value = getValue( CANON_PI_IMAGE_WIDTH ); return value != null ? value.getIntValue() : 0; } /** * {@inheritDoc} */ public int getISO() { ImageMetaValue value = getValue( CANON_SI_ISO ); boolean isAPEX = true; if ( value == null ) { // CANON_CS_ISO can be "Auto" that is not a number, // therefore it shouldn't be a default choice. value = getValue( CANON_CS_ISO ); isAPEX = false; } if ( value == null ) return 0; int iso = value.getIntValue(); if ( isAPEX ) iso = MetadataUtil.convertISOFromAPEX( iso ); return iso >= 1 && iso <= 10000 ? iso : 0; } /** * Gets the name of this directory. * * @return Always returns &quot;Canon&quot;. */ public String getName() { return "Canon"; } /** * {@inheritDoc} */ public String getLens() { final ImageMetaValue lensValue = getValue( CANON_CS_LENS_TYPE ); final String label = hasTagValueLabelFor( lensValue ); if ( label != null ) return label; return makeLensLabelFrom( getValue( CANON_CS_SHORT_FOCAL_LENGTH ), getValue( CANON_CS_LONG_FOCAL_LENGTH ), getValue( CANON_CS_FOCAL_UNITS_PER_MM ) ); } /** * {@inheritDoc} */ public ImageOrientation getOrientation() { final ImageMetaValue value = getValue( CANON_SI_AUTO_ROTATE ); if ( value != null ) { switch ( value.getIntValue() ) { // The CIFF constants are the same for the CanonDirectory. case CIFF_AUTO_ROTATE_NONE: return ORIENTATION_LANDSCAPE; case CIFF_AUTO_ROTATE_90CCW: return ORIENTATION_90CCW; case CIFF_AUTO_ROTATE_180: return ORIENTATION_180; case CIFF_AUTO_ROTATE_90CW: return ORIENTATION_90CW; } } return ORIENTATION_UNKNOWN; } /** * {@inheritDoc} */ public RenderedImage getPreviewImage( ImageInfo imageInfo, int maxWidth, int maxHeight ) throws BadImageFileException { // TODO: verify that this is actually an sRGB image, what about Adobe RGB shooting, etc.? return JPEGImageType.getImageFromBuffer( imageInfo.getByteBuffer(), getValue( CANON_PII_IMAGE_START ), 1 // JPEG_MARKER_BYTE + 1 // JPEG_SOI_MARKER + 1 // JPEG_MARKER_BYTE + 1 // JPEG_APP1_MARKER + 2 // APP1 length + EXIF_HEADER_START_SIZE, getValue( CANON_PII_IMAGE_LENGTH ), maxWidth, maxHeight ); } /** * {@inheritDoc} */ public RenderedImage getThumbnailImage( ImageInfo imageInfo ) throws BadImageFileException, IOException, UnknownImageTypeException { final ImageMetadataDirectory dir = imageInfo.getMetadata().getDirectoryFor( TIFFDirectory.class ); if ( dir == null ) { // This should never be null, but just in case ... return null; } return JPEGImageType.getImageFromBuffer( imageInfo.getByteBuffer(), dir.getValue( TIFF_JPEG_INTERCHANGE_FORMAT ), 0, dir.getValue( TIFF_JPEG_INTERCHANGE_FORMAT_LENGTH ), 0, 0 ); } /** * {@inheritDoc} */ public float getShutterSpeed() { final ImageMetaValue value = getValue( CANON_SI_EXPOSURE_TIME ); return value != null ? getShutterSpeedFrom( value ) : 0; } /** * {@inheritDoc} */ public ImageMetaTagInfo getTagInfoFor( Integer id ) { return m_tagsByID.get( id ); } /** * {@inheritDoc} */ public ImageMetaTagInfo getTagInfoFor( String name ) { return m_tagsByName.get( name ); } /** * Puts a key/value pair into this directory. For a Canon tag that has * subfields, expands the values into multiple key/value pairs. * * @param tagID The metadata tag ID (the key). * @param value The value to put. * @see #valueToString(ImageMetaValue) */ public void putValue( Integer tagID, final ImageMetaValue value ) { switch ( tagID ) { case CANON_CAMERA_SETTINGS: case CANON_COLOR_INFO_D30: case CANON_FOCAL_LENGTH: case CANON_PROCESSING_INFO: case CANON_SENSOR_INFO: case CANON_SHOT_INFO: explodeSubfields( tagID, 1, value, false ); return; case CANON_COLOR_INFO: case CANON_FILE_INFO: case CANON_PICTURE_INFO: case CANON_PREVIEW_IMAGE_INFO: explodeSubfields( tagID, 1, value, true ); return; case CANON_CUSTOM_FUNCTIONS: value.setNonDisplayable(); if ( value instanceof LongMetaValue ) { final long[] longs = ((LongMetaValue)value).getLongValues(); final int cfTagIDStart = tagID << 8; for ( int i = 1; i < longs.length; ++i ) { final int n = (int)longs[i]; putValue( cfTagIDStart | (n >>> 8), new ShortMetaValue( (short)(n & 0xFF) ) ); } } return; case CANON_FLASH_INFO: // TODO: handle this case return; } super.putValue( tagID, value ); } /** * {@inheritDoc} */ public String valueToString( ImageMetaValue value ) { switch ( value.getOwningTagID() ) { case CANON_CS_LENS_TYPE: { final String label = hasTagValueLabelFor( CANON_CS_LENS_TYPE ); return label != null ? label : "unknown"; // TODO: localize } case CANON_CS_LONG_FOCAL_LENGTH: case CANON_CS_SHORT_FOCAL_LENGTH: case CANON_FL_FOCAL_LENGTH: case CANON_LI_FOCAL_LENGTH: case CANON_LI_LONG_FOCAL_LENGTH: case CANON_LI_SHORT_FOCAL_LENGTH: return value.getStringValue() + "mm"; // TODO: localize "mm" case CANON_PI_DIGITAL_GAIN: return TextUtil.tenths( value.getIntValue() / 10F ); case CANON_SI_EXPOSURE_TIME: case CANON_SI_TARGET_EXPOSURE_TIME: { final float shutterSpeed = getShutterSpeedFrom( value ); return MetadataUtil.shutterSpeedString( shutterSpeed ); } case CANON_SI_FNUMBER: case CANON_SI_TARGET_APERTURE: { final int apex = value.getIntValue(); return TextUtil.tenths( MetadataUtil.convertFStopFromAPEX( apex ) ); } default: return super.valueToString( value ); } } ////////// protected ////////////////////////////////////////////////////// /** * Gets the priority of this directory for providing the metadata supplied * by implementing the given provider interface. * <p> * By default, the priority for maker notes directories is higher than * {@link ImageMetadataDirectory#getProviderPriorityFor(Class)} because * they have more detailed metadata about a given image. * <p> * However, an exception is made for {@link ShutterSpeedProvider} for Canon * because it yields weird values. * * @param provider The provider interface to get the priority for. * @return Returns said priority. */ protected int getProviderPriorityFor( Class<? extends ImageMetadataProvider> provider ) { return provider == ShutterSpeedProvider.class ? 0 : super.getProviderPriorityFor( provider ); } /** * Get the {@link ResourceBundle} to use for tags. * * @return Returns said {@link ResourceBundle}. */ protected ResourceBundle getTagLabelBundle() { return m_tagBundle; } /** * {@inheritDoc} */ protected Class<? extends ImageMetaTags> getTagsInterface() { return CanonTags.class; } ////////// private //////////////////////////////////////////////////////// /** * Add the tag mappings. * * @param id The tag's ID. * @param name The tag's name. * @param type The tag's {@link ImageMetaType}. */ private static void add( int id, String name, ImageMetaType type ) { final ImageMetaTagInfo tagInfo = new ImageMetaTagInfo( id, name, type, false ); m_tagsByID.put( id, tagInfo ); m_tagsByName.put( name, tagInfo ); } /** * Gets the shutter speed from the given {@link ImageMetaValue}. * * @param value The {@link ImageMetaValue} to get the shutter speed from. * @return Returns the shutter speed. */ private float getShutterSpeedFrom( ImageMetaValue value ) { final int apex = value.getIntValue(); double speed = Math.exp( - MetadataUtil.convertAPEXToEV( apex ) * MetadataUtil.LN_2 ); final String model = getOwningMetadata().getCameraMake( true ); if ( model != null ) { if ( model.contains( "20D" ) || model.contains( "350D" ) || model.contains( "REBEL XT" ) ) speed *= 1000.0 / 32.0; } return (float)speed; } /** * This is where the actual labels for the tags are. */ private static final ResourceBundle m_tagBundle = ResourceBundle.getBundle( "com.lightcrafts.image.metadata.makernotes.CanonTags" ); /** * A mapping of tags by ID. */ private static final Map<Integer,ImageMetaTagInfo> m_tagsByID = new HashMap<Integer,ImageMetaTagInfo>(); /** * A mapping of tags by name. */ private static final Map<String,ImageMetaTagInfo> m_tagsByName = new HashMap<String,ImageMetaTagInfo>(); static { add( CANON_CAMERA_SETTINGS, "CameraSettings", META_UNDEFINED ); add( CANON_CF_AF_ASSIST_LIGHT, "CFAssistLight", META_SSHORT ); add( CANON_CF_AUTO_EXPOSURE_BRACKETING, "CFAutoExposureBracketing", META_SSHORT ); add( CANON_CF_AUTO_EXPOSURE_LOCK_BUTTONS, "CFAutoExposureLockButtons", META_SSHORT ); add( CANON_CF_FILL_FLASH_AUTO_REDUCTION, "CFFillFlashAutoReduction", META_SSHORT ); add( CANON_CF_LENS_AUTO_FOCUS_STOP_BUTTON, "CFLensAutoFocusStopButton", META_SSHORT ); add( CANON_CF_LONG_EXPOSURE_NOISE_REDUCTION, "CFLongExposureNoiseReduction", META_SSHORT ); add( CANON_CF_MENU_BUTTON_RETURN_POSITION, "CFMenuButtonReturnPosition", META_SSHORT ); add( CANON_CF_MIRROR_LOCKUP, "CFMirrorLockup", META_SSHORT ); add( CANON_CF_SENSOR_CLEANING, "CFSensorCleaning", META_SSHORT ); add( CANON_CF_SET_BUTTON_FUNCTION, "CFSetButtonFunction", META_SSHORT ); add( CANON_CF_SHUTTER_CURTAIN_SYNC, "CFShutterCurtainSync", META_SSHORT ); add( CANON_CF_SHUTTER_SPEED_IN_AV_MODE, "CFShutterSpeedInAvMode", META_SSHORT ); add( CANON_CF_TV_AV_EXPOSURE_LEVEL, "CFTVAVExposureLevel", META_SSHORT ); add( CANON_CI_COLOR_HUE, "CIColorHue", META_SSHORT ); add( CANON_CI_COLOR_SPACE, "CIColorSpace", META_SSHORT ); add( CANON_CI_D30_COLOR_MATRIX, "CID30ColorMatrix", META_SSHORT ); add( CANON_CI_D30_COLOR_TEMPERATURE, "CID30ColorTemperature", META_USHORT ); add( CANON_COLOR_INFO, "ColorInfo", META_UNDEFINED ); add( CANON_COLOR_INFO_D30, "ColorInfoD30", META_UNDEFINED ); add( CANON_COLOR_SPACE, "ColorSpace", META_USHORT ); add( CANON_COLOR_TEMPERATURE, "ColorTemperature", META_USHORT ); add( CANON_CS_AF_POINT_SELECTED, "CSAFPointSelected", META_SSHORT ); add( CANON_CS_CONTINUOUS_DRIVE_MODE, "CSContinuousDriveMode", META_SSHORT ); add( CANON_CS_CONTRAST, "CSContrast", META_SSHORT ); add( CANON_CS_DIGITAL_ZOOM, "CSDigitalZoom", META_SSHORT ); add( CANON_CS_EASY_SHOOTING_MODE, "CSEasyShootingMode", META_SSHORT ); add( CANON_CS_EXPOSURE_MODE, "CSExposureMode", META_SSHORT ); add( CANON_CS_FLASH_ACTIVITY, "CSFlashActivity", META_SSHORT ); add( CANON_CS_FLASH_DETAILS, "CSFlashDetails", META_SSHORT ); add( CANON_CS_FLASH_MODE, "CSFlashMode", META_SSHORT ); add( CANON_CS_FOCAL_UNITS_PER_MM, "CSFocalUnitsPerMM", META_SSHORT ); add( CANON_CS_FOCUS_MODE, "CSFocusMode", META_SSHORT ); add( CANON_CS_FOCUS_MODE_G1, "CSFocusModeG1", META_SSHORT ); add( CANON_CS_FOCUS_TYPE, "CSFocusType", META_SSHORT ); add( CANON_CS_IMAGE_SIZE, "CSImageSize", META_SSHORT ); add( CANON_CS_ISO, "CSISO", META_SSHORT ); add( CANON_CS_LENS_TYPE, "CSLensType", META_SSHORT ); add( CANON_CS_LONG_FOCAL_LENGTH, "CSLongFocalLength", META_SSHORT ); add( CANON_CS_MACRO_MODE, "CSMacroMode", META_SSHORT ); add( CANON_CS_METERING_MODE, "CSMeteringMode", META_SSHORT ); add( CANON_CS_QUALITY, "CSQuality", META_SSHORT ); add( CANON_CS_SATURATION, "CSSaturation", META_SSHORT ); add( CANON_CS_SELF_TIMER_DELAY, "CSSelfTimerDelay", META_SSHORT ); add( CANON_CS_SHARPNESS, "CSSharpness", META_SSHORT ); add( CANON_CS_SHORT_FOCAL_LENGTH, "CSShortFocalLength", META_SSHORT ); add( CANON_CS_ZOOMED_RESOLUTION, "CSZoomedResolution", META_SSHORT ); add( CANON_CS_ZOOMED_RESOLUTION_BASE, "CSZoomedResolutionBase", META_SSHORT ); add( CANON_CUSTOM_FUNCTIONS, "CustomFunctions", META_SSHORT ); add( CANON_FILE_INFO, "FileInfo", META_UNDEFINED ); add( CANON_FILE_LENGTH, "FileLength", META_ULONG ); add( CANON_FIRMWARE_VERSION, "FirmwareVersion", META_STRING ); add( CANON_FI_FILE_NUMBER, "FIFileNumber", META_ULONG ); add( CANON_FI_SHUTTER_COUNT, "FIShutterCount", META_ULONG ); add( CANON_FLASH_INFO, "FlashInfo", META_UNDEFINED ); add( CANON_FL_FOCAL_LENGTH, "FLFocalLength", META_USHORT ); add( CANON_FL_FOCAL_PLANE_X_SIZE, "FLFocalPlaneXSize", META_USHORT ); add( CANON_FL_FOCAL_PLANE_Y_SIZE, "FLFocalPlaneYSize", META_USHORT ); add( CANON_FOCAL_LENGTH, "FocalLength", META_UNDEFINED ); add( CANON_IMAGE_NUMBER, "ImageNumber", META_ULONG ); add( CANON_IMAGE_TYPE, "ImageType", META_STRING ); add( CANON_LENS_INFO_1D, "LensInfo1D", META_UNDEFINED ); add( CANON_LI_FOCAL_LENGTH, "LIFocalLength", META_USHORT ); add( CANON_LI_LENS_TYPE, "LILensType", META_USHORT ); add( CANON_LI_LONG_FOCAL_LENGTH, "LILongFocalLength", META_USHORT ); add( CANON_LI_SHORT_FOCAL_LENGTH, "LIShortFocalLength", META_USHORT ); add( CANON_OWNER_NAME, "OwnerName", META_STRING ); add( CANON_PI_AF_POINTS_USED, "PIAFPointsUsed", META_USHORT ); add( CANON_PI_COLOR_TEMPERATURE, "PIColorTemperature", META_SSHORT ); add( CANON_PI_DIGITAL_GAIN, "PIDigitalGain", META_SSHORT ); add( CANON_PI_IMAGE_HEIGHT, "PIImageHeight", META_USHORT ); add( CANON_PI_IMAGE_HEIGHT_AS_SHOT, "PIImageHeightAsShot", META_USHORT ); add( CANON_PI_IMAGE_WIDTH, "PIImageWidth", META_USHORT ); add( CANON_PI_IMAGE_WIDTH_AS_SHOT, "PIImageWidthAsShot", META_USHORT ); add( CANON_PI_PICTURE_STYLE, "PIPictureStyle", META_SSHORT ); add( CANON_PI_SENSOR_BLUE_LEVEL, "PISensorBlueLevel", META_SSHORT ); add( CANON_PI_SENSOR_RED_LEVEL, "PISensorRedLevel", META_SSHORT ); add( CANON_PI_TONE_CURVE, "PIToneCurve", META_SSHORT ); add( CANON_PI_WB_SHIFT_AB, "PIWBShiftAB", META_SSHORT ); add( CANON_PI_WB_SHIFT_GM, "PIWBShiftGM", META_SSHORT ); add( CANON_PI_WHITE_BALANCE_BLUE, "PIWhiteBalanceBlue", META_SSHORT ); add( CANON_PI_WHITE_BALANCE_RED, "PIWhiteBalanceRed", META_SSHORT ); add( CANON_PICTURE_INFO, "PictureInfo", META_UNDEFINED ); add( CANON_PII_FOCAL_PLANE_X_RESOLUTION, "PIIFocalPlaneXResolution", META_SRATIONAL ); add( CANON_PII_FOCAL_PLANE_Y_RESOLUTION, "PIIFocalPlaneYResolution", META_SRATIONAL ); add( CANON_PII_IMAGE_HEIGHT, "PIIImageHeight", META_ULONG ); add( CANON_PII_IMAGE_LENGTH, "PIIImageLength", META_ULONG ); add( CANON_PII_IMAGE_START, "PIIImageStart", META_ULONG ); add( CANON_PII_IMAGE_WIDTH, "PIIImageWidth", META_ULONG ); add( CANON_PREVIEW_IMAGE_INFO, "PreviewImageInfo", META_UNDEFINED ); add( CANON_PROCESSING_INFO, "ColorProcessingInfo", META_UNDEFINED ); add( CANON_SENSOR_INFO, "SensorInfo", META_UNDEFINED ); add( CANON_SERIAL_NUMBER, "SerialNumber", META_ULONG ); add( CANON_SHOT_INFO, "ShotInfo", META_UNDEFINED ); add( CANON_SI_AEB_BRACKET_VALUE, "AEBBracketValue", META_SSHORT ); add( CANON_SI_AF_POINT_USED, "SIAFPointUsed", META_SSHORT ); add( CANON_SI_AUTO_EXPOSURE_BRACKETING, "SIAutoExposureBracketing", META_SSHORT ); add( CANON_SI_AUTO_ROTATE, "SIAutoRotate", META_SSHORT ); add( CANON_SI_BULB_DURATION, "SIBulbDuration", META_SSHORT ); add( CANON_SI_EXPOSURE_COMPENSATION, "SIExposureCompensation", META_SSHORT ); add( CANON_SI_EXPOSURE_TIME, "ExposureTime", META_SSHORT ); add( CANON_SI_FLASH_BIAS, "SIFlashBias", META_SSHORT ); add( CANON_SI_FNUMBER, "FNumber", META_SSHORT ); add( CANON_SI_FOCUS_DISTANCE_LOWER, "FocusDistanceLower", META_SSHORT ); add( CANON_SI_FOCUS_DISTANCE_LOWER, "SIFocusDistanceLower", META_SSHORT ); add( CANON_SI_FOCUS_DISTANCE_UPPER, "SIFocusDistanceUpper", META_SSHORT ); add( CANON_SI_ISO, "SIISO", META_SSHORT ); add( CANON_SI_SENSOR_WIDTH, "SISensorWidth", META_SSHORT ); add( CANON_SI_SENSOR_HEIGHT, "SISensorHeight", META_SSHORT ); add( CANON_SI_SENSOR_LEFT_BORDER, "SISensorLeftBorder", META_SSHORT ); add( CANON_SI_SENSOR_TOP_BORDER, "SISensorTopBorder", META_SSHORT ); add( CANON_SI_SENSOR_RIGHT_BORDER, "SISensorRightBorder", META_SSHORT ); add( CANON_SI_SENSOR_BOTTOM_BORDER, "SISensorBottomBorder", META_SSHORT ); add( CANON_SI_SEQUENCE_NUMBER, "SISequenceNumber", META_SSHORT ); add( CANON_SI_TARGET_APERTURE, "TargetAperture", META_SSHORT ); add( CANON_SI_TARGET_EXPOSURE_TIME, "TargetExposure", META_SSHORT ); add( CANON_SI_WHITE_BALANCE, "SIWhiteBalance", META_SSHORT ); add( CANON_WHITE_BALANCE_TABLE, "WhiteBalanceTable", META_SSHORT ); } } /* vim:set et sw=4 ts=4: */
package org.exist.xquery.functions.util; import org.apache.log4j.Logger; import org.exist.dom.DocumentSet; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.indexing.IndexWorker; import org.exist.indexing.OrderedValuesIndex; import org.exist.indexing.QNamedKeysIndex; import org.exist.storage.DBBroker; import org.exist.storage.IndexSpec; import org.exist.storage.Indexable; import org.exist.util.Occurrences; import org.exist.util.ValueOccurrences; import org.exist.xquery.*; import org.exist.xquery.value.*; import java.util.*; /** * @author wolf * */ public class IndexKeys extends BasicFunction { protected static final Logger logger = Logger.getLogger(IndexKeys.class); public final static FunctionSignature[] signatures = { new FunctionSignature( new QName("index-keys", UtilModule.NAMESPACE_URI, UtilModule.PREFIX), "Can be used to query existing range indexes defined on a set of nodes. " + "All index keys defined for the given node set are reported to a callback function. " + "The function will check for indexes defined on path as well as indexes defined by QName. ", new SequenceType[] { new FunctionParameterSequenceType("node-set", Type.NODE, Cardinality.ZERO_OR_MORE, "The node set"), new FunctionParameterSequenceType("start-value", Type.ATOMIC, Cardinality.ZERO_OR_ONE, "Only index keys of the same type but being greater than $start-value will be reported for non-string types. For string types, only keys starting with the given prefix are reported."), new FunctionParameterSequenceType("function-reference", Type.FUNCTION_REFERENCE, Cardinality.EXACTLY_ONE, "The function reference as created by the util:function function. " + "It can be an arbitrary user-defined function, but it should take exactly 2 arguments: " + "1) the current index key as found in the range index as an atomic value, 2) a sequence " + "containing three int values: a) the overall frequency of the key within the node set, " + "b) the number of distinct documents in the node set the key occurs in, " + "c) the current position of the key in the whole list of keys returned."), new FunctionParameterSequenceType("max-number-returned", Type.INT, Cardinality.ZERO_OR_ONE, "The maximum number of returned keys") }, new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE, "the results of the eval of the $function-reference")), new FunctionSignature( new QName("index-keys", UtilModule.NAMESPACE_URI, UtilModule.PREFIX), "Can be used to query existing range indexes defined on a set of nodes. " + "All index keys defined for the given node set are reported to a callback function. " + "The function will check for indexes defined on path as well as indexes defined by QName. ", new SequenceType[] { new FunctionParameterSequenceType("node-set", Type.NODE, Cardinality.ZERO_OR_MORE, "The node set"), new FunctionParameterSequenceType("start-value", Type.ATOMIC, Cardinality.ZERO_OR_ONE, "Only index keys of the same type but being greater than $start-value will be reported for non-string types. For string types, only keys starting with the given prefix are reported."), new FunctionParameterSequenceType("function-reference", Type.FUNCTION_REFERENCE, Cardinality.EXACTLY_ONE, "The function reference as created by the util:function function. " + "It can be an arbitrary user-defined function, but it should take exactly 2 arguments: " + "1) the current index key as found in the range index as an atomic value, 2) a sequence " + "containing three int values: a) the overall frequency of the key within the node set, " + "b) the number of distinct documents in the node set the key occurs in, " + "c) the current position of the key in the whole list of keys returned."), new FunctionParameterSequenceType("max-number-returned", Type.INT, Cardinality.ZERO_OR_ONE , "The maximum number of returned keys"), new FunctionParameterSequenceType("index", Type.STRING, Cardinality.EXACTLY_ONE, "The index in which the search is made") }, new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE, "the results of the eval of the $function-reference")), new FunctionSignature( new QName("index-keys-by-qname", UtilModule.NAMESPACE_URI, UtilModule.PREFIX), "Can be used to query existing range indexes defined on a set of nodes. " + "All index keys defined for the given node set are reported to a callback function. " + "The function will check for indexes defined on path as well as indexes defined by QName. ", new SequenceType[] { new FunctionParameterSequenceType("qname", Type.QNAME, Cardinality.ZERO_OR_MORE, "The node set"), new FunctionParameterSequenceType("start-value", Type.ATOMIC, Cardinality.ZERO_OR_ONE, "Only index keys of the same type but being greater than $start-value will be reported for non-string types. For string types, only keys starting with the given prefix are reported."), new FunctionParameterSequenceType("function-reference", Type.FUNCTION_REFERENCE, Cardinality.EXACTLY_ONE, "The function reference as created by the util:function function. " + "It can be an arbitrary user-defined function, but it should take exactly 2 arguments: " + "1) the current index key as found in the range index as an atomic value, 2) a sequence " + "containing three int values: a) the overall frequency of the key within the node set, " + "b) the number of distinct documents in the node set the key occurs in, " + "c) the current position of the key in the whole list of keys returned."), new FunctionParameterSequenceType("max-number-returned", Type.INT, Cardinality.ZERO_OR_ONE, "The maximum number of returned keys"), new FunctionParameterSequenceType("index", Type.STRING, Cardinality.EXACTLY_ONE, "The index in which the search is made") }, new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE, "the results of the eval of the $function-reference")), }; /** * @param context */ public IndexKeys(XQueryContext context, FunctionSignature signature) { super(context, signature); } /* * (non-Javadoc) * * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], * org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { if (args[0].isEmpty()) return Sequence.EMPTY_SEQUENCE; NodeSet nodes = null; DocumentSet docs = null; Sequence qnames = null; if (isCalledAs("index-keys-by-qname")) { qnames = args[0]; docs = contextSequence == null ? context.getStaticallyKnownDocuments() : contextSequence.getDocumentSet(); } else { nodes = args[0].toNodeSet(); docs = nodes.getDocumentSet(); } FunctionReference ref = (FunctionReference) args[2].itemAt(0); int max = -1; if (args[3].hasOne()) max = ((IntegerValue) args[3].itemAt(0)).getInt(); FunctionCall call = ref.getFunctionCall(); Sequence result = new ValueSequence(); if (this.getArgumentCount() == 5) { IndexWorker indexWorker = context.getBroker().getIndexController().getWorkerByIndexName(args[4].itemAt(0).getStringValue()); //Alternate design //IndexWorker indexWorker = context.getBroker().getBrokerPool().getIndexManager().getIndexByName(args[4].itemAt(0).getStringValue()).getWorker(); if (indexWorker == null) throw new XPathException(this, "Unknown index: " + args[4].itemAt(0).getStringValue()); Map<String, Object> hints = new HashMap<String, Object>(); if (max != -1) hints.put(IndexWorker.VALUE_COUNT, new IntegerValue(max)); if (indexWorker instanceof OrderedValuesIndex) hints.put(OrderedValuesIndex.START_VALUE, args[1].getStringValue()); else logger.warn(indexWorker.getClass().getName() + " isn't an instance of org.exist.indexing.OrderedIndexWorker. Start value '" + args[1] + "' ignored." ); if (qnames != null) { List<QName> qnameList = new ArrayList<QName>(qnames.getItemCount()); for (SequenceIterator i = qnames.iterate(); i.hasNext();) { QNameValue qv = (QNameValue) i.nextItem(); qnameList.add(qv.getQName()); } hints.put(QNamedKeysIndex.QNAMES_KEY, qnameList); } Occurrences[] occur = indexWorker.scanIndex(context, docs, nodes, hints); //TODO : add an extra argument to pass the END_VALUE ? int len = (max != -1 && occur.length > max ? max : occur.length); Sequence params[] = new Sequence[2]; ValueSequence data = new ValueSequence(); for (int j = 0; j < len; j++) { params[0] = new StringValue(occur[j].getTerm().toString()); data.add(new IntegerValue(occur[j].getOccurrences(), Type.UNSIGNED_INT)); data.add(new IntegerValue(occur[j].getDocuments(), Type.UNSIGNED_INT)); data.add(new IntegerValue(j + 1, Type.UNSIGNED_INT)); params[1] = data; result.addAll(call.evalFunction(contextSequence, null, params)); data.clear(); } } else { Indexable indexable = (Indexable) args[1].itemAt(0); ValueOccurrences occur[] = null; // First check for indexes defined on qname QName[] allQNames = getDefinedIndexes(context.getBroker(), docs); if (qnames != null && allQNames.length > 0) occur = context.getBroker().getValueIndex().scanIndexKeys(docs, nodes, allQNames, indexable); // Also check if there's an index defined by path ValueOccurrences occur2[] = context.getBroker().getValueIndex().scanIndexKeys(docs, nodes, indexable); // Merge the two results if (occur == null || occur.length == 0) occur = occur2; else { ValueOccurrences t[] = new ValueOccurrences[occur.length + occur2.length]; System.arraycopy(occur, 0, t, 0, occur.length); System.arraycopy(occur2, 0, t, occur.length, occur2.length); occur = t; } int len = (max != -1 && occur.length > max ? max : occur.length); Sequence params[] = new Sequence[2]; ValueSequence data = new ValueSequence(); for (int j = 0; j < len; j++) { params[0] = occur[j].getValue(); data.add(new IntegerValue(occur[j].getOccurrences(), Type.UNSIGNED_INT)); data.add(new IntegerValue(occur[j].getDocuments(), Type.UNSIGNED_INT)); data.add(new IntegerValue(j + 1, Type.UNSIGNED_INT)); params[1] = data; result.addAll(call.evalFunction(contextSequence, null, params)); data.clear(); } } logger.debug("Returning: " + result.getItemCount()); return result; } /** * Check index configurations for all collection in the given DocumentSet and return * a list of QNames, which have indexes defined on them. * * @param broker * @param docs * @return */ private QName[] getDefinedIndexes(DBBroker broker, DocumentSet docs) { Set<QName> indexes = new HashSet<QName>(); for (Iterator<org.exist.collections.Collection> i = docs.getCollectionIterator(); i.hasNext(); ) { final org.exist.collections.Collection collection = i.next(); final IndexSpec idxConf = collection.getIndexConfiguration(broker); if (idxConf != null) { final List<QName> qnames = idxConf.getIndexedQNames(); for (int j = 0; j < qnames.size(); j++) { final QName qName = (QName) qnames.get(j); indexes.add(qName); } } } QName qnames[] = new QName[indexes.size()]; return indexes.toArray(qnames); } }
package dynamake.models; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Stack; import javax.swing.JComponent; import dynamake.commands.AddObserverCommand; import dynamake.commands.Command; import dynamake.commands.CommandState; import dynamake.commands.CommandStateWithOutput; import dynamake.commands.MappableForwardable; import dynamake.commands.PendingCommandFactory; import dynamake.commands.PendingCommandState; import dynamake.commands.RemoveObserverCommand; import dynamake.commands.RevertingCommandStateSequence; import dynamake.commands.SetPropertyCommand; import dynamake.delegates.Action1; import dynamake.delegates.Func1; import dynamake.menubuilders.ColorMenuBuilder; import dynamake.menubuilders.CompositeMenuBuilder; import dynamake.models.factories.CloneFactory; import dynamake.models.factories.ModelFactory; import dynamake.models.factories.DeriveFactory; import dynamake.numbers.Fraction; import dynamake.numbers.RectangleF; import dynamake.transcription.Collector; import dynamake.transcription.Connection; import dynamake.transcription.ExPendingCommandFactory2; import dynamake.transcription.Execution; import dynamake.transcription.LocalHistoryHandler; import dynamake.transcription.RedoHistoryHandler; import dynamake.transcription.Trigger; import dynamake.transcription.UndoHistoryHandler; /** * Instances of implementors are supposed to represent alive-like sensitive entities, each with its own local history. */ public abstract class Model implements Serializable, Observer { public static class UndoRedoPart implements Serializable, CommandStateWithOutput<Model> { private static final long serialVersionUID = 1L; public final Execution<Model> origin; public final CommandStateWithOutput<Model> revertible; public UndoRedoPart(Execution<Model> origin, CommandStateWithOutput<Model> revertible) { this.origin = origin; this.revertible = revertible; } @Override public CommandState<Model> executeOn(PropogationContext propCtx, Model prevalentSystem, Collector<Model> collector, Location location) { CommandState<Model> reverted = revertible.executeOn(propCtx, prevalentSystem, collector, location); return new UndoRedoPart(origin, (CommandStateWithOutput<Model>)reverted); } @Override public CommandState<Model> mapToReferenceLocation(Model sourceReference, Model targetReference) { return new UndoRedoPart( origin.mapToReferenceLocation(sourceReference, targetReference), (CommandStateWithOutput<Model>)revertible.mapToReferenceLocation(sourceReference, targetReference) ); } @Override public CommandState<Model> offset(Location offset) { return new UndoRedoPart(origin.offset(offset), (CommandStateWithOutput<Model>)revertible.offset(offset)); } public CommandState<Model> forForwarding() { return new UndoRedoPart(origin.forForwarding(), (CommandStateWithOutput<Model>)revertible.forForwarding()); } @Override public void appendPendings(List<CommandState<Model>> pendingCommands) { // origin.appendPendings(pendingCommands); pendingCommands.add(revertible); } @Override public CommandState<Model> forForwarding(Object output) { return null; } @Override public Object getOutput() { return revertible.getOutput(); } } public static class HistoryAppendLogChange { public final List<Execution<Model>> pendingUndoablePairs; public HistoryAppendLogChange(List<Execution<Model>> pendingCommands) { this.pendingUndoablePairs = pendingCommands; } } public static class TellProperty { public final String name; public TellProperty(String name) { this.name = name; } } public static class MouseDown { } public static class MouseUp { } public static final String PROPERTY_COLOR = "Color"; public static final String PROPERTY_VIEW = "View"; private static final long serialVersionUID = 1L; public static final int VIEW_APPLIANCE = 1; public static final int VIEW_ENGINEERING = 0; public static class Atom { public final Object value; public Atom(Object value) { this.value = value; } } public static class PropertyChanged { public final String name; public final Object value; public PropertyChanged(String name, Object value) { this.name = name; this.value = value; } } public static class SetProperty { public final String name; public final Object value; public SetProperty(String name, Object value) { this.name = name; this.value = value; } } private ArrayList<Observer> observers = new ArrayList<Observer>(); private ArrayList<Observer> observees = new ArrayList<Observer>(); protected Hashtable<String, Object> properties = new Hashtable<String, Object>(); /* Both undo- and stack are assumed to contain RevertingCommandStateSequence<Model> objects */ protected Stack<CommandState<Model>> undoStack = new Stack<CommandState<Model>>(); protected Stack<CommandState<Model>> redoStack = new Stack<CommandState<Model>>(); // private ArrayList<Execution<Model>> newLog = new ArrayList<Execution<Model>>(); private Locator locator; private Model parent; private void writeObject(ObjectOutputStream ous) throws IOException { ArrayList<Observer> observersToSerialize = new ArrayList<Observer>(); for(Observer o: observers) { if(o instanceof Serializable) observersToSerialize.add(o); } ous.writeObject(observersToSerialize); ArrayList<Observer> observeesToSerialize = new ArrayList<Observer>(); for(Observer o: observees) { if(o instanceof Serializable) observeesToSerialize.add(o); } ous.writeObject(observeesToSerialize); ous.writeObject(properties); ous.writeObject(undoStack); ous.writeObject(redoStack); } @SuppressWarnings("unchecked") private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { observers = (ArrayList<Observer>)ois.readObject(); observees = (ArrayList<Observer>)ois.readObject(); properties = (Hashtable<String, Object>)ois.readObject(); undoStack = (Stack<CommandState<Model>>)ois.readObject(); redoStack = (Stack<CommandState<Model>>)ois.readObject(); // newLog = new ArrayList<Execution<Model>>(); } public void appendLog(ArrayList<Execution<Model>> pendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) { // System.out.println("Log"); redoStack.clear(); // newLog.addAll(pendingUndoablePairs); sendChanged(new HistoryAppendLogChange(pendingUndoablePairs), propCtx, propDistance, 0, collector); } public void postLog(ArrayList<Execution<Model>> pendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) { // System.out.println("Log"); sendChanged(new HistoryAppendLogChange(pendingUndoablePairs), propCtx, propDistance, 0, collector); } // public void commitLog(PropogationContext propCtx, int propDistance, Collector<Model> collector) { // if(newLog.size() > 0) { // @SuppressWarnings("unchecked") // CommandState<Model>[] compressedLogPartAsArray = (CommandState<Model>[])new CommandState[newLog.size()]; // for(int i = 0; i < newLog.size(); i++) { // compressedLogPartAsArray[i] = new UndoRedoPart(newLog.get(i), newLog.get(i).undoable); // RevertingCommandStateSequence<Model> compressedLogPart = RevertingCommandStateSequence.reverse(compressedLogPartAsArray); // undoStack.add(compressedLogPart); // newLog.clear(); public void commitLog(CommandState<Model> logPart) { undoStack.add(logPart); } public void rejectLog(PropogationContext propCtx, int propDistance, Collector<Model> collector) { // newLog.clear(); } public void unplay(int count, PropogationContext propCtx, int propDistance, Collector<Model> collector) { for(int i = 0; i < count; i++) { CommandState<Model> toUndo = undoStack.pop(); CommandState<Model> redoable = toUndo.executeOn(propCtx, this, collector, new ModelRootLocation()); redoStack.push(redoable); } // @SuppressWarnings("unchecked") // CommandState<Model>[] toUndos = (CommandState<Model>[])new CommandState[count]; // for(int i = 0; i < count; i++) { // toUndos[i] = undoStack.pop(); // executeSequence(toUndos, 0, UnplayHistoryHandler.class, propCtx, propDistance, collector); } public void replay(int count, PropogationContext propCtx, int propDistance, Collector<Model> collector) { for(int i = 0; i < count; i++) { CommandState<Model> toRedo = redoStack.pop(); CommandState<Model> undoable = toRedo.executeOn(propCtx, this, collector, new ModelRootLocation()); undoStack.push(undoable); } } public CommandState<Model> undo(PropogationContext propCtx, int propDistance, Collector<Model> collector) { if(!undoStack.isEmpty()) { CommandState<Model> toUndo = undoStack.pop(); CommandState<Model> redoable = toUndo.executeOn(propCtx, this, collector, new ModelRootLocation()); redoStack.push(redoable); return toUndo; } return null; } public CommandState<Model> undo2(PropogationContext propCtx, int propDistance, Collector<Model> collector) { // An undo method which starts all undo parts and ensure the sequence // A new kind of history handler is probably needed? // undo stack is assumed to consist only of RevertingCommandStateSequence<Model>. // These could probably be replaced by simpler structures; just lists of CommandState objects. RevertingCommandStateSequence<Model> toUndo = (RevertingCommandStateSequence<Model>)undoStack.pop(); ExPendingCommandFactory2.Util.sequence(collector, this, Arrays.asList(toUndo.commandStates), UndoHistoryHandler.class); // executeSequence(toUndo.commandStates, 0, UndoHistoryHandler.class, propCtx, propDistance, collector); return toUndo; // if(!undoStack.isEmpty()) { // CommandState<Model> toUndo = undoStack.pop(); // CommandState<Model> redoable = toUndo.executeOn(propCtx, this, collector, new ModelRootLocation()); // redoStack.push(redoable); // return toUndo; // return null; } public void commitUndo(CommandState<Model> redoable) { redoStack.push(redoable); } // private void executeSequence(final CommandState<Model>[] commandStates, final int i, final Class<? extends HistoryHandler<Model>> historyHandlerClass, // PropogationContext propCtx, int propDistance, Collector<Model> collector) { // if(i < commandStates.length) { // CommandState<Model> reversible = ((CommandState<Model>)commandStates[i]); // collector.execute(new SimpleExPendingCommandFactory<Model>(this, reversible) { // @Override // public void afterPropogationFinished(List<Execution<Model>> pendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) { // executeSequence(commandStates, i + 1, historyHandlerClass, propCtx, propDistance, collector); // @Override // public Class<? extends HistoryHandler<Model>> getHistoryHandlerClass() { // return historyHandlerClass; public CommandState<Model> redo(PropogationContext propCtx, int propDistance, Collector<Model> collector) { if(!redoStack.isEmpty()) { CommandState<Model> toRedo = redoStack.pop(); CommandState<Model> undoable = toRedo.executeOn(propCtx, this, collector, new ModelRootLocation()); undoStack.push(undoable); return toRedo; } return null; } public CommandState<Model> redo2(PropogationContext propCtx, int propDistance, Collector<Model> collector) { RevertingCommandStateSequence<Model> toRedo = (RevertingCommandStateSequence<Model>)redoStack.pop(); ExPendingCommandFactory2.Util.sequence(collector, this, Arrays.asList(toRedo.commandStates), RedoHistoryHandler.class); // executeSequence(toRedo.commandStates, 0, RedoHistoryHandler.class, propCtx, propDistance, collector); return toRedo; } public void commitRedo(CommandState<Model> undoable) { undoStack.push(undoable); } public List<CommandState<Model>> playThenReverse(List<CommandState<Model>> toPlay, PropogationContext propCtx, int propDistance, Collector<Model> collector) { ArrayList<CommandState<Model>> newCommandStates = new ArrayList<CommandState<Model>>(); for(CommandState<Model> cs: toPlay) { CommandState<Model> newCS = cs.executeOn(propCtx, this, collector, new ModelRootLocation()); newCommandStates.add(newCS); } Collections.reverse(newCommandStates); return newCommandStates; } public boolean canUndo() { return undoStack.size() > 0; } public boolean canRedo() { return redoStack.size() > 0; } public CommandState<Model> getUnplayable() { return RevertingCommandStateSequence.reverse(undoStack); } public List<CommandState<Model>> getLocalChangesWithOutput() { ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); for(CommandState<Model> undoable: undoStack) { RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); origins.add(undoPart); } } return origins; } public List<CommandState<Model>> getLocalChanges() { // ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); // for(CommandState<Model> undoable: undoStack) { // RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; // for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { // UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); // origins.add(undoPart.origin.pending); // return origins; ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); for(CommandState<Model> undoable: undoStack) { RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); origins.add(undoPart.origin); } } return origins; } public List<CommandState<Model>> getLocalChangesForExecution() { // ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); // for(CommandState<Model> undoable: undoStack) { // RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; // for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { // UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); // origins.add(undoPart.origin.pending); // return origins; ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); for(CommandState<Model> undoable: undoStack) { RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); origins.add(undoPart.origin.pending); } } return origins; } public List<Execution<Model>> getLocalChangesAsPairs() { ArrayList<Execution<Model>> origins = new ArrayList<Execution<Model>>(); for(CommandState<Model> undoable: undoStack) { RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); origins.add(undoPart.origin); } } return origins; } public List<CommandState<Model>> getLocalChangesBackwards() { ArrayList<CommandState<Model>> backwards = new ArrayList<CommandState<Model>>(); for(CommandState<Model> undoable: undoStack) { RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; for(int i = undoableAsRevertiable.getCommandStateCount() - 1; i >= 0; i UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); backwards.add(undoPart.revertible); } } Collections.reverse(backwards); return backwards; } public int getLocalChangeCount() { return undoStack.size(); } public void setLocator(Locator locator) { // if(locator == null) // System.out.println("Nulled locator of " + this); // System.out.println("Set locator to " + locator + " of " + this); this.locator = locator; } public Locator getLocator() { return locator; } public void setParent(Model parent) { this.parent = parent; // System.out.println("Set parent of " + this + " to " + parent); } public Model getParent() { return parent; } public void setProperty(String name, Object value, PropogationContext propCtx, int propDistance, Collector<Model> collector) { if(value != null) properties.put(name, value); else properties.remove(name); sendChanged(new PropertyChanged(name, value), propCtx, propDistance, 0, collector); } public void setBounds(RectangleF bounds, PropogationContext propCtx, int propDistance, Collector<Model> collector) { setProperty("X", bounds.x, propCtx, propDistance, collector); setProperty("Y", bounds.y, propCtx, propDistance, collector); setProperty("Width", bounds.width, propCtx, propDistance, collector); setProperty("Height", bounds.height, propCtx, propDistance, collector); } public Object getProperty(String name) { return properties.get(name); } public RectangleF getBounds() { Fraction x = (Fraction)getProperty("X"); Fraction y = (Fraction)getProperty("Y"); Fraction width = (Fraction)getProperty("Width"); Fraction height = (Fraction)getProperty("Height"); return new RectangleF(x, y, width, height); } @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof SetProperty && changeDistance == 1) { // Side-effect final SetProperty setProperty = (SetProperty)change; ExPendingCommandFactory2.Util.single(collector, this, LocalHistoryHandler.class, new PendingCommandState<Model>( new SetPropertyCommand(setProperty.name, setProperty.value), new SetPropertyCommand.AfterSetProperty() )); } else if(change instanceof TellProperty && changeDistance == 1) { // Side-effect TellProperty tellProperty = (TellProperty)change; Object value = getProperty(tellProperty.name); if(value != null) sendChanged(new Model.PropertyChanged(tellProperty.name, value), propCtx, propDistance, 0, collector); } else { modelChanged(sender, change, propCtx, propDistance, changeDistance, collector); } } protected void modelChanged(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { } public static class RemovableListener implements Binding<Model> { private Observer listener; private Model model; public RemovableListener(Observer listener, Model model) { this.listener = listener; this.model = model; } @Override public Model getBindingTarget() { return model; } @Override public void releaseBinding() { model.removeObserver(listener); } public static RemovableListener addObserver(Model model, Observer listener) { model.addObserver(listener); return new RemovableListener(listener, model); } public static Binding<Model> addAll(final Model model, final RemovableListener... removableListeners) { return new Binding<Model>() { @Override public Model getBindingTarget() { return model; } @Override public void releaseBinding() { for(RemovableListener rl: removableListeners) rl.releaseBinding(); } }; } } public abstract Binding<ModelComponent> createView(ModelComponent rootView, ViewManager viewManager, ModelTranscriber modelTranscriber); public void setView(int view, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { setProperty(Model.PROPERTY_VIEW, view, propCtx, propDistance, collector); } public void sendChanged(Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { int nextChangeDistance = changeDistance + 1; int nextPropDistance = propDistance + 1; for(Observer observer: observers) { PropogationContext propCtxBranch = propCtx.branch(); observer.changed(this, change, propCtxBranch, nextPropDistance, nextChangeDistance, collector); } } public void addObserver(Observer observer) { observers.add(observer); observer.addObservee(this); } public void removeObserver(Observer observer) { observers.remove(observer); observer.removeObservee(this); } public void removeObserverLike(Observer observer) { observers.remove(observer); observer.removeObservee(this); } @SuppressWarnings("unchecked") public <T extends Observer> T getObserverOfLike(T observer) { int indexOfObserver = observers.indexOf(observer); return (T)observers.get(indexOfObserver); } public Observer getObserverWhere(Func1<Observer, Boolean> filter) { for(Observer observer: observers) { if(filter.call(observer)) return observer; } return null; } @SuppressWarnings("unchecked") public <T extends Observer> T getObserverOfType(Class<T> c) { for(Observer observer: observers) { if(c.isInstance(observer)) return (T)observer; } return null; } @SuppressWarnings("unchecked") public <T extends Observer> T getObserveeOfType(Class<T> c) { for(Observer observee: observees) { if(c.isInstance(observee)) return (T)observee; } return null; } public void addObservee(Observer observee) { observees.add(observee); } public void removeObservee(Observer observee) { observees.remove(observee); } public boolean isObservedBy(Observer observer) { return observers.contains(observer); } public static RemovableListener wrapForBoundsChanges(final Model model, final ModelComponent target, final ViewManager viewManager) { return RemovableListener.addObserver(model, new ObserverAdapter() { @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof Model.PropertyChanged && changeDistance == 1 /* And not a forwarded change */) { final Model.PropertyChanged propertyChanged = (Model.PropertyChanged)change; final Component targetComponent = ((Component)target); if(propertyChanged.name.equals("X")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setLocation(new Point(((Number)propertyChanged.value).intValue(), targetComponent.getY())); } }); } else if(propertyChanged.name.equals("Y")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setLocation(new Point(targetComponent.getX(), ((Number)propertyChanged.value).intValue())); } }); } else if(propertyChanged.name.equals("Width")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setSize(new Dimension(((Number)propertyChanged.value).intValue(), targetComponent.getHeight())); } }); } else if(propertyChanged.name.equals("Height")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setSize(new Dimension(targetComponent.getWidth(), ((Number)propertyChanged.value).intValue())); } }); } } } }); } public static final int COMPONENT_COLOR_BACKGROUND = 0; public static final int COMPONENT_COLOR_FOREGROUND = 1; public static RemovableListener wrapForComponentColorChanges(Model model, final ModelComponent view, final JComponent targetComponent, final ViewManager viewManager, final int componentColor) { return RemovableListener.addObserver(model, new ObserverAdapter() { @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof Model.PropertyChanged) { final Model.PropertyChanged propertyChanged = (Model.PropertyChanged)change; if(propertyChanged.name.equals(PROPERTY_COLOR)) { switch(componentColor) { case COMPONENT_COLOR_BACKGROUND: { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setBackground((Color)propertyChanged.value); // System.out.println("Change background"); } }); break; } case COMPONENT_COLOR_FOREGROUND: { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setForeground((Color)propertyChanged.value); } }); break; } } } } } }); } private static class MouseUpCommand implements Command<Model> { private static final long serialVersionUID = 1L; @Override public Object executeOn(PropogationContext propCtx, Model rootPrevalentSystem, Collector<Model> collector, Location location) { Model model = (Model)location.getChild(rootPrevalentSystem); model.sendChanged(new MouseUp(), propCtx, 0, 0, collector); return null; } } private static class MouseDownCommand implements Command<Model> { private static final long serialVersionUID = 1L; @Override public Object executeOn(PropogationContext propCtx, Model rootPrevalentSystem, Collector<Model> collector, Location location) { Model model = (Model)location.getChild(rootPrevalentSystem); model.sendChanged(new MouseDown(), propCtx, 0, 0, collector); return null; } } public static void wrapForComponentGUIEvents(final Model model, final ModelComponent view, final JComponent targetComponent, final ViewManager viewManager) { ((JComponent)view).addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { Connection<Model> connection = view.getModelTranscriber().createConnection(); connection.trigger(new Trigger<Model>() { @Override public void run(Collector<Model> collector) { collector.execute(new PendingCommandFactory<Model>() { @Override public Model getReference() { return view.getModelBehind(); } @Override public void createPendingCommands(List<CommandState<Model>> commandStates) { commandStates.add(new PendingCommandState<Model>( new MouseUpCommand(), new Command.Null<Model>() )); } }); collector.commit(); } }); } @Override public void mousePressed(MouseEvent arg0) { Connection<Model> connection = view.getModelTranscriber().createConnection(); connection.trigger(new Trigger<Model>() { @Override public void run(Collector<Model> collector) { collector.execute(new PendingCommandFactory<Model>() { @Override public Model getReference() { return view.getModelBehind(); } @Override public void createPendingCommands(List<CommandState<Model>> commandStates) { commandStates.add(new PendingCommandState<Model>( new MouseDownCommand(), new Command.Null<Model>() )); } }); collector.commit(); } }); } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseClicked(MouseEvent arg0) { } }); } public static void loadComponentProperties(Model model, Component view, final int componentColor) { Object color = model.getProperty(Model.PROPERTY_COLOR); if(color != null) { switch(componentColor) { case COMPONENT_COLOR_BACKGROUND: { view.setBackground((Color)color); } case COMPONENT_COLOR_FOREGROUND: { view.setForeground((Color)color); } } } } public static void loadComponentBounds(Model model, Component view) { Number x = (Number)model.getProperty("X"); if(x != null) view.setLocation(x.intValue(), view.getY()); Number y = (Number)model.getProperty("Y"); if(y != null) view.setLocation(view.getX(), y.intValue()); Integer width = (Integer)model.getProperty("Width"); if(width != null) view.setSize(width.intValue(), view.getHeight()); Integer height = (Integer)model.getProperty("Height"); if(height != null) view.setSize(view.getWidth(), height.intValue()); } @SuppressWarnings("unchecked") public static <T> Model.RemovableListener bindProperty(Model model, final String modelPropertyName, final Action1<T> propertySetter) { Object value = model.getProperty(modelPropertyName); if(value != null) propertySetter.run((T)value); return Model.RemovableListener.addObserver(model, new ObserverAdapter() { @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof Model.PropertyChanged && changeDistance == 1 /* And not a forwarded change */) { final Model.PropertyChanged propertyChanged = (Model.PropertyChanged)change; if(propertyChanged.name.equals(modelPropertyName)) { collector.afterNextTrigger(new Runnable() { @Override public void run() { propertySetter.run((T)propertyChanged.value); } }); } } } }); } public static void appendComponentPropertyChangeTransactions(final ModelComponent livePanel, final Model model, final ModelTranscriber modelTranscriber, CompositeMenuBuilder transactions) { transactions.addMenuBuilder("Set " + PROPERTY_COLOR, new ColorMenuBuilder((Color)model.getProperty(PROPERTY_COLOR), new Func1<Color, Object>() { @Override public Object call(final Color color) { return new Trigger<Model>() { @Override public void run(Collector<Model> collector) { ExPendingCommandFactory2.Util.single(collector, model, LocalHistoryHandler.class, new PendingCommandState<Model>( new SetPropertyCommand(PROPERTY_COLOR, color), new SetPropertyCommand.AfterSetProperty() )); // collector.execute(new PendingCommandFactory<Model>() { // @Override // public Model getReference() { // return model; // @Override // public void createPendingCommands(List<CommandState<Model>> dualCommands) { // dualCommands.add(new PendingCommandState<Model>( // new SetPropertyCommand(PROPERTY_COLOR, color), // new SetPropertyCommand.AfterSetProperty() } }; } })); } public static void appendGeneralDroppedTransactions(final ModelComponent livePanel, final ModelComponent dropped, final ModelComponent target, final Rectangle droppedBounds, CompositeMenuBuilder transactions) { if(target.getModelBehind() instanceof CanvasModel) { transactions.addMenuBuilder("Clone", new Trigger<Model>() { @Override public void run(Collector<Model> collector) { final Rectangle creationBounds = droppedBounds; collector.execute(new Trigger<Model>() { public void run(Collector<Model> collector) { ModelComponent cca = ModelComponent.Util.closestCommonAncestor(target, dropped); Location fromTargetToCCA = ModelComponent.Util.locationToAncestor(cca, target); Location fromCCAToDropped = new CompositeLocation(fromTargetToCCA, ModelComponent.Util.locationFromAncestor(cca, dropped)); // Probably, the "version" of dropped to be cloned is important // Dropped may change and, thus, in a undo/redo scenario on target, the newer version is cloned. Location droppedLocation = fromCCAToDropped; ExPendingCommandFactory2.Util.single(collector, target.getModelBehind(), LocalHistoryHandler.class, new PendingCommandState<Model>( new CanvasModel.AddModelCommand(new CloneFactory(new RectangleF(creationBounds), droppedLocation)), new CanvasModel.RemoveModelCommand.AfterAdd(), new CanvasModel.RestoreModelCommand.AfterRemove() )); } }); } }); transactions.addMenuBuilder("Derive", new Trigger<Model>() { @Override public void run(Collector<Model> collector) { final Rectangle creationBounds = droppedBounds; collector.execute(new Trigger<Model>() { public void run(Collector<Model> collector) { ModelComponent cca = ModelComponent.Util.closestCommonAncestor(target, dropped); Location fromTargetToCCA = ModelComponent.Util.locationToAncestor(cca, target); Location fromCCAToDropped = new CompositeLocation(fromTargetToCCA, ModelComponent.Util.locationFromAncestor(cca, dropped)); // Probably, the "version" of dropped to be cloned is important // Dropped may change and, thus, in a undo/redo scenario on target, the newer version is cloned. Location droppedLocation = fromCCAToDropped; ModelFactory factory = new DeriveFactory(new RectangleF(creationBounds), droppedLocation); ExPendingCommandFactory2.Util.single(collector, target.getModelBehind(), LocalHistoryHandler.class, new PendingCommandState<Model>( new CanvasModel.AddModelCommand(factory), new CanvasModel.RemoveModelCommand.AfterAdd(), new CanvasModel.RestoreModelCommand.AfterRemove() )); } }); } }); } } public abstract Model modelCloneIsolated(); protected Model modelCloneDeep(Hashtable<Model, Model> visited, HashSet<Model> contained) { return modelCloneIsolated(); } public Model cloneIsolated() { Model clone = modelCloneIsolated(); if(clone.properties == null) clone.properties = new Hashtable<String, Object>(); // Assumed that cloning is not necessary for properties // I.e., all property values are immutable clone.properties.putAll(this.properties); clone.undoStack.addAll(this.undoStack); clone.redoStack.addAll(this.redoStack); return clone; } public Model cloneDeep() { Hashtable<Model, Model> sourceToCloneMap = new Hashtable<Model, Model>(); cloneAndMap(sourceToCloneMap); for(Map.Entry<Model, Model> sourceToCloneEntry: sourceToCloneMap.entrySet()) { Model source = sourceToCloneEntry.getKey(); Model clone = sourceToCloneEntry.getValue(); for(Observer observer: source.observers) { if(observer instanceof Model) { Model observerClone = sourceToCloneMap.get(observer); if(observerClone != null) { // Only if observer is contained clone.observers.add(observerClone); observerClone.observees.add(clone); } } } } return sourceToCloneMap.get(this); } protected void addContent(HashSet<Model> contained) { contained.add(this); modelAddContent(contained); } protected void modelAddContent(HashSet<Model> contained) { } protected void cloneAndMap(Hashtable<Model, Model> sourceToCloneMap) { Model clone = cloneIsolated(); sourceToCloneMap.put(this, clone); } public void inject(Model model) { for(Observer observer: this.observers) { if(observer instanceof Model) { model.addObserver(observer); } } for(Observer observee: this.observees) { if(observee instanceof Model) { ((Model)observee).addObserver(model); } } } public void deject(Model model) { for(Observer observer: this.observers) { if(observer instanceof Model) { model.removeObserver(observer); } } for(Observer observee: this.observees) { if(observee instanceof Model) { ((Model)observee).removeObserver(model); } } } public boolean conformsToView(int value) { Integer view = (Integer)getProperty(Model.PROPERTY_VIEW); if(view == null) view = 1; return view <= value; } public boolean viewConformsTo(int value) { Integer view = (Integer)getProperty(Model.PROPERTY_VIEW); if(view == null) view = 1; return view >= value; } public void resize(Fraction xDelta, Fraction tDelta, Fraction widthDelta, Fraction heightDelta, PropogationContext propCtx, int propDistance, Collector<Model> collector) { Fraction currentX = (Fraction)getProperty("X"); Fraction currentY = (Fraction)getProperty("Y"); Fraction newX = currentX.add(xDelta); Fraction newY = currentY.add(tDelta); Fraction currentWidth = (Fraction)getProperty("Width"); Fraction currentHeight = (Fraction)getProperty("Height"); Fraction newWidth = currentWidth.add(widthDelta); Fraction newHeight = currentHeight.add(heightDelta); setProperty("X", newX, propCtx, propDistance, collector); setProperty("Y", newY, propCtx, propDistance, collector); setProperty("Width", newWidth, propCtx, propDistance, collector); setProperty("Height", newHeight, propCtx, propDistance, collector); } public void scale(Fraction xDelta, Fraction tDelta, Fraction hChange, Fraction vChange, PropogationContext propCtx, int propDistance, Collector<Model> collector) { Fraction currentX = (Fraction)getProperty("X"); Fraction currentY = (Fraction)getProperty("Y"); Fraction newX = currentX.add(xDelta); Fraction newY = currentY.add(tDelta); Fraction currentWidth = (Fraction)getProperty("Width"); Fraction currentHeight = (Fraction)getProperty("Height"); Fraction newWidth = currentWidth.multiply(hChange); Fraction newHeight = currentHeight.multiply(vChange); setProperty("X", newX, propCtx, propDistance, collector); setProperty("Y", newY, propCtx, propDistance, collector); setProperty("Width", newWidth, propCtx, propDistance, collector); setProperty("Height", newHeight, propCtx, propDistance, collector); modelScale(hChange, vChange, propCtx, propDistance, collector); } public void scale(final Fraction hChange, final Fraction vChange, PropogationContext propCtx, int propDistance, Collector<Model> collector) { Fraction currentX = (Fraction)getProperty("X"); Fraction currentY = (Fraction)getProperty("Y"); Fraction currentWidth = (Fraction)getProperty("Width"); Fraction currentHeight = (Fraction)getProperty("Height"); Fraction newX = currentX.multiply(hChange); Fraction newY = currentY.multiply(vChange); Fraction newWidth = currentWidth.multiply(hChange); Fraction newHeight = currentHeight.multiply(vChange); setProperty("X", newX, propCtx, propDistance, collector); setProperty("Y", newY, propCtx, propDistance, collector); setProperty("Width", newWidth, propCtx, propDistance, collector); setProperty("Height", newHeight, propCtx, propDistance, collector); modelScale(hChange, vChange, propCtx, propDistance, collector); } protected void modelScale(Fraction hChange, Fraction vChange, PropogationContext propCtx, int propDistance, Collector<Model> collector) { } public static void executeRemoveObserver(Collector<Model> collector, final ModelComponent observable, final ModelComponent observer) { collector.execute(new Trigger<Model>() { @Override public void run(Collector<Model> collector) { ModelComponent referenceMC = ModelComponent.Util.closestCommonAncestor(observable, observer); Location observableLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observable); Location observerLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observer); ExPendingCommandFactory2.Util.single(collector, referenceMC.getModelBehind(), LocalHistoryHandler.class, new PendingCommandState<Model>( new RemoveObserverCommand(observableLocation, observerLocation), new AddObserverCommand(observableLocation, observerLocation) )); } }); } public static void executeAddObserver(Collector<Model> collector, final ModelComponent observable, final ModelComponent observer) { collector.execute(new Trigger<Model>() { @Override public void run(Collector<Model> collector) { ModelComponent referenceMC = ModelComponent.Util.closestCommonAncestor(observable, observer); Location observableLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observable); Location observerLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observer); ExPendingCommandFactory2.Util.single(collector, referenceMC.getModelBehind(), LocalHistoryHandler.class, new PendingCommandState<Model>( new AddObserverCommand(observableLocation, observerLocation), new RemoveObserverCommand(observableLocation, observerLocation) )); } }); } public abstract Model cloneBase(); private static class History implements MappableForwardable, Serializable { private static final long serialVersionUID = 1L; public final boolean includeHistory; public final Stack<CommandState<Model>> undoStack; public final Stack<CommandState<Model>> redoStack; public History(boolean includeHistory, Stack<CommandState<Model>> undoStack, Stack<CommandState<Model>> redoStack) { this.includeHistory = includeHistory; this.undoStack = undoStack; this.redoStack = redoStack; } @Override public MappableForwardable mapToReferenceLocation(Model sourceReference, Model targetReference) { Stack<CommandState<Model>> mappedUndoStack = new Stack<CommandState<Model>>(); for(CommandState<Model> cs: undoStack) mappedUndoStack.add(cs.mapToReferenceLocation(sourceReference, targetReference)); Stack<CommandState<Model>> mappedRedoStack = new Stack<CommandState<Model>>(); for(CommandState<Model> cs: redoStack) mappedRedoStack.add(cs.mapToReferenceLocation(sourceReference, targetReference)); return new History(includeHistory, mappedUndoStack, mappedRedoStack); } @Override public MappableForwardable forForwarding() { Stack<CommandState<Model>> forForwardingUndoStack = new Stack<CommandState<Model>>(); for(CommandState<Model> cs: undoStack) forForwardingUndoStack.add(cs.forForwarding()); Stack<CommandState<Model>> forForwardingRedoStack = new Stack<CommandState<Model>>(); for(CommandState<Model> cs: redoStack) forForwardingRedoStack.add(cs.forForwarding()); return new History(includeHistory, forForwardingUndoStack, forForwardingRedoStack); } } public MappableForwardable cloneHistory(boolean includeHistory) { return new History(includeHistory, undoStack, redoStack); } public void restoreHistory(Object history, PropogationContext propCtx, int propDistance, Collector<Model> collector) { if(((History)history).includeHistory) { this.undoStack = ((History)history).undoStack; this.redoStack = ((History)history).redoStack; } ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); for(CommandState<Model> undoable: ((History)history).undoStack) { RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); origins.add(undoPart.origin.pending); } } ExPendingCommandFactory2.Util.sequence(collector, this, origins); // collector.execute(new SimpleExPendingCommandFactory<Model>(this, origins)); } public RestorableModel toRestorable(boolean includeLocalHistory) { return RestorableModel.wrap(this, includeLocalHistory); } public void destroy(PropogationContext propCtx, int propDistance, Collector<Model> collector) { @SuppressWarnings("unchecked") List<Execution<Model>> creation = (List<Execution<Model>>)getProperty(RestorableModel.PROPERTY_CREATION); if(creation != null) { List<CommandState<Model>> destruction = new ArrayList<CommandState<Model>>(); for(Execution<Model> creationPart: creation) destruction.add(creationPart.undoable); Collections.reverse(destruction); ExPendingCommandFactory2.Util.sequence(collector, this, destruction); // collector.execute(new SimpleExPendingCommandFactory<Model>(this, destruction)); } } }
package org.exist.xquery.functions.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Properties; import javax.xml.transform.OutputKeys; import org.exist.dom.QName; import org.exist.storage.serializers.Serializer; import org.exist.util.serializer.SAXSerializer; import org.exist.util.serializer.SerializerPool; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Pragma; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.xml.sax.SAXException; public class Serialize extends BasicFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("serialize", UtilModule.NAMESPACE_URI, UtilModule.PREFIX), "Writes the node set passed in parameter $a into a file on the file system. The " + "full path to the file is specified in parameter $b. $c contains a " + "sequence of zero or more serialization parameters specified as key=value pairs. The " + "serialization options are the same as those recognized by \"declare option exist:serialize\". " + "The function does NOT automatically inherit the serialization options of the XQuery it is " + "called from. False is returned if the " + "specified file can not be created or is not writable, true on success. The empty " + "sequence if returned if the argument sequence is empty.", new SequenceType[] { new SequenceType(Type.NODE, Cardinality.ZERO_OR_MORE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.ZERO_OR_MORE) }, new SequenceType(Type.BOOLEAN, Cardinality.ZERO_OR_ONE)); public Serialize(XQueryContext context) { super(context, signature); } public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { if (args[0].getLength() == 0) return Sequence.EMPTY_SEQUENCE; // check the file output path String path = args[1].itemAt(0).getStringValue(); File file = new File(path); if (file.isDirectory()) { LOG.debug("Output file is a directory: " + file.getAbsolutePath()); return BooleanValue.FALSE; } if (file.exists() && !file.canWrite()) { LOG.debug("Cannot write to file " + file.getAbsolutePath()); return BooleanValue.FALSE; } // parse serialization options Properties outputProperties = new Properties(); outputProperties.setProperty(OutputKeys.INDENT, "yes"); outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); for (SequenceIterator i = args[2].iterate(); i.hasNext(); ) { String opt[] = Pragma.parseKeyValuePair(i.nextItem().getStringValue()); outputProperties.setProperty(opt[0], opt[1]); } // serialize the node set SAXSerializer sax = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class); try { String encoding = outputProperties.getProperty(OutputKeys.ENCODING, "UTF-8"); Writer writer = new OutputStreamWriter(new FileOutputStream(file), encoding); sax.setOutput(writer, outputProperties); Serializer serializer = context.getBroker().getSerializer(); serializer.reset(); serializer.setProperties(outputProperties); serializer.setReceiver(sax); sax.startDocument(); for (SequenceIterator i = args[0].iterate(); i.hasNext(); ) { NodeValue next = (NodeValue) i.nextItem(); serializer.toSAX(next); } sax.endDocument(); writer.close(); } catch (SAXException e) { throw new XPathException(getASTNode(), "A problem ocurred while serializing the node set: " + e.getMessage(), e); } catch (IOException e) { throw new XPathException(getASTNode(), "A problem ocurred while serializing the node set: " + e.getMessage(), e); } finally { SerializerPool.getInstance().returnObject(sax); } return BooleanValue.TRUE; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder.optimization; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import nl.uva.cs.lobcder.catalogue.SDNSweep; import nl.uva.cs.lobcder.catalogue.SDNSweep.Port; import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.SimpleWeightedGraph; /** * * @author S. Koulouzis */ public class SDNControllerClient { // private final Client client; private String uri; // private int floodlightPort = 8080; // private int sflowRTPrt = 8008; // private static List<Switch> switches; // private static Map<String, String> networkEntitySwitchMap; // private static Map<String, Integer> sFlowHostPortMap; // private static Map<String, List<NetworkEntity>> networkEntityCache; private static SimpleWeightedGraph<String, DefaultWeightedEdge> graph; // private static List<Link> linkCache; public SDNControllerClient(String uri) throws IOException { // ClientConfig clientConfig = new DefaultClientConfig(); // clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); // client = Client.create(clientConfig); // this.uri = uri; } public List<DefaultWeightedEdge> getShortestPath(String dest, Set<String> sources) throws InterruptedException, IOException { if (graph == null) { graph = new SimpleWeightedGraph<>(DefaultWeightedEdge.class); } List<SDNSweep.Switch> sw = SDNSweep.getSwitches(); for (int i = 0; i < sw.size(); i++) { List<Port> ports = sw.get(i).ports; for (int j = 0; j < ports.size(); j++) { for (int k = 0; k < ports.size(); k++) { if (ports.get(j).state == 0 && ports.get(k).state == 0 && j != k) { String vertex1 = sw.get(i).dpid + "-" + ports.get(j).portNumber; String vertex2 = sw.get(i).dpid + "-" + ports.get(k).portNumber; // Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "From: {0} to: {1}", new Object[]{vertex1, vertex2}); if (!graph.containsVertex(vertex1)) { graph.addVertex(vertex1); } if (!graph.containsVertex(vertex2)) { graph.addVertex(vertex2); } DefaultWeightedEdge e1; if (!graph.containsEdge(vertex1, vertex2)) { e1 = graph.addEdge(vertex1, vertex2); } else { e1 = graph.getEdge(vertex1, vertex2); } graph.setEdgeWeight(e1, 1); } } } } // dest = "192.168.100.1"; // Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "Destination: {0}", new Object[]{dest}); if (!graph.containsVertex(dest)) { graph.addVertex(dest); } SDNSweep.NetworkEntity destinationEntityArray = SDNSweep.getNetworkEntity(dest); // List<NetworkEntity> destinationEntityArray = getNetworkEntity(dest); // for (SDNSweep.NetworkEntity ne : destinationEntityArray) { for (SDNSweep.AttachmentPoint ap : destinationEntityArray.attachmentPoint) { String vertex = ap.switchDPID + "-" + ap.port; // Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "vertex: {0}", new Object[]{vertex}); if (!graph.containsVertex(vertex)) { graph.addVertex(vertex); } DefaultWeightedEdge e1; if (!graph.containsEdge(dest, vertex)) { e1 = graph.addEdge(dest, vertex); } else { e1 = graph.getEdge(dest, vertex); } //Don't calculate the cost from the destination to the switch. //There is nothing we can do about it so why waste cycles ? // graph.setEdgeWeight(e1, 2); graph.setEdgeWeight(e1, getCost(dest, vertex)); } // List<NetworkEntity> sourceEntityArray = getNetworkEntity(sources); for (String s : sources) { SDNSweep.NetworkEntity ne = SDNSweep.getNetworkEntity(s); for (String ip : ne.ipv4) { if (!graph.containsVertex(ip)) { graph.addVertex(ip); } for (SDNSweep.AttachmentPoint ap : ne.attachmentPoint) { String vertex = ap.switchDPID + "-" + ap.port; if (!graph.containsVertex(vertex)) { graph.addVertex(vertex); } DefaultWeightedEdge e2; if (!graph.containsEdge(ip, vertex)) { e2 = graph.addEdge(ip, vertex); } else { e2 = graph.getEdge(ip, vertex); } // Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "vertex: {0}", new Object[]{vertex}); graph.setEdgeWeight(e2, getCost(ip, vertex)); } } } List<SDNSweep.Link> links = SDNSweep.getSwitchLinks(); for (SDNSweep.Link l : links) { String srcVertex = l.srcSwitch + "-" + l.srcPort; if (!graph.containsVertex(srcVertex)) { graph.addVertex(srcVertex); } String dstVertex = l.dstSwitch + "-" + l.dstPort; if (!graph.containsVertex(dstVertex)) { graph.addVertex(dstVertex); } DefaultWeightedEdge e3; if (!graph.containsEdge(srcVertex, dstVertex)) { e3 = graph.addEdge(srcVertex, dstVertex); } else { e3 = graph.getEdge(srcVertex, dstVertex); } // Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "dstVertex: {0}", new Object[]{dstVertex}); graph.setEdgeWeight(e3, getCost(srcVertex, dstVertex)); } double cost = Double.MAX_VALUE; List<DefaultWeightedEdge> shortestPath = null; for (String s : sources) { if (graph.containsVertex(dest) && graph.containsVertex(s)) { List<DefaultWeightedEdge> shorPath = DijkstraShortestPath.findPathBetween(graph, s, dest); double w = 0; if (shorPath != null) { for (DefaultWeightedEdge e : shorPath) { w += graph.getEdgeWeight(e); } if (w <= cost) { cost = w; shortestPath = shorPath; if (cost <= 2) { break; } } } } } return shortestPath; } private double getCost(String v1, String v2) throws InterruptedException, IOException { // String[] agentPort = getsFlowPort(v1, v2); // double tpp = getTimePerPacket(agentPort[0], Integer.valueOf(agentPort[1])); String dpi; if (v1.contains(":")) { dpi = v1; } else { dpi = v2; } // SDNSweep.FloodlightStats[] stats = getFloodlightPortStats(dpi, port); Double rpps = SDNSweep.getReceivePacketsMap().get(dpi); Double tpps = SDNSweep.getTransmitPacketsMap().get(dpi); // double rrrt = (interval / rpps); // double trrt = (interval / tpps); double tpp = (rpps > tpps) ? rpps : tpps; if (tpp <= 0) { tpp = 1; } Double rbytes = SDNSweep.getReceiveBytesMap().get(dpi); Double tbytes = SDNSweep.getTransmitBytesMap().get(dpi); if (rbytes <= 0) { rbytes = Double.valueOf(1); } if (tbytes <= 0) { tbytes = Double.valueOf(1); } double rMTU = rbytes / rpps * 1.0; double tMTU = tbytes / tpps * 1.0; double mtu = (rMTU > tMTU) ? rMTU : tMTU; // if (mtu <= 500) { // mtu = 1500; //TT=TpP * NoP //NoP = {MTU}/{FS} //TpP =[({MTU} / {bps}) + RTT] // is the time it takes to transmit one packet or time per packet //TT = [({MTU} / {bps}) + RTT] * [ {MTU}/{FS}] double nop = mtu / 1024.0; double ett = tpp * nop; // SDNSweep.OFlow f = SDNSweep.getOFlowsMap().get(dpi); // double bps = -1; // if (f != null) { // bps = f.byteCount / f.durationSeconds * 1.0; // double tmp = f.packetCount / f.durationSeconds * 1.0; // if (tpp <= 1 && tmp > tpp) { // ett = tmp * nop; Double averageLinkUsage = SDNSweep.getAverageLinkUsageMap().get(dpi); if (averageLinkUsage != null) { Double factor = 0.1; //For each sec of usage how much extra time we get ? //We asume a liner ralationship //The longer the usage it means either more transfers per flow or larger files or both // ett += averageLinkUsage * factor; } Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "From: {0} to: {1} tt: {2}", new Object[]{v1, v2, ett}); return ett; } public void pushFlow(final List<DefaultWeightedEdge> shortestPath) throws IOException { Thread thread = new Thread() { public void run() { try { DefaultWeightedEdge e = shortestPath.get(0); String pair = e.toString().substring(1, e.toString().length() - 1); String[] workerSwitch = pair.toString().split(" : "); String srcIP = workerSwitch[0]; String srcMac = SDNSweep.getNetworkEntity(srcIP).mac.get(0); String srcSwitchAndPort = workerSwitch[1]; String srcSwitch = srcSwitchAndPort.split("-")[0]; String srcIngressPort = String.valueOf(SDNSweep.getNetworkEntity(srcIP).attachmentPoint.get(0).port); String srcOutput; e = shortestPath.get(1); pair = e.toString().substring(1, e.toString().length() - 1); workerSwitch = pair.split(" : "); if (workerSwitch[0].equals(srcSwitch + "-" + srcIngressPort)) { srcOutput = workerSwitch[1].split("-")[1]; } else { srcOutput = workerSwitch[0].split("-")[1]; } e = shortestPath.get(shortestPath.size() - 1); pair = e.toString().substring(1, e.toString().length() - 1); workerSwitch = pair.toString().split(" : "); String dstIP = workerSwitch[0]; String dstMac = SDNSweep.getNetworkEntity(dstIP).mac.get(0); String dstSwitchAndPort = workerSwitch[1]; String dstSwitch = dstSwitchAndPort.split("-")[0]; String dstOutput = String.valueOf(SDNSweep.getNetworkEntity(dstIP).attachmentPoint.get(0).port); e = shortestPath.get(shortestPath.size() - 2); pair = e.toString().substring(1, e.toString().length() - 1); workerSwitch = pair.toString().split(" : "); String node1 = workerSwitch[0]; String node2 = workerSwitch[1]; String dstIngressPort = ""; if (node1.equals(dstSwitch + "-" + dstOutput)) { dstIngressPort = node2.split("-")[1]; } else { dstIngressPort = node1.split("-")[1]; } // String rulesrcToSw = "{\"switch\": \"" + srcSwitch + "\", \"name\":\"tmp\", \"cookie\":\"0\", \"priority\":\"5\", " // + "\"src-ip\":\"" + srcIP + "\", \"ingress-port\":\"" + srcIngressPort + "\", " // + "\"dst-ip\": \"" + dstIP + "\", \"active\":\"true\",\"ether-type\":\"0x0800\", " // + "\"actions\":\"output=" + srcOutput + "\"}"; // String ruleSwTodst = "{\"switch\": \"" + dstSwitch + "\", \"name\":\"tmp\", \"cookie\":\"0\", \"priority\":\"5\", " // + "\"src-ip\":\"" + srcIP + "\", \"ingress-port\":\"" + dstIngressPort + "\", " // + "\"dst-ip\": \"" + dstIP + "\", \"active\":\"true\",\"ether-type\":\"0x0800\", " // + "\"actions\":\"output=" + dstOutput + "\"}"; String rule11 = "{\"switch\": \"" + srcSwitch + "\", \"name\":\"tmp1-1\", \"cookie\":\"0\", \"priority\":\"5\", " + "\"src-mac\":\"" + srcMac + "\", \"ingress-port\":\"" + srcIngressPort + "\", " + "\"dst-mac\": \"" + dstMac + "\", \"active\":\"true\",\"vlan-id\":\"-1\", " + "\"actions\":\"output=" + srcOutput + "\"}"; String rule12 = "{\"switch\": \"" + srcSwitch + "\", \"name\":\"tmp1-2\", \"cookie\":\"0\", \"priority\":\"5\", " + "\"src-mac\":\"" + dstMac + "\", \"ingress-port\":\"" + srcOutput + "\", " + "\"dst-mac\": \"" + srcMac + "\", \"active\":\"true\",\"vlan-id\":\"-1\", " + "\"actions\":\"output=" + srcIngressPort + "\"}"; String rule21 = "{\"switch\": \"" + dstSwitch + "\", \"name\":\"tmp2-1\", \"cookie\":\"0\", \"priority\":\"5\", " + "\"src-mac\":\"" + srcMac + "\", \"ingress-port\":\"" + dstIngressPort + "\", " + "\"dst-mac\": \"" + dstMac + "\", \"active\":\"true\",\"vlan-id\":\"-1\", " + "\"actions\":\"output=" + dstOutput + "\"}"; String rule22 = "{\"switch\": \"" + dstSwitch + "\", \"name\":\"tmp2-2\", \"cookie\":\"0\", \"priority\":\"5\", " + "\"src-mac\":\"" + dstMac + "\", \"ingress-port\":\"" + dstOutput + "\", " + "\"dst-mac\": \"" + srcMac + "\", \"active\":\"true\",\"vlan-id\":\"-1\", " + "\"actions\":\"output=" + dstIngressPort + "\"}"; List<String> rules = new ArrayList<>(); rules.add(rule11); rules.add(rule12); rules.add(rule21); rules.add(rule22); try { new SDNSweep(null).pushFlows(rules); } catch (IOException ex) { Logger.getLogger(SDNControllerClient.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { Logger.getLogger(SDNControllerClient.class.getName()).log(Level.SEVERE, null, ex); } } }; thread.start(); } // private SDNSweep.FloodlightStats[] getFloodlightPortStats(String dpi, int port) throws IOException, InterruptedException { // SDNSweep.FloodlightStats stats1 = null; // SDNSweep.FloodlightStats stats2 = null; // // List<FloodlightStats> stats1 = getFloodlightPortStats(dpi); // // Thread.sleep((long) interval); // // List<FloodlightStats> stats2 = getFloodlightPortStats(dpi); // Map<String, SDNSweep.StatsHolder> map = SDNSweep.getStatsMap(); // if (map != null) { // SDNSweep.StatsHolder h = map.get(dpi+"-"+port); // if (h != null) { // stats1 = h.getStats1(); // stats2 = h.getStats2(); // SDNSweep.FloodlightStats stat1 = null; // for (SDNSweep.FloodlightStats s : stats1) { // if (s.portNumber == port) { // stat1 = s; // break; // SDNSweep.FloodlightStats stat2 = null; // for (SDNSweep.FloodlightStats s : stats2) { // if (s.portNumber == port) { // stat2 = s; // break; // return new SDNSweep.FloodlightStats[]{stats1, stats2}; // private String[] getsFlowPort(String v1, String v2) { // String[] tuple = new String[2]; // if (sFlowHostPortMap == null) { // sFlowHostPortMap = new HashMap<>(); // if (v1.contains(":") && v2.contains(":")) { // String switch1IP = getSwitchIPFromDPI(v1); //// String switch2IP = getSwitchIPFromDPI(v2); // if (!sFlowHostPortMap.containsKey(switch1IP)) { // List<Flow> flows = getAgentFlows(switch1IP); // for (Flow f : flows) { // String[] keys = f.flowKeys.split(","); // String from = keys[0]; // String to = keys[1]; // if (!isAttached(from, v1) && isAttached(to, v1)) { //// Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "Switch: " + switch1IP + " -> " + f.dataSource); // sFlowHostPortMap.put(switch1IP, f.dataSource); // break; //// Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "Host: " + switch1IP + " port: " + sFlowHostPortMap.get(switch1IP)); // tuple[0] = switch1IP; // tuple[1] = String.valueOf(sFlowHostPortMap.get(switch1IP)); // return tuple; // } else { // String switchIP = null; // String hostIP = null; // if (v1.contains(".")) { // switchIP = getSwitchIPFromHostIP(v1); // hostIP = v1; // } else { // switchIP = getSwitchIPFromHostIP(v2); // hostIP = v2; // if (!sFlowHostPortMap.containsKey(hostIP)) { // List<Flow> flows = getAgentFlows(switchIP); // for (Flow f : flows) { // String[] keys = f.flowKeys.split(","); // if (keys[0].equals(hostIP)) { // sFlowHostPortMap.put(hostIP, f.dataSource); // break; // Logger.getLogger(SDNControllerClient.class.getName()).log(Level.INFO, "Host: " + hostIP + " is attached to: " + switchIP + " port: " + sFlowHostPortMap.get(hostIP)); // tuple[0] = switchIP; // tuple[1] = String.valueOf(sFlowHostPortMap.get(hostIP)); // return tuple; // private Map<String, Integer> getifNameOpenFlowPortNumberMap(String dpi) { // HashMap<String, Integer> ifNamePortMap = new HashMap<>(); // List<Switch> sw = getSwitches(); // for (Switch s : sw) { // if (s.dpid.equals(dpi)) { // List<Port> ports = s.ports; // for (Port p : ports) { // ifNamePortMap.put(p.name, p.portNumber); // break; // return ifNamePortMap; // private String getSwitchIPFromDPI(String dpi) { // for (Switch s : getSwitches()) { // if (s.dpid.equals(dpi)) { // return s.inetAddress.split(":")[0].substring(1); // return null; // private boolean isAttached(String from, String dpi) { // for (NetworkEntity ne : getNetworkEntity(from)) { // for (AttachmentPoint ap : ne.attachmentPoint) { // if (ap.switchDPID.equals(dpi)) { // return true; // return false; // private List<NetworkEntity> getNetworkEntity(String address) { // if (networkEntityCache == null) { // networkEntityCache = new HashMap(); // if (!networkEntityCache.containsKey(address)) { // WebResource webResource = client.resource(uri + ":" + floodlightPort); // WebResource res = null; // if (address.contains(".")) { // res = webResource.path("wm").path("device/").queryParam("ipv4", address); // } else { // res = webResource.path("wm").path("device/").queryParam("mac", address); // List<NetworkEntity> ne = res.get(new GenericType<List<NetworkEntity>>() { // networkEntityCache.put(address, ne); // return networkEntityCache.get(address); // private List<NetworkEntity> getNetworkEntity(Set<String> sources) { // List<NetworkEntity> entities = new ArrayList<>(); // for (String e : sources) { // entities.addAll(getNetworkEntity(e)); // return entities; // private List<Link> getSwitchLinks() { // if (linkCache == null) { // linkCache = new ArrayList<>(); // if (linkCache.isEmpty()) { // WebResource webResource = client.resource(uri + ":" + floodlightPort); // WebResource res = webResource.path("wm").path("topology").path("links").path("json"); // linkCache = res.get(new GenericType<List<Link>>() { // return linkCache; // private List<Switch> getSwitches() { // if (switches == null) { // WebResource webResource = client.resource(uri + ":" + floodlightPort); // WebResource res = webResource.path("wm").path("core").path("controller").path("switches").path("json"); // switches = res.get(new GenericType<List<Switch>>() { // return switches; // private String getSwitchIPFromHostIP(String address) { // if (networkEntitySwitchMap == null) { // networkEntitySwitchMap = new HashMap<>(); // if (!networkEntitySwitchMap.containsKey(address)) { // List<NetworkEntity> ne = getNetworkEntity(address); // String dpi = ne.get(0).attachmentPoint.get(0).switchDPID; // for (Switch sw : getSwitches()) { // if (sw.dpid.equals(dpi)) { // String ip = sw.inetAddress.split(":")[0].substring(1); // networkEntitySwitchMap.put(address, ip); // break; // return networkEntitySwitchMap.get(address); // private List<Flow> getAgentFlows(String switchIP) { // List<Flow> agentFlows = new ArrayList<>(); // for (Flow f : getAllFlows()) { // if (f.agent.equals(switchIP)) { // agentFlows.add(f); // return agentFlows; // private List<Flow> getAllFlows() { // WebResource webResource = client.resource(uri + ":" + sflowRTPrt); // WebResource res = webResource.path("flows").path("json"); // return res.get(new GenericType<List<Flow>>() { // private List<Ifpkts> getifoutpktsMetric(String agent, int port) { // WebResource webResource = client.resource(uri + ":" + sflowRTPrt); // WebResource res = webResource.path("metric").path(agent).path(port + ".ifoutpkts").path("json"); // return res.get(new GenericType<List<Ifpkts>>() { // private List<FloodlightStats> getFloodlightPortStats(String dpi) throws IOException { // WebResource webResource = client.resource(uri + ":" + floodlightPort); // WebResource res = webResource.path("wm").path("core").path("switch").path(dpi).path("port").path("json"); // String output = res.get(String.class); // String out = output.substring(27, output.length() - 1); // ObjectMapper mapper = new ObjectMapper(); // return mapper.readValue(out, mapper.getTypeFactory().constructCollectionType(List.class, FloodlightStats.class)); // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class Ifpkts { // @XmlElement(name = "agent") // String agent; // @XmlElement(name = "dataSource") // int dataSource; // @XmlElement(name = "lastUpdate") // long lastUpdate; // /** // * The lastUpdateMax and lastUpdateMin values indicate how long ago (in // * milliseconds) the most recent and oldest updates // */ // @XmlElement(name = "lastUpdateMax") // long lastUpdateMax; // @XmlElement(name = "lastUpdateMin") // /** // * The metricN field in the query result indicates the number of data // * sources that contributed to the summary metrics // */ // long lastUpdateMin; // @XmlElement(name = "metricN") // int metricN; // @XmlElement(name = "metricName") // String metricName; // @XmlElement(name = "metricValue") // double value; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class Flow { // @XmlElement(name = "agent") // String agent; // @XmlElement(name = "dataSource") // int dataSource; // @XmlElement(name = "end") // String end; // @XmlElement(name = "flowID") // int flowID; // @XmlElement(name = "flowKeys") // String flowKeys; // @XmlElement(name = "name") // String name; // @XmlElement(name = "start") // long start; // @XmlElement(name = "value") // double value; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class NetworkEntity { // @XmlElement(name = "entityClass") // String entityClass; // @XmlElement(name = "lastSeen") // String lastSeen; // @XmlElement(name = "ipv4") // List<String> ipv4; // @XmlElement(name = "vlan") // List<String> vlan; // @XmlElement(name = "mac") // List<String> mac; // @XmlElement(name = "attachmentPoint") // List<AttachmentPoint> attachmentPoint; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class AttachmentPoint { // @XmlElement(name = "port") // int port; // @XmlElement(name = "errorStatus") // String errorStatus; // @XmlElement(name = "switchDPID") // String switchDPID; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // private static class Link { // @XmlElement(name = "src-switch") // String srcSwitch; // @XmlElement(name = "src-port") // int srcPort; // @XmlElement(name = "dst-switch") // String dstSwitch; // @XmlElement(name = "dst-port") // int dstPort; // @XmlElement(name = "type") // String type; // @XmlElement(name = "direction") // String direction; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class Switch { // @XmlElement(name = "actions") // int actions; // @XmlElement(name = "attributes") // Attributes attributes; // @XmlElement(name = "ports") // List<Port> ports; // @XmlElement(name = "buffers") // int buffers; // @XmlElement(name = "description") // Description description; // @XmlElement(name = "capabilities") // int capabilities; // @XmlElement(name = "inetAddress") // String inetAddress; // @XmlElement(name = "connectedSince") // long connectedSince; // @XmlElement(name = "dpid") // String dpid; // @XmlElement(name = "harole") // String harole; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // private static class Description { // @XmlElement(name = "software") // String software; // @XmlElement(name = "hardware") // String hardware; // @XmlElement(name = "manufacturer") // String manufacturer; // @XmlElement(name = "serialNum") // String serialNum; // @XmlElement(name = "datapath") // String datapath; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // private static class Port { // @XmlElement(name = "portNumber") // int portNumber; // @XmlElement(name = "hardwareAddress") // String hardwareAddress; // @XmlElement(name = "name") // String name; // @XmlElement(name = "config") // int config; // @XmlElement(name = "state") // int state; // @XmlElement(name = "currentFeatures") // int currentFeatures; // @XmlElement(name = "advertisedFeatures") // int advertisedFeatures; // @XmlElement(name = "supportedFeatures") // int supportedFeatures; // @XmlElement(name = "peerFeatures") // int peerFeatures; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // private static class Attributes { // @XmlElement(name = "supportsOfppFlood") // boolean supportsOfppFlood; // @XmlElement(name = "supportsNxRole") // boolean supportsNxRole; // @XmlElement(name = "FastWildcards") // int fastWildcards; // @XmlElement(name = "supportsOfppTable") // boolean supportsOfppTable; //// @XmlRootElement //// @XmlAccessorType(XmlAccessType.FIELD) ////// @JsonIgnoreProperties(ignoreUnknown = true) //// public static class FloodlightStatsWrapper { ////// @XmlElement(name = "00:00:4e:cd:a6:8d:c9:44") //// @XmlElementWrapper ////// @XmlElement //// List<FloodlightStats> stats; // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class FloodlightStats { // @JsonProperty("portNumber") // int portNumber; // @JsonProperty("receivePackets") // long receivePackets; // @JsonProperty("transmitPackets") // long transmitPackets; // @JsonProperty("receiveBytes") // long receiveBytes; // @JsonProperty("transmitBytes") // long transmitBytes; // @JsonProperty("receiveDropped") // long receiveDropped; // @JsonProperty("transmitDropped") // long transmitDropped; // @JsonProperty("receiveErrors") // long receiveErrors; // @JsonProperty("transmitErrors") // long transmitErrors; // @JsonProperty("receiveFrameErrors") // long receiveFrameErrors; // @JsonProperty("receiveOverrunErrors") // long receiveOverrunErrors; // @JsonProperty("receiveCRCErrors") // long receiveCRCErrors; // @JsonProperty("collisions") // long collisions; }
package dynamake.models; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.List; import java.util.Stack; import javax.swing.JComponent; import dynamake.commands.AddObserverCommand; import dynamake.commands.CommandSequence; import dynamake.commands.CommandState; import dynamake.commands.CommandStateWithOutput; import dynamake.commands.ExecutionScope; import dynamake.commands.MappableForwardable; import dynamake.commands.PURCommand; import dynamake.commands.PendingCommandState; import dynamake.commands.RemoveObserverCommand; import dynamake.commands.ReversibleCommand; import dynamake.commands.ReversibleCommandPair; import dynamake.commands.SetPropertyCommand; import dynamake.commands.SetPropertyCommandFromScope; import dynamake.commands.TriStatePURCommand; import dynamake.delegates.Action1; import dynamake.delegates.Func1; import dynamake.menubuilders.ColorMenuBuilder; import dynamake.menubuilders.CompositeMenuBuilder; import dynamake.models.factories.CloneFactory; import dynamake.models.factories.ModelFactory; import dynamake.models.factories.DeriveFactory; import dynamake.models.transcription.NewChangeTransactionHandler; import dynamake.models.transcription.PostOnlyTransactionHandler; import dynamake.numbers.Fraction; import dynamake.numbers.RectangleF; import dynamake.transcription.Collector; import dynamake.transcription.LoadScopeTransactionHandlerFactory; import dynamake.transcription.PendingCommandFactory; import dynamake.transcription.Execution; import dynamake.transcription.Trigger; import dynamake.tuples.Tuple2; /** * Instances of implementors are supposed to represent alive-like sensitive entities, each with its own local history. */ public abstract class Model implements Serializable, Observer { public static class UndoRedoPart implements Serializable, CommandStateWithOutput<Model> { private static final long serialVersionUID = 1L; public final Execution<Model> origin; public final CommandStateWithOutput<Model> revertible; public UndoRedoPart(Execution<Model> origin, CommandStateWithOutput<Model> revertible) { this.origin = origin; this.revertible = revertible; } @Override public CommandState<Model> executeOn(PropogationContext propCtx, Model prevalentSystem, Collector<Model> collector, Location location, ExecutionScope scope) { CommandState<Model> reverted = revertible.executeOn(propCtx, prevalentSystem, collector, location, scope); return new UndoRedoPart(origin, (CommandStateWithOutput<Model>)reverted); } @Override public CommandState<Model> mapToReferenceLocation(Model sourceReference, Model targetReference) { return new UndoRedoPart( origin.mapToReferenceLocation(sourceReference, targetReference), (CommandStateWithOutput<Model>)revertible.mapToReferenceLocation(sourceReference, targetReference) ); } @Override public CommandState<Model> offset(Location offset) { return new UndoRedoPart(origin.offset(offset), (CommandStateWithOutput<Model>)revertible.offset(offset)); } public CommandState<Model> forForwarding() { return new UndoRedoPart(origin.forForwarding(), (CommandStateWithOutput<Model>)revertible.forForwarding()); } public CommandState<Model> forUpwarding() { return new UndoRedoPart(origin.forUpwarding(), (CommandStateWithOutput<Model>)revertible.forUpwarding()); } @Override public void appendPendings(List<CommandState<Model>> pendingCommands) { pendingCommands.add(revertible); } @Override public CommandState<Model> forForwarding(Object output) { return null; } @Override public Object getOutput() { return revertible.getOutput(); } } public static class HistoryAppendLogChange { public final List<ReversibleCommand<Model>> pendingUndoablePairs; public HistoryAppendLogChange(List<ReversibleCommand<Model>> pendingCommands) { this.pendingUndoablePairs = pendingCommands; } } public static class TellProperty { public final String name; public TellProperty(String name) { this.name = name; } } public static class MouseDown { } public static class MouseUp { } public static final String PROPERTY_COLOR = "Color"; public static final String PROPERTY_VIEW = "View"; private static final long serialVersionUID = 1L; public static final int VIEW_APPLIANCE = 1; public static final int VIEW_ENGINEERING = 0; public static class Atom { public final Object value; public Atom(Object value) { this.value = value; } } public static class PropertyChanged { public final String name; public final Object value; public PropertyChanged(String name, Object value) { this.name = name; this.value = value; } } public static class SetProperty { public final String name; public final Object value; public SetProperty(String name, Object value) { this.name = name; this.value = value; } } private ArrayList<Observer> observers = new ArrayList<Observer>(); private ArrayList<Observer> observees = new ArrayList<Observer>(); protected Hashtable<String, Object> properties = new Hashtable<String, Object>(); /* Both undo- and stack are assumed to contain RevertingCommandStateSequence<Model> objects */ protected Stack<HistoryPart> undoStack = new Stack<HistoryPart>(); protected Stack<HistoryPart> redoStack = new Stack<HistoryPart>(); private Locator locator; private Model parent; private void writeObject(ObjectOutputStream ous) throws IOException { ArrayList<Observer> observersToSerialize = new ArrayList<Observer>(); for(Observer o: observers) { if(o instanceof Serializable) observersToSerialize.add(o); } ous.writeObject(observersToSerialize); ArrayList<Observer> observeesToSerialize = new ArrayList<Observer>(); for(Observer o: observees) { if(o instanceof Serializable) observeesToSerialize.add(o); } ous.writeObject(observeesToSerialize); ous.writeObject(properties); ous.writeObject(undoStack); ous.writeObject(redoStack); } @SuppressWarnings("unchecked") private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { observers = (ArrayList<Observer>)ois.readObject(); observees = (ArrayList<Observer>)ois.readObject(); properties = (Hashtable<String, Object>)ois.readObject(); undoStack = (Stack<HistoryPart>)ois.readObject(); redoStack = (Stack<HistoryPart>)ois.readObject(); } public void appendLog(ArrayList<ReversibleCommand<Model>> pendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) { // System.out.println("Log"); redoStack.clear(); // Should the clearing of the redo stack be moved to commitLog? sendChanged(new HistoryAppendLogChange(pendingUndoablePairs), propCtx, propDistance, 0, collector); } public void postLog(ArrayList<ReversibleCommand<Model>> pendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) { // System.out.println("Log"); sendChanged(new HistoryAppendLogChange(pendingUndoablePairs), propCtx, propDistance, 0, collector); } public static class HistoryPart implements Serializable { private static final long serialVersionUID = 1L; private List<Tuple2<PURCommand<Model>, ExecutionScope>> purCommands; public HistoryPart(List<Tuple2<PURCommand<Model>, ExecutionScope>> purCommands) { this.purCommands = purCommands; } public HistoryPart forUndo() { ArrayList<Tuple2<PURCommand<Model>, ExecutionScope>> undoables = new ArrayList<Tuple2<PURCommand<Model>, ExecutionScope>>(); for(Tuple2<PURCommand<Model>, ExecutionScope> purAndScope: purCommands) { // pur.back is assumed to be insignificant PURCommand<Model> pur = purAndScope.value1; PURCommand<Model> undoable = pur.inUndoState(); undoables.add(new Tuple2<PURCommand<Model>, ExecutionScope>(undoable, purAndScope.value2)); } Collections.reverse(undoables); return new HistoryPart(undoables); } public HistoryPart forRedo() { ArrayList<Tuple2<PURCommand<Model>, ExecutionScope>> redoables = new ArrayList<Tuple2<PURCommand<Model>, ExecutionScope>>(); for(Tuple2<PURCommand<Model>, ExecutionScope> purAndScope: purCommands) { // pur.back is assumed to be insignificant PURCommand<Model> pur = purAndScope.value1; PURCommand<Model> redoable = pur.inRedoState(); redoables.add(new Tuple2<PURCommand<Model>, ExecutionScope>(redoable, purAndScope.value2)); } Collections.reverse(redoables); return new HistoryPart(redoables); } public ExecutionScope getScope(int partIndex) { return purCommands.get(partIndex).value2; } } public void commitLog(List<Tuple2<PURCommand<Model>, ExecutionScope>> logPart) { // ArrayList<PURCommand<Model>> undoables = new ArrayList<PURCommand<Model>>(); // for(ReversibleCommand<Model> pur: logPart) { // // pur.back is assumed to be insignificant // PURCommand<Model> undoable = ((PURCommand<Model>)pur.forth).inUndoState(); // undoables.add(undoable); // Collections.reverse(undoables); HistoryPart undoPart = new HistoryPart(logPart).forUndo(); undoStack.add(undoPart); } public void unplay(int count, PropogationContext propCtx, int propDistance, Collector<Model> collector) { for(int i = 0; i < count; i++) { HistoryPart toUndo = undoStack.pop(); // Probably, unplay should be invoked repeatedly from another outer command somehow, where the // scope is derived in a dynamic way (looking it up via the model reference) rather having to // serialize the scope via LoadScopeTransactionHandlerFactory. for(Tuple2<PURCommand<Model>, ExecutionScope> purAndScope: toUndo.purCommands) { collector.startTransaction(this, new LoadScopeTransactionHandlerFactory<Model>(purAndScope.value2)); collector.execute(purAndScope.value1); collector.commitTransaction(); } // CommandState<Model> redoable = toUndo.executeOn(propCtx, this, collector, new ModelRootLocation(), scope); HistoryPart redoable = toUndo.forRedo(); redoStack.push(redoable); } } public void replay(int count, PropogationContext propCtx, int propDistance, Collector<Model> collector, ExecutionScope scope) { for(int i = 0; i < count; i++) { HistoryPart toRedo = redoStack.pop(); for(Tuple2<PURCommand<Model>, ExecutionScope> purAndScope: toRedo.purCommands) { collector.startTransaction(this, new LoadScopeTransactionHandlerFactory<Model>(purAndScope.value2)); collector.execute(purAndScope.value1); collector.commitTransaction(); } // CommandState<Model> undoable = toRedo.executeOn(propCtx, this, collector, new ModelRootLocation(), scope); HistoryPart undoable = toRedo.forUndo(); undoStack.push(undoable); } } public HistoryPart undo(PropogationContext propCtx, int propDistance, Collector<Model> collector) { // An undo method which starts all undo parts and ensure the sequence // A new kind of history handler is probably needed? // undo stack is assumed to consist only of RevertingCommandStateSequence<Model>. // These could probably be replaced by simpler structures; just lists of CommandState objects. // RevertingCommandStateSequence<Model> toUndo = (RevertingCommandStateSequence<Model>)undoStack.pop(); // PendingCommandFactory.Util.executeSequence(collector, Arrays.asList(toUndo.commandStates)); // return toUndo; HistoryPart toUndo = undoStack.peek(); for(Tuple2<PURCommand<Model>, ExecutionScope> purAndScope: toUndo.purCommands) { // collector.startTransaction(this, new LoadScopeTransactionHandlerFactory<Model>(purAndScope.value2)); collector.execute(purAndScope.value1); // collector.commitTransaction(); } return toUndo; } public void commitUndo() { //CommandState<Model> redoable) { // redoStack.push(redoable); HistoryPart undone = undoStack.pop(); redoStack.push(undone.forRedo()); } public HistoryPart redo(PropogationContext propCtx, int propDistance, Collector<Model> collector) { // RevertingCommandStateSequence<Model> toRedo = (RevertingCommandStateSequence<Model>)redoStack.pop(); // PendingCommandFactory.Util.executeSequence(collector, Arrays.asList(toRedo.commandStates)); // return toRedo; HistoryPart toRedo = redoStack.peek(); for(Tuple2<PURCommand<Model>, ExecutionScope> purAndScope: toRedo.purCommands) { // collector.startTransaction(this, new LoadScopeTransactionHandlerFactory<Model>(purAndScope.value2)); collector.execute(purAndScope.value1); // collector.commitTransaction(); } return toRedo; } public void commitRedo() { // undoStack.push(undoable); HistoryPart redone = redoStack.pop(); undoStack.push(redone.forUndo()); } public List<CommandState<Model>> playThenReverse(List<CommandState<Model>> toPlay, PropogationContext propCtx, int propDistance, Collector<Model> collector, ExecutionScope scope) { ArrayList<CommandState<Model>> newCommandStates = new ArrayList<CommandState<Model>>(); for(CommandState<Model> cs: toPlay) { CommandState<Model> newCS = cs.executeOn(propCtx, this, collector, new ModelRootLocation(), scope); newCommandStates.add(newCS); } Collections.reverse(newCommandStates); return newCommandStates; } public boolean canUndo() { return undoStack.size() > 0; } public boolean canRedo() { return redoStack.size() > 0; } public HistoryPart getUndoScope() { return undoStack.peek(); } public HistoryPart getRedoScope() { return redoStack.peek(); } // public CommandState<Model> getUnplayable() { // return RevertingCommandStateSequence.reverse(undoStack); public int getLocalChangeCount() { return undoStack.size(); } public List<CommandState<Model>> getLocalChanges() { ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); // TODO: METHOD DEACTIVETED! MUST BE REIMPLEMENTED! // for(CommandState<Model> undoable: undoStack) { // RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; // for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { // UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); // origins.add(undoPart.origin); return origins; } public List<CommandState<Model>> getLocalChangesBackwards() { ArrayList<CommandState<Model>> backwards = new ArrayList<CommandState<Model>>(); // TODO: METHOD DEACTIVETED! MUST BE REIMPLEMENTED! // for(CommandState<Model> undoable: undoStack) { // RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; // for(int i = undoableAsRevertiable.getCommandStateCount() - 1; i >= 0; i--) { // UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); // backwards.add(undoPart.revertible); Collections.reverse(backwards); return backwards; } public void setLocator(Locator locator) { // if(locator == null) // System.out.println("Nulled locator of " + this); // System.out.println("Set locator to " + locator + " of " + this); this.locator = locator; } public Locator getLocator() { return locator; } public void setParent(Model parent) { this.parent = parent; // System.out.println("Set parent of " + this + " to " + parent); } public Model getParent() { return parent; } public void setProperty(String name, Object value, PropogationContext propCtx, int propDistance, Collector<Model> collector) { if(value != null) properties.put(name, value); else properties.remove(name); sendChanged(new PropertyChanged(name, value), propCtx, propDistance, 0, collector); } public void setBounds(RectangleF bounds, PropogationContext propCtx, int propDistance, Collector<Model> collector) { setProperty("X", bounds.x, propCtx, propDistance, collector); setProperty("Y", bounds.y, propCtx, propDistance, collector); setProperty("Width", bounds.width, propCtx, propDistance, collector); setProperty("Height", bounds.height, propCtx, propDistance, collector); } public Object getProperty(String name) { return properties.get(name); } public RectangleF getBounds() { Fraction x = (Fraction)getProperty("X"); Fraction y = (Fraction)getProperty("Y"); Fraction width = (Fraction)getProperty("Width"); Fraction height = (Fraction)getProperty("Height"); return new RectangleF(x, y, width, height); } @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof SetProperty && changeDistance == 1) { // Side-effect final SetProperty setProperty = (SetProperty)change; collector.startTransaction(this, PostOnlyTransactionHandler.class); PendingCommandFactory.Util.executeSingle(collector, new PendingCommandState<Model>( new SetPropertyCommand(setProperty.name, setProperty.value), new SetPropertyCommand.AfterSetProperty() )); collector.commitTransaction(); } else if(change instanceof TellProperty && changeDistance == 1) { // Side-effect TellProperty tellProperty = (TellProperty)change; Object value = getProperty(tellProperty.name); if(value != null) sendChanged(new Model.PropertyChanged(tellProperty.name, value), propCtx, propDistance, 0, collector); } else { modelChanged(sender, change, propCtx, propDistance, changeDistance, collector); } } protected void modelChanged(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { } public static class RemovableListener implements Binding<Model> { private Observer listener; private Model model; public RemovableListener(Observer listener, Model model) { this.listener = listener; this.model = model; } @Override public Model getBindingTarget() { return model; } @Override public void releaseBinding() { model.removeObserver(listener); } public static RemovableListener addObserver(Model model, Observer listener) { model.addObserver(listener); return new RemovableListener(listener, model); } public static Binding<Model> addAll(final Model model, final RemovableListener... removableListeners) { return new Binding<Model>() { @Override public Model getBindingTarget() { return model; } @Override public void releaseBinding() { for(RemovableListener rl: removableListeners) rl.releaseBinding(); } }; } } public abstract Binding<ModelComponent> createView(ModelComponent rootView, ViewManager viewManager, ModelTranscriber modelTranscriber); public void setView(int view, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { setProperty(Model.PROPERTY_VIEW, view, propCtx, propDistance, collector); } public void sendChanged(Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { int nextChangeDistance = changeDistance + 1; int nextPropDistance = propDistance + 1; for(Observer observer: observers) { PropogationContext propCtxBranch = propCtx.branch(); observer.changed(this, change, propCtxBranch, nextPropDistance, nextChangeDistance, collector); } } public void addObserver(Observer observer) { observers.add(observer); observer.addObservee(this); } public void removeObserver(Observer observer) { observers.remove(observer); observer.removeObservee(this); } public void removeObserverLike(Observer observer) { observers.remove(observer); observer.removeObservee(this); } @SuppressWarnings("unchecked") public <T extends Observer> T getObserverOfLike(T observer) { int indexOfObserver = observers.indexOf(observer); return (T)observers.get(indexOfObserver); } public Observer getObserverWhere(Func1<Observer, Boolean> filter) { for(Observer observer: observers) { if(filter.call(observer)) return observer; } return null; } @SuppressWarnings("unchecked") public <T extends Observer> T getObserverOfType(Class<T> c) { for(Observer observer: observers) { if(c.isInstance(observer)) return (T)observer; } return null; } @SuppressWarnings("unchecked") public <T extends Observer> T getObserveeOfType(Class<T> c) { for(Observer observee: observees) { if(c.isInstance(observee)) return (T)observee; } return null; } public void addObservee(Observer observee) { observees.add(observee); } public void removeObservee(Observer observee) { observees.remove(observee); } public boolean isObservedBy(Observer observer) { return observers.contains(observer); } public static RemovableListener wrapForBoundsChanges(final Model model, final ModelComponent target, final ViewManager viewManager) { return RemovableListener.addObserver(model, new ObserverAdapter() { @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof Model.PropertyChanged && changeDistance == 1 /* And not a forwarded change */) { final Model.PropertyChanged propertyChanged = (Model.PropertyChanged)change; final Component targetComponent = ((Component)target); if(propertyChanged.name.equals("X")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setLocation(new Point(((Number)propertyChanged.value).intValue(), targetComponent.getY())); } }); } else if(propertyChanged.name.equals("Y")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setLocation(new Point(targetComponent.getX(), ((Number)propertyChanged.value).intValue())); } }); } else if(propertyChanged.name.equals("Width")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setSize(new Dimension(((Number)propertyChanged.value).intValue(), targetComponent.getHeight())); } }); } else if(propertyChanged.name.equals("Height")) { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setSize(new Dimension(targetComponent.getWidth(), ((Number)propertyChanged.value).intValue())); } }); } } } }); } public static final int COMPONENT_COLOR_BACKGROUND = 0; public static final int COMPONENT_COLOR_FOREGROUND = 1; public static RemovableListener wrapForComponentColorChanges(Model model, final ModelComponent view, final JComponent targetComponent, final ViewManager viewManager, final int componentColor) { return RemovableListener.addObserver(model, new ObserverAdapter() { @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof Model.PropertyChanged) { final Model.PropertyChanged propertyChanged = (Model.PropertyChanged)change; if(propertyChanged.name.equals(PROPERTY_COLOR)) { switch(componentColor) { case COMPONENT_COLOR_BACKGROUND: { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setBackground((Color)propertyChanged.value); // System.out.println("Change background"); } }); break; } case COMPONENT_COLOR_FOREGROUND: { collector.afterNextTrigger(new Runnable() { @Override public void run() { targetComponent.setForeground((Color)propertyChanged.value); } }); break; } } } } } }); } public static void loadComponentProperties(Model model, Component view, final int componentColor) { Object color = model.getProperty(Model.PROPERTY_COLOR); if(color != null) { switch(componentColor) { case COMPONENT_COLOR_BACKGROUND: { view.setBackground((Color)color); } case COMPONENT_COLOR_FOREGROUND: { view.setForeground((Color)color); } } } } public static void loadComponentBounds(Model model, Component view) { Number x = (Number)model.getProperty("X"); if(x != null) view.setLocation(x.intValue(), view.getY()); Number y = (Number)model.getProperty("Y"); if(y != null) view.setLocation(view.getX(), y.intValue()); Integer width = (Integer)model.getProperty("Width"); if(width != null) view.setSize(width.intValue(), view.getHeight()); Integer height = (Integer)model.getProperty("Height"); if(height != null) view.setSize(view.getWidth(), height.intValue()); } @SuppressWarnings("unchecked") public static <T> Model.RemovableListener bindProperty(Model model, final String modelPropertyName, final Action1<T> propertySetter) { Object value = model.getProperty(modelPropertyName); if(value != null) propertySetter.run((T)value); return Model.RemovableListener.addObserver(model, new ObserverAdapter() { @Override public void changed(Model sender, Object change, PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) { if(change instanceof Model.PropertyChanged && changeDistance == 1 /* And not a forwarded change */) { final Model.PropertyChanged propertyChanged = (Model.PropertyChanged)change; if(propertyChanged.name.equals(modelPropertyName)) { collector.afterNextTrigger(new Runnable() { @Override public void run() { propertySetter.run((T)propertyChanged.value); } }); } } } }); } public static void appendComponentPropertyChangeTransactions(final ModelComponent livePanel, final Model model, final ModelTranscriber modelTranscriber, CompositeMenuBuilder transactions) { transactions.addMenuBuilder("Set " + PROPERTY_COLOR, new ColorMenuBuilder((Color)model.getProperty(PROPERTY_COLOR), new Func1<Color, Object>() { @Override public Object call(final Color color) { return new Trigger<Model>() { @Override public void run(Collector<Model> collector) { // PendingCommandFactory.Util.executeSingle(collector, new PendingCommandState<Model>( // new SetPropertyCommand(PROPERTY_COLOR, color), // new SetPropertyCommand.AfterSetProperty() // For now, don't support rollback of property setting here (thus the null arguments for the ReversibleCommandPair's) collector.execute(new TriStatePURCommand<Model>( new CommandSequence<Model>( collector.createProduceCommand(PROPERTY_COLOR), collector.createProduceCommand(color), new ReversibleCommandPair<Model>(new SetPropertyCommandFromScope(), null) // Outputs name of changed property and the previous value ), new ReversibleCommandPair<Model>(new SetPropertyCommandFromScope(), new SetPropertyCommandFromScope()), // Outputs name of changed property and the previous value new ReversibleCommandPair<Model>(new SetPropertyCommandFromScope(), new SetPropertyCommandFromScope()) // Outputs name of changed property and the previous value )); } }; } })); } public static void appendGeneralDroppedTransactions(final ModelComponent livePanel, final ModelComponent dropped, final ModelComponent target, final Rectangle droppedBounds, CompositeMenuBuilder transactions) { if(target.getModelBehind() instanceof CanvasModel) { transactions.addMenuBuilder("Clone", new Trigger<Model>() { @Override public void run(Collector<Model> collector) { final Rectangle creationBounds = droppedBounds; collector.execute(new Trigger<Model>() { public void run(Collector<Model> collector) { ModelComponent cca = ModelComponent.Util.closestCommonAncestor(target, dropped); Location fromTargetToCCA = ModelComponent.Util.locationToAncestor(cca, target); Location fromTargetToDropped = new CompositeLocation(fromTargetToCCA, ModelComponent.Util.locationFromAncestor(cca, dropped)); // Probably, the "version" of dropped to be cloned is important // Dropped may change and, thus, in a undo/redo scenario on target, the newer version is cloned. Location droppedLocation = fromTargetToDropped; collector.startTransaction(target.getModelBehind(), NewChangeTransactionHandler.class); PendingCommandFactory.Util.executeSingle(collector, new PendingCommandState<Model>( new CanvasModel.AddModelCommand(new CloneFactory(new RectangleF(creationBounds), droppedLocation)), new CanvasModel.RemoveModelCommand.AfterAdd(), new CanvasModel.RestoreModelCommand.AfterRemove() )); collector.commitTransaction(); } }); } }); transactions.addMenuBuilder("Derive", new Trigger<Model>() { @Override public void run(Collector<Model> collector) { final Rectangle creationBounds = droppedBounds; collector.execute(new Trigger<Model>() { public void run(Collector<Model> collector) { ModelComponent cca = ModelComponent.Util.closestCommonAncestor(target, dropped); Location fromTargetToCCA = ModelComponent.Util.locationToAncestor(cca, target); Location fromTargetToDropped = new CompositeLocation(fromTargetToCCA, ModelComponent.Util.locationFromAncestor(cca, dropped)); // Probably, the "version" of dropped to be cloned is important // Dropped may change and, thus, in a undo/redo scenario on target, the newer version is cloned. Location droppedLocation = fromTargetToDropped; ModelFactory factory = new DeriveFactory(new RectangleF(creationBounds), droppedLocation); collector.startTransaction(target.getModelBehind(), NewChangeTransactionHandler.class); PendingCommandFactory.Util.executeSingle(collector, new PendingCommandState<Model>( new CanvasModel.AddModelCommand(factory), new CanvasModel.RemoveModelCommand.AfterAdd(), new CanvasModel.RestoreModelCommand.AfterRemove() )); collector.commitTransaction(); } }); } }); } } public void inject(Model model) { for(Observer observer: this.observers) { if(observer instanceof Model) { model.addObserver(observer); } } for(Observer observee: this.observees) { if(observee instanceof Model) { ((Model)observee).addObserver(model); } } } public void deject(Model model) { for(Observer observer: this.observers) { if(observer instanceof Model) { model.removeObserver(observer); } } for(Observer observee: this.observees) { if(observee instanceof Model) { ((Model)observee).removeObserver(model); } } } public boolean conformsToView(int value) { Integer view = (Integer)getProperty(Model.PROPERTY_VIEW); if(view == null) view = 1; return view <= value; } public boolean viewConformsTo(int value) { Integer view = (Integer)getProperty(Model.PROPERTY_VIEW); if(view == null) view = 1; return view >= value; } public void resize(Fraction xDelta, Fraction tDelta, Fraction widthDelta, Fraction heightDelta, PropogationContext propCtx, int propDistance, Collector<Model> collector) { Fraction currentX = (Fraction)getProperty("X"); Fraction currentY = (Fraction)getProperty("Y"); Fraction newX = currentX.add(xDelta); Fraction newY = currentY.add(tDelta); Fraction currentWidth = (Fraction)getProperty("Width"); Fraction currentHeight = (Fraction)getProperty("Height"); Fraction newWidth = currentWidth.add(widthDelta); Fraction newHeight = currentHeight.add(heightDelta); setProperty("X", newX, propCtx, propDistance, collector); setProperty("Y", newY, propCtx, propDistance, collector); setProperty("Width", newWidth, propCtx, propDistance, collector); setProperty("Height", newHeight, propCtx, propDistance, collector); } public void scale(Fraction xDelta, Fraction tDelta, Fraction hChange, Fraction vChange, PropogationContext propCtx, int propDistance, Collector<Model> collector) { Fraction currentX = (Fraction)getProperty("X"); Fraction currentY = (Fraction)getProperty("Y"); Fraction newX = currentX.add(xDelta); Fraction newY = currentY.add(tDelta); Fraction currentWidth = (Fraction)getProperty("Width"); Fraction currentHeight = (Fraction)getProperty("Height"); Fraction newWidth = currentWidth.multiply(hChange); Fraction newHeight = currentHeight.multiply(vChange); setProperty("X", newX, propCtx, propDistance, collector); setProperty("Y", newY, propCtx, propDistance, collector); setProperty("Width", newWidth, propCtx, propDistance, collector); setProperty("Height", newHeight, propCtx, propDistance, collector); modelScale(hChange, vChange, propCtx, propDistance, collector); } public void scale(final Fraction hChange, final Fraction vChange, PropogationContext propCtx, int propDistance, Collector<Model> collector) { Fraction currentX = (Fraction)getProperty("X"); Fraction currentY = (Fraction)getProperty("Y"); Fraction currentWidth = (Fraction)getProperty("Width"); Fraction currentHeight = (Fraction)getProperty("Height"); Fraction newX = currentX.multiply(hChange); Fraction newY = currentY.multiply(vChange); Fraction newWidth = currentWidth.multiply(hChange); Fraction newHeight = currentHeight.multiply(vChange); setProperty("X", newX, propCtx, propDistance, collector); setProperty("Y", newY, propCtx, propDistance, collector); setProperty("Width", newWidth, propCtx, propDistance, collector); setProperty("Height", newHeight, propCtx, propDistance, collector); modelScale(hChange, vChange, propCtx, propDistance, collector); } protected void modelScale(Fraction hChange, Fraction vChange, PropogationContext propCtx, int propDistance, Collector<Model> collector) { } public static void executeRemoveObserver(Collector<Model> collector, final ModelComponent observable, final ModelComponent observer) { collector.execute(new Trigger<Model>() { @Override public void run(Collector<Model> collector) { ModelComponent referenceMC = ModelComponent.Util.closestCommonAncestor(observable, observer); Location observableLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observable); Location observerLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observer); collector.startTransaction(referenceMC.getModelBehind(), NewChangeTransactionHandler.class); PendingCommandFactory.Util.executeSingle(collector, new PendingCommandState<Model>( new RemoveObserverCommand(observableLocation, observerLocation), new AddObserverCommand(observableLocation, observerLocation) )); collector.commitTransaction(); } }); } public static void executeAddObserver(Collector<Model> collector, final ModelComponent observable, final ModelComponent observer) { collector.execute(new Trigger<Model>() { @Override public void run(Collector<Model> collector) { ModelComponent referenceMC = ModelComponent.Util.closestCommonAncestor(observable, observer); Location observableLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observable); Location observerLocation = ModelComponent.Util.locationFromAncestor(referenceMC, observer); collector.startTransaction(referenceMC.getModelBehind(), NewChangeTransactionHandler.class); PendingCommandFactory.Util.executeSingle(collector, new PendingCommandState<Model>( new AddObserverCommand(observableLocation, observerLocation), new RemoveObserverCommand(observableLocation, observerLocation) )); collector.commitTransaction(); } }); } public abstract Model cloneBase(); private static class History implements MappableForwardable, Serializable { private static final long serialVersionUID = 1L; public final boolean includeHistory; public final Stack<HistoryPart> undoStack; public final Stack<HistoryPart> redoStack; public History(boolean includeHistory, Stack<HistoryPart> undoStack, Stack<HistoryPart> redoStack) { this.includeHistory = includeHistory; this.undoStack = undoStack; this.redoStack = redoStack; } @Override public MappableForwardable mapToReferenceLocation(Model sourceReference, Model targetReference) { Stack<HistoryPart> mappedUndoStack = new Stack<HistoryPart>(); // TODO: DO MAPPING OF UNDO STACK! // for(CommandState<Model> cs: undoStack) // mappedUndoStack.add(cs.mapToReferenceLocation(sourceReference, targetReference)); Stack<HistoryPart> mappedRedoStack = new Stack<HistoryPart>(); // TODO: DO MAPPING OF UNDO STACK! // for(CommandState<Model> cs: redoStack) // mappedRedoStack.add(cs.mapToReferenceLocation(sourceReference, targetReference)); return new History(includeHistory, mappedUndoStack, mappedRedoStack); } @Override public MappableForwardable forForwarding() { Stack<HistoryPart> forForwardingUndoStack = new Stack<HistoryPart>(); // TODO: DO FORWARDING OF UNDO STACK! // for(CommandState<Model> cs: undoStack) // forForwardingUndoStack.add(cs.forForwarding()); Stack<HistoryPart> forForwardingRedoStack = new Stack<HistoryPart>(); // TODO: DO FORWARDING OF UNDO STACK! // for(CommandState<Model> cs: redoStack) // forForwardingRedoStack.add(cs.forForwarding()); return new History(includeHistory, forForwardingUndoStack, forForwardingRedoStack); } } public MappableForwardable cloneHistory(boolean includeHistory) { return new History(includeHistory, undoStack, redoStack); } public void restoreHistory(Object history, PropogationContext propCtx, int propDistance, Collector<Model> collector) { if(((History)history).includeHistory) { this.undoStack = ((History)history).undoStack; this.redoStack = ((History)history).redoStack; } ArrayList<CommandState<Model>> origins = new ArrayList<CommandState<Model>>(); // for(CommandState<Model> undoable: ((History)history).undoStack) { // RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; // for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { // UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); // origins.add(undoPart.origin.pending); // TODO: FIGURE OUT HOW TO EXTRACT REVERSIBLE COMMAND TO APPEND TO ORIGINS! AND THEN EXECUTE THEM! // for(HistoryPart undoable: ((History)history).undoStack) { // RevertingCommandStateSequence<Model> undoableAsRevertiable = (RevertingCommandStateSequence<Model>)undoable; // for(int i = 0; i < undoableAsRevertiable.getCommandStateCount(); i++) { // UndoRedoPart undoPart = (UndoRedoPart)undoableAsRevertiable.getCommandState(i); // origins.add(undoPart.origin.pending); PendingCommandFactory.Util.executeSequence(collector, origins); } public RestorableModel toRestorable(boolean includeLocalHistory) { return RestorableModel.wrap(this, includeLocalHistory); } public void destroy(PropogationContext propCtx, int propDistance, Collector<Model> collector) { @SuppressWarnings("unchecked") List<Execution<Model>> creation = (List<Execution<Model>>)getProperty(RestorableModel.PROPERTY_CREATION); if(creation != null) { List<CommandState<Model>> destruction = new ArrayList<CommandState<Model>>(); for(Execution<Model> creationPart: creation) destruction.add(creationPart.undoable); Collections.reverse(destruction); PendingCommandFactory.Util.executeSequence(collector, destruction); } } }
package cgeo.geocaching.settings.fragments; import cgeo.geocaching.BuildConfig; import cgeo.geocaching.R; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.SettingsActivity; import android.content.Intent; import android.os.Bundle; import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import java.util.Locale; public class PreferenceAppearanceFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { setPreferencesFromResource(R.xml.preferences_appearence, rootKey); final Preference themePref = findPreference(getString(R.string.pref_theme_setting)); themePref.setOnPreferenceChangeListener((Preference preference, Object newValue) -> { final Settings.DarkModeSetting darkTheme = Settings.DarkModeSetting.valueOf((String) newValue); Settings.setAppTheme(darkTheme); requireActivity().recreate(); return true; }); final ListPreference languagePref = findPreference(getString(R.string.pref_selected_language)); final String[] entries = new String[BuildConfig.TRANSLATION_ARRAY.length + 1]; final String[] entryValues = new String[BuildConfig.TRANSLATION_ARRAY.length + 1]; final Locale currentLocale = Settings.getApplicationLocale(); entries[0] = getString(R.string.init_use_default_language); entryValues[0] = ""; for (int i = 0; i < BuildConfig.TRANSLATION_ARRAY.length; i++) { entryValues[1 + i] = BuildConfig.TRANSLATION_ARRAY[i]; final Locale l = new Locale(BuildConfig.TRANSLATION_ARRAY[i], ""); entries[1 + i] = BuildConfig.TRANSLATION_ARRAY[i] + " (" + l.getDisplayLanguage(currentLocale) + ")"; } languagePref.setEntries(entries); languagePref.setEntryValues(entryValues); } @Override public void onResume() { super.onResume(); getActivity().setTitle(R.string.settings_title_appearance); } }
package org.mockito.internal.stubbing; import java.util.LinkedList; import java.util.List; import org.mockito.exceptions.Reporter; import org.mockito.internal.util.MockUtil; import org.mockito.stubbing.Answer; @SuppressWarnings("unchecked") public class StubberImpl implements Stubber { final List<Answer> answers = new LinkedList<Answer>(); private final Reporter reporter = new Reporter(); public <T> T when(T mock) { if (mock == null) { reporter.nullPassedToWhenMethod(); } else if (!MockUtil.isMock(mock)) { reporter.notAMockPassedToWhenMethod(); } MockUtil.getMockHandler(mock).setAnswersForStubbing(answers); return mock; } public Stubber doReturn(Object toBeReturned) { answers.add(new Returns(toBeReturned)); return this; } public Stubber doThrow(Throwable toBeThrown) { answers.add(new ThrowsException(toBeThrown)); return this; } public Stubber doNothing() { answers.add(new DoesNothing()); return this; } public Stubber doAnswer(Answer answer) { answers.add(answer); return this; } }
package cgeo.geocaching.settings.fragments; import cgeo.geocaching.R; import cgeo.geocaching.apps.navi.NavigationAppFactory; import cgeo.geocaching.brouter.BRouterConstants; import cgeo.geocaching.brouter.util.DefaultFilesUtils; import cgeo.geocaching.maps.routing.RoutingMode; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.SettingsActivity; import cgeo.geocaching.storage.ContentStorage; import cgeo.geocaching.storage.PersistableFolder; import cgeo.geocaching.utils.ProcessUtils; import static cgeo.geocaching.utils.SettingsUtils.initPublicFolders; import android.os.Bundle; import androidx.annotation.StringRes; import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import java.util.ArrayList; import java.util.List; public class PreferenceNavigationFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { setPreferencesFromResource(R.xml.preferences_navigation, rootKey); initDefaultNavigationPreferences(); initOfflineRoutingPreferences(); // TODO: Logic for ProximityDistance needs to be reimplemented } @Override public void onResume() { super.onResume(); getActivity().setTitle(R.string.settings_title_navigation); initPublicFolders(this, ((SettingsActivity) getActivity()).getCsah()); final Preference tool1 = findPreference(getString(R.string.pref_defaultNavigationTool)); assert tool1 != null; setToolSummary(tool1, Settings.getDefaultNavigationTool()); tool1.setOnPreferenceChangeListener((preference, newValue) -> { setToolSummary(tool1, Integer.parseInt((String) newValue)); return true; }); final Preference tool2 = findPreference(getString(R.string.pref_defaultNavigationTool2)); assert tool2 != null; setToolSummary(tool2, Settings.getDefaultNavigationTool2()); tool2.setOnPreferenceChangeListener((preference, newValue) -> { setToolSummary(tool2, Integer.parseInt((String) newValue)); return true; }); } private void setToolSummary(final Preference preference, final int value) { try { preference.setSummary(NavigationAppFactory.getNavigationAppForId(value).getName()); } catch (Exception ignore) { preference.setSummary(""); } } /** * Fill the choice list for default navigation tools. */ private void initDefaultNavigationPreferences() { final List<NavigationAppFactory.NavigationAppsEnum> apps = NavigationAppFactory.getInstalledDefaultNavigationApps(); final CharSequence[] entries = new CharSequence[apps.size()]; final CharSequence[] values = new CharSequence[apps.size()]; for (int i = 0; i < apps.size(); ++i) { entries[i] = apps.get(i).toString(); values[i] = String.valueOf(apps.get(i).id); } final ListPreference defaultNavigationTool = findPreference(getString(R.string.pref_defaultNavigationTool)); defaultNavigationTool.setEntries(entries); defaultNavigationTool.setEntryValues(values); final ListPreference defaultNavigationTool2 = findPreference(getString(R.string.pref_defaultNavigationTool2)); defaultNavigationTool2.setEntries(entries); defaultNavigationTool2.setEntryValues(values); } private void initOfflineRoutingPreferences() { DefaultFilesUtils.checkDefaultFiles(); findPreference(getString(R.string.pref_useInternalRouting)).setOnPreferenceChangeListener((preference, newValue) -> { updateRoutingPrefs(!Settings.useInternalRouting()); return true; }); updateRoutingPrefs(Settings.useInternalRouting()); updateRoutingProfilesPrefs(); } private void updateRoutingProfilesPrefs() { final ArrayList<String> profiles = new ArrayList<>(); final List<ContentStorage.FileInformation> files = ContentStorage.get().list(PersistableFolder.ROUTING_BASE); for (ContentStorage.FileInformation file : files) { if (file.name.endsWith(BRouterConstants.BROUTER_PROFILE_FILEEXTENSION)) { profiles.add(file.name); } } final CharSequence[] entries = profiles.toArray(new CharSequence[0]); final CharSequence[] values = profiles.toArray(new CharSequence[0]); updateRoutingProfilePref(R.string.pref_brouterProfileWalk, RoutingMode.WALK, entries, values); updateRoutingProfilePref(R.string.pref_brouterProfileBike, RoutingMode.BIKE, entries, values); updateRoutingProfilePref(R.string.pref_brouterProfileCar, RoutingMode.CAR, entries, values); } private void updateRoutingProfilePref(@StringRes final int prefId, final RoutingMode mode, final CharSequence[] entries, final CharSequence[] values) { final String current = Settings.getRoutingProfile(mode); final ListPreference pref = findPreference(getString(prefId)); pref.setEntries(entries); pref.setEntryValues(values); pref.setSummary(current); pref.setOnPreferenceChangeListener((preference, newValue) -> { preference.setSummary(newValue.toString()); return true; }); if (current != null) { for (int i = 0; i < entries.length; i++) { if (current.contentEquals(entries[i])) { pref.setValueIndex(i); break; } } } } private void updateRoutingPrefs(final boolean useInternalRouting) { final boolean anyRoutingAvailable = useInternalRouting || ProcessUtils.isInstalled(getString(R.string.package_brouter)); findPreference(getString(R.string.pref_brouterDistanceThreshold)).setEnabled(anyRoutingAvailable); findPreference(getString(R.string.pref_brouterShowBothDistances)).setEnabled(anyRoutingAvailable); findPreference(getString(R.string.pref_brouterProfileWalk)).setEnabled(useInternalRouting); findPreference(getString(R.string.pref_brouterProfileBike)).setEnabled(useInternalRouting); findPreference(getString(R.string.pref_brouterProfileCar)).setEnabled(useInternalRouting); } }
package org.pentaho.ui.xul.binding; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulEventSource; import org.pentaho.ui.xul.binding.BindingConvertor.Direction; public class BindingContext { private XulDomContainer container; private List<Binding> bindings = new ArrayList<Binding>(); private static final Log logger = LogFactory.getLog(BindingContext.class); public BindingContext(XulDomContainer container) { this.container = container; } public void add(XulComponent source, String expr) { BindingExpression expression = BindingExpression.parse(expr); XulComponent target = container.getDocumentRoot().getElementById(expression.target); Binding newBinding = new Binding(source, expression.sourceAttr, target, expression.targetAttr); add(newBinding); } public void add(Binding bind) { try { bindings.add(bind); //forward binding setupBinding(bind, bind.getSource(), bind.getSourceAttr(), bind.getTarget(), bind.getTargetAttr(), Direction.FORWARD); //reverse binding if (bind.getBindingType() == Binding.Type.BI_DIRECTIONAL) { logger.info("Bi-directional"); setupBinding(bind, bind.getTarget(), bind.getTargetAttr(), bind.getSource(), bind.getSourceAttr(), Direction.BACK); } else { logger.info("Uni-directional"); } } catch (Throwable t) { throw new BindingException("Binding failed: " + bind.getSource() + "." + bind.getSourceAttr() + " <==> " + bind.getTarget() + "." + bind.getTargetAttr(), t); } } private Method findGetMethod(Object o, String property) { String methodName = null; try { methodName = "get" + (String.valueOf(property.charAt(0)).toUpperCase()) + property.substring(1); Method getMethod = o.getClass().getMethod(methodName); return getMethod; } catch (NoSuchMethodException e) { logger.debug("could not resolve getter method [" + methodName + "] for property [" + property + "] on object [" + o.getClass().getName() + "]. Trying to resolve as boolean style getter..."); try { String isMethodName = "is" + (String.valueOf(property.charAt(0)).toUpperCase()) + property.substring(1); Method getMethod = o.getClass().getMethod(isMethodName); return getMethod; } catch (NoSuchMethodException ex) { throw new BindingException("Could not resolve getter method for property [" + property + "] on object [" + o.getClass().getName() + "]", ex); } } } private Method findSetMethod(Object o, String property, Class paramClass) { String methodName = "set" + (String.valueOf(property.charAt(0)).toUpperCase()) + property.substring(1); try { //try to resolve by name and the Type of object returned by the getter Method setMethod = o.getClass().getMethod(methodName, paramClass); logger.debug("Found set method by name and type"); return setMethod; } catch (NoSuchMethodException e) { logger.debug("could not find set method by name and type, trying name alone"); //last resort, just return the set method regardless of paramater type (generics workaround) for (Method m : o.getClass().getMethods()) { //just match on name if (m.getName().equals(methodName)) { return m; } } } throw new BindingException("Could not resolve setter method for property [" + property + "] on object [" + o.getClass().getName() + "]"); } private Class getObjectClassOrType(Object o) { if (o instanceof Boolean) { return Boolean.TYPE; } else if (o instanceof Integer) { return Integer.TYPE; } else if (o instanceof Float) { return Float.TYPE; } else if (o instanceof Double) { return Double.TYPE; } else if (o instanceof Short) { return Short.TYPE; } else if (o instanceof Long) { return Long.TYPE; } else { return o.getClass(); } } private void setupBinding(final Binding bind, final XulEventSource source, final String sourceAttr, final XulEventSource target, final String targetAttr, final Direction dir) { if (source == null || sourceAttr == null) { throw new BindingException("source bean or property is null"); } if (target == null || targetAttr == null) { throw new BindingException("target bean or property is null"); } Method sourceGetMethod = findGetMethod(source, sourceAttr); //get class of object returned by getter Class getClazz = null; Object getRetVal = null; try { getRetVal = sourceGetMethod.invoke(source); logger.debug("Found get Return Value: " + getRetVal); } catch (IllegalAccessException e) { /*consume*/ } catch (InvocationTargetException e) { /*consume*/ } if (getRetVal != null) { logger.debug("Get Return was not null, checking it's type"); //checks for Boxed primatives getClazz = getObjectClassOrType(getRetVal); logger.debug("Get Return type is: " + getClazz); } //find set method final Method targetSetMethod = findSetMethod(target, targetAttr, getClazz); //setup prop change listener to handle binding PropertyChangeListener listener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equalsIgnoreCase(sourceAttr)) { try { Object value = bind.evaluateExpressions(evt.getNewValue()); value = bind.doConversions(value, dir); targetSetMethod.invoke(target, value); } catch (Exception e) { throw new BindingException("Error invoking setter method [" + targetSetMethod.getName() + "]", e); } } } }; source.addPropertyChangeListener(listener); logger.info("Binding established: " + source + "." + sourceAttr + " ==> " + target + "." + targetAttr); } }
package org.photon.jackson.flatjson; import com.fasterxml.jackson.annotation.ObjectIdGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.Hack; import com.fasterxml.jackson.databind.deser.ValueInstantiator; import com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator; import com.fasterxml.jackson.databind.deser.impl.ReadableObjectId; import com.fasterxml.jackson.databind.introspect.AnnotatedMember; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.type.CollectionType; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.LazyLoader; import java.io.IOException; import java.util.Collection; public final class Deserializers { public static JavaType getJavaType(AnnotatedMember member, DeserializationContext ctx) { if (member instanceof AnnotatedMethod) { return ctx.constructType(((AnnotatedMethod) member).getGenericParameterType(0)); } return ctx.constructType(member.getGenericType()); } public static BeanDescription getBeanDescription(DeserializationContext ctx, JavaType jt) { return ctx.getConfig().getClassIntrospector() .forDeserializationWithBuilder(ctx.getConfig(), jt, ctx.getConfig()); } public static ValueInstantiator findCollectionValueInstantiator(DeserializationContext ctx, JavaType jt) throws JsonMappingException { BeanDescription bd = getBeanDescription(ctx, jt); ValueInstantiator vi = ctx.getFactory().findValueInstantiator(ctx, bd); if (vi == null) { if (jt.isInterface()) { Class<?> implClazz = Hack.findCollectionCallback(jt.getRawClass().getName()); if (implClazz == null) throw new IllegalStateException("can't find any implementation for " + jt); bd = getBeanDescription(ctx, jt.narrowBy(implClazz)); vi = ctx.getFactory().findValueInstantiator(ctx, bd); } // more to come... } return vi; } public static class ManyToOne extends JsonDeserializer<Object> { private final AnnotatedMember member; public ManyToOne(AnnotatedMember member) { this.member = member; } @Override public Object deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { JavaType jt = getJavaType(member, ctx); BeanDescription bd = getBeanDescription(ctx, jt); AnnotatedMember member = Utils.getObjectIdMember(bd); if (member == null) throw new IllegalStateException(String.format( "unknown property `%s' on `%s'", bd.getObjectIdInfo().getPropertyName(), bd.getType())); Object id = jp.readValueAs(member.getRawType()); final ReadableObjectId roi = ctx.findObjectId(id, new FakeObjectIdGenerator(bd.getBeanClass(), member)); if (roi.item != null) { return roi.item; } else { return Enhancer.create(this.member.getRawType(), new LazyLoader() { @Override public Object loadObject() throws Exception { return roi.item; } }); } } } public static class OneToMany extends JsonDeserializer<Collection<Object>> { private final AnnotatedMember member; public OneToMany(AnnotatedMember member) { this.member = member; } @Override public Collection<Object> deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { JavaType jt = getJavaType(member, ctx); BeanDescription bd = getBeanDescription(ctx, jt.getContentType()); AnnotatedMember member = Utils.getObjectIdMember(bd); if (member == null) throw new IllegalStateException(String.format( "unknown property `%s' on `%s'", bd.getObjectIdInfo().getPropertyName(), bd.getType())); @SuppressWarnings("unchecked") Collection<Object> result = (Collection<Object>) findCollectionValueInstantiator(ctx, jt) .createUsingDefault(ctx); JsonDeserializer<Object> des = ctx.findRootValueDeserializer(CollectionType.construct( jt.getRawClass(), ctx.constructType(member.getRawType()))); for (Object id : (Iterable) des.deserialize(jp, ctx)) { final ReadableObjectId roi = ctx.findObjectId(id, new FakeObjectIdGenerator(bd.getBeanClass(), member)); if (roi.item != null) { result.add(roi.item); } else { result.add(Enhancer.create(bd.getBeanClass(), new LazyLoader() { @Override public Object loadObject() throws Exception { return roi.item; } })); } } return result; } } public static class FakeObjectIdGenerator extends ObjectIdGenerator<Object> { private final Class<?> scope; private final AnnotatedMember member; public FakeObjectIdGenerator(Class<?> scope, AnnotatedMember member) { this.scope = scope; this.member = member; } @Override public Class<?> getScope() { return scope; } @Override public boolean canUseFor(ObjectIdGenerator<?> gen) { return gen.getScope() == this.getScope(); } @Override public ObjectIdGenerator<Object> forScope(Class<?> scope) { return new FakeObjectIdGenerator(scope, member); } @Override public ObjectIdGenerator<Object> newForSerialization(Object context) { return this; } @Override public IdKey key(Object key) { return new IdKey(PropertyBasedObjectIdGenerator.class, scope, key); } @Override public Object generateId(Object forPojo) { return member.getValue(forPojo); } } }
package org.treetank.xmllayer; import org.treetank.api.IConstants; import org.treetank.api.INode; import org.treetank.api.IReadTransaction; import org.treetank.utils.FastStack; import org.treetank.utils.UTF; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; public class SubtreeSAXGenerator extends SAXGenerator { private boolean firstElement = true; private boolean lastElement = true; private final FastStack<Long> subtreeKeyStack = new FastStack<Long>(); public SubtreeSAXGenerator( final IReadTransaction input, final ContentHandler contentHandler, final boolean prettyPrint) throws Exception { super(input, contentHandler, prettyPrint); } @Override public final void run() { try { while (fireNextEvent()) { Thread.yield(); } } catch (Exception e) { throw new IllegalStateException(e); } } public final boolean fireNextEvent() throws Exception { // Iterate over all descendants. if (firstElement) { mHandler.startDocument(); firstElement = false; return true; } while (lastElement && mRTX.moveTo(mNextKey)) { // debug(); while (mRightSiblingKeyStack.size() > 0 && mRTX.getNodeKey() == mRightSiblingKeyStack.peek()) { mRightSiblingKeyStack.pop(); final INode node = mNodeStack.pop(); final String localPart = mRTX.nameForKey(node.getLocalPartKey()); final String prefix = mRTX.nameForKey(node.getPrefixKey()); final String uri = mRTX.nameForKey(node.getURIKey()); if (localPart.length() > 0) { mHandler.endElement(uri, localPart, qName(prefix, localPart)); return true; } } setNextKey(); switch (mRTX.getKind()) { case IConstants.ELEMENT: final INode node = mNodeStack.peek(); final String localPart = mRTX.nameForKey(node.getLocalPartKey()); final String prefix = mRTX.nameForKey(node.getPrefixKey()); final String uri = mRTX.nameForKey(node.getURIKey()); mHandler.startElement( uri, localPart, qName(prefix, localPart), visitAttributes()); return true; case IConstants.TEXT: final char[] text = UTF.convert(mRTX.getValue()).toCharArray(); mHandler.characters(text, 0, text.length); return true; case IConstants.PROCESSING_INSTRUCTION: mHandler.processingInstruction(mRTX.getLocalPart(), UTF.convert(mRTX .getValue())); return true; default: throw new IllegalStateException("Unknown kind: " + mRTX.getKind()); } } // Clean up all pending closing tags. while (mNodeStack.size() > 0) { mRightSiblingKeyStack.pop(); final INode node = mNodeStack.pop(); final String localPart = mRTX.nameForKey(node.getLocalPartKey()); final String prefix = mRTX.nameForKey(node.getPrefixKey()); final String uri = mRTX.nameForKey(node.getURIKey()); if (localPart.length() > 0) { mHandler.endElement(uri, localPart, qName(prefix, localPart)); return true; } } if (lastElement) { mHandler.endDocument(); mRTX.close(); lastElement = false; return true; } return false; } public void subtreeStarting(final long subtreeID) throws SAXException { try { subtreeKeyStack.push(this.mNextKey); mRTX.moveToRoot(); mRTX.moveToFirstChild(); do { if (mRTX.getLocalPart().matches("((\\D)+)(.{1})((\\d)+){1}")) { final long currentSubtreeID = Long.parseLong(mRTX.getLocalPart().replaceAll("((\\D)+)", "")); if (currentSubtreeID == subtreeID) { mNextKey = mRTX.getNodeKey(); } } else { throw new SAXException( "Invalid XML Layout, just splitelements should occur on the first level!"); } } while (mRTX.moveToRightSibling()); } catch (Exception e) { throw new SAXException(e); } } public void subtreeEnding(final long subtreeID) throws SAXException { try { mNextKey = subtreeKeyStack.pop(); } catch (Exception e) { throw new SAXException(e); } } public ContentHandler getHandler() { return mHandler; } public void closeTransaction() { this.mRTX.close(); } }
package com.mongodb.migratecluster.migrators; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.migratecluster.AppException; import com.mongodb.migratecluster.commandline.ApplicationOptions; import com.mongodb.migratecluster.commandline.Resource; import com.mongodb.migratecluster.commandline.ResourceFilter; import com.mongodb.migratecluster.observables.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class DataMigrator { final static Logger logger = LoggerFactory.getLogger(DataMigrator.class); private ApplicationOptions appOptions; public DataMigrator(ApplicationOptions appOptions) { this.appOptions = appOptions; } private boolean isValidOptions() { // on appOptions source, target, oplog must all be present if ( (this.appOptions.getSourceCluster().equals("")) || (this.appOptions.getTargetCluster().equals("")) || (this.appOptions.getOplogStore().equals("")) ) { // invalid input return false; } return true; } public void process() throws AppException { // check if the appOptions are valid if (!this.isValidOptions()) { String message = String.format("invalid input args for sourceCluster, targetCluster and oplog. \ngiven: %s", this.appOptions.toString()); throw new AppException(message); } // loop through source and copy to target readSourceClusterDatabases(); } private void readSourceClusterDatabases() throws AppException { MongoClient sourceClient = getSourceMongoClient(); MongoClient targetClient = getTargetMongoClient(); //Map<String, List<Resource>> sourceResources = MongoDBIteratorHelper.getSourceResources(sourceClient); //Map<String, List<Resource>> filteredSourceResources = getFilteredResources(sourceResources); //FilterIterable filterIterable = new FilterIterable(this.appOptions.getBlackListFilter()); // TODO: BUG; code not proceeding to below try { Date startDateTime = new Date(); logger.info(" started processing at {}", startDateTime); readAndWriteResourceDocuments(sourceClient, targetClient); Date endDateTime = new Date(); logger.info(" completed processing at {}", endDateTime); logger.info(" total time to process is {}", TimeUnit.SECONDS.convert(endDateTime.getTime() - startDateTime.getTime(), TimeUnit.MILLISECONDS)); } catch (Exception e) { String message = "error in while processing server migration."; logger.error(message, e); throw new AppException(message, e); } sourceClient.close(); logger.info("Absolutely nothing should be here after this line"); } private void readAndWriteResourceDocuments(MongoClient sourceClient, MongoClient targetClient) { // Note: Working; get the list of databases new DatabaseFlowable(sourceClient) .filter(db -> { String database = "social"; logger.info("db.name: [{}], string: [{}], comparision: [{}]", db.getString("name"), database, db.getString("name").equals(database)); return db.getString("name").equalsIgnoreCase(database); }) // Note: Working; for each database get the list of collections in it .flatMap(db -> { logger.info(" => found database {}", db.getString("name")); return new CollectionFlowable(sourceClient, db.getString("name")); // Note: Working; CollectionFlowable::subscribeActual works as well }) .filter(resource -> { String collection = "people"; logger.info("collection.name: [{}], string: [{}], comparision: [{}]", resource.getCollection(), collection, resource.getCollection().equals(collection)); return resource.getCollection().equalsIgnoreCase(collection); }) .map(resource -> { // Note: Nothing in here gets executed logger.info(" ====> map -> found resource {}", resource.toString()); return new DocumentReader(sourceClient, resource); //return resource; }) .map(reader -> { logger.info(" ====> reader -> found resource {}", reader.getResource()); return new DocumentWriter(targetClient, reader); }) .subscribe(writer -> { // Note: Nothing in here gets executed logger.info(" ====> writer -> found resource {}", writer); writer.blockingLast(); }); } private boolean isEntireDatabaseBlackListed(String database) { logger.info(this.appOptions.getBlackListFilter().toString()); return this.appOptions.getBlackListFilter() .stream() .anyMatch(bl -> bl.getDatabase().equals(database) && bl.isEntireDatabase()); } private MongoClient getMongoClient(String cluster) { String connectionString = String.format("mongodb://%s", cluster); MongoClientURI uri = new MongoClientURI(connectionString); return new MongoClient(uri); } private MongoClient getSourceMongoClient() { return getMongoClient(this.appOptions.getSourceCluster()); } private MongoClient getTargetMongoClient() { return getMongoClient(this.appOptions.getTargetCluster()); } private Map<String, List<Resource>> getFilteredResources(Map<String, List<Resource>> resources) { List<ResourceFilter> blacklist = appOptions.getBlackListFilter(); Map<String, List<Resource>> filteredResources = new HashMap<>(resources); // for all resources in blacklist remove them from filteredResources blacklist.forEach(r -> { String db = r.getDatabase(); String coll = r.getCollection(); if (filteredResources.containsKey(db)) { // check if entire database needs to be skipped if (r.isEntireDatabase()) { filteredResources.remove(db); } else { // otherwise just remove the resources by collection name List<Resource> list = filteredResources.get(db); list.removeIf(i -> i.getCollection().equals(coll)); } } }); // remove database if it has any empty resource list in it Object[] dbNames = filteredResources.keySet().toArray(); for (Object db : dbNames) { String name = db.toString(); if (filteredResources.get(name).size() == 0) { filteredResources.remove(name); } } return filteredResources; } }
package org.usfirst.frc.team4915.stronghold; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team4915.stronghold.commands.AutoCommand1; import org.usfirst.frc.team4915.stronghold.commands.DriveTrain.MoveStraightPositionModeCommand; import org.usfirst.frc.team4915.stronghold.subsystems.Autonomous; import org.usfirst.frc.team4915.stronghold.subsystems.DriveTrain; import org.usfirst.frc.team4915.stronghold.subsystems.GearShift; import org.usfirst.frc.team4915.stronghold.subsystems.IntakeLauncher; import org.usfirst.frc.team4915.stronghold.subsystems.Scaler; import org.usfirst.frc.team4915.stronghold.utils.BNO055; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static DriveTrain driveTrain; public static IntakeLauncher intakeLauncher; public static OI oi; public static GearShift gearShift; public static Scaler scaler; Command autonomousCommand; SendableChooser autonomousProgramChooser; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { RobotMap.init(); // 1. Initialize RobotMap prior to initializing modules // 2. conditionally create the modules if (ModuleManager.DRIVE_MODULE_ON) { driveTrain = new DriveTrain(); gearShift = new GearShift(); System.out.println("ModuleManager initialized: DriveTrain"); } if (ModuleManager.GEARSHIFT_MODULE_ON) { SmartDashboard.putString("Gear shift", "Initialized"); gearShift = new GearShift(); } if (ModuleManager.INTAKELAUNCHER_MODULE_ON) { intakeLauncher = new IntakeLauncher(); SmartDashboard.putNumber("Launcher Set Point: ", intakeLauncher.aimMotor.getPosition()); SmartDashboard.putString("Module Manager", "IntakeLauncher Initialized"); System.out.println("ModuleManager initialized: IntakeLauncher"); System.out.println(intakeLauncher.getSetPoint()); } if (ModuleManager.GYRO_MODULE_ON) { RobotMap.gyro.initGyro(); // Sensitivity in VEX Yaw Rate Gyro data sheet: 0.0011 RobotMap.gyro.setSensitivity(0.0011); RobotMap.gyro.calibrate(); SmartDashboard.putString("Module Manager", "initialize gyro"); System.out.println("ModuleManager initialize gyro: " + RobotMap.gyro.getAngle()); RobotMap.gyro.reset(); } if (ModuleManager.SCALING_MODULE_ON) { scaler = new Scaler(); } if (ModuleManager.IMU_MODULE_ON) { BNO055.CalData calData = RobotMap.imu.getCalibration(); SmartDashboard.putBoolean("IMU present", RobotMap.imu.isSensorPresent()); SmartDashboard.putBoolean("IMU initialized", RobotMap.imu.isInitialized()); SmartDashboard.putNumber("IMU calibration status", (calData.sys * 1000 + calData.accel * 100 + calData.gyro * 10 + calData.mag)); // Calibration values range from 0-3, // Right to left: mag, gyro, accel } oi = new OI(); // 3. Construct OI after subsystems created } @Override public void disabledPeriodic() { Scheduler.getInstance().run(); } @Override public void autonomousInit() { // schedule the autonomous command autonomousCommand = new MoveStraightPositionModeCommand((14 * Math.PI), 0.5); //autonomousCommand = new AutoCommand1((Autonomous.Type) oi.barrierType.getSelected(), (Autonomous.Strat) oi.strategy.getSelected(), // (Autonomous.Position) oi.startingFieldPosition.getSelected()); if (this.autonomousCommand != null) { this.autonomousCommand.start(); } } /** * This function is called periodically during autonomous */ @Override public void autonomousPeriodic() { Scheduler.getInstance().run(); } @Override public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. //set speed // RobotMap.rightBackMotor.changeControlMode(CANTalon.TalonControlMode.Speed); // RobotMap.leftBackMotor.changeControlMode(CANTalon.TalonControlMode.Speed); if (this.autonomousCommand != null) { this.autonomousCommand.cancel(); } } /** * This function is called when the disabled button is hit. You can use it * to reset subsystems before shutting down. */ @Override public void disabledInit() { } /** * This function is called periodically during operator control */ @Override public void teleopPeriodic() { Scheduler.getInstance().run(); if (ModuleManager.INTAKELAUNCHER_MODULE_ON) { SmartDashboard.putNumber("aimMotor Potentiometer position = ", intakeLauncher.getPosition()); SmartDashboard.putNumber("Aimer JoystickY Position: ", Robot.oi.aimStick.getAxis((Joystick.AxisType.kY))); SmartDashboard.putNumber("Aimer Set Point: ", intakeLauncher.getSetPoint()); SmartDashboard.putBoolean("Top Limit Switch: ", intakeLauncher.isLauncherAtTop()); SmartDashboard.putBoolean("Bottom Limit Switch: ", intakeLauncher.isLauncherAtBottom()); } } /** * This function is called periodically during test mode */ @Override public void testPeriodic() { LiveWindow.run(); if (ModuleManager.INTAKELAUNCHER_MODULE_ON) { SmartDashboard.putNumber("aimMotor Potentiometer position = ", intakeLauncher.getPosition()); SmartDashboard.putNumber("Aimer JoystickY Position: ", Robot.oi.aimStick.getAxis((Joystick.AxisType.kY))); SmartDashboard.putNumber("Aimer Set Point: ", intakeLauncher.getSetPoint()); SmartDashboard.putBoolean("Top Limit Switch: ", intakeLauncher.isLauncherAtTop()); SmartDashboard.putBoolean("Bottom Limit Switch: ", intakeLauncher.isLauncherAtBottom()); SmartDashboard.putBoolean("Boulder Limit Switch ", Robot.intakeLauncher.boulderLoaded()); } } }
package org.yvka.Beleg2.gui; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.DepthTest; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Duration; import org.yvka.Beleg2.game.GameBoard; /** * <p> * The main entry point of the java-fx based GUI implementation <br> * of the Game Othello.<br> * <br> * The class is responsible for assemble the gui out of <br> * the {@link GameBoardUI} and the {@link GameControlPanel}.<br> * <br> * </p> * @author Yves Kaufmann * */ public class OthelloGuiApplication extends Application { /** * The id of modal dimmer pane which can be used to style modal dimmer pane with css. */ public static final String MODAL_DIMMER_ID = "modalDimmer"; /** * The id of the game field pane which can be used to style game field pane with css. */ public static final String GAME_FIELD_ID = "gameField"; /** * The id of the control panel pane which can be used to style control panel pane with css. */ public static final String CONTROL_PANEL_ID = "controlPanel"; private static OthelloGuiApplication instance = null; /** * Convenient method for retrieving the instance of the OthelloGuiApplication. * * @return the single instance of the OthelloGuiApllication. */ public static OthelloGuiApplication getInstance() { return instance; } /** * Main entry points of the java-fx based GUI implementation for the game Othello * * @param args the application arguments. */ public static void main(String[] args) { launch(args); } private VBox root; private StackPane layeredPane; private GameBoardUI gameField; private GameControlPanel gameControlPanel; private Scene scene; private StackPane modalDimmer; @Override public void start(Stage primaryStage) { try { // store the instance in the static instance methode instance = this; layeredPane = new StackPane(); layeredPane.setDepthTest(DepthTest.DISABLE); modalDimmer = new StackPane(); modalDimmer.setId(MODAL_DIMMER_ID); modalDimmer.setVisible(false); modalDimmer.setOnMouseClicked((event) -> { event.consume(); hideModalDimmer(); }); GameBoard gameLogic = new GameBoard(); gameControlPanel = new GameControlPanel(gameLogic); gameControlPanel.setId(CONTROL_PANEL_ID); gameControlPanel.gameFieldSizeProperty().addListener(( observable, oldValue, newValue) -> { gameField.setSize(newValue); primaryStage.sizeToScene(); primaryStage.centerOnScreen(); }); gameField = new GameBoardUI(gameLogic); gameField.setId(GAME_FIELD_ID); gameControlPanel.setOnNewGameClicked((event) -> { gameField.startNewGame(); }); root = new VBox(); root.setId("root"); root.getChildren().addAll(gameField, gameControlPanel); layeredPane.getChildren().addAll(root, modalDimmer); scene = new Scene(layeredPane); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); primaryStage.setResizable(false); primaryStage.getIcons().add(new Image( getClass().getResourceAsStream("icon.png") )); primaryStage.sizeToScene(); primaryStage.setScene(scene); primaryStage.setTitle("Reversis"); primaryStage.centerOnScreen(); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } /** * <p> * Display a transparent black colored overlay <br> * with a specified Node component. <br> * <br> * For example the Overlay is used to display the result of a game. * </p> * @param content the content node which should display on the overlay. */ public void showModalDimmer(Node content) { modalDimmer.setOpacity(0); modalDimmer.getChildren().add(content); modalDimmer.setVisible(true); modalDimmer.setCache(true); EventHandler<ActionEvent> onAnimationFinished = (event) -> { modalDimmer.setCache(false); }; Timeline transitionAnimation = new Timeline( new KeyFrame( new Duration(500), onAnimationFinished , new KeyValue(modalDimmer.opacityProperty(), 1.0, Interpolator.EASE_BOTH) ) ); transitionAnimation.play(); } /** * Hide the modal dimmer. */ public void hideModalDimmer() { modalDimmer.setCache(true); EventHandler<ActionEvent> onAnimationFinished = (event) -> { modalDimmer.setCache(false); modalDimmer.setVisible(false); modalDimmer.getChildren().clear(); }; Timeline transitionAnimation = new Timeline( new KeyFrame( new Duration(500), onAnimationFinished , new KeyValue(modalDimmer.opacityProperty(), 0.0, Interpolator.EASE_BOTH) ) ); transitionAnimation.play(); } }
package com.touchboarder.weekdaysbuttons; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.AttrRes; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.IdRes; import android.support.annotation.IntRange; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SimpleItemAnimator; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; public class WeekdaysDataSource implements Parcelable { public interface Callback { void onWeekdaysItemClicked(int attachId,WeekdaysDataItem weekdaysItem); void onWeekdaysSelected(int attachId,ArrayList<WeekdaysDataItem> weekdaysArray); } public interface TextDrawableListener { Drawable onDrawTextDrawable(int attachId, int calendarDayId, String label, boolean selected); } public WeekdaysDataSource setOnTextDrawableListener(TextDrawableListener textDrawableCallback) { this.textDrawableCallback = textDrawableCallback; return this; } private TextDrawableListener textDrawableCallback; private transient AppCompatActivity mContext; protected transient RecyclerView mRecyclerView; private transient Callback mCallback; private ArrayList<WeekdaysDataItem> mDataSource; private WeekdaysDrawableProvider mDrawableProvider; private Locale locale = Locale.getDefault(); protected LinearLayoutManager mLayoutManager; @IdRes private int mAttachId = R.id.weekdays_recycler_view; @LayoutRes private int mWeekdayLayoutId = -1;//R.layout.weekdays_image_view; @IdRes private int mWeekdayViewId = -1;//R.id.weekday_view; @ColorInt private int mBackgroundColor = Color.TRANSPARENT; @ColorInt private int mTextColorSelected; @ColorInt private int mTextColorUnselected; @ColorInt private int mSelectedColor; @ColorInt private int mUnselectedColor; private Typeface fontTypeFace; private boolean mIsVisible; private boolean mFillWidth = true; private boolean mIsAllDaysSelected = false; private int mFirstDayOfWeek = Calendar.SUNDAY; private int mTextDrawableType = WeekdaysDrawableProvider.MW_ROUND; private int mNumberOfLetters = 1; private int mViewWidth; private int mViewHeight; private int mViewMargin; private int mViewGravity = Gravity.CENTER; private int mLayoutPadding; private boolean mNestedScrollEnable = false; private LinkedHashMap<Integer, String> mWeekdaysMap; private HashMap<Integer, Boolean> mSelectedDaysMap; private View mParentView = null; public WeekdaysDataSource(@NonNull AppCompatActivity context, @IdRes int attacherId) { mContext = context; mAttachId = attacherId; reset(context); } public WeekdaysDataSource(@NonNull AppCompatActivity context, @IdRes int attacherId, View view) { mContext = context; mAttachId = attacherId; reset(context); mParentView = view; } public WeekdaysDataSource setWeekdayItemLayoutRes(@LayoutRes int mWeekdayLayoutId) { this.mWeekdayLayoutId = mWeekdayLayoutId; return this; } public WeekdaysDataSource setWeekdayItemViewId(@IdRes int weekdayViewId) { this.mWeekdayViewId = weekdayViewId; return this; } private WeekdaysDrawableProvider getDrawableProvider() { if (mDrawableProvider == null) { mDrawableProvider = new WeekdaysDrawableProvider(); mDrawableProvider.setSelectedColor(mSelectedColor); mDrawableProvider.setUnselectedColor(mUnselectedColor); mDrawableProvider.setTextColorSelected(mTextColorSelected); mDrawableProvider.setTextColorUnselected(mTextColorUnselected); mDrawableProvider.setFontTypeFace(fontTypeFace); } return mDrawableProvider; } private LinkedHashMap<Integer, String> getDays() { if (mWeekdaysMap == null) { String[] days = new DateFormatSymbols(getLocale()).getWeekdays(); mWeekdaysMap = new LinkedHashMap<>(); for (int i = mFirstDayOfWeek; i < days.length; i++) { if (!TextUtils.isEmpty(days[i])) { mWeekdaysMap.put(i, days[i]); getSelectedDays().put(i, mIsAllDaysSelected); } } if (mFirstDayOfWeek == Calendar.MONDAY) { mWeekdaysMap.put(Calendar.SUNDAY, days[Calendar.SUNDAY]); getSelectedDays().put(Calendar.SUNDAY, mIsAllDaysSelected); } } return mWeekdaysMap; } private HashMap<Integer, Boolean> getSelectedDays() { if (mSelectedDaysMap == null) mSelectedDaysMap = new HashMap<>(); for (WeekdaysDataItem item : getWeekdaysItems()) { mSelectedDaysMap.put(item.getCalendarDayId(), item.isSelected()); } return mSelectedDaysMap; } public void setContext(@NonNull AppCompatActivity context) { mContext = context; } public boolean isActive() { return mIsVisible; } @UiThread public WeekdaysDataSource reset(Context context) { mBackgroundColor = WeekdaysUtil.resolveColor(context, R.attr.weekdays_background_color, WeekdaysUtil.resolveColor(context, R.attr.weekdays_background_color, Color.TRANSPARENT)); mSelectedColor = WeekdaysUtil.resolveColor(context, R.attr.weekdays_selected_color, WeekdaysUtil.resolveColor(context, R.attr.colorAccent, Color.RED)); mUnselectedColor = WeekdaysUtil.resolveColor(context, R.attr.weekdays_unselected_color, WeekdaysUtil.resolveColor(context, R.attr.colorPrimary, Color.GRAY)); mTextColorSelected = WeekdaysUtil.resolveColor(context, R.attr.weekdays_text_selected_color, WeekdaysUtil.resolveColor(context, R.attr.titleTextColor, Color.WHITE)); mTextColorUnselected = WeekdaysUtil.resolveColor(context, R.attr.weekdays_text_unselected_color, WeekdaysUtil.resolveColor(context, R.attr.titleTextColor, Color.WHITE)); mViewMargin = WeekdaysUtil.resolveDimension(context, R.attr.weekdays_item_margin, R.dimen.weekdays_button_default_margin); mViewWidth = WeekdaysUtil.resolveDimension(context, R.attr.weekdays_item_width, R.dimen.weekdays_button_default_width); mViewHeight = WeekdaysUtil.resolveDimension(context, R.attr.weekdays_item_height, R.dimen.weekdays_button_default_height); mLayoutPadding = WeekdaysUtil.resolveDimension(context, R.attr.weekdays_layout_padding, R.dimen.weekdays_layout_default_padding); return this; } @UiThread public WeekdaysDataSource setFirstDayOfWeek(@IntRange(from = Calendar.SUNDAY, to = Calendar.MONDAY) int firstDayOfWeek) { this.mFirstDayOfWeek = firstDayOfWeek; return this; } @UiThread public WeekdaysDataSource setFillWidth(boolean mFillView) { this.mFillWidth = mFillView; if (mRecyclerView != null) mRecyclerView.setAdapter(createAdapter()); return this; } public boolean getFillWidth() { return mFillWidth; } public boolean isNestedScrollEnable() { return mNestedScrollEnable; } @UiThread public WeekdaysDataSource setNestedScrollEnable(boolean enable) { this.mNestedScrollEnable = enable; if (mRecyclerView != null) mRecyclerView.setNestedScrollingEnabled(enable); return this; } @UiThread public WeekdaysDataSource setDrawableType(int mType) { this.mTextDrawableType = mType; return this; } public Locale getLocale() { return locale; } public WeekdaysDataSource setLocale(Locale locale) { this.locale = locale; return this; } public WeekdaysDataSource setFontTypeFace(Typeface fontTypeFace) { this.fontTypeFace = fontTypeFace; if (getDrawableProvider() != null) getDrawableProvider().setFontTypeFace(fontTypeFace); return this; } @UiThread public WeekdaysDataSource setNumberOfLetters(int numberOfLetters) { this.mNumberOfLetters = numberOfLetters; for (WeekdaysDataItem item : getWeekdaysItems()) { item.setNumberOfLetters(numberOfLetters); } return this; } @UiThread public WeekdaysDataSource setFontBaseSize(int fontBaseSize) { if (getDrawableProvider() != null) getDrawableProvider().setFontBaseSize(fontBaseSize); return this; } @UiThread public WeekdaysDataSource setSelectedDays(boolean... days) { if (days.length > getDays().size()) days = Arrays.copyOf(days, getDays().size()); for (int i = 0; i < days.length; i++) { mIsAllDaysSelected = false; getSelectedDays().put(i, days[i]); if (i < getWeekdaysCount()) { setSelected(i, days[i], false); } } if (mRecyclerView != null) mRecyclerView.getAdapter().notifyDataSetChanged(); return this; } @UiThread public WeekdaysDataSource setSelectedDays(int... indexes) { if (indexes.length > getDays().size()) indexes = Arrays.copyOf(indexes, getDays().size()); for (Integer index : indexes) { mIsAllDaysSelected = false; if (index <= getDays().size()) getSelectedDays().put(index, true); if (index < getWeekdaysCount()) { setSelected(index, true, false); } } if (mRecyclerView != null) mRecyclerView.getAdapter().notifyDataSetChanged(); return this; } @UiThread public WeekdaysDataSource start(@Nullable Callback callback) { mCallback = callback; invalidateVisibility(attach()); return this; } @UiThread public WeekdaysDataSource setBackgroundColor(@ColorInt int color) { mBackgroundColor = color; if (mRecyclerView != null) mRecyclerView.setBackgroundColor(color); return this; } @UiThread public WeekdaysDataSource setBackgroundColorRes(@ColorRes int colorRes) { return setBackgroundColor(ContextCompat.getColor(mContext,colorRes)); } @UiThread public WeekdaysDataSource setBackgroundColorAttr(@AttrRes int colorAttr) { return setBackgroundColor(WeekdaysUtil.resolveColor(mContext, colorAttr, 0)); } @UiThread public WeekdaysDataSource setTextColorSelected(@ColorInt int color) { mTextColorSelected = color; if (getDrawableProvider() != null) getDrawableProvider().setTextColorSelected(color); return this; } @UiThread public WeekdaysDataSource setTextColorSelectedRes(@ColorRes int colorRes) { return setTextColorSelected(ContextCompat.getColor(mContext,colorRes)); } @UiThread public WeekdaysDataSource setTextColorSelectedAttr(@AttrRes int colorAttr) { return setTextColorSelected(WeekdaysUtil.resolveColor(mContext, colorAttr, 0)); } @UiThread public WeekdaysDataSource setTextColorUnselected(@ColorInt int color) { mTextColorUnselected = color; if (getDrawableProvider() != null) getDrawableProvider().setTextColorUnselected(color); return this; } @UiThread public WeekdaysDataSource setTextColorUnselectedRes(@ColorRes int colorRes) { return setTextColorUnselected(ContextCompat.getColor(mContext,colorRes)); } @UiThread public WeekdaysDataSource setTextColorUnselectedAttr(@AttrRes int colorAttr) { return setTextColorUnselected(WeekdaysUtil.resolveColor(mContext, colorAttr, 0)); } @UiThread public WeekdaysDataSource setSelectedColor(@ColorInt int color) { mSelectedColor = color; if (getDrawableProvider() != null) getDrawableProvider().setSelectedColor(color); return this; } @UiThread public WeekdaysDataSource setSelectedColorRes(@ColorRes int colorRes) { return setSelectedColor(ContextCompat.getColor(mContext,colorRes)); } @UiThread public WeekdaysDataSource setSelectedColorAttr(@AttrRes int colorAttr) { return setSelectedColor(WeekdaysUtil.resolveColor(mContext, colorAttr, 0)); } @UiThread public WeekdaysDataSource setUnselectedColor(@ColorInt int color) { mUnselectedColor = color; if (getDrawableProvider() != null) getDrawableProvider().setUnselectedColor(color); return this; } @UiThread public WeekdaysDataSource setUnselectedColorRes(@ColorRes int colorRes) { return setUnselectedColor(ContextCompat.getColor(mContext,colorRes)); } @UiThread public WeekdaysDataSource setUnselectedColorAttr(@AttrRes int colorAttr) { return setUnselectedColor(WeekdaysUtil.resolveColor(mContext, colorAttr, 0)); } @UiThread public WeekdaysDataSource setViewMargin(int mViewMargin) { this.mViewMargin = mViewMargin; return this; } @UiThread public WeekdaysDataSource setViewMarginRes(@DimenRes int marginRes) { return setViewMargin((int) mContext.getResources().getDimension(marginRes)); } @UiThread public WeekdaysDataSource setViewMarginAttr(@AttrRes int marginAttr) { return setViewMargin(WeekdaysUtil.resolveInt(mContext, marginAttr, 0)); } @UiThread public WeekdaysDataSource setViewWidth(int mViewWidth) { this.mViewWidth = mViewWidth; return this; } @UiThread public WeekdaysDataSource setViewWidthRes(@DimenRes int widthRes) { return setViewWidth((int) mContext.getResources().getDimension(widthRes)); } @UiThread public WeekdaysDataSource setViewWidthAttr(@AttrRes int widthAttr) { return setViewWidth(WeekdaysUtil.resolveInt(mContext, widthAttr, 0)); } @UiThread public WeekdaysDataSource setViewHeight(int mViewHeight) { this.mViewHeight = mViewHeight; return this; } @UiThread public WeekdaysDataSource setViewHeightRes(@DimenRes int heigthRes) { return setViewHeight((int) mContext.getResources().getDimension(heigthRes)); } @UiThread public WeekdaysDataSource setViewHeightAttr(@AttrRes int heightAttr) { return setViewHeight(WeekdaysUtil.resolveInt(mContext, heightAttr, 0)); } @UiThread public WeekdaysDataSource setLayoutPadding(int layoutPadding) { this.mLayoutPadding = layoutPadding; return this; } @UiThread public WeekdaysDataSource setLayoutPaddingRes(@DimenRes int layoutPaddingRes) { return setLayoutPadding((int) mContext.getResources().getDimension(layoutPaddingRes)); } @UiThread public WeekdaysDataSource setLayoutPaddingAttr(@AttrRes int layoutPaddingAttr) { return setLayoutPadding(WeekdaysUtil.resolveInt(mContext, layoutPaddingAttr, 0)); } @UiThread public WeekdaysDataSource setViewParams(int width, int height, int margin, int gravity,int layoutPadding) { setViewWidth(width); setViewHeight(height); setViewMargin(margin); setViewGravity(gravity); setLayoutPadding(layoutPadding); if (mRecyclerView != null) mRecyclerView.setAdapter(createAdapter()); return this; } @UiThread public WeekdaysDataSource setViewParamsRes(@DimenRes int widthRes, @DimenRes int heightRes, @DimenRes int marginRes, int gravity,@DimenRes int layoutPaddingRes) { setViewWidthRes(widthRes); setViewHeightRes(heightRes); setViewMarginRes(marginRes); setViewGravity(gravity); setLayoutPaddingRes(layoutPaddingRes); if (mRecyclerView != null) mRecyclerView.setAdapter(createAdapter()); return this; } @UiThread public WeekdaysDataSource setViewParamsAttr(@AttrRes int widthAttr, @AttrRes int heightAttr, @AttrRes int marginAttr, int gravity, @AttrRes int layoutPaddingAttr) { setViewWidthAttr(widthAttr); setViewHeightAttr(heightAttr); setViewMarginAttr(marginAttr); setViewGravity(gravity); setLayoutPaddingAttr(layoutPaddingAttr); if (mRecyclerView != null) mRecyclerView.setAdapter(createAdapter()); return this; } /** * Use Gravity.CENTER etc. * * @param gravity Gravity * @return WeekdaysDataSource */ @UiThread public WeekdaysDataSource setViewGravity(int gravity) { this.mViewGravity = gravity; return this; } public int getViewMargin() { return mViewMargin; } public int getViewWidth() { return mViewWidth; } public int getViewHeight() { return mViewHeight; } public int getViewGravity() { return mViewGravity; } public int getLayoutPadding() { return mLayoutPadding; } @Nullable public View getWeekdaysRecycleView() { return mRecyclerView; } @UiThread public void setVisible(boolean visible) { invalidateVisibility(visible); } private void invalidateVisibility(boolean visible) { if (mRecyclerView == null) return; mRecyclerView.setVisibility(visible ? View.VISIBLE : View.GONE); mIsVisible = visible; } public int getWeekdaysCount() { return getWeekdaysItems().size(); } public WeekdaysDataSource selectAll(boolean selected) { mIsAllDaysSelected = selected; for (int i = 0; i < getWeekdaysCount(); i++) { setSelected(i, selected, false); } if (mRecyclerView != null) mRecyclerView.getAdapter().notifyDataSetChanged(); mCallback.onWeekdaysSelected(mAttachId,getWeekdaysItems()); return this; } private void setSelected(int index, boolean selected, boolean notify) { WeekdaysDataItem item = getItem(index); if (item != null) { if (mIsAllDaysSelected) mIsAllDaysSelected = selected; getItem(index).setSelected(selected); getItem(index).setDrawable(getDrawableFromWeekdayItemProperties(item)); if (notify && mRecyclerView != null) mRecyclerView.getAdapter().notifyItemChanged(index); } } public boolean isAllDaysSelected() { if (mIsAllDaysSelected) return true; int countSelected = 0; for (WeekdaysDataItem item : getWeekdaysItems()) { if (item.isSelected()) countSelected++; } return countSelected == getWeekdaysCount(); } private WeekdaysDataItem toggleSelected(WeekdaysDataItem item) { item.toggleSelected(); item.setDrawable(getDrawableFromWeekdayItemProperties(item)); if (mIsAllDaysSelected) mIsAllDaysSelected = item.isSelected(); return item; } public ArrayList<WeekdaysDataItem> getWeekdaysItems() { if (mDataSource == null) mDataSource = new ArrayList<>(); return mDataSource; } public int getWeekdayLayoutId() { return mWeekdayLayoutId; } @IdRes public int getWeekdayViewId() { return mWeekdayViewId; } public WeekdaysDataItem getItem(int position) { return mDataSource.get(position); } private WeekdaysDataItem itemFromType(int position, int calendarDayId, String label, boolean selected) { return new WeekdaysDataItem.Builder() .setLayoutParentId(mAttachId) .setPosition(position) .setCalendarId(calendarDayId) .setLabel(label) .setDrawable(getDrawableFromType( calendarDayId, mTextDrawableType, label, selected)) .setType(mTextDrawableType) .setNumberOfLetters(mNumberOfLetters) .setSelected(selected) .createWeekdaysDataItem(); } private Drawable getDrawableFromType( int calendarDayId, int textDrawableType, String label, boolean selected) { int subStringLength = label.length(); if (subStringLength > mNumberOfLetters) subStringLength = mNumberOfLetters; Drawable drawable = null; if (textDrawableCallback != null) drawable = textDrawableCallback.onDrawTextDrawable(mAttachId, calendarDayId, label.substring(0, subStringLength), selected); if (drawable == null && getDrawableProvider() != null) drawable = getDrawableProvider().getDrawableFromType(mContext, textDrawableType, label.substring(0, subStringLength), selected); return drawable; } public Drawable getDrawableFromWeekdayItemProperties(WeekdaysDataItem dayItem) { return getDrawableFromType( dayItem.getCalendarDayId(), dayItem.getTextDrawableType(), dayItem.getLabel(), dayItem.isSelected()); } private void initRecyclerView(Context context) { if (mRecyclerView == null) return; mRecyclerView.setBackgroundColor(mBackgroundColor); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(createAdapter()); mRecyclerView.setNestedScrollingEnabled(isNestedScrollEnable()); // mRecyclerView.getItemAnimator().setSupportsChangeAnimations(true); RecyclerView.ItemAnimator animator = mRecyclerView.getItemAnimator(); if (animator instanceof SimpleItemAnimator) { ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); } onRecyclerViewInit(mRecyclerView); } protected void onRecyclerViewInit(RecyclerView recyclerView) { } protected RecyclerView.Adapter<WeekdaysAdapter.ViewHolder> createAdapter() { return new WeekdaysAdapter( getWeekdayLayoutId(), getWeekdayViewId(), getWeekdaysItems(), getFillWidth(), getViewWidth(), getViewHeight(), getViewMargin(), getViewGravity(), getLayoutPadding() ) { @Override public WeekdaysAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final WeekdaysAdapter.ViewHolder vh = super.onCreateViewHolder(parent, viewType); vh.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int pos = vh.getAdapterPosition(); if (pos != RecyclerView.NO_POSITION && pos < getItemCount()) { mCallback.onWeekdaysItemClicked(mAttachId,toggleSelected(getValueAt(pos))); notifyItemChanged(pos); mCallback.onWeekdaysSelected(mAttachId,getWeekdaysItems()); } } }); return vh; } }; } //INIT CODE private boolean attach() { final View attachView = mParentView == null ? mContext.findViewById(mAttachId) : mParentView.findViewById(mAttachId); if (attachView instanceof RecyclerView) { mRecyclerView = (RecyclerView) attachView; } else if (attachView instanceof ViewStub) { ViewStub stub = (ViewStub) attachView; stub.setLayoutResource(R.layout.weekdays_recycler_view); stub.setInflatedId(mAttachId); mRecyclerView = (RecyclerView) stub.inflate(); } else { throw new IllegalStateException("Weeekdays Buttons was unable to attach to your Layout, required [ViewStub],[recycleView] or ['parent' View] doesn't exist."); } if (mRecyclerView != null) { getDrawableProvider(); if (mTextDrawableType == WeekdaysDrawableProvider.MW_MULTIPLE_LETTERS && mNumberOfLetters < 2) mNumberOfLetters = 2; int position = 0; for (Map.Entry<Integer, String> map : getDays().entrySet()) { String day = map.getValue(); int calendarDayId = map.getKey(); if (!TextUtils.isEmpty(day)) { WeekdaysDataItem item = itemFromType(position, calendarDayId, day, getSelectedDays().get(calendarDayId)); if (getWeekdaysCount() == position) getWeekdaysItems().add(item); else getWeekdaysItems().set(position, item); position++; } } initRecyclerView(mContext); return true; } return false; } @UiThread public void saveState(@NonNull String tag, Bundle dest) { dest.putParcelable("weekdays_state_" + tag, this); } @UiThread public static WeekdaysDataSource restoreState(@NonNull String tag, Bundle source, AppCompatActivity context, Callback callback, TextDrawableListener drawableListener) { if (source == null || !source.containsKey("weekdays_state_" + tag)) return null; WeekdaysDataSource weekdaysDataSource = source.getParcelable("weekdays_state_" + tag); if (weekdaysDataSource != null) { weekdaysDataSource.mContext = context; if (weekdaysDataSource.mIsVisible) { weekdaysDataSource.setOnTextDrawableListener(drawableListener); // weekdaysDataSource.reset(context); weekdaysDataSource.start(callback); } } return weekdaysDataSource; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeList(this.mDataSource); dest.writeSerializable(this.locale); dest.writeInt(this.mAttachId); dest.writeInt(this.mWeekdayLayoutId); dest.writeInt(this.mWeekdayViewId); dest.writeInt(this.mBackgroundColor); dest.writeInt(this.mTextColorSelected); dest.writeInt(this.mTextColorUnselected); dest.writeInt(this.mSelectedColor); dest.writeInt(this.mUnselectedColor); dest.writeByte(mIsVisible ? (byte) 1 : (byte) 0); dest.writeByte(mFillWidth ? (byte) 1 : (byte) 0); dest.writeByte(mIsAllDaysSelected ? (byte) 1 : (byte) 0); dest.writeInt(this.mFirstDayOfWeek); dest.writeInt(this.mTextDrawableType); dest.writeInt(this.mNumberOfLetters); dest.writeInt(this.mViewWidth); dest.writeInt(this.mViewHeight); dest.writeInt(this.mViewMargin); dest.writeInt(this.mViewGravity); dest.writeInt(this.mLayoutPadding); dest.writeByte(mNestedScrollEnable ? (byte) 1 : (byte) 0); } protected WeekdaysDataSource(Parcel in) { this.mDataSource = new ArrayList<>(); in.readList(this.mDataSource, List.class.getClassLoader()); this.locale = (Locale) in.readSerializable(); this.mAttachId = in.readInt(); this.mWeekdayLayoutId = in.readInt(); this.mWeekdayViewId = in.readInt(); this.mBackgroundColor = in.readInt(); this.mTextColorSelected = in.readInt(); this.mTextColorUnselected = in.readInt(); this.mSelectedColor = in.readInt(); this.mUnselectedColor = in.readInt(); this.mIsVisible = in.readByte() != 0; this.mFillWidth = in.readByte() != 0; this.mIsAllDaysSelected = in.readByte() != 0; this.mFirstDayOfWeek = in.readInt(); this.mTextDrawableType = in.readInt(); this.mNumberOfLetters = in.readInt(); this.mViewWidth= in.readInt(); this.mViewHeight= in.readInt(); this.mViewMargin= in.readInt(); this.mViewGravity= in.readInt(); this.mLayoutPadding= in.readInt(); this.mNestedScrollEnable = in.readByte() != 0; } public static final Parcelable.Creator<WeekdaysDataSource> CREATOR = new Parcelable.Creator<WeekdaysDataSource>() { public WeekdaysDataSource createFromParcel(Parcel source) { return new WeekdaysDataSource(source); } public WeekdaysDataSource[] newArray(int size) { return new WeekdaysDataSource[size]; } }; }
package org.torquebox.core.runtime; import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.net.URISyntaxException; import java.util.ArrayList; 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 java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.jboss.logging.Logger; import org.jboss.msc.service.ServiceRegistry; import org.jboss.vfs.TempFileProvider; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jruby.CompatVersion; import org.jruby.Ruby; import org.jruby.RubyInstanceConfig; import org.jruby.RubyInstanceConfig.CompileMode; import org.jruby.RubyModule; import org.jruby.ast.executable.Script; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.Constants; import org.jruby.util.ClassCache; import org.torquebox.bootstrap.JRubyHomeLocator; import org.torquebox.core.pool.InstanceFactory; /** * Default Ruby runtime interpreter factory implementation. * * @author Bob McWhirter <bmcwhirt@redhat.com> */ public class RubyRuntimeFactory implements InstanceFactory<Ruby> { private static final Logger log = Logger.getLogger( "org.torquebox.core.runtime" ); /** Re-usable initializer. */ private RuntimeInitializer initializer; /** ClassLoader for interpreter. */ private ClassLoader classLoader; /** Shared interpreter class cache. */ private ClassCache<Script> classCache; /** Application name. */ private String applicationName; /** Load paths for the interpreter. */ private List<String> loadPaths; /** Output stream for the interpreter. */ private PrintStream outputStream = System.out; /** Error stream for the interpreter. */ private PrintStream errorStream = System.err; /** JRUBY_HOME. */ private String jrubyHome; /** GEM_PATH. */ private String gemPath; /** Should environment $JRUBY_HOME be considered? */ private boolean useJRubyHomeEnvVar = true; /** Additional application environment variables. */ private Map<String, String> applicationEnvironment; private Set<Ruby> undisposed = Collections.synchronizedSet( new HashSet<Ruby>() ); /** Ruby compatibility version. */ private CompatVersion rubyVersion; /** JRuby compile mode. */ private CompileMode compileMode; private ServiceRegistry serviceRegistry; private Closeable mountedJRubyHome; /** * Construct. */ public RubyRuntimeFactory() { this( null ); } /** * Construct with an initializer. * * @param initializer * The initializer (or null) to use for each created runtime. */ public RubyRuntimeFactory(RuntimeInitializer initializer) { this.initializer = initializer; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getApplicationName() { return this.applicationName; } public void setGemPath(String gemPath) { this.gemPath = gemPath; } public String getGemPath() { return this.gemPath; } public void setJRubyHome(String jrubyHome) { this.jrubyHome = jrubyHome; } public String getJRubyHome() { return this.jrubyHome; } public void setUseJRubyHomeEnvVar(boolean useJRubyEnvVar) { this.useJRubyHomeEnvVar = useJRubyEnvVar; } public boolean useJRubyHomeEnvVar() { return this.useJRubyHomeEnvVar; } /** * Set the interpreter classloader. * * @param classLoader * The classloader. */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Retrieve the interpreter classloader. * * @return The classloader. */ public ClassLoader getClassLoader() { if (this.classLoader != null) { log.info( "Using configured classload: " + this.classLoader ); return this.classLoader; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { log.info( "using TCCL" ); return cl; } log.info( "Using our own classloader" ); return getClass().getClassLoader(); } /** * Set the Ruby compatibility version. * * @param rubyVersion * The version. */ public void setRubyVersion(CompatVersion rubyVersion) { this.rubyVersion = rubyVersion; } /** * Retrieve the Ruby compatibility version. * * @return The version. */ public CompatVersion getRubyVersion() { return this.rubyVersion; } /** * Set the compile mode. * * @param compileMode * The mode. */ public void setCompileMode(CompileMode compileMode) { this.compileMode = compileMode; } /** * Retrieve the compile mode. * * @return The mode. */ public CompileMode getCompileMode() { return this.compileMode; } /** * Set the application-specific environment additions. * * @param applicationEnvironment * The environment. */ public void setApplicationEnvironment(Map<String, String> applicationEnvironment) { this.applicationEnvironment = applicationEnvironment; } /** * Retrieve the application-specific environment additions. * * @return The environment. */ public Map<String, String> getApplicationEnvironment() { return this.applicationEnvironment; } /** * Create a new instance of a fully-initialized runtime. */ public Ruby createInstance(String contextInfo) throws Exception { RubyInstanceConfig config = new TorqueBoxRubyInstanceConfig(); config.setLoader( getClassLoader() ); // config.setClassCache( getClassCache() ); config.setLoadServiceCreator( new VFSLoadServiceCreator() ); if (this.rubyVersion != null) { config.setCompatVersion( this.rubyVersion ); } if (this.compileMode != null) { config.setCompileMode( this.compileMode ); } String jrubyHome = this.jrubyHome; if (jrubyHome == null) { jrubyHome = JRubyHomeLocator.determineJRubyHome( this.useJRubyHomeEnvVar ); if (jrubyHome == null) { jrubyHome = attemptMountJRubyHomeFromClassPath(); } } if (jrubyHome != null) { config.setJRubyHome( jrubyHome ); } config.setEnvironment( createEnvironment() ); config.setOutput( getOutput() ); config.setError( getError() ); List<String> loadPath = new ArrayList<String>(); if (this.loadPaths != null) { loadPath.addAll( this.loadPaths ); } config.setLoadPaths( loadPath ); long startTime = logRuntimeCreationStart( config, contextInfo ); Ruby runtime = null; try { runtime = Ruby.newInstance( config ); runtime.getLoadService().require( "java" ); prepareRuntime( runtime, contextInfo ); if (this.initializer != null) { ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( runtime.getJRubyClassLoader().getParent() ); this.initializer.initialize( runtime ); } finally { Thread.currentThread().setContextClassLoader( originalCl ); } } else { log.warn( "No initializer set for runtime" ); } performRuntimeInitialization( runtime ); } catch (Exception ex) { ex.printStackTrace(); log.error( "Failed to initialize runtime: ", ex ); } finally { if (runtime != null) { this.undisposed.add( runtime ); } logRuntimeCreationComplete( config, contextInfo, startTime ); } return runtime; } private String attemptMountJRubyHomeFromClassPath() throws URISyntaxException, IOException { String internalJRubyHome = RubyInstanceConfig.class.getResource( "/META-INF/jruby.home" ).toURI().getSchemeSpecificPart(); if (internalJRubyHome.startsWith( "file:" ) && internalJRubyHome.contains( "!/" )) { int slashLoc = internalJRubyHome.indexOf( '/' ); int bangLoc = internalJRubyHome.indexOf( '!' ); String jarPath = internalJRubyHome.substring( slashLoc, bangLoc ); String extraPath = internalJRubyHome.substring( bangLoc + 1 ); VirtualFile vfsJar = VFS.getChild( jarPath ); if (vfsJar.exists()) { if (!vfsJar.isDirectory()) { ScheduledExecutorService executor = Executors.newScheduledThreadPool( 1 ); TempFileProvider tempFileProvider = TempFileProvider.create( "jruby.home", executor ); this.mountedJRubyHome = VFS.mountZip( vfsJar, vfsJar, tempFileProvider ); } if (vfsJar.isDirectory()) { VirtualFile vfsJrubyHome = vfsJar.getChild( extraPath ); if (vfsJrubyHome.exists()) { return vfsJrubyHome.toURL().toExternalForm(); } } } } return null; } private long logRuntimeCreationStart(RubyInstanceConfig config, String contextInfo) { log.info( "Creating ruby runtime (ruby_version: " + config.getCompatVersion() + ", compile_mode: " + config.getCompileMode() + getFullContext( contextInfo ) + ")" ); return System.currentTimeMillis(); } private void logRuntimeCreationComplete(RubyInstanceConfig config, String contextInfo, long startTime) { long elapsedMillis = System.currentTimeMillis() - startTime; double elapsedSeconds = Math.floor( (elapsedMillis * 1.0) / 10.0 ) / 100; log.info( "Created ruby runtime (ruby_version: " + config.getCompatVersion() + ", compile_mode: " + config.getCompileMode() + getFullContext( contextInfo ) + ") in " + elapsedSeconds + "s" ); } protected String getFullContext(String contextInfo) { String fullContext = null; if (this.applicationName != null) { fullContext = "app: " + this.applicationName; } if (contextInfo != null) { if (fullContext != null) { fullContext += ", "; } else { fullContext = ""; } fullContext += "context: " + contextInfo; } if (fullContext == null) { fullContext = ""; } else { fullContext = ", " + fullContext; } return fullContext; } public synchronized void destroyInstance(Ruby instance) { if (undisposed.remove( instance )) { instance.tearDown( false ); } } private void performRuntimeInitialization(Ruby runtime) { runtime.evalScriptlet( "require %q(org/torquebox/core/runtime/runtime_initialization)\n" ); defineVersions( runtime ); setApplicationName( runtime ); } private void defineVersions(Ruby runtime) { RubyModule torqueBoxModule = runtime.getClassFromPath( "TorqueBox" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxModule, "define_versions", new Object[] { log }, void.class ); } private void setApplicationName(Ruby runtime) { RubyModule torqueBoxModule = runtime.getClassFromPath( "TorqueBox" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxModule, "application_name=", new Object[] { applicationName }, void.class ); } private void prepareRuntime(Ruby runtime, String contextInfo) { if ("1.6.3".equals( Constants.VERSION )) { log.info( "Disabling POSIX ENV passthrough for " + contextInfo + " runtime (TORQUE-497)" ); StringBuffer env_fix = new StringBuffer(); env_fix.append( "update_real_env_attr = org.jruby.RubyGlobal::StringOnlyRubyHash.java_class.declared_fields.find { |f| f.name == 'updateRealENV' }\n" ); env_fix.append( "update_real_env_attr.accessible = true\n" ); env_fix.append( "update_real_env_attr.set_value(ENV.to_java, false)\n" );; runtime.evalScriptlet( env_fix.toString() ); } runtime.getLoadService().require( "rubygems" ); runtime.evalScriptlet( "require %q(torquebox-vfs)" ); runtime.evalScriptlet( "require %q(torquebox-core)" ); injectServiceRegistry( runtime ); } private void injectServiceRegistry(Ruby runtime) { runtime.evalScriptlet( "require %q(torquebox/service_registry)" ); RubyModule torqueBoxServiceRegistry = runtime.getClassFromPath( "TorqueBox::ServiceRegistry" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxServiceRegistry, "service_registry=", new Object[] { this.serviceRegistry }, void.class ); } protected Map<String, String> createEnvironment() { Map<String, String> env = new HashMap<String, String>(); env.putAll( System.getenv() ); String path = (String) env.get( "PATH" ); if (path == null) { env.put( "PATH", "" ); } String gemPath = System.getProperty( "gem.path" ); if (gemPath == null) { gemPath = this.gemPath; } if ("default".equals( gemPath )) { env.remove( "GEM_PATH" ); env.remove( "GEM_HOME" ); gemPath = null; } if (gemPath != null) { env.put( "GEM_PATH", gemPath ); env.put( "GEM_HOME", gemPath ); } if (this.applicationEnvironment != null) { env.putAll( this.applicationEnvironment ); } return env; } /** * Set the interpreter output stream. * * @param outputStream * The output stream. */ public void setOutput(PrintStream outputStream) { this.outputStream = outputStream; } /** * Retrieve the interpreter output stream. * * @return The output stream. */ public PrintStream getOutput() { return this.outputStream; } /** * Set the interpreter error stream. * * @param errorStream * The error stream. */ public void setError(PrintStream errorStream) { this.errorStream = errorStream; } /** * Retrieve the interpreter error stream. * * @return The error stream. */ public PrintStream getError() { return this.errorStream; } /** * Set the interpreter load paths. * * <p> * Load paths may be either real filesystem paths or VFS URLs * </p> * * @param loadPaths * The list of load paths. */ public void setLoadPaths(List<String> loadPaths) { this.loadPaths = loadPaths; } /** * Retrieve the interpreter load paths. * * @return The list of load paths. */ public List<String> getLoadPaths() { return this.loadPaths; } public void create() { this.classCache = new ClassCache<Script>( getClassLoader() ); } public synchronized void destroy() { Set<Ruby> toDispose = new HashSet<Ruby>(); toDispose.addAll( this.undisposed ); for (Ruby ruby : toDispose) { destroyInstance( ruby ); } this.undisposed.clear(); if (this.mountedJRubyHome != null) { try { this.mountedJRubyHome.close(); } catch (IOException e) { // ignore } this.mountedJRubyHome = null; } } public ClassCache getClassCache() { return this.classCache; } public void setServiceRegistry(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } public ServiceRegistry getServiceRegistry() { return this.serviceRegistry; } }
package com.haulmont.chile.core.loader; import com.haulmont.bali.util.ReflectionHelper; import com.haulmont.chile.core.annotations.*; import com.haulmont.chile.core.datatypes.Datatype; import com.haulmont.chile.core.datatypes.Datatypes; import com.haulmont.chile.core.datatypes.impl.EnumerationImpl; import com.haulmont.chile.core.model.*; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.chile.core.model.impl.*; import com.haulmont.cuba.core.entity.annotation.SystemLevel; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.ClassMetadata; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import javax.annotation.Nullable; import java.io.IOException; import java.lang.reflect.*; import java.util.*; /** * @author krivopustov * @version $Id$ */ public class ChileAnnotationsLoader implements ClassMetadataLoader { private Log log = LogFactory.getLog(ChileAnnotationsLoader.class); protected Session session; protected String packageName; protected ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); protected MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver); public ChileAnnotationsLoader(Session session) { this.session = session; } @Override public Session loadPackage(String modelName, final String packageName) { this.packageName = packageName; List<MetadataObjectInitTask> tasks = new ArrayList<>(); final String packagePrefix = packageName.replace(".", "/") + "*.class"; String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + packagePrefix; Resource[] resources; try { resources = resourcePatternResolver.getResources(packageSearchPath); } catch (IOException e) { throw new RuntimeException(e); } List<Class<?>> annotated = getClasses(resources); for (Class<?> aClass : annotated) { if (aClass.getName().startsWith(packageName)) { tasks.addAll(__loadClass(modelName, aClass).getTasks()); } } for (MetadataObjectInitTask task : tasks) { task.execute(); } return session; } protected List<Class<?>> getClasses(Resource[] resources) { List<Class<?>> annotated = new ArrayList<>(); for (Resource resource : resources) { if (resource.isReadable()) { try { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName())) { ClassMetadata classMetadata = metadataReader.getClassMetadata(); Class c = ReflectionHelper.getClass(classMetadata.getClassName()); annotated.add(c); } } catch (IOException e) { throw new RuntimeException(e); } } } return annotated; } protected Class getTypeOverride(AnnotatedElement element) { return null; } protected boolean isMandatory(Field field) { com.haulmont.chile.core.annotations.MetaProperty metaPropertyAnnotation = field.getAnnotation(com.haulmont.chile.core.annotations.MetaProperty.class); return metaPropertyAnnotation != null && metaPropertyAnnotation.mandatory(); } protected boolean isMetaPropertyField(Field field) { return field.isAnnotationPresent(com.haulmont.chile.core.annotations.MetaProperty.class); } protected boolean isMetaPropertyMethod(Method method) { return method.isAnnotationPresent(com.haulmont.chile.core.annotations.MetaProperty.class); } protected MetaClassImpl createMetaClass(String modelName, String className) { MetaModel model = session.getModel(modelName); if (model == null) { model = new MetaModelImpl(session, modelName); } return new MetaClassImpl(model, className); } protected MetaClassImpl __createClass(Class<?> clazz, String modelName) { if (Object.class.equals(clazz)) return null; final com.haulmont.chile.core.annotations.MetaClass metaClassAnnotaion = clazz.getAnnotation(com.haulmont.chile.core.annotations.MetaClass.class); if (metaClassAnnotaion == null) { log.trace(String.format("Class '%s' isn't annotated as metadata entity, ignore it", clazz.getName())); return null; } String className = metaClassAnnotaion.name(); if (StringUtils.isEmpty(className)) { className = clazz.getSimpleName(); } return __createClass(clazz, modelName, className); } protected boolean isCollection(Field field) { final Class<?> type = field.getType(); return Collection.class.isAssignableFrom(type); } protected boolean isMap(Field field) { final Class<?> type = field.getType(); return Map.class.isAssignableFrom(type); } protected boolean isMap(Method method) { final Class<?> type = method.getReturnType(); return Map.class.isAssignableFrom(type); } protected boolean isCollection(Method method) { final Class<?> type = method.getReturnType(); return Collection.class.isAssignableFrom(type); } public MetadataObjectInfo<MetaClass> __loadClass(String modelName, Class<?> clazz) { final MetaClassImpl metaClass = __createClass(clazz, modelName); if (metaClass == null) return null; Collection<MetadataObjectInitTask> tasks = new ArrayList<>(); Collection<MetaClass> ancestors = metaClass.getAncestors(); for (MetaClass ancestor : ancestors) { initProperties(ancestor.getJavaClass(), ((MetaClassImpl) ancestor), tasks); } initProperties(clazz, metaClass, tasks); return new MetadataObjectInfo<MetaClass>(metaClass, tasks); } protected void initProperties(Class<?> clazz, MetaClassImpl metaClass, Collection<MetadataObjectInitTask> tasks) { if (!metaClass.getOwnProperties().isEmpty()) return; // load collection properties after non-collection in order to have all inverse properties loaded up ArrayList<Field> collectionProps = new ArrayList<>(); for (Field field : clazz.getDeclaredFields()) { if (field.isSynthetic()) continue; final String fieldName = field.getName(); if (isMetaPropertyField(field)) { MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(fieldName); if (property == null) { MetadataObjectInfo<MetaProperty> info; if (isCollection(field) || isMap(field)) { collectionProps.add(field); } else { info = __loadProperty(metaClass, field); tasks.addAll(info.getTasks()); final MetaProperty metaProperty = info.getObject(); onPropertyLoaded(metaProperty, field); } } else { log.warn("Field " + clazz.getSimpleName() + "." + field.getName() + " is not included in metadata because property " + property + " already exists"); } } } for (Field f : collectionProps) { MetadataObjectInfo<MetaProperty> info = __loadCollectionProperty(metaClass, f); tasks.addAll(info.getTasks()); final MetaProperty metaProperty = info.getObject(); onPropertyLoaded(metaProperty, f); } for (Method method : clazz.getDeclaredMethods()) { if (method.isSynthetic()) continue; String methodName = method.getName(); if (!methodName.startsWith("get") || method.getReturnType() == void.class) continue; if (isMetaPropertyMethod(method)) { String name = StringUtils.uncapitalize(methodName.substring(3)); MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(name); if (property == null) { MetadataObjectInfo<MetaProperty> info; if (isCollection(method) || isMap(method)) { throw new UnsupportedOperationException("Method-based properties don't support collections and maps"); } else { info = __loadProperty(metaClass, method, name); tasks.addAll(info.getTasks()); } final MetaProperty metaProperty = info.getObject(); onPropertyLoaded(metaProperty, method); } else { log.warn("Method " + clazz.getSimpleName() + "." + method.getName() + " is not included in metadata because property " + property + " already exists"); } } } } @Override public Session loadClass(String modelName, Class<?> clazz) { final MetadataObjectInfo<MetaClass> info = __loadClass(modelName, clazz); checkWarnings(info); return session; } protected void checkWarnings(MetadataObjectInfo<? extends MetadataObject> info) { if (info != null) { for (MetadataObjectInitTask task : info.getTasks()) { log.warn(task.getWarning()); } } } @Override public Session loadClass(String modelName, String className) { final Class<?> clazz = ReflectionHelper.getClass(className); final MetadataObjectInfo<MetaClass> info = __loadClass(modelName, clazz); checkWarnings(info); return session; } @Override public Session getSession() { return session; } protected void onPropertyLoaded(MetaProperty metaProperty, Field field) { SystemLevel systemLevel = field.getAnnotation(SystemLevel.class); if (systemLevel != null) { metaProperty.getAnnotations().put(SystemLevel.class.getName(), systemLevel.value()); } } private void onPropertyLoaded(MetaProperty metaProperty, Method method) { } protected void onClassLoaded(MetaClass metaClass, Class<?> clazz) { } protected MetadataObjectInfo<MetaProperty> __loadProperty(MetaClassImpl metaClass, Field field) { Collection<MetadataObjectInitTask> tasks = new ArrayList<>(); MetaPropertyImpl property = new MetaPropertyImpl(metaClass, field.getName()); Range.Cardinality cardinality = getCardinality(field); Map<String, Object> map = new HashMap<>(); map.put("cardinality", cardinality); boolean mandatory = isMandatory(field); map.put("mandatory", mandatory); Datatype datatype = getDatatype(field); map.put("datatype", datatype); Class<?> type; Class typeOverride = getTypeOverride(field); if (typeOverride != null) type = typeOverride; else type = field.getType(); MetadataObjectInfo<Range> info = __loadRange(property, type, map); final Range range = info.getObject(); if (range != null) { ((AbstractRange) range).setCardinality(cardinality); property.setRange(range); assignPropertyType(field, property, range); } property.setMandatory(mandatory); property.setReadOnly(!setterExists(field)); property.setAnnotatedElement(field); property.setDeclaringClass(field.getDeclaringClass()); if (info.getObject() != null && info.getObject().isEnum()) { property.setJavaType(info.getObject().asEnumeration().getJavaClass()); } else { property.setJavaType(field.getType()); } tasks.addAll(info.getTasks()); return new MetadataObjectInfo<MetaProperty>(property, tasks); } @Nullable protected Datatype getDatatype(AnnotatedElement annotatedElement) { com.haulmont.chile.core.annotations.MetaProperty annotation = annotatedElement.getAnnotation(com.haulmont.chile.core.annotations.MetaProperty.class); return annotation != null && !annotation.datatype().equals("") ? Datatypes.get(annotation.datatype()) : null; } private boolean setterExists(Field field) { String name = "set" + StringUtils.capitalize(field.getName()); Method[] methods = field.getDeclaringClass().getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(name)) return true; } return false; } protected MetadataObjectInfo<MetaProperty> __loadProperty(MetaClassImpl metaClass, Method method, String name) { Collection<MetadataObjectInitTask> tasks = new ArrayList<>(); MetaPropertyImpl property = new MetaPropertyImpl(metaClass, name); Map<String, Object> map = new HashMap<>(); map.put("cardinality", Range.Cardinality.NONE); map.put("mandatory", false); Datatype datatype = getDatatype(method); map.put("datatype", datatype); Class<?> type; Class typeOverride = getTypeOverride(method); if (typeOverride != null) type = typeOverride; else type = method.getReturnType(); MetadataObjectInfo<Range> info = __loadRange(property, type, map); final Range range = info.getObject(); if (range != null) { ((AbstractRange) range).setCardinality(Range.Cardinality.NONE); property.setRange(range); assignPropertyType(method, property, range); } property.setMandatory(false); property.setReadOnly(!setterExists(method)); property.setAnnotatedElement(method); property.setDeclaringClass(method.getDeclaringClass()); property.setJavaType(method.getReturnType()); tasks.addAll(info.getTasks()); return new MetadataObjectInfo<MetaProperty>(property, tasks); } private boolean setterExists(Method getter) { if (getter.getName().startsWith("get")) { String setterName = "set" + getter.getName().substring(3); Method[] methods = getter.getDeclaringClass().getDeclaredMethods(); for (Method method : methods) { if (setterName.equals(method.getName())) { return true; } } } return false; } protected void assignPropertyType(AnnotatedElement field, MetaProperty property, Range range) { if (range.isClass()) { Composition composition = field.getAnnotation(Composition.class); if (composition != null) { ((MetaPropertyImpl) property).setType(MetaProperty.Type.COMPOSITION); } else { ((MetaPropertyImpl) property).setType(MetaProperty.Type.ASSOCIATION); } } else if (range.isDatatype()) { ((MetaPropertyImpl) property).setType(MetaProperty.Type.DATATYPE); } else if (range.isEnum()) { ((MetaPropertyImpl) property).setType(MetaProperty.Type.ENUM); } else { throw new UnsupportedOperationException(); } } @SuppressWarnings({"unchecked"}) protected MetadataObjectInfo<Range> __loadRange(MetaProperty metaProperty, Class type, Map<String, Object> map) { Datatype datatype = (Datatype) map.get("datatype"); if (datatype != null) { return new MetadataObjectInfo<Range>(new DatatypeRange(datatype)); } datatype = Datatypes.get(type); if (datatype != null) { final MetaClass metaClass = metaProperty.getDomain(); final Class javaClass = metaClass.getJavaClass(); try { final String name = "get" + StringUtils.capitalize(metaProperty.getName()); final Method method = javaClass.getMethod(name); final Class<Enum> returnType = (Class<Enum>) method.getReturnType(); if (returnType.isEnum()) { return new MetadataObjectInfo<Range>(new EnumerationRange(new EnumerationImpl<>(returnType))); } } catch (NoSuchMethodException e) { // ignore } return new MetadataObjectInfo<Range>(new DatatypeRange(datatype)); } else if (type.isEnum()) { return new MetadataObjectInfo<Range>(new EnumerationRange(new EnumerationImpl<Enum>(type))); } else { MetaClassImpl rangeClass = (MetaClassImpl) session.getClass(type); if (rangeClass != null) { return new MetadataObjectInfo<Range>(new ClassRange(rangeClass)); } else { return new MetadataObjectInfo<>(null, Collections.singletonList(new RangeInitTask(metaProperty, type, map))); } } } protected Class getFieldType(Field field) { Type genericType = field.getGenericType(); Class type; if (genericType instanceof ParameterizedType) { Type[] types = ((ParameterizedType) genericType).getActualTypeArguments(); if (Map.class.isAssignableFrom(field.getType())) type = (Class<?>) types[1]; else type = (Class<?>) types[0]; } else { type = getFieldTypeAccordingAnnotations(field); } if (type == null) throw new IllegalArgumentException("Field " + field + " must either be of parameterized type or have a JPA annotation declaring a targetEntity"); return type; } protected Class getFieldTypeAccordingAnnotations(Field field) { throw new UnsupportedOperationException(); } protected Range.Cardinality getCardinality(Field field) { Class<?> type = field.getType(); if (Collection.class.isAssignableFrom(type)) { return Range.Cardinality.ONE_TO_MANY; } else if (type.isPrimitive() || type.equals(String.class) || Number.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type) || UUID.class.isAssignableFrom(type)) { return Range.Cardinality.NONE; } else return Range.Cardinality.MANY_TO_ONE; } protected String getInverseField(Field field) { return null; } protected MetadataObjectInfo<MetaProperty> __loadCollectionProperty(MetaClassImpl metaClass, Field field) { Collection<MetadataObjectInitTask> tasks = new ArrayList<>(); MetaPropertyImpl property = new MetaPropertyImpl(metaClass, field.getName()); Class type = getFieldType(field); Range.Cardinality cardinality = getCardinality(field); boolean ordered = isOrdered(field); boolean mandatory = isMandatory(field); String inverseField = getInverseField(field); Map<String, Object> map = new HashMap<>(); map.put("cardinality", cardinality); map.put("ordered", ordered); map.put("mandatory", mandatory); if (inverseField != null) map.put("inverseField", inverseField); MetadataObjectInfo<Range> info = __loadRange(property, type, map); Range range = info.getObject(); if (range != null) { ((AbstractRange) range).setCardinality(cardinality); ((AbstractRange) range).setOrdered(ordered); property.setRange(range); assignPropertyType(field, property, range); assignInverse(property, range, inverseField); } property.setMandatory(mandatory); tasks.addAll(info.getTasks()); property.setAnnotatedElement(field); property.setDeclaringClass(field.getDeclaringClass()); property.setJavaType(field.getType()); return new MetadataObjectInfo<MetaProperty>(property, tasks); } private void assignInverse(MetaPropertyImpl property, Range range, String inverseField) { if (inverseField == null) return; if (!range.isClass()) throw new IllegalArgumentException("Range of class type expected"); MetaClass metaClass = range.asClass(); MetaProperty inverseProp = metaClass.getProperty(inverseField); if (inverseProp == null) throw new RuntimeException(String.format( "Unable to assign inverse property '%s' for '%s'", inverseField, property)); property.setInverse(inverseProp); } protected boolean isOrdered(Field field) { final Class<?> type = field.getType(); return List.class.isAssignableFrom(type) || Set.class.isAssignableFrom(type); } protected MetaClassImpl __createClass(Class<?> clazz, String modelName, String className) { MetaClassImpl metaClass = (MetaClassImpl) session.getClass(clazz); if (metaClass != null) { return metaClass; } else if (packageName == null || clazz.getName().startsWith(packageName)) { metaClass = createMetaClass(modelName, className); metaClass.setJavaClass(clazz); final Class<?> ancestor = clazz.getSuperclass(); if (ancestor != null) { MetaClass ancestorClass = __createClass(ancestor, modelName); if (ancestorClass != null) { metaClass.addAncestor(ancestorClass); } } onClassLoaded(metaClass, clazz); return metaClass; } else { return null; } } protected class RangeInitTask implements MetadataObjectInitTask { private MetaProperty metaProperty; private Class rangeClass; private Map<String, Object> map; public RangeInitTask(MetaProperty metaProperty, Class rangeClass, Map<String, Object> map) { this.metaProperty = metaProperty; this.rangeClass = rangeClass; this.map = map; } @Override public String getWarning() { return String.format( "Range for propery '%s' wasn't initialized (range class '%s')", metaProperty.getName(), rangeClass.getName()); } @Override public void execute() { final MetaClass rangeClass = session.getClass(this.rangeClass); if (rangeClass == null) { throw new IllegalStateException( String.format("Can't find range class '%s' for property '%s.%s'", this.rangeClass.getName(), metaProperty.getDomain(), metaProperty.getName())); } else { final ClassRange range = new ClassRange(rangeClass); Range.Cardinality cardinality = (Range.Cardinality) map.get("cardinality"); range.setCardinality(cardinality); if (Range.Cardinality.ONE_TO_MANY.equals(cardinality) || Range.Cardinality.MANY_TO_MANY.equals(cardinality)) { range.setOrdered((Boolean) map.get("ordered")); } final Boolean mandatory = (Boolean) map.get("mandatory"); if (mandatory != null) { ((MetaPropertyImpl) metaProperty).setMandatory(mandatory); } ((MetaPropertyImpl) metaProperty).setRange(range); assignPropertyType(metaProperty.getAnnotatedElement(), metaProperty, range); assignInverse((MetaPropertyImpl) metaProperty, range, (String) map.get("inverseField")); } } } }
package org.testcontainers.containers; import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.core.command.ExecStartResultCallback; import lombok.SneakyThrows; import org.testcontainers.utility.Base58; import org.testcontainers.utility.TestcontainersConfiguration; import java.util.concurrent.TimeUnit; /** * This container wraps Confluent Kafka and Zookeeper (optionally) * */ public class KafkaContainer extends GenericContainer<KafkaContainer> { public static final int KAFKA_PORT = 9093; public static final int ZOOKEEPER_PORT = 2181; private static final int PORT_NOT_ASSIGNED = -1; protected String externalZookeeperConnect = null; private int port = PORT_NOT_ASSIGNED; public KafkaContainer() { this("5.2.1"); } public KafkaContainer(String confluentPlatformVersion) { super(TestcontainersConfiguration.getInstance().getKafkaImage() + ":" + confluentPlatformVersion); // TODO Only for backward compatibility withNetwork(Network.newNetwork()); withNetworkAliases("kafka-" + Base58.randomString(6)); withExposedPorts(KAFKA_PORT); // Use two listeners with different names, it will force Kafka to communicate with itself via internal // listener when KAFKA_INTER_BROKER_LISTENER_NAME is set, otherwise Kafka will try to use the advertised listener withEnv("KAFKA_LISTENERS", "PLAINTEXT://0.0.0.0:" + KAFKA_PORT + ",BROKER://0.0.0.0:9092"); withEnv("KAFKA_LISTENER_SECURITY_PROTOCOL_MAP", "BROKER:PLAINTEXT,PLAINTEXT:PLAINTEXT"); withEnv("KAFKA_INTER_BROKER_LISTENER_NAME", "BROKER"); withEnv("KAFKA_BROKER_ID", "1"); withEnv("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", "1"); withEnv("KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS", "1"); withEnv("KAFKA_LOG_FLUSH_INTERVAL_MESSAGES", Long.MAX_VALUE + ""); withEnv("KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS", "0"); } public KafkaContainer withEmbeddedZookeeper() { externalZookeeperConnect = null; return self(); } public KafkaContainer withExternalZookeeper(String connectString) { externalZookeeperConnect = connectString; return self(); } public String getBootstrapServers() { if (port == PORT_NOT_ASSIGNED) { throw new IllegalStateException("You should start Kafka container first"); } return String.format("PLAINTEXT://%s:%s", getContainerIpAddress(), port); } @Override protected void doStart() { withCommand("sleep infinity"); if (externalZookeeperConnect == null) { addExposedPort(ZOOKEEPER_PORT); } super.doStart(); } @Override @SneakyThrows protected void containerIsStarting(InspectContainerResponse containerInfo, boolean reused) { super.containerIsStarting(containerInfo, reused); port = getMappedPort(KAFKA_PORT); if (reused) { return; } final String zookeeperConnect; if (externalZookeeperConnect != null) { zookeeperConnect = externalZookeeperConnect; } else { zookeeperConnect = startZookeeper(); } String internalIp = containerInfo.getNetworkSettings().getIpAddress(); ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(getContainerId()) .withCmd("sh", "-c", "" + "export KAFKA_ZOOKEEPER_CONNECT=" + zookeeperConnect + "\n" + "export KAFKA_ADVERTISED_LISTENERS=" + getBootstrapServers() + "," + String.format("BROKER://%s:9092", internalIp) + "\n" + "/etc/confluent/docker/run" ) .exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback()).awaitStarted(10, TimeUnit.SECONDS); } @SneakyThrows(InterruptedException.class) private String startZookeeper() { ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(getContainerId()) .withCmd("sh", "-c", "" + "printf 'clientPort=" + ZOOKEEPER_PORT + "\ndataDir=/var/lib/zookeeper/data\ndataLogDir=/var/lib/zookeeper/log' > /zookeeper.properties\n" + "zookeeper-server-start /zookeeper.properties\n" ) .exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback()).awaitStarted(10, TimeUnit.SECONDS); return "localhost:" + ZOOKEEPER_PORT; } }
package entity.mob.projectiles; import indieQuest.entity.Entity; import indieQuest.graphics.Screen; import indieQuest.graphics.Sprite; public class Projectile extends Entity { public final int startX, startY; public double angle; public double x, y; public double targetX, targetY; public double speed, damage, range, fireRate; public Sprite sprite; public Projectile(int sx, int sy, double dir) { startX = sx; startY = sy; angle = dir; this.x = sx; this.y = sy; } public void render(Screen screen) { } public void move() { } protected double distance() { return 0; } }
package com.awplab.core.mongodb.command; import com.awplab.core.mongodb.Log; import com.awplab.core.mongodb.MDCLoggerAutoClosable; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.apache.log4j.MDC; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Command(scope = "mongo", name="add-log-entry") @Service public class AddLogEntryCommand implements Action { Logger logger = LoggerFactory.getLogger(AddLogEntryCommand.class); @Argument(index = 0, name = "level", description = "level", required = true) private String level; @Argument(index = 1, name = "entry", description = "log entry", required = true) private String logEntry; @Argument(index = 2, name = "database", description = "name of database", required = true) private String database; @Argument(index = 3, name = "collection", description = "name of collection", required = true) private String collection; @Override public Object execute() throws Exception { try (AutoCloseable ignored = new MDCLoggerAutoClosable(database, collection)) { if (level.equalsIgnoreCase("warn")) logger.warn(logEntry); if (level.equalsIgnoreCase("info")) logger.info(logEntry); if (level.equalsIgnoreCase("error")) logger.error(logEntry); if (level.equalsIgnoreCase("debug")) logger.debug(logEntry); } return null; } }
package org.hibernate.ogm.datastore.mongodb; import static org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoDBTupleSnapshot.SnapshotType.INSERT; import static org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoDBTupleSnapshot.SnapshotType.UPDATE; import static org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoHelpers.hasField; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bson.types.ObjectId; import org.hibernate.HibernateException; import org.hibernate.annotations.common.AssertionFailure; import org.hibernate.engine.spi.QueryParameters; import org.hibernate.ogm.datastore.document.options.AssociationStorageType; import org.hibernate.ogm.datastore.document.options.spi.AssociationStorageOption; import org.hibernate.ogm.datastore.map.impl.MapTupleSnapshot; import org.hibernate.ogm.datastore.mongodb.configuration.impl.MongoDBConfiguration; import org.hibernate.ogm.datastore.mongodb.dialect.impl.AssociationStorageStrategy; import org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoDBAssociationSnapshot; import org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoDBTupleSnapshot; import org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoDBTupleSnapshot.SnapshotType; import org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoHelpers; import org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider; import org.hibernate.ogm.datastore.mongodb.logging.impl.Log; import org.hibernate.ogm.datastore.mongodb.logging.impl.LoggerFactory; import org.hibernate.ogm.datastore.mongodb.options.AssociationDocumentType; import org.hibernate.ogm.datastore.mongodb.options.impl.AssociationDocumentStorageOption; import org.hibernate.ogm.datastore.mongodb.options.impl.ReadPreferenceOption; import org.hibernate.ogm.datastore.mongodb.options.impl.WriteConcernOption; import org.hibernate.ogm.datastore.mongodb.query.impl.MongoDBQueryDescriptor; import org.hibernate.ogm.datastore.mongodb.query.parsing.nativequery.impl.MongoDBQueryDescriptorBuilder; import org.hibernate.ogm.datastore.mongodb.query.parsing.nativequery.impl.NativeQueryParser; import org.hibernate.ogm.datastore.mongodb.type.impl.ByteStringType; import org.hibernate.ogm.datastore.mongodb.type.impl.ObjectIdGridType; import org.hibernate.ogm.datastore.mongodb.type.impl.StringAsObjectIdGridType; import org.hibernate.ogm.datastore.mongodb.type.impl.StringAsObjectIdType; import org.hibernate.ogm.dialect.batch.spi.BatchableGridDialect; import org.hibernate.ogm.dialect.batch.spi.InsertOrUpdateAssociationOperation; import org.hibernate.ogm.dialect.batch.spi.InsertOrUpdateTupleOperation; import org.hibernate.ogm.dialect.batch.spi.Operation; import org.hibernate.ogm.dialect.batch.spi.OperationsQueue; import org.hibernate.ogm.dialect.batch.spi.RemoveAssociationOperation; import org.hibernate.ogm.dialect.batch.spi.RemoveTupleOperation; import org.hibernate.ogm.dialect.identity.spi.IdentityColumnAwareGridDialect; import org.hibernate.ogm.dialect.optimisticlock.spi.OptimisticLockingAwareGridDialect; import org.hibernate.ogm.dialect.query.spi.BackendQuery; import org.hibernate.ogm.dialect.query.spi.ClosableIterator; import org.hibernate.ogm.dialect.query.spi.NoOpParameterMetadataBuilder; import org.hibernate.ogm.dialect.query.spi.ParameterMetadataBuilder; import org.hibernate.ogm.dialect.query.spi.QueryableGridDialect; import org.hibernate.ogm.dialect.spi.AssociationContext; import org.hibernate.ogm.dialect.spi.AssociationTypeContext; import org.hibernate.ogm.dialect.spi.BaseGridDialect; import org.hibernate.ogm.dialect.spi.DuplicateInsertPreventionStrategy; import org.hibernate.ogm.dialect.spi.ModelConsumer; import org.hibernate.ogm.dialect.spi.NextValueRequest; import org.hibernate.ogm.dialect.spi.TupleAlreadyExistsException; import org.hibernate.ogm.dialect.spi.TupleContext; import org.hibernate.ogm.model.key.spi.AssociationKey; import org.hibernate.ogm.model.key.spi.AssociationKeyMetadata; import org.hibernate.ogm.model.key.spi.EntityKey; import org.hibernate.ogm.model.key.spi.EntityKeyMetadata; import org.hibernate.ogm.model.key.spi.IdSourceKey; import org.hibernate.ogm.model.key.spi.RowKey; import org.hibernate.ogm.model.spi.Association; import org.hibernate.ogm.model.spi.AssociationKind; import org.hibernate.ogm.model.spi.Tuple; import org.hibernate.ogm.model.spi.TupleOperation; import org.hibernate.ogm.type.impl.StringCalendarDateType; import org.hibernate.ogm.type.spi.GridType; import org.hibernate.ogm.util.impl.CollectionHelper; import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.Type; import org.parboiled.Parboiled; import org.parboiled.errors.ErrorUtils; import org.parboiled.parserunners.RecoveringParseRunner; import org.parboiled.support.ParsingResult; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.DuplicateKeyException; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; /** * Each Tuple entry is stored as a property in a MongoDB document. * * Each association is stored in an association document containing three properties: * - the association table name (optionally) * - the RowKey column names and values * - the tuples as an array of elements * * Associations can be stored as: * - one MongoDB collection per association class. The collection name is prefixed. * - one MongoDB collection for all associations (the association table name property in then used) * - embed the collection info in the owning entity document is planned but not supported at the moment (OGM-177) * * Collection of embeddable are stored within the owning entity document under the * unqualified collection role * * In MongoDB is possible to batch operations but only for the creation of new documents * and only if they don't have invalid characters in the field name. * If these conditions are not met, the MongoDB mechanism for batch operations * is not going to be used. * * @author Guillaume Scheibel &lt;guillaume.scheibel@gmail.com&gt; * @author Alan Fitton &lt;alan at eth0.org.uk&gt; * @author Emmanuel Bernard &lt;emmanuel@hibernate.org&gt; */ public class MongoDBDialect extends BaseGridDialect implements QueryableGridDialect<MongoDBQueryDescriptor>, BatchableGridDialect, IdentityColumnAwareGridDialect, OptimisticLockingAwareGridDialect { public static final String ID_FIELDNAME = "_id"; public static final String PROPERTY_SEPARATOR = "."; public static final String ROWS_FIELDNAME = "rows"; public static final String TABLE_FIELDNAME = "table"; public static final String ASSOCIATIONS_COLLECTION_PREFIX = "associations_"; private static final Log log = LoggerFactory.getLogger(); private static final List<String> ROWS_FIELDNAME_LIST = Collections.singletonList( ROWS_FIELDNAME ); private final MongoDBDatastoreProvider provider; private final DB currentDB; public MongoDBDialect(MongoDBDatastoreProvider provider) { this.provider = provider; this.currentDB = this.provider.getDatabase(); } @Override public Tuple getTuple(EntityKey key, TupleContext tupleContext) { DBObject found = this.getObject( key, tupleContext ); if ( found != null ) { return new Tuple( new MongoDBTupleSnapshot( found, key.getMetadata(), UPDATE ) ); } else if ( isInTheQueue( key, tupleContext ) ) { // The key has not been inserted in the db but it is in the queue return new Tuple( new MongoDBTupleSnapshot( prepareIdObject( key ), key.getMetadata(), INSERT ) ); } else { return null; } } private boolean isInTheQueue(EntityKey key, TupleContext tupleContext) { OperationsQueue queue = tupleContext.getOperationsQueue(); return queue != null && queue.contains( key ); } @Override public Tuple createTuple(EntityKeyMetadata entityKeyMetadata, TupleContext tupleContext) { return new Tuple( new MongoDBTupleSnapshot( new BasicDBObject(), entityKeyMetadata, SnapshotType.INSERT ) ); } @Override public Tuple createTuple(EntityKey key, TupleContext tupleContext) { DBObject toSave = this.prepareIdObject( key ); return new Tuple( new MongoDBTupleSnapshot( toSave, key.getMetadata(), SnapshotType.INSERT ) ); } /** * Returns a {@link DBObject} representing the entity which embeds the specified association. */ private DBObject getEmbeddingEntity(AssociationKey key, AssociationContext associationContext) { DBObject embeddingEntityDocument = associationContext.getEntityTuple() != null ? ( (MongoDBTupleSnapshot) associationContext.getEntityTuple().getSnapshot() ).getDbObject() : null; if ( embeddingEntityDocument != null ) { return embeddingEntityDocument; } else { ReadPreference readPreference = getReadPreference( associationContext ); DBCollection collection = getCollection( key.getEntityKey() ); DBObject searchObject = prepareIdObject( key.getEntityKey() ); DBObject projection = getProjection( key, true ); return collection.findOne( searchObject, projection, readPreference ); } } private DBObject getObject(EntityKey key, TupleContext tupleContext) { ReadPreference readPreference = getReadPreference( tupleContext ); DBCollection collection = getCollection( key ); DBObject searchObject = prepareIdObject( key ); BasicDBObject projection = getProjection( tupleContext ); return collection.findOne( searchObject, projection, readPreference ); } private BasicDBObject getProjection(TupleContext tupleContext) { return getProjection( tupleContext.getSelectableColumns() ); } /** * Returns a projection object for specifying the fields to retrieve during a specific find operation. */ private BasicDBObject getProjection(List<String> fieldNames) { BasicDBObject projection = new BasicDBObject( fieldNames.size() ); for ( String column : fieldNames ) { projection.put( column, 1 ); } return projection; } private BasicDBObject prepareIdObject(EntityKey key) { return this.prepareIdObject( key.getColumnNames(), key.getColumnValues() ); } private BasicDBObject prepareIdObject(IdSourceKey key) { return this.prepareIdObject( key.getColumnNames(), key.getColumnValues() ); } private BasicDBObject prepareIdObject(String[] columnNames, Object[] columnValues) { BasicDBObject object; if ( columnNames.length == 1 ) { object = new BasicDBObject( ID_FIELDNAME, columnValues[0] ); } else { object = new BasicDBObject(); DBObject idObject = new BasicDBObject(); for ( int i = 0; i < columnNames.length; i++ ) { String columnName = columnNames[i]; Object columnValue = columnValues[i]; if ( columnName.contains( PROPERTY_SEPARATOR ) ) { int dotIndex = columnName.indexOf( PROPERTY_SEPARATOR ); String shortColumnName = columnName.substring( dotIndex + 1 ); idObject.put( shortColumnName, columnValue ); } else { idObject.put( columnNames[i], columnValue ); } } object.put( ID_FIELDNAME, idObject ); } return object; } private DBCollection getCollection(String table) { return currentDB.getCollection( table ); } private DBCollection getCollection(EntityKey key) { return getCollection( key.getTable() ); } private DBCollection getCollection(EntityKeyMetadata entityKeyMetadata) { return getCollection( entityKeyMetadata.getTable() ); } private DBCollection getAssociationCollection(AssociationKey key, AssociationStorageStrategy storageStrategy) { if ( storageStrategy == AssociationStorageStrategy.GLOBAL_COLLECTION ) { return getCollection( MongoDBConfiguration.DEFAULT_ASSOCIATION_STORE ); } else { return getCollection( ASSOCIATIONS_COLLECTION_PREFIX + key.getTable() ); } } private BasicDBObject getSubQuery(String operator, BasicDBObject query) { return query.get( operator ) != null ? (BasicDBObject) query.get( operator ) : new BasicDBObject(); } private void addSubQuery(String operator, BasicDBObject query, String column, Object value) { BasicDBObject subQuery = this.getSubQuery( operator, query ); query.append( operator, subQuery.append( column, value ) ); } @Override public void insertOrUpdateTuple(EntityKey key, Tuple tuple, TupleContext tupleContext) { BasicDBObject idObject = this.prepareIdObject( key ); DBObject updater = objectForUpdate( tuple, idObject ); WriteConcern writeConcern = getWriteConcern( tupleContext ); try { getCollection( key ).update( idObject, updater, true, false, writeConcern ); } catch ( DuplicateKeyException dke ) { throw new TupleAlreadyExistsException( key.getMetadata(), tuple, dke ); } } @Override //TODO deal with dotted column names once this method is used for ALL / Dirty optimistic locking public boolean updateTupleWithOptimisticLock(EntityKey entityKey, Tuple oldLockState, Tuple tuple, TupleContext tupleContext) { BasicDBObject idObject = this.prepareIdObject( entityKey ); for ( String versionColumn : oldLockState.getColumnNames() ) { idObject.put( versionColumn, oldLockState.get( versionColumn ) ); } DBObject updater = objectForUpdate( tuple, idObject ); DBObject doc = getCollection( entityKey ).findAndModify( idObject, updater ); return doc != null; } @Override public void insertTuple(EntityKeyMetadata entityKeyMetadata, Tuple tuple, TupleContext tupleContext) { WriteConcern writeConcern = getWriteConcern( tupleContext ); DBObject objectWithId = insertDBObject( entityKeyMetadata, tuple, writeConcern ); String idColumnName = entityKeyMetadata.getColumnNames()[0]; tuple.put( idColumnName, objectWithId.get( ID_FIELDNAME ) ); } /* * Insert the tuple and return an object containing the id in the field ID_FIELDNAME */ private DBObject insertDBObject(EntityKeyMetadata entityKeyMetadata, Tuple tuple, WriteConcern writeConcern) { DBObject dbObject = objectForInsert( tuple, ( (MongoDBTupleSnapshot) tuple.getSnapshot() ).getDbObject() ); getCollection( entityKeyMetadata ).insert( dbObject, writeConcern ); return dbObject; } /** * Creates a dbObject that can be pass to the mongoDB batch insert function */ private DBObject objectForInsert(Tuple tuple, DBObject dbObject) { MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot(); for ( TupleOperation operation : tuple.getOperations() ) { String column = operation.getColumn(); if ( notInIdField( snapshot, column ) ) { switch ( operation.getType() ) { case PUT: MongoHelpers.setValue( dbObject, column, operation.getValue() ); break; case PUT_NULL: case REMOVE: MongoHelpers.resetValue( dbObject, column ); break; } } } return dbObject; } private DBObject objectForUpdate(Tuple tuple, DBObject idObject) { MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot(); BasicDBObject updater = new BasicDBObject(); for ( TupleOperation operation : tuple.getOperations() ) { String column = operation.getColumn(); if ( notInIdField( snapshot, column ) ) { switch ( operation.getType() ) { case PUT: this.addSubQuery( "$set", updater, column, operation.getValue() ); break; case PUT_NULL: case REMOVE: this.addSubQuery( "$unset", updater, column, Integer.valueOf( 1 ) ); break; } } } if ( updater.size() == 0 ) { return idObject; } return updater; } private boolean notInIdField(MongoDBTupleSnapshot snapshot, String column) { return !column.equals( ID_FIELDNAME ) && !column.endsWith( PROPERTY_SEPARATOR + ID_FIELDNAME ) && !snapshot.isKeyColumn( column ); } @Override public void removeTuple(EntityKey key, TupleContext tupleContext) { DBCollection collection = getCollection( key ); DBObject toDelete = prepareIdObject( key ); WriteConcern writeConcern = getWriteConcern( tupleContext ); collection.remove( toDelete, writeConcern ); } @Override public boolean removeTupleWithOptimisticLock(EntityKey entityKey, Tuple oldLockState, TupleContext tupleContext) { DBObject toDelete = prepareIdObject( entityKey ); for ( String versionColumn : oldLockState.getColumnNames() ) { toDelete.put( versionColumn, oldLockState.get( versionColumn ) ); } DBCollection collection = getCollection( entityKey ); DBObject deleted = collection.findAndRemove( toDelete ); return deleted != null; } //not for embedded private DBObject findAssociation(AssociationKey key, AssociationContext associationContext, AssociationStorageStrategy storageStrategy) { ReadPreference readPreference = getReadPreference( associationContext ); final DBObject associationKeyObject = associationKeyToObject( key, storageStrategy ); return getAssociationCollection( key, storageStrategy ).findOne( associationKeyObject, getProjection( key, false ), readPreference ); } private DBObject getProjection(AssociationKey key, boolean embedded) { if ( embedded ) { return getProjection( Collections.singletonList( key.getMetadata().getCollectionRole() ) ); } else { return getProjection( ROWS_FIELDNAME_LIST ); } } private boolean isInTheQueue(EntityKey key, AssociationContext associationContext) { OperationsQueue queue = associationContext.getOperationsQueue(); return queue != null && queue.contains( key ); } @Override public Association getAssociation(AssociationKey key, AssociationContext associationContext) { AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( key, associationContext ); if ( isEmbeddedAssociation( key ) && isInTheQueue( key.getEntityKey(), associationContext ) ) { // The association is embedded and the owner of the association is in the insertion queue DBObject idObject = prepareIdObject( key.getEntityKey() ); return new Association( new MongoDBAssociationSnapshot( idObject, key, storageStrategy ) ); } // We need to execute the previous operations first or it won't be able to find the key that should have // been created executeBatch( associationContext.getOperationsQueue() ); if ( storageStrategy == AssociationStorageStrategy.IN_ENTITY ) { DBObject entity = getEmbeddingEntity( key, associationContext ); if ( entity != null && hasField( entity, key.getMetadata().getCollectionRole() ) ) { return new Association( new MongoDBAssociationSnapshot( entity, key, storageStrategy ) ); } else { return null; } } final DBObject result = findAssociation( key, associationContext, storageStrategy ); if ( result == null ) { return null; } else { return new Association( new MongoDBAssociationSnapshot( result, key, storageStrategy ) ); } } private boolean isEmbeddedAssociation(AssociationKey key) { return AssociationKind.EMBEDDED_COLLECTION == key.getMetadata().getAssociationKind(); } @Override public Association createAssociation(AssociationKey key, AssociationContext associationContext) { AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( key, associationContext ); DBObject document = storageStrategy == AssociationStorageStrategy.IN_ENTITY ? getEmbeddingEntity( key, associationContext ) : associationKeyToObject( key, storageStrategy ); return new Association( new MongoDBAssociationSnapshot( document, key, storageStrategy ) ); } /** * Returns the rows of the given association as to be stored in the database. Elements of the returned list are * either * <ul> * <li>plain values such as {@code String}s, {@code int}s etc. in case there is exactly one row key column which is * not part of the association key (in this case we don't need to persist the key name as it can be restored from * the association key upon loading) or</li> * <li>{@code DBObject}s with keys/values for all row key columns which are not part of the association key</li> * </ul> */ private List<?> getAssociationRows(Association association, AssociationKey key) { List<Object> rows = new ArrayList<Object>(); for ( RowKey rowKey : association.getKeys() ) { rows.add( getAssociationRow( association.get( rowKey ), key ) ); } return rows; } private Object getAssociationRow(Tuple row, AssociationKey associationKey) { String[] rowKeyColumnsToPersist = associationKey.getMetadata().getColumnsWithoutKeyColumns( row.getColumnNames() ); // return value itself if there is only a single column to store if ( rowKeyColumnsToPersist.length == 1 ) { return row.get( rowKeyColumnsToPersist[0] ); } // otherwise a DBObject with the row contents else { DBObject rowObject = new BasicDBObject( rowKeyColumnsToPersist.length ); for ( String column : rowKeyColumnsToPersist ) { Object value = row.get( column ); if ( value != null ) { MongoHelpers.setValue( rowObject, column, value ); } } return rowObject; } } @Override public void insertOrUpdateAssociation(AssociationKey key, Association association, AssociationContext associationContext) { DBCollection collection; DBObject query; MongoDBAssociationSnapshot assocSnapshot = (MongoDBAssociationSnapshot) association.getSnapshot(); String associationField; AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( key, associationContext ); WriteConcern writeConcern = getWriteConcern( associationContext ); List<?> rows = getAssociationRows( association, key ); Object toStore = key.getMetadata().isOneToOne() ? rows.get( 0 ) : rows; if ( storageStrategy == AssociationStorageStrategy.IN_ENTITY ) { collection = this.getCollection( key.getEntityKey() ); query = this.prepareIdObject( key.getEntityKey() ); associationField = key.getMetadata().getCollectionRole(); //TODO would that fail if getCollectionRole has dots? ( (MongoDBTupleSnapshot) associationContext.getEntityTuple().getSnapshot() ).getDbObject().put( key.getMetadata().getCollectionRole(), toStore ); } else { collection = getAssociationCollection( key, storageStrategy ); query = assocSnapshot.getQueryObject(); associationField = ROWS_FIELDNAME; } DBObject update = new BasicDBObject( "$set", new BasicDBObject( associationField, toStore ) ); collection.update( query, update, true, false, writeConcern ); } @Override public void removeAssociation(AssociationKey key, AssociationContext associationContext) { AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( key, associationContext ); WriteConcern writeConcern = getWriteConcern( associationContext ); if ( storageStrategy == AssociationStorageStrategy.IN_ENTITY ) { DBObject entity = this.prepareIdObject( key.getEntityKey() ); if ( entity != null ) { BasicDBObject updater = new BasicDBObject(); addSubQuery( "$unset", updater, key.getMetadata().getCollectionRole(), Integer.valueOf( 1 ) ); DBObject dbObject = getEmbeddingEntity( key, associationContext ); if ( dbObject != null ) { dbObject.removeField( key.getMetadata().getCollectionRole() ); getCollection( key.getEntityKey() ).update( entity, updater, true, false, writeConcern ); } } } else { DBCollection collection = getAssociationCollection( key, storageStrategy ); DBObject query = associationKeyToObject( key, storageStrategy ); int nAffected = collection.remove( query, writeConcern ).getN(); log.removedAssociation( nAffected ); } } @Override public Number nextValue(NextValueRequest request) { DBCollection currentCollection = getCollection( request.getKey().getTable() ); DBObject query = this.prepareIdObject( request.getKey() ); //all columns should match to find the value String valueColumnName = request.getKey().getMetadata().getValueColumnName(); BasicDBObject update = new BasicDBObject(); //FIXME how to set the initialValue if the document is not present? It seems the inc value is used as initial new value Integer incrementObject = Integer.valueOf( request.getIncrement() ); this.addSubQuery( "$inc", update, valueColumnName, incrementObject ); DBObject result = currentCollection.findAndModify( query, null, null, false, update, false, true ); Object idFromDB; idFromDB = result == null ? null : result.get( valueColumnName ); if ( idFromDB == null ) { //not inserted yet so we need to add initial value to increment to have the right next value in the DB //FIXME that means there is a small hole as when there was not value in the DB, we do add initial value in a non atomic way BasicDBObject updateForInitial = new BasicDBObject(); this.addSubQuery( "$inc", updateForInitial, valueColumnName, request.getInitialValue() ); currentCollection.findAndModify( query, null, null, false, updateForInitial, false, true ); idFromDB = request.getInitialValue(); //first time we ask this value } else { idFromDB = result.get( valueColumnName ); } if ( idFromDB.getClass().equals( Integer.class ) || idFromDB.getClass().equals( Long.class ) ) { Number id = (Number) idFromDB; //idFromDB is the one used and the BD contains the next available value to use return id; } else { throw new HibernateException( "Cannot increment a non numeric field" ); } } @Override public boolean isStoredInEntityStructure(AssociationKeyMetadata associationKeyMetadata, AssociationTypeContext associationTypeContext) { return getAssociationStorageStrategy( associationKeyMetadata, associationTypeContext ) == AssociationStorageStrategy.IN_ENTITY; } @Override public GridType overrideType(Type type) { // Override handling of calendar types if ( type == StandardBasicTypes.CALENDAR || type == StandardBasicTypes.CALENDAR_DATE ) { return StringCalendarDateType.INSTANCE; } else if ( type == StandardBasicTypes.BYTE ) { return ByteStringType.INSTANCE; } else if ( type.getReturnedClass() == ObjectId.class ) { return ObjectIdGridType.INSTANCE; } else if ( type instanceof StringAsObjectIdType ) { return StringAsObjectIdGridType.INSTANCE; } return null; // all other types handled as in hibernate-ogm-core } @Override public void forEachTuple(ModelConsumer consumer, EntityKeyMetadata... entityKeyMetadatas) { DB db = provider.getDatabase(); for ( EntityKeyMetadata entityKeyMetadata : entityKeyMetadatas ) { DBCollection collection = db.getCollection( entityKeyMetadata.getTable() ); for ( DBObject dbObject : collection.find() ) { consumer.consume( new Tuple( new MongoDBTupleSnapshot( dbObject, entityKeyMetadata, UPDATE ) ) ); } } } @Override public ClosableIterator<Tuple> executeBackendQuery(BackendQuery<MongoDBQueryDescriptor> backendQuery, QueryParameters queryParameters) { MongoDBQueryDescriptor queryDescriptor = backendQuery.getQuery(); EntityKeyMetadata entityKeyMetadata = backendQuery.getSingleEntityKeyMetadataOrNull(); String collectionName = getCollectionName( backendQuery, queryDescriptor, entityKeyMetadata ); DBCollection collection = provider.getDatabase().getCollection( collectionName ); switch( queryDescriptor.getOperation() ) { case FIND: return doFind( queryDescriptor, queryParameters, collection, entityKeyMetadata ); case COUNT: return doCount( queryDescriptor, collection ); default: throw new IllegalArgumentException( "Unexpected query operation: " + queryDescriptor ); } } @Override public MongoDBQueryDescriptor parseNativeQuery(String nativeQuery) { NativeQueryParser parser = Parboiled.createParser( NativeQueryParser.class ); ParsingResult<MongoDBQueryDescriptorBuilder> parseResult = new RecoveringParseRunner<MongoDBQueryDescriptorBuilder>( parser.Query() ) .run( nativeQuery ); if (parseResult.hasErrors() ) { throw new IllegalArgumentException( "Unsupported native query: " + ErrorUtils.printParseErrors( parseResult.parseErrors ) ); } return parseResult.resultValue.build(); } @Override public DuplicateInsertPreventionStrategy getDuplicateInsertPreventionStrategy(EntityKeyMetadata entityKeyMetadata) { return DuplicateInsertPreventionStrategy.NATIVE; } private ClosableIterator<Tuple> doFind(MongoDBQueryDescriptor query, QueryParameters queryParameters, DBCollection collection, EntityKeyMetadata entityKeyMetadata) { DBCursor cursor = collection.find( query.getCriteria(), query.getProjection() ); if ( query.getOrderBy() != null ) { cursor.sort( query.getOrderBy() ); } // apply firstRow/maxRows if present if ( queryParameters.getRowSelection().getFirstRow() != null ) { cursor.skip( queryParameters.getRowSelection().getFirstRow() ); } if ( queryParameters.getRowSelection().getMaxRows() != null ) { cursor.limit( queryParameters.getRowSelection().getMaxRows() ); } return new MongoDBResultsCursor( cursor, entityKeyMetadata ); } private ClosableIterator<Tuple> doCount(MongoDBQueryDescriptor query, DBCollection collection) { long count = collection.count( query.getCriteria() ); MapTupleSnapshot snapshot = new MapTupleSnapshot( Collections.<String, Object>singletonMap( "n", count ) ); return CollectionHelper.newClosableIterator( Collections.singletonList( new Tuple( snapshot ) ) ); } /** * Returns the name of the MongoDB collection to execute the given query against. Will either be retrieved * <ul> * <li>from the given query descriptor (in case the query has been translated from JP-QL or it is a native query * using the extended syntax {@code db.<COLLECTION>.<OPERATION>(...)}</li> * <li>or from the single mapped entity type if it is a native query using the criteria-only syntax * * @param customQuery the original query to execute * @param queryDescriptor descriptor for the query * @param entityKeyMetadata meta-data in case this is a query with exactly one entity return * @return the name of the MongoDB collection to execute the given query against */ private String getCollectionName(BackendQuery<?> customQuery, MongoDBQueryDescriptor queryDescriptor, EntityKeyMetadata entityKeyMetadata) { if ( queryDescriptor.getCollectionName() != null ) { return queryDescriptor.getCollectionName(); } else if ( entityKeyMetadata != null ) { return entityKeyMetadata.getTable(); } else { throw log.unableToDetermineCollectionName( customQuery.getQuery().toString() ); } } private DBObject associationKeyToObject(AssociationKey key, AssociationStorageStrategy storageStrategy) { if ( storageStrategy == AssociationStorageStrategy.IN_ENTITY ) { throw new AssertionFailure( MongoHelpers.class.getName() + ".associationKeyToObject should not be called for associations embedded in entity documents"); } Object[] columnValues = key.getColumnValues(); DBObject columns = new BasicDBObject( columnValues.length ); int i = 0; for ( String name : key.getColumnNames() ) { columns.put( name, columnValues[i++] ); } BasicDBObject idObject = new BasicDBObject( 1 ); if ( storageStrategy == AssociationStorageStrategy.GLOBAL_COLLECTION ) { columns.put( MongoDBDialect.TABLE_FIELDNAME, key.getTable() ); } idObject.put( MongoDBDialect.ID_FIELDNAME, columns ); return idObject; } private AssociationStorageStrategy getAssociationStorageStrategy(AssociationKey key, AssociationContext associationContext) { return getAssociationStorageStrategy( key.getMetadata(), associationContext.getAssociationTypeContext() ); } /** * Returns the {@link AssociationStorageStrategy} effectively applying for the given association. If a setting is * given via the option mechanism, that one will be taken, otherwise the default value as given via the * corresponding configuration property is applied. */ private AssociationStorageStrategy getAssociationStorageStrategy(AssociationKeyMetadata keyMetadata, AssociationTypeContext associationTypeContext) { AssociationStorageType associationStorage = associationTypeContext .getOptionsContext() .getUnique( AssociationStorageOption.class ); AssociationDocumentType associationDocumentType = associationTypeContext .getOptionsContext() .getUnique( AssociationDocumentStorageOption.class ); return AssociationStorageStrategy.getInstance( keyMetadata, associationStorage, associationDocumentType ); } @Override public void executeBatch(OperationsQueue queue) { if ( !queue.isClosed() ) { Operation operation = queue.poll(); Map<DBCollection, BatchInsertionTask> inserts = new HashMap<DBCollection, BatchInsertionTask>(); List<MongoDBTupleSnapshot> insertSnapshots = new ArrayList<MongoDBTupleSnapshot>(); while ( operation != null ) { if ( operation instanceof InsertOrUpdateTupleOperation ) { InsertOrUpdateTupleOperation update = (InsertOrUpdateTupleOperation) operation; executeBatchUpdate( inserts, update ); MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) update.getTuple().getSnapshot(); if ( snapshot.getSnapshotType() == INSERT ) { insertSnapshots.add( snapshot ); } } else if ( operation instanceof RemoveTupleOperation ) { RemoveTupleOperation tupleOp = (RemoveTupleOperation) operation; executeBatchRemove( inserts, tupleOp ); } else if ( operation instanceof InsertOrUpdateAssociationOperation ) { InsertOrUpdateAssociationOperation update = (InsertOrUpdateAssociationOperation) operation; executeBatchUpdateAssociation( inserts, update ); } else if ( operation instanceof RemoveAssociationOperation ) { RemoveAssociationOperation remove = (RemoveAssociationOperation) operation; removeAssociation( remove.getAssociationKey(), remove.getContext() ); } else { throw new UnsupportedOperationException( "Operation not supported on MongoDB: " + operation.getClass().getName() ); } operation = queue.poll(); } flushInserts( inserts ); for ( MongoDBTupleSnapshot insertSnapshot : insertSnapshots ) { insertSnapshot.setSnapshotType( UPDATE ); } queue.close(); } } private void executeBatchRemove(Map<DBCollection, BatchInsertionTask> inserts, RemoveTupleOperation tupleOperation) { EntityKey entityKey = tupleOperation.getEntityKey(); DBCollection collection = getCollection( entityKey ); BatchInsertionTask batchedInserts = inserts.get( collection ); if ( batchedInserts != null && batchedInserts.containsKey( entityKey ) ) { batchedInserts.remove( entityKey ); } else { removeTuple( entityKey, tupleOperation.getTupleContext() ); } } private void executeBatchUpdate(Map<DBCollection, BatchInsertionTask> inserts, InsertOrUpdateTupleOperation tupleOperation) { EntityKey entityKey = tupleOperation.getEntityKey(); Tuple tuple = tupleOperation.getTuple(); MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tupleOperation.getTuple().getSnapshot(); WriteConcern writeConcern = getWriteConcern( tupleOperation.getTupleContext() ); if ( INSERT == snapshot.getSnapshotType() ) { prepareForInsert( inserts, snapshot, entityKey, tuple, writeConcern ); } else { // Object already exists in the db or has invalid fields: insertOrUpdateTuple( entityKey, tuple, tupleOperation.getTupleContext() ); } } private void executeBatchUpdateAssociation(Map<DBCollection, BatchInsertionTask> inserts, InsertOrUpdateAssociationOperation updateOp) { AssociationKey associationKey = updateOp.getAssociationKey(); if ( isEmbeddedAssociation( associationKey ) ) { DBCollection collection = getCollection( associationKey.getEntityKey() ); BatchInsertionTask batchInserts = inserts.get( collection ); if ( batchInserts != null && batchInserts.containsKey( associationKey.getEntityKey() ) ) { // The owner of the association is in the insertion queue, // we are going to update it with the collection of elements WriteConcern writeConcern = getWriteConcern( updateOp.getContext() ); BatchInsertionTask insertTask = getOrCreateBatchInsertionTask( inserts, associationKey.getEntityKey().getMetadata(), collection, writeConcern ); DBObject documentForInsertion = insertTask.get( associationKey.getEntityKey() ); List<?> embeddedElements = getAssociationRows( updateOp.getAssociation(), updateOp.getAssociationKey() ); String collectionRole = associationKey.getMetadata().getCollectionRole(); MongoHelpers.setValue( documentForInsertion, collectionRole, embeddedElements ); } else { insertOrUpdateAssociation( updateOp.getAssociationKey(), updateOp.getAssociation(), updateOp.getContext() ); } } else { insertOrUpdateAssociation( updateOp.getAssociationKey(), updateOp.getAssociation(), updateOp.getContext() ); } } @Override public ParameterMetadataBuilder getParameterMetadataBuilder() { return NoOpParameterMetadataBuilder.INSTANCE; } private void prepareForInsert(Map<DBCollection, BatchInsertionTask> inserts, MongoDBTupleSnapshot snapshot, EntityKey entityKey, Tuple tuple, WriteConcern writeConcern) { DBCollection collection = getCollection( entityKey ); BatchInsertionTask batchInsertion = getOrCreateBatchInsertionTask( inserts, entityKey.getMetadata(), collection, writeConcern ); DBObject document = getCurrentDocument( snapshot, batchInsertion, entityKey ); DBObject newDocument = objectForInsert( tuple, document ); inserts.get( collection ).put( entityKey, newDocument ); } private DBObject getCurrentDocument(MongoDBTupleSnapshot snapshot, BatchInsertionTask batchInsert, EntityKey entityKey) { DBObject fromBatchInsertion = batchInsert.get( entityKey ); return fromBatchInsertion != null ? fromBatchInsertion : snapshot.getDbObject(); } private BatchInsertionTask getOrCreateBatchInsertionTask(Map<DBCollection, BatchInsertionTask> inserts, EntityKeyMetadata entityKeyMetadata, DBCollection collection, WriteConcern writeConcern) { BatchInsertionTask insertsForCollection = inserts.get( collection ); if ( insertsForCollection == null ) { insertsForCollection = new BatchInsertionTask( entityKeyMetadata, writeConcern ); inserts.put( collection, insertsForCollection ); } return insertsForCollection; } private void flushInserts(Map<DBCollection, BatchInsertionTask> inserts) { for ( Map.Entry<DBCollection, BatchInsertionTask> entry : inserts.entrySet() ) { DBCollection collection = entry.getKey(); if ( entry.getValue().isEmpty() ) { // has been emptied due to subsequent removals before flushes continue; } try { collection.insert( entry.getValue().getAll(), entry.getValue().getWriteConcern() ); } catch ( DuplicateKeyException dke ) { throw new TupleAlreadyExistsException( entry.getValue().getEntityKeyMetadata(), null, dke ); } } inserts.clear(); } private WriteConcern getWriteConcern(TupleContext tupleContext) { return tupleContext.getOptionsContext().getUnique( WriteConcernOption.class ); } private WriteConcern getWriteConcern(AssociationContext associationContext) { return associationContext.getAssociationTypeContext().getOptionsContext().getUnique( WriteConcernOption.class ); } private ReadPreference getReadPreference(TupleContext tupleContext) { return tupleContext.getOptionsContext().getUnique( ReadPreferenceOption.class ); } private ReadPreference getReadPreference(AssociationContext associationContext) { return associationContext.getAssociationTypeContext().getOptionsContext().getUnique( ReadPreferenceOption.class ); } private static class MongoDBResultsCursor implements ClosableIterator<Tuple> { private final DBCursor cursor; private final EntityKeyMetadata metadata; public MongoDBResultsCursor(DBCursor cursor, EntityKeyMetadata metadata) { this.cursor = cursor; this.metadata = metadata; } @Override public boolean hasNext() { return cursor.hasNext(); } @Override public Tuple next() { DBObject dbObject = cursor.next(); return new Tuple( new MongoDBTupleSnapshot( dbObject, metadata, UPDATE ) ); } @Override public void remove() { cursor.remove(); } @Override public void close() { cursor.close(); } } private static class BatchInsertionTask { private final EntityKeyMetadata entityKeyMetadata; private final Map<EntityKey, DBObject> inserts; private final WriteConcern writeConcern; public BatchInsertionTask(EntityKeyMetadata entityKeyMetadata, WriteConcern writeConcern) { this.entityKeyMetadata = entityKeyMetadata; this.inserts = new HashMap<EntityKey, DBObject>(); this.writeConcern = writeConcern; } public EntityKeyMetadata getEntityKeyMetadata() { return entityKeyMetadata; } public List<DBObject> getAll() { return new ArrayList<DBObject>( inserts.values() ); } public DBObject get(EntityKey entityKey) { return inserts.get( entityKey ); } public boolean containsKey(EntityKey entityKey) { return inserts.containsKey( entityKey ); } public DBObject remove(EntityKey entityKey) { return inserts.remove( entityKey ); } public void put(EntityKey entityKey, DBObject object) { inserts.put( entityKey, object ); } public WriteConcern getWriteConcern() { return writeConcern; } public boolean isEmpty() { return inserts.isEmpty(); } } }
package mb.nabl2.terms.unification.u; import java.io.Serializable; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Optional; import org.metaborg.util.Ref; import org.metaborg.util.functions.Predicate1; import com.google.common.collect.ImmutableSet; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multiset; import io.usethesource.capsule.Map; import io.usethesource.capsule.Set; import mb.nabl2.terms.IListTerm; import mb.nabl2.terms.ITerm; import mb.nabl2.terms.ITermVar; import mb.nabl2.terms.ListTerms; import mb.nabl2.terms.Terms; import mb.nabl2.terms.substitution.IRenaming; import mb.nabl2.terms.substitution.ISubstitution; import mb.nabl2.terms.substitution.PersistentSubstitution; import mb.nabl2.terms.unification.OccursException; import mb.nabl2.terms.unification.RigidException; import mb.nabl2.util.CapsuleUtil; import mb.nabl2.util.Tuple2; import mb.nabl2.util.collections.MultiSet; public abstract class PersistentUnifier extends BaseUnifier implements IUnifier, Serializable { private static final long serialVersionUID = 42L; // class Immutable public static class Immutable extends PersistentUnifier implements IUnifier.Immutable, Serializable { private static final long serialVersionUID = 42L; private final boolean finite; private final Ref<Map.Immutable<ITermVar, ITermVar>> reps; private final Map.Immutable<ITermVar, Integer> ranks; private final Map.Immutable<ITermVar, ITerm> terms; private final Ref<MultiSet.Immutable<ITermVar>> repAndTermVarsCache; private final Set.Immutable<ITermVar> domainSetCache; private final Set.Immutable<ITermVar> rangeSetCache; private final Set.Immutable<ITermVar> varSetCache; // FIXME Should be `package`, but is `public` for constructor in PersistentUniDisunifier public Immutable(final boolean finite, final Map.Immutable<ITermVar, ITermVar> reps, final Map.Immutable<ITermVar, Integer> ranks, final Map.Immutable<ITermVar, ITerm> terms, MultiSet.Immutable<ITermVar> repAndTermVarsCache, Set.Immutable<ITermVar> domainSetCache, Set.Immutable<ITermVar> rangeSetCache, Set.Immutable<ITermVar> varSetCache) { this.finite = finite; this.reps = new Ref<>(reps); this.ranks = ranks; this.terms = terms; this.repAndTermVarsCache = new Ref<>(repAndTermVarsCache); this.domainSetCache = domainSetCache; this.rangeSetCache = rangeSetCache; this.varSetCache = varSetCache; } @Override public boolean isFinite() { return finite; } @Override protected Map.Immutable<ITermVar, ITermVar> reps() { return reps.get(); } @Override protected Map.Immutable<ITermVar, ITerm> terms() { return terms; } @Override public ITermVar findRep(ITermVar var) { final Map.Transient<ITermVar, ITermVar> reps = this.reps.get().asTransient(); final MultiSet.Transient<ITermVar> repAndTermVarsCache = this.repAndTermVarsCache.get().melt(); final ITermVar rep = findRep(var, reps, repAndTermVarsCache); this.reps.set(reps.freeze()); this.repAndTermVarsCache.set(repAndTermVarsCache.freeze()); return rep; } // unifier functions @Override public Set.Immutable<ITermVar> domainSet() { return domainSetCache; } @Override public Set.Immutable<ITermVar> rangeSet() { return rangeSetCache; } @Override public Set.Immutable<ITermVar> varSet() { return varSetCache; } // unify(ITerm, ITerm) @Override public Optional<ImmutableResult<IUnifier.Immutable>> unify(ITerm left, ITerm right, Predicate1<ITermVar> isRigid) throws OccursException, RigidException { return new Unify(this, left, right, isRigid).apply(); } @Override public Optional<ImmutableResult<IUnifier.Immutable>> unify( Iterable<? extends Entry<? extends ITerm, ? extends ITerm>> equalities, Predicate1<ITermVar> isRigid) throws OccursException, RigidException { return new Unify(this, equalities, isRigid).apply(); } @Override public Optional<ImmutableResult<IUnifier.Immutable>> unify(IUnifier other, Predicate1<ITermVar> isRigid) throws OccursException, RigidException { return new Unify(this, other, isRigid).apply(); } private static class Unify extends PersistentUnifier.Transient { private final Predicate1<ITermVar> isRigid; private final Deque<Map.Entry<ITerm, ITerm>> worklist = Lists.newLinkedList(); private final List<ITermVar> result = Lists.newArrayList(); public Unify(PersistentUnifier.Immutable unifier, ITerm left, ITerm right, Predicate1<ITermVar> isRigid) { super(unifier); this.isRigid = isRigid; worklist.push(Tuple2.of(left, right)); } public Unify(PersistentUnifier.Immutable unifier, Iterable<? extends Entry<? extends ITerm, ? extends ITerm>> equalities, Predicate1<ITermVar> isRigid) { super(unifier); this.isRigid = isRigid; equalities.forEach(e -> { worklist.push(Tuple2.of(e)); }); } public Unify(PersistentUnifier.Immutable unifier, IUnifier other, Predicate1<ITermVar> isRigid) { super(unifier); this.isRigid = isRigid; other.domainSet().forEach(v -> { worklist.push(Tuple2.of(v, other.findTerm(v))); }); } public Optional<ImmutableResult<IUnifier.Immutable>> apply() throws OccursException, RigidException { while(!worklist.isEmpty()) { final Map.Entry<ITerm, ITerm> work = worklist.pop(); if(!unifyTerms(work.getKey(), work.getValue())) { return Optional.empty(); } } final PersistentUnifier.Immutable unifier = freeze(); if(finite) { final ImmutableSet<ITermVar> cyclicVars = result.stream().filter(v -> unifier.isCyclic(v)).collect(ImmutableSet.toImmutableSet()); if(!cyclicVars.isEmpty()) { throw new OccursException(cyclicVars); } } final IUnifier.Immutable diffUnifier = diffUnifier(result); return Optional.of(new ImmutableResult<>(diffUnifier, unifier)); } private boolean unifyTerms(final ITerm left, final ITerm right) throws RigidException { // @formatter:off return left.matchOrThrow(Terms.<Boolean,RigidException>checkedCases( applLeft -> right.matchOrThrow(Terms.<Boolean,RigidException>checkedCases() .appl(applRight -> { return applLeft.getArity() == applRight.getArity() && applLeft.getOp().equals(applRight.getOp()) && unifys(applLeft.getArgs(), applRight.getArgs()); }) .var(varRight -> { return unifyTerms(varRight, applLeft) ; }) .otherwise(t -> { return false; }) ), listLeft -> right.matchOrThrow(Terms.<Boolean,RigidException>checkedCases() .list(listRight -> { return unifyLists(listLeft, listRight); }) .var(varRight -> { return unifyTerms(varRight, listLeft); }) .otherwise(t -> { return false; }) ), stringLeft -> right.matchOrThrow(Terms.<Boolean,RigidException>checkedCases() .string(stringRight -> { return stringLeft.getValue().equals(stringRight.getValue()); }) .var(varRight -> { return unifyTerms(varRight, stringLeft); }) .otherwise(t -> { return false; }) ), integerLeft -> right.matchOrThrow(Terms.<Boolean,RigidException>checkedCases() .integer(integerRight -> { return integerLeft.getValue() == integerRight.getValue(); }) .var(varRight -> { return unifyTerms(varRight, integerLeft); }) .otherwise(t -> { return false; }) ), blobLeft -> right.matchOrThrow(Terms.<Boolean,RigidException>checkedCases() .blob(blobRight -> { return blobLeft.getValue().equals(blobRight.getValue()); }) .var(varRight -> { return unifyTerms(varRight, blobLeft); }) .otherwise(t -> { return false; }) ), varLeft -> right.matchOrThrow(Terms.<Boolean,RigidException>checkedCases() .var(varRight -> { return unifyVars(varLeft, varRight); }) .otherwise(termRight -> { return unifyVarTerm(varLeft, termRight); }) ) )); // @formatter:on } private boolean unifyLists(final IListTerm left, final IListTerm right) throws RigidException { // @formatter:off return left.matchOrThrow(ListTerms.<Boolean,RigidException>checkedCases( consLeft -> right.matchOrThrow(ListTerms.<Boolean,RigidException>checkedCases() .cons(consRight -> { worklist.push(Tuple2.of(consLeft.getHead(), consRight.getHead())); worklist.push(Tuple2.of(consLeft.getTail(), consRight.getTail())); return true; }) .var(varRight -> { return unifyLists(varRight, consLeft); }) .otherwise(l -> { return false; }) ), nilLeft -> right.matchOrThrow(ListTerms.<Boolean,RigidException>checkedCases() .nil(nilRight -> { return true; }) .var(varRight -> { return unifyVarTerm(varRight, nilLeft) ; }) .otherwise(l -> { return false; }) ), varLeft -> right.matchOrThrow(ListTerms.<Boolean,RigidException>checkedCases() .var(varRight -> { return unifyVars(varLeft, varRight); }) .otherwise(termRight -> { return unifyVarTerm(varLeft, termRight); }) ) )); // @formatter:on } private boolean unifyVarTerm(final ITermVar var, final ITerm term) throws RigidException { final ITermVar rep = findRep(var); if(term instanceof ITermVar) { throw new IllegalStateException(); } final ITerm repTerm = getTerm(rep); // term for the representative if(repTerm != null) { worklist.push(Tuple2.of(repTerm, term)); } else { if(isRigid.test(var)) { throw new RigidException(var); } putTerm(rep, term); result.add(rep); } return true; } private boolean unifyVars(final ITermVar left, final ITermVar right) throws RigidException { final ITermVar leftRep = findRep(left); final ITermVar rightRep = findRep(right); if(leftRep.equals(rightRep)) { return true; } final ITerm leftTerm = getTerm(leftRep); final ITerm rightTerm = getTerm(rightRep); // If the variable has an associated term, it is safe to unify even if it is rigid. // The variable is already bound, and unifying the variable only serves as an internal // optimization: next time the two variables are compared, there is no need to compare // the terms anymore. final boolean leftRigid = leftTerm == null && isRigid.test(leftRep); final boolean rightRigid = rightTerm == null && isRigid.test(rightRep); final int leftRank = Optional.ofNullable(ranks.__remove(leftRep)).orElse(1); final int rightRank = Optional.ofNullable(ranks.__remove(rightRep)).orElse(1); final ITermVar var; // the eliminated variable final ITermVar rep; // the new representative if(leftRigid && rightRigid) { throw new RigidException(leftRep, rightRep); } else if(leftRigid) { var = rightRep; rep = leftRep; } else if(rightRigid) { var = leftRep; rep = rightRep; } else { final boolean swap = leftRank > rightRank; var = swap ? rightRep : leftRep; // the eliminated variable rep = swap ? leftRep : rightRep; // the new representative } ranks.__put(rep, leftRank + rightRank); final ITerm varTerm = removeTerm(var); // term for the eliminated var putRep(var, rep); if(varTerm != null) { final ITerm repTerm = getTerm(rep); // term for the representative if(repTerm != null) { worklist.push(Tuple2.of(varTerm, repTerm)); // don't add to result } else { putTerm(rep, varTerm); result.add(rep); } } else { result.add(var); } return true; } private boolean unifys(final Iterable<ITerm> lefts, final Iterable<ITerm> rights) { Iterator<ITerm> itLeft = lefts.iterator(); Iterator<ITerm> itRight = rights.iterator(); while(itLeft.hasNext()) { if(!itRight.hasNext()) { return false; } worklist.push(Tuple2.of(itLeft.next(), itRight.next())); } if(itRight.hasNext()) { return false; } return true; } // diffUnifier(Set<ITermVar>) private IUnifier.Immutable diffUnifier(Collection<ITermVar> vars) { final PersistentUnifier.Transient diff = new PersistentUnifier.Transient(finite); for(ITermVar var : vars) { final ITermVar rep; final ITerm term; if((rep = getRep(var)) != null) { diff.putRep(var, rep); } else if((term = getTerm(var)) != null) { diff.putTerm(var, term); } } return diff.freeze(); } } // diff(ITerm, ITerm) @Override public Optional<IUnifier.Immutable> diff(ITerm term1, ITerm term2) { try { return unify(term1, term2).map(Result::result); } catch(OccursException e) { return Optional.empty(); } } // retain(ITermVar) @Override public IUnifier.Immutable.Result<ISubstitution.Immutable> retain(ITermVar var) { return retainAll(Set.Immutable.of(var)); } @Override public IUnifier.Immutable.Result<ISubstitution.Immutable> retainAll(Iterable<ITermVar> vars) { return removeAll(Set.Immutable.subtract(domainSet(), CapsuleUtil.toSet(vars))); } // remove(ITermVar) @Override public ImmutableResult<ISubstitution.Immutable> remove(ITermVar var) { return removeAll(Set.Immutable.of(var)); } @Override public ImmutableResult<ISubstitution.Immutable> removeAll(Iterable<ITermVar> vars) { return new RemoveAll(this, vars).apply(); } private static class RemoveAll extends PersistentUnifier.Transient { private final Set.Immutable<ITermVar> vars; public RemoveAll(PersistentUnifier.Immutable unifier, Iterable<ITermVar> vars) { super(unifier); this.vars = CapsuleUtil.toSet(vars); } public ImmutableResult<ISubstitution.Immutable> apply() { // remove vars from unifier final ISubstitution.Immutable subst = removeAll(); // TODO Check if variables escaped? final PersistentUnifier.Immutable newUnifier = freeze(); return new BaseUnifier.ImmutableResult<>(subst, newUnifier); } private ISubstitution.Immutable removeAll() { final ISubstitution.Transient subst = PersistentSubstitution.Transient.of(); if(vars.isEmpty()) { return subst.freeze(); } final ListMultimap<ITermVar, ITermVar> invReps = getInvReps(); // rep |-> [var] for(ITermVar var : vars) { ITermVar rep; if((rep = removeRep(var)) != null) { // Case 1. Var _has_ a rep; var |-> rep invReps.remove(rep, var); subst.compose(var, rep); for(ITermVar notRep : invReps.get(var)) { putRep(notRep, rep); invReps.put(rep, notRep); } } else { final Collection<ITermVar> newReps = invReps.removeAll(var); if(!newReps.isEmpty()) { // Case 2. Var _is_ a rep; rep |-> var rep = newReps.stream().max((r1, r2) -> Integer.compare(getRank(r1), getRank(r2))).get(); removeRep(rep); invReps.remove(rep, var); subst.compose(var, rep); for(ITermVar notRep : newReps) { if(!notRep.equals(rep)) { putRep(notRep, rep); invReps.put(rep, notRep); } } final ITerm term; if((term = removeTerm(var)) != null) { // var |-> term putTerm(rep, term); } } else { // Case 3. Var neither _is_ nor _has_ a rep final ITerm term; if((term = removeTerm(var)) != null) { // var |-> term subst.compose(var, term); } } } } for(Entry<ITermVar, ITerm> entry : termEntries()) { final ITermVar rep = entry.getKey(); final ITerm term = entry.getValue(); putTerm(rep, subst.apply(term)); } return subst.freeze(); } } // rename(IRenaming) @Override public PersistentUnifier.Immutable rename(IRenaming renaming) { if(renaming.isEmpty()) { return this; } final Map.Transient<ITermVar, ITermVar> reps = Map.Transient.of(); for(Entry<ITermVar, ITermVar> e : this.reps.get().entrySet()) { reps.__put(renaming.rename(e.getKey()), renaming.rename(e.getValue())); } final Map.Transient<ITermVar, Integer> ranks = Map.Transient.of(); for(Entry<ITermVar, Integer> e : this.ranks.entrySet()) { ranks.__put(renaming.rename(e.getKey()), e.getValue()); } final Map.Transient<ITermVar, ITerm> terms = Map.Transient.of(); for(Entry<ITermVar, ITerm> e : this.terms.entrySet()) { terms.__put(renaming.rename(e.getKey()), renaming.apply(e.getValue())); } final MultiSet.Transient<ITermVar> repAndTermVarsCache = MultiSet.Transient.of(); for(Entry<ITermVar, Integer> e : this.repAndTermVarsCache.get().entrySet()) { repAndTermVarsCache.add(renaming.rename(e.getKey()), e.getValue()); } final Set.Transient<ITermVar> domainSetCache = Set.Transient.of(); for(ITermVar var : this.domainSetCache) { domainSetCache.__insert(renaming.rename(var)); } final Set.Transient<ITermVar> rangeSetCache = Set.Transient.of(); for(ITermVar var : this.rangeSetCache) { rangeSetCache.__insert(renaming.rename(var)); } final Set.Transient<ITermVar> varSetCache = Set.Transient.of(); for(ITermVar var : this.varSetCache) { varSetCache.__insert(renaming.rename(var)); } return new PersistentUnifier.Immutable(finite, reps.freeze(), ranks.freeze(), terms.freeze(), repAndTermVarsCache.freeze(), domainSetCache.freeze(), rangeSetCache.freeze(), varSetCache.freeze()); } // construction @Override public IUnifier.Transient melt() { return new BaseUnifier.Transient(this); } public static PersistentUnifier.Immutable of() { return of(true); } public static PersistentUnifier.Immutable of(boolean finite) { return new PersistentUnifier.Immutable(finite, Map.Immutable.of(), Map.Immutable.of(), Map.Immutable.of(), MultiSet.Immutable.of(), Set.Immutable.of(), Set.Immutable.of(), Set.Immutable.of()); } public static PersistentUnifier.Immutable of(final boolean finite, final Map.Immutable<ITermVar, ITermVar> reps, final Map.Immutable<ITermVar, Integer> ranks, final Map.Immutable<ITermVar, ITerm> terms) { final MultiSet.Transient<ITermVar> repAndTermVarsCache = MultiSet.Transient.of(); final Set.Transient<ITermVar> domainSetCache = Set.Transient.of(); final Set.Transient<ITermVar> varSetCache = Set.Transient.of(); for(Entry<ITermVar, ITermVar> e : reps.entrySet()) { domainSetCache.__insert(e.getKey()); varSetCache.__insert(e.getKey()); repAndTermVarsCache.add(e.getValue()); varSetCache.__insert(e.getValue()); } for(Entry<ITermVar, ITerm> e : terms.entrySet()) { domainSetCache.__insert(e.getKey()); varSetCache.__insert(e.getKey()); for(Multiset.Entry<ITermVar> te : e.getValue().getVars().entrySet()) { repAndTermVarsCache.add(te.getElement(), te.getCount()); varSetCache.__insert(te.getElement()); } } final Set.Transient<ITermVar> rangeSetCache = Set.Transient.of(); for(ITermVar var : repAndTermVarsCache.elementSet()) { if(!domainSetCache.contains(var)) { rangeSetCache.__insert(var); } } return new PersistentUnifier.Immutable(finite, reps, ranks, terms, repAndTermVarsCache.freeze(), domainSetCache.freeze(), rangeSetCache.freeze(), varSetCache.freeze()); } } // class Transient // FIXME public because of use in PersistentUniDisunifier public static class Transient { protected final boolean finite; private final Map.Transient<ITermVar, ITermVar> reps; protected final Map.Transient<ITermVar, Integer> ranks; private final Map.Transient<ITermVar, ITerm> terms; private final MultiSet.Transient<ITermVar> repAndTermVarsCache; private final Set.Transient<ITermVar> domainSetCache; private final Set.Transient<ITermVar> rangeSetCache; private final Set.Transient<ITermVar> varSetCache; Transient(boolean finite) { this(finite, Map.Transient.of(), Map.Transient.of(), Map.Transient.of(), MultiSet.Transient.of(), Set.Transient.of(), Set.Transient.of(), Set.Transient.of()); } public Transient(PersistentUnifier.Immutable unifier) { this(unifier.finite, unifier.reps.get().asTransient(), unifier.ranks.asTransient(), unifier.terms.asTransient(), unifier.repAndTermVarsCache.get().melt(), unifier.domainSetCache.asTransient(), unifier.rangeSetCache.asTransient(), unifier.varSetCache.asTransient()); } Transient(boolean finite, Map.Transient<ITermVar, ITermVar> reps, Map.Transient<ITermVar, Integer> ranks, Map.Transient<ITermVar, ITerm> terms, MultiSet.Transient<ITermVar> repAndTermVarsCache, Set.Transient<ITermVar> domainSetCache, Set.Transient<ITermVar> rangeSetCache, Set.Transient<ITermVar> varSetCache) { this.finite = finite; this.reps = reps; this.ranks = ranks; this.terms = terms; this.repAndTermVarsCache = repAndTermVarsCache; this.domainSetCache = domainSetCache; this.rangeSetCache = rangeSetCache; this.varSetCache = varSetCache; } protected Iterable<Entry<ITermVar, ITermVar>> repEntries() { return reps.entrySet(); } protected Iterable<Entry<ITermVar, ITerm>> termEntries() { return terms.entrySet(); } protected ITermVar findRep(ITermVar var) { return PersistentUnifier.findRep(var, reps, repAndTermVarsCache); } protected ITermVar getRep(ITermVar var) { return reps.get(var); } protected ListMultimap<ITermVar, ITermVar> getInvReps() { final ListMultimap<ITermVar, ITermVar> invReps = LinkedListMultimap.create(); reps.forEach((var, rep) -> { invReps.put(rep, var); }); return invReps; } protected void putRep(ITermVar var, ITermVar rep) { if(terms.containsKey(var)) { throw new IllegalStateException(); } final ITermVar oldRep = reps.__put(var, rep); if(oldRep == null) { addDomainVar(var); } else { removeRangeVar(oldRep, 1); } addRangeVar(rep, 1); } protected ITermVar removeRep(ITermVar var) { final ITermVar rep = reps.__remove(var); if(rep != null) { removeDomainVar(var); removeRangeVar(rep, 1); } return rep; } protected ITerm getTerm(ITermVar rep) { return terms.get(rep); } protected void putTerm(ITermVar rep, ITerm term) { if(reps.containsKey(rep)) { throw new IllegalStateException(); } final ITerm oldTerm = terms.__put(rep, term); if(oldTerm == null) { addDomainVar(rep); } else { for(Multiset.Entry<ITermVar> var : oldTerm.getVars().entrySet()) { removeRangeVar(var.getElement(), var.getCount()); } } for(Multiset.Entry<ITermVar> var : term.getVars().entrySet()) { addRangeVar(var.getElement(), var.getCount()); } } protected ITerm removeTerm(ITermVar rep) { final ITerm term = terms.__remove(rep); if(term != null) { removeDomainVar(rep); for(Multiset.Entry<ITermVar> var : term.getVars().entrySet()) { removeRangeVar(var.getElement(), var.getCount()); } } return term; } private void addDomainVar(ITermVar var) { if(domainSetCache.contains(var)) { throw new IllegalStateException(); } domainSetCache.__insert(var); if(repAndTermVarsCache.count(var) > 0) { // pre-existing var rangeSetCache.__remove(var); } else { // added var varSetCache.__insert(var); } } private void removeDomainVar(ITermVar var) { if(!domainSetCache.contains(var)) { throw new IllegalStateException(); } domainSetCache.__remove(var); if(repAndTermVarsCache.count(var) > 0) { // still existing var rangeSetCache.__insert(var); } else { // removed var varSetCache.__remove(var); } } public void addRangeVar(ITermVar var, int k) { if(k <= 0) { throw new IllegalStateException(); } final int n = repAndTermVarsCache.add(var, k); if(n == k) { // added var if(!domainSetCache.contains(var)) { rangeSetCache.__insert(var); varSetCache.__insert(var); } } } public void removeRangeVar(ITermVar var, int k) { if(k <= 0) { throw new IllegalStateException(); } final int n = repAndTermVarsCache.remove(var, k); if(n == 0) { // removed var if(!domainSetCache.contains(var)) { rangeSetCache.__remove(var); varSetCache.__remove(var); } } } protected int getRank(ITermVar var) { return ranks.getOrDefault(var, 1); } public PersistentUnifier.Immutable freeze() { final PersistentUnifier.Immutable unifier = new PersistentUnifier.Immutable(finite, reps.freeze(), ranks.freeze(), terms.freeze(), repAndTermVarsCache.freeze(), domainSetCache.freeze(), rangeSetCache.freeze(), varSetCache.freeze()); return unifier; } } // utils protected static ITermVar findRep(ITermVar var, Map.Transient<ITermVar, ITermVar> reps, MultiSet.Transient<ITermVar> repAndTermVarsCache) { final ITermVar rep = reps.get(var); if(rep == null) { return var; } else { final ITermVar rep2 = findRep(rep, reps, repAndTermVarsCache); if(!rep2.equals(rep)) { reps.__put(var, rep2); repAndTermVarsCache.remove(rep); repAndTermVarsCache.add(rep2); } return rep2; } } }
package net.nemerosa.ontrack.service.job; import com.codahale.metrics.MetricRegistry; import net.nemerosa.ontrack.job.JobListener; import net.nemerosa.ontrack.job.JobScheduler; import net.nemerosa.ontrack.job.Schedule; import net.nemerosa.ontrack.job.orchestrator.JobOrchestrator; import net.nemerosa.ontrack.job.orchestrator.JobOrchestratorSupplier; import net.nemerosa.ontrack.job.support.DefaultJobScheduler; import net.nemerosa.ontrack.model.support.ApplicationLogService; import net.nemerosa.ontrack.model.support.OntrackConfigProperties; import net.nemerosa.ontrack.model.support.SettingsRepository; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.metrics.CounterService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Collection; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @Configuration public class JobConfig { @Autowired private OntrackConfigProperties ontrackConfigProperties; @Autowired private DefaultJobDecorator jobDecorator; @Autowired private ApplicationLogService logService; @Autowired private MetricRegistry metricRegistry; @Autowired private CounterService counterService; @Autowired private SettingsRepository settingsRepository; @Autowired(required = false) private Collection<JobOrchestratorSupplier> jobOrchestratorSuppliers; @Bean public JobOrchestrator jobOrchestrator() { return new JobOrchestrator( jobScheduler(), Schedule.EVERY_MINUTE, // TODO Makes this configurable in OntrackConfigProperties "Job orchestration", jobOrchestratorSuppliers ); } @Bean public JobListener jobListener() { return new DefaultJobListener( logService, metricRegistry, counterService, settingsRepository ); } @Bean public ScheduledExecutorService jobExecutorService() { return Executors.newScheduledThreadPool( ontrackConfigProperties.getJobs().getPoolSize(), new BasicThreadFactory.Builder() .daemon(true) .namingPattern("job-%s") .build() ); } @Bean public JobScheduler jobScheduler() { return new DefaultJobScheduler( jobDecorator, jobExecutorService(), jobListener() ); } }
package de.geeksfactory.opacclient.apis; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.FormElement; import org.jsoup.select.Elements; import java.io.IOException; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.geeksfactory.opacclient.i18n.StringProvider; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.Status; import de.geeksfactory.opacclient.searchfields.BarcodeSearchField; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchField.Meaning; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; import de.geeksfactory.opacclient.utils.Base64; //@formatter:off //@formatter:on public class WinBiap extends BaseApi implements OpacApi { protected static final String QUERY_TYPE_CONTAINS = "8"; protected static final String QUERY_TYPE_FROM = "6"; protected static final String QUERY_TYPE_TO = "4"; protected static final String QUERY_TYPE_STARTS_WITH = "7"; protected static final String QUERY_TYPE_EQUALS = "1"; protected static HashMap<String, SearchResult.MediaType> defaulttypes = new HashMap<>(); static { defaulttypes.put("sb_buch", SearchResult.MediaType.BOOK); defaulttypes.put("sl_buch", SearchResult.MediaType.BOOK); defaulttypes.put("kj_buch", SearchResult.MediaType.BOOK); defaulttypes.put("hoerbuch", SearchResult.MediaType.AUDIOBOOK); defaulttypes.put("musik", SearchResult.MediaType.CD_MUSIC); defaulttypes.put("cdrom", SearchResult.MediaType.CD_SOFTWARE); defaulttypes.put("dvd", SearchResult.MediaType.DVD); defaulttypes.put("online", SearchResult.MediaType.EBOOK); } protected String opac_url = ""; protected JSONObject data; protected List<List<NameValuePair>> query; public void init(Library lib) { super.init(lib); this.data = lib.getData(); try { this.opac_url = data.getString("baseurl"); } catch (JSONException e) { throw new RuntimeException(e); } } /** * For documentation of the parameters, @see {@link #addParametersManual(String, String, String, * String, String, List, int)} */ protected int addParameters(Map<String, String> query, String key, String searchkey, String type, List<List<NameValuePair>> params, int index) { if (!query.containsKey(key) || query.get(key).equals("")) { return index; } return addParametersManual("1", "1", searchkey, type, query.get(key), params, index); } /** * @param combination "Combination" (probably And, Or, ...): Meaning unknown, seems to always be * "1" except in some mysterious queries the website adds every time that * don't change the result * @param mode "Mode": Meaning unknown, seems to always be "1" except in some mysterious * queries the website adds every time that don't change the result * @param field "Field": The key for the property that is queried, for example "12" for * "title" * @param operator "Operator": The type of search that is made (one of the QUERY_TYPE_ * constants above), for example "8" for "contains" * @param value "Value": The value that was input by the user */ @SuppressWarnings("SameParameterValue") protected int addParametersManual(String combination, String mode, String field, String operator, String value, List<List<NameValuePair>> params, int index) { List<NameValuePair> list = new ArrayList<>(); if (data.optBoolean("longParameterNames")) { // A few libraries use longer names for the parameters (e.g. Hohen Neuendorf) list.add(new BasicNameValuePair("Combination_" + index, combination)); list.add(new BasicNameValuePair("Mode_" + index, mode)); list.add(new BasicNameValuePair("Searchfield_" + index, field)); list.add(new BasicNameValuePair("Searchoperator_" + index, operator)); list.add(new BasicNameValuePair("Searchvalue_" + index, value)); } else { list.add(new BasicNameValuePair("c_" + index, combination)); list.add(new BasicNameValuePair("m_" + index, mode)); list.add(new BasicNameValuePair("f_" + index, field)); list.add(new BasicNameValuePair("o_" + index, operator)); list.add(new BasicNameValuePair("v_" + index, value)); } params.add(list); return index + 1; } @Override public SearchRequestResult search(List<SearchQuery> queries) throws IOException, OpacErrorException { Map<String, String> query = searchQueryListToMap(queries); List<List<NameValuePair>> queryParams = new ArrayList<>(); int index = 0; index = addParameters(query, KEY_SEARCH_QUERY_FREE, data.optString("KEY_SEARCH_QUERY_FREE", "2"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_AUTHOR, data.optString("KEY_SEARCH_QUERY_AUTHOR", "3"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_TITLE, data.optString("KEY_SEARCH_QUERY_TITLE", "12"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_KEYWORDA, data.optString("KEY_SEARCH_QUERY_KEYWORDA", "24"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_AUDIENCE, data.optString("KEY_SEARCH_QUERY_AUDIENCE", "25"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_SYSTEM, data.optString("KEY_SEARCH_QUERY_SYSTEM", "26"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_ISBN, data.optString("KEY_SEARCH_QUERY_ISBN", "29"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_PUBLISHER, data.optString("KEY_SEARCH_QUERY_PUBLISHER", "32"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_BARCODE, data.optString("KEY_SEARCH_QUERY_BARCODE", "46"), QUERY_TYPE_CONTAINS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_YEAR_RANGE_START, data.optString("KEY_SEARCH_QUERY_BARCODE", "34"), QUERY_TYPE_FROM, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_YEAR_RANGE_END, data.optString("KEY_SEARCH_QUERY_BARCODE", "34"), QUERY_TYPE_TO, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_CATEGORY, data.optString("KEY_SEARCH_QUERY_CATEGORY", "42"), QUERY_TYPE_EQUALS, queryParams, index); index = addParameters(query, KEY_SEARCH_QUERY_BRANCH, data.optString("KEY_SEARCH_QUERY_BRANCH", "48"), QUERY_TYPE_EQUALS, queryParams, index); if (index == 0) { throw new OpacErrorException( stringProvider.getString(StringProvider.NO_CRITERIA_INPUT)); } // if (index > 4) { // throw new OpacErrorException( this.query = queryParams; String encodedQueryParams = encode(queryParams, "=", "%%", "++"); List<NameValuePair> params = new ArrayList<>(); start(); params.add(new BasicNameValuePair("cmd", "5")); if (data.optBoolean("longParameterNames")) // A few libraries use longer names for the parameters // (e.g. Hohen Neuendorf) { params.add(new BasicNameValuePair("searchConditions", encodedQueryParams)); } else { params.add(new BasicNameValuePair("sC", encodedQueryParams)); } params.add(new BasicNameValuePair("Sort", "Autor")); String text = encode(params, "=", "&amp;"); String base64 = URLEncoder.encode( Base64.encodeBytes(text.getBytes("UTF-8")), "UTF-8"); String html = httpGet(opac_url + "/search.aspx?data=" + base64, getDefaultEncoding(), false); return parse_search(html, 1); } private SearchRequestResult parse_search(String html, int page) throws OpacErrorException, IOException { Document doc = Jsoup.parse(html); if (doc.select(".alert h4").text().contains("Keine Treffer gefunden")) { // no media found return new SearchRequestResult(new ArrayList<SearchResult>(), 0, page); } if (doc.select("errortype").size() > 0) { // Error (e.g. 404) throw new OpacErrorException(doc.select("errortype").text()); } // Total count String header = doc.select(".ResultHeader").text(); Pattern pattern = Pattern.compile("Die Suche ergab (\\d*) Treffer"); Matcher matcher = pattern.matcher(header); int results_total; if (matcher.find()) { results_total = Integer.parseInt(matcher.group(1)); } else { throw new OpacErrorException( stringProvider.getString(StringProvider.INTERNAL_ERROR)); } // Results Elements trs = doc.select("#listview .ResultItem"); List<SearchResult> results = new ArrayList<>(); for (Element tr : trs) { SearchResult sr = new SearchResult(); String author = tr.select(".autor").text(); String title = tr.select(".title").text(); String titleAddition = tr.select(".titleZusatz").text(); String desc = tr.select(".smallDescription").text(); sr.setInnerhtml("<b>" + (author.equals("") ? "" : author + "<br />") + title + (titleAddition.equals("") ? "" : " - <i>" + titleAddition + "</i>") + "</b><br /><small>" + desc + "</small>"); if (tr.select(".coverWrapper input, .coverWrapper img").size() > 0) { Element cover = tr.select(".coverWrapper input, .coverWrapper img").first(); if (cover.hasAttr("data-src")) { sr.setCover(cover.attr("data-src")); } else if (cover.hasAttr("src") && !cover.attr("src").contains("empty.gif") && !cover.attr("src").contains("leer.gif")) { sr.setCover(cover.attr("src")); } sr.setType(getMediaType(cover, data)); } String link = tr.select("a[href*=detail.aspx]").attr("href"); String base64 = getQueryParamsFirst(link).get("data"); if (base64.contains("-")) // Most of the time, the base64 string is // followed by a hyphen and some // mysterious // letters that we don't want { base64 = base64.substring(0, base64.indexOf("-") - 1); } String decoded = new String(Base64.decode(base64), "UTF-8"); pattern = Pattern.compile("CatalogueId=(\\d*)"); matcher = pattern.matcher(decoded); if (matcher.find()) { sr.setId(matcher.group(1)); } else { throw new OpacErrorException( stringProvider.getString(StringProvider.INTERNAL_ERROR)); } if (tr.select(".mediaStatus").size() > 0) { Element status = tr.select(".mediaStatus").first(); if (status.hasClass("StatusNotAvailable")) { sr.setStatus(Status.RED); } else if (status.hasClass("StatusAvailable")) { sr.setStatus(Status.GREEN); } else { sr.setStatus(Status.YELLOW); } } else if (tr.select(".showCopies").size() > 0) { // Multiple copies if (tr.nextElementSibling().select(".StatusNotAvailable") .size() == 0) { sr.setStatus(Status.GREEN); } else if (tr.nextElementSibling().select(".StatusAvailable") .size() == 0) { sr.setStatus(Status.RED); } else { sr.setStatus(Status.YELLOW); } } results.add(sr); } return new SearchRequestResult(results, results_total, page); } private String encode(List<List<NameValuePair>> list, String equals, String separator, String separator2) { if (list.size() > 0) { String encoded = encode(list.get(0), equals, separator); for (int i = 1; i < list.size(); i++) { encoded += separator2; encoded += encode(list.get(i), equals, separator); } return encoded; } else { return ""; } } private String encode(List<NameValuePair> list, String equals, String separator) { if (list.size() > 0) { String encoded = list.get(0).getName() + equals + list.get(0).getValue(); for (int i = 1; i < list.size(); i++) { encoded += separator; encoded += list.get(i).getName() + equals + list.get(i).getValue(); } return encoded; } else { return ""; } } @Override public SearchRequestResult filterResults(Filter filter, Option option) throws IOException, OpacErrorException { return null; } @Override public SearchRequestResult searchGetPage(int page) throws IOException, OpacErrorException { String encodedQueryParams = encode(query, "=", "%%", "++"); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("cmd", "1")); if (data.optBoolean("longParameterNames")) { // A few libraries use longer names for the parameters // (e.g. Hohen Neuendorf) params.add(new BasicNameValuePair("searchConditions", encodedQueryParams)); params.add(new BasicNameValuePair("PageIndex", String .valueOf(page - 1))); } else { params.add(new BasicNameValuePair("sC", encodedQueryParams)); params.add(new BasicNameValuePair("pI", String.valueOf(page - 1))); } params.add(new BasicNameValuePair("Sort", "Autor")); String text = encode(params, "=", "&amp;"); String base64 = URLEncoder.encode( Base64.encodeBytes(text.getBytes("UTF-8")), "UTF-8"); String html = httpGet(opac_url + "/search.aspx?data=" + base64, getDefaultEncoding(), false); return parse_search(html, page); } @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, OpacErrorException { String html = httpGet(opac_url + "/detail.aspx?Id=" + id, getDefaultEncoding(), false); return parse_result(html); } private DetailledItem parse_result(String html) { Document doc = Jsoup.parse(html); DetailledItem item = new DetailledItem(); if (doc.select(".cover").size() > 0) { Element cover = doc.select(".cover").first(); if (cover.hasAttr("data-src")) { item.setCover(cover.attr("data-src")); } else if (cover.hasAttr("src") && !cover.attr("src").equals("images/empty.gif")) { item.setCover(cover.attr("src")); } item.setMediaType(getMediaType(cover, data)); } String permalink = doc.select(".PermalinkTextarea").text(); item.setId(getQueryParamsFirst(permalink).get("Id")); Elements trs = doc.select(".DetailInformation").first().select("tr"); for (Element tr : trs) { String name = tr.select(".DetailInformationEntryName").text() .replace(":", ""); String value = tr.select(".DetailInformationEntryContent").text(); switch (name) { case "Titel": item.setTitle(value); break; case "Stücktitel": item.setTitle(item.getTitle() + " " + value); break; default: item.addDetail(new Detail(name, value)); break; } } trs = doc.select(".detailCopies .tableCopies > tbody > tr:not(.headerCopies)"); for (Element tr : trs) { Map<String, String> copy = new HashMap<>(); copy.put(DetailledItem.KEY_COPY_BARCODE, tr.select(".mediaBarcode") .text().replace(" copy.put(DetailledItem.KEY_COPY_STATUS, tr.select(".mediaStatus") .text()); if (tr.select(".mediaBranch").size() > 0) { copy.put(DetailledItem.KEY_COPY_BRANCH, tr.select(".mediaBranch").text()); } copy.put(DetailledItem.KEY_COPY_LOCATION, tr.select(".cellMediaItemLocation span").text()); if (tr.select("#HyperLinkReservation").size() > 0) { copy.put(DetailledItem.KEY_COPY_RESINFO, tr.select("#HyperLinkReservation") .attr("href")); item.setReservable(true); item.setReservation_info("reservable"); } item.addCopy(copy); } return item; } private static SearchResult.MediaType getMediaType(Element cover, JSONObject data) { if (cover.hasAttr("grp")) { String[] parts = cover.attr("grp").split("/"); String fname = parts[parts.length - 1]; if (data.has("mediatypes")) { try { return SearchResult.MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname)); } catch (JSONException | IllegalArgumentException e) { return defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } } else { return defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } } return null; } @Override public DetailledItem getResult(int position) throws IOException, OpacErrorException { // Should not be called because every media has an ID return null; } @Override public ReservationResult reservation(DetailledItem item, Account account, int useraction, String selection) throws IOException { if (selection == null) { // Which copy? List<Map<String, String>> options = new ArrayList<>(); for (Map<String, String> copy : item.getCopies()) { if (!copy.containsKey(DetailledItem.KEY_COPY_RESINFO)) continue; Map<String, String> option = new HashMap<>(); option.put("key", copy.get(DetailledItem.KEY_COPY_RESINFO)); option.put("value", copy.get(DetailledItem.KEY_COPY_BARCODE) + " - " + copy.get(DetailledItem.KEY_COPY_BRANCH) + " - " + copy.get(DetailledItem.KEY_COPY_RETURN)); options.add(option); } if (options.size() == 0) { return new ReservationResult(MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.NO_COPY_RESERVABLE)); } else if (options.size() == 1) { return reservation(item, account, useraction, options.get(0).get("key")); } else { ReservationResult res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED); res.setSelection(options); return res; } } else { // Reservation // the URL stored in selection contains "=" and other things inside params // and will be messed up by our cleanUrl function Document doc = Jsoup.parse(convertStreamToString( http_client.execute(new HttpGet(opac_url + "/" + selection)) .getEntity().getContent())); if (doc.select("[id$=LabelLoginMessage]").size() > 0) { doc.select("[id$=TextBoxLoginName]").val(account.getName()); doc.select("[id$=TextBoxLoginPassword]").val(account.getPassword()); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> formData = form.formData(); List<NameValuePair> params = new ArrayList<>(); for (Connection.KeyVal kv : formData) { if (!kv.key().contains("Button") || kv.key().endsWith("ButtonLogin")) { params.add(new BasicNameValuePair(kv.key(), kv.value())); } } doc = Jsoup.parse(httpPost(opac_url + "/user/" + form.attr("action"), new UrlEncodedFormEntity(params), getDefaultEncoding())); } FormElement confirmationForm = (FormElement) doc.select("form").first(); List<Connection.KeyVal> formData = confirmationForm.formData(); List<NameValuePair> params = new ArrayList<>(); for (Connection.KeyVal kv : formData) { if (!kv.key().contains("Button") || kv.key().endsWith("ButtonVorbestOk")) { params.add(new BasicNameValuePair(kv.key(), kv.value())); } } httpPost(opac_url + "/user/" + confirmationForm.attr("action"), new UrlEncodedFormEntity(params), getDefaultEncoding()); // TODO: handle errors (I did not encounter any) return new ReservationResult(MultiStepResult.Status.OK); } } @Override public ProlongResult prolong(String media, Account account, int useraction, String selection) throws IOException { try { login(account); } catch (OpacErrorException e) { return new ProlongResult(MultiStepResult.Status.ERROR, e.getMessage()); } Document lentPage = Jsoup.parse( httpGet(opac_url + "/user/borrow.aspx", getDefaultEncoding())); lentPage.select("input[name=" + media + "]").first().attr("checked", true); List<Connection.KeyVal> formData = ((FormElement) lentPage.select("form").first()).formData(); List<NameValuePair> params = new ArrayList<>(); for (Connection.KeyVal kv : formData) { params.add(new BasicNameValuePair(kv.key(), kv.value())); } String html = httpPost(opac_url + "/user/borrow.aspx", new UrlEncodedFormEntity (params), getDefaultEncoding()); Document confirmationPage = Jsoup.parse(html); FormElement confirmationForm = (FormElement) confirmationPage.select("form").first(); List<Connection.KeyVal> formData2 = confirmationForm.formData(); List<NameValuePair> params2 = new ArrayList<>(); for (Connection.KeyVal kv : formData2) { if (!kv.key().contains("Button") || kv.key().endsWith("ButtonProlongationOk")) { params2.add(new BasicNameValuePair(kv.key(), kv.value())); } } httpPost(opac_url + "/user/" + confirmationForm.attr("action"), new UrlEncodedFormEntity(params2), getDefaultEncoding()); // TODO: handle errors (I did not encounter any) return new ProlongResult(MultiStepResult.Status.OK); } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { return null; } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { try { login(account); } catch (OpacErrorException e) { return new CancelResult(MultiStepResult.Status.ERROR, e.getMessage()); } List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("action", "reservationdelete")); params.add(new BasicNameValuePair("data", media)); String response = httpPost(opac_url + "/service/UserService.ashx", new UrlEncodedFormEntity(params), getDefaultEncoding()); System.out.println("Antwort: " + response); // Response: [number of reservations deleted];[number of remaining reservations] String[] parts = response.split(";"); if (parts[0].equals("1")) { return new CancelResult(MultiStepResult.Status.OK); } else { return new CancelResult(MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.UNKNOWN_ERROR)); } } @Override public AccountData account(Account account) throws IOException, JSONException, OpacErrorException { Document startPage = login(account); AccountData adata = new AccountData(account.getId()); if (startPage.select("#ctl00_ContentPlaceHolderMain_LabelCharges").size() > 0) { String fees = startPage.select("#ctl00_ContentPlaceHolderMain_LabelCharges").text() .replace("Kontostand:", "").trim(); if (!fees.equals("ausgeglichen")) adata.setPendingFees(fees); } Document lentPage = Jsoup.parse( httpGet(opac_url + "/user/borrow.aspx", getDefaultEncoding())); adata.setLent(parseMediaList(lentPage)); Document reservationsPage = Jsoup.parse( httpGet(opac_url + "/user/reservations.aspx", getDefaultEncoding())); adata.setReservations(parseResList(reservationsPage, stringProvider, data)); return adata; } static List<Map<String, String>> parseMediaList(Document doc) { List<Map<String, String>> lent = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN); // the account page differs between WinBiap versions 4.2 and >= 4.3 boolean winBiap43; if (doc.select(".GridView_RowStyle").size() > 0) { winBiap43 = false; } else { winBiap43 = true; } // 4.2: .GridView_RowStyle // 4.3: id=...DetailItemMain_rowBorrow // 4.4: id=...DetailItemMain_0_rowBorrow_0 for (Element tr : doc.select(winBiap43 ? ".detailTable tr[id*=_rowBorrow]" : ".GridView_RowStyle")) { Map<String, String> item = new HashMap<>(); Element detailsTr = winBiap43 ? tr.nextElementSibling() : tr; // the second column contains an img tag with the cover if (tr.select(".cover, img[id*=ImageCover]").size() > 0) { // find media ID using cover URL Element img = tr.select(".cover, img[id*=ImageCover]").first(); String url = img.hasAttr("data-src") ? img.attr("data-src") : img.attr("src"); Map<String, String> params = getQueryParamsFirst(url); if (params.containsKey("catid")) { item.put(AccountData.KEY_LENT_ID, params.get("catid")); } } // The IDs and classes of the detail fields slightly differ between WinBiap versions. // 4.2 uses German names like, some with underscores and some without // 4.3 changes most of them to English and without underscore // 4.4 adds numbers to the end of the id, separated by an underscore, // and has simpler classes like ".author" for some of the fields putIfNotEmpty(item, AccountData.KEY_LENT_AUTHOR, tr.select("[id$=LabelAutor], .autor").text()); putIfNotEmpty(item, AccountData.KEY_LENT_TITLE, tr.select("[id$=LabelTitel], [id$=LabelTitle], .title").text()); putIfNotEmpty(item, AccountData.KEY_LENT_BARCODE, detailsTr .select("[id$=Label_Mediennr], [id$=labelMediennr], [id*=labelMediennr_]") .text()); putIfNotEmpty(item, AccountData.KEY_LENT_FORMAT, detailsTr .select("[id$=Label_Mediengruppe], [id$=labelMediagroup], [id*=labelMediagroup_]") .text()); putIfNotEmpty(item, AccountData.KEY_LENT_BRANCH, detailsTr .select("[id$=Label_Zweigstelle], [id$=labelBranch], [id*=labelBranch_]") .text()); // Label_Entliehen/LabelStartDate/.startDate contains the date when the medium was lent putIfNotEmpty(item, AccountData.KEY_LENT_DEADLINE, tr.select("[id$=LabelFaellig], [id$=LabelMatureDate], .matureDate").text()); try { item.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String.valueOf(sdf.parse( tr.select("[id$=LabelFaellig], [id$=LabelMatureDate], .matureDate").text()) .getTime())); } catch (ParseException e) { e.printStackTrace(); } if (tr.select("input[id$=chkSelect]").size() > 0) { item.put(AccountData.KEY_LENT_LINK, tr.select("input[id$=chkSelect]").attr("name")); } else { item.put(AccountData.KEY_LENT_RENEWABLE, "N"); } lent.add(item); } return lent; } private static void putIfNotEmpty(Map<String, String> map, String key, String value) { if (value != null && !value.equals("")) { map.put(key, value); } } static List<Map<String, String>> parseResList(Document doc, StringProvider stringProvider, JSONObject data) { List<Map<String, String>> reservations = new ArrayList<>(); // the account page differs between WinBiap versions 4.2 and 4.3 boolean winBiap43; if (doc.select("tr[id*=GridViewReservation]").size() > 0) { winBiap43 = false; } else { winBiap43 = true; } for (Element tr : doc .select(winBiap43 ? ".detailTable tr[id$=ReservationDetailItemMain_rowBorrow]" : "tr[id*=GridViewReservation]")) { Map<String, String> item = new HashMap<>(); Element detailsTr = winBiap43 ? tr.nextElementSibling() : tr; // the second column contains an img tag with the cover if (tr.select(".cover").size() > 0) { // find media ID using cover URL Map<String, String> params = getQueryParamsFirst(tr.select(".cover").attr("src")); if (params.containsKey("catid")) { item.put(AccountData.KEY_RESERVATION_ID, params.get("catid")); } // find media type SearchResult.MediaType mt = getMediaType(tr.select(".cover").first(), data); if (mt != null) { item.put(AccountData.KEY_RESERVATION_FORMAT, stringProvider.getMediaTypeName(mt)); } } putIfNotEmpty(item, AccountData.KEY_RESERVATION_READY, winBiap43 ? detailsTr.select("[id$=labelStatus]").text() : tr.select("[id$=ImageBorrow]").attr("title")); putIfNotEmpty(item, AccountData.KEY_RESERVATION_AUTHOR, tr.select("[id$=LabelAutor], .autor").text()); putIfNotEmpty(item, AccountData.KEY_RESERVATION_TITLE, tr.select("[id$=LabelTitle], .title").text()); putIfNotEmpty(item, AccountData.KEY_RESERVATION_BRANCH, detailsTr.select("[id$=LabelBranch], [id$=labelBranch], [id*=labelBranch_]") .text()); putIfNotEmpty(item, AccountData.KEY_RESERVATION_FORMAT, detailsTr .select("[id$=Label_Mediengruppe], [id$=labelMediagroup], [id*=labelMediagroup_]") .text()); // Label_Vorbestelltam contains the date when the medium was reserved if (tr.select("a[id$=ImageReservationDelete]").size() > 0) { String javascript = tr.select("a[id$=ImageReservationDelete]").attr("onclick"); Pattern regex = Pattern.compile("javascript:DeleteReservation\\('" + "(?:\\\\[\\\\']|[^\\\\'])*'\\s*,\\s*'(?:\\\\[\\\\']|[^\\\\'])*'\\s*,\\s*'" + "((?:\\\\[\\\\']|[^\\\\'])*)'\\s*,\\s*'(?:\\\\[\\\\']|[^\\\\'])*'\\s*," + "\\s*'(?:\\\\[\\\\']|[^\\\\'])*'\\s*,\\s*'(?:\\\\[\\\\']|[^\\\\'])*'\\s*," + "\\s*'(?:\\\\[\\\\']|[^\\\\'])*'\\s*\\);"); Matcher matcher = regex.matcher(javascript); if (matcher.find()) { String base64 = matcher.group(1); item.put(AccountData.KEY_RESERVATION_CANCEL, base64); } } reservations.add(item); } return reservations; } @Override public List<SearchField> getSearchFields() throws IOException { // extract branches and categories String html = httpGet(opac_url + "/search.aspx", getDefaultEncoding()); Document doc = Jsoup.parse(html); Elements mediaGroupOptions = doc .select("#ctl00_ContentPlaceHolderMain_searchPanel_ListBoxMediagroups_ListBoxMultiselection option"); Elements branchOptions = doc .select("#ctl00_ContentPlaceHolderMain_searchPanel_MultiSelectionBranch_ListBoxMultiselection option"); final DropdownSearchField mediaGroups = new DropdownSearchField(KEY_SEARCH_QUERY_CATEGORY, "Mediengruppe", false, null); mediaGroups.setMeaning(Meaning.CATEGORY); final DropdownSearchField branches = new DropdownSearchField(KEY_SEARCH_QUERY_BRANCH, "Zweigstelle", false, null); branches.setMeaning(Meaning.BRANCH); mediaGroups.addDropdownValue("", "Alle"); branches.addDropdownValue("", "Alle"); for (Element option : mediaGroupOptions) { mediaGroups.addDropdownValue(option.attr("value"), option.text()); } for (Element option : branchOptions) { branches.addDropdownValue(option.attr("value"), option.text()); } List<SearchField> searchFields = new ArrayList<>(); SearchField field = new TextSearchField(KEY_SEARCH_QUERY_FREE, "", false, false, "Beliebig", true, false); field.setMeaning(Meaning.FREE); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_AUTHOR, "Autor", false, false, "Nachname, Vorname", false, false); field.setMeaning(Meaning.AUTHOR); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_TITLE, "Titel", false, false, "Stichwort", false, false); field.setMeaning(Meaning.TITLE); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_KEYWORDA, "Schlagwort", true, false, "", false, false); field.setMeaning(Meaning.KEYWORD); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_AUDIENCE, "Interessenkreis", true, false, "", false, false); field.setMeaning(Meaning.AUDIENCE); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_SYSTEM, "Systematik", true, false, "", false, false); field.setMeaning(Meaning.SYSTEM); searchFields.add(field); field = new BarcodeSearchField(KEY_SEARCH_QUERY_ISBN, "Strichcode", false, false, "ISBN"); field.setMeaning(Meaning.ISBN); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_PUBLISHER, "Verlag", false, false, "", false, false); field.setMeaning(Meaning.PUBLISHER); searchFields.add(field); field = new BarcodeSearchField(KEY_SEARCH_QUERY_BARCODE, "Strichcode", false, true, "Mediennummer"); field.setMeaning(Meaning.BARCODE); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_YEAR_RANGE_START, "Jahr", false, false, "von", false, true); field.setMeaning(Meaning.YEAR); searchFields.add(field); field = new TextSearchField(KEY_SEARCH_QUERY_YEAR_RANGE_END, "Jahr", false, true, "bis", false, true); field.setMeaning(Meaning.YEAR); searchFields.add(field); searchFields.add(branches); searchFields.add(mediaGroups); return searchFields; } @Override public boolean shouldUseMeaningDetector() { return false; } @Override public boolean isAccountSupported(Library library) { return library.isAccountSupported(); } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account account) throws IOException { return null; } @Override public String getShareUrl(String id, String title) { return opac_url + "/detail.aspx?Id=" + id; } @Override public int getSupportFlags() { return SUPPORT_FLAG_ENDLESS_SCROLLING; } @Override public void checkAccountData(Account account) throws IOException, JSONException, OpacErrorException { login(account); } protected Document login(Account account) throws IOException, OpacErrorException { Document loginPage = Jsoup.parse( httpGet(opac_url + "/user/login.aspx", getDefaultEncoding())); List<NameValuePair> data = new ArrayList<>(); data.add(new BasicNameValuePair("__LASTFOCUS", "")); data.add(new BasicNameValuePair("__EVENTTARGET", "")); data.add(new BasicNameValuePair("__EVENTARGUMENT", "")); data.add(new BasicNameValuePair("__VIEWSTATE", loginPage.select("#__VIEWSTATE").val())); data.add(new BasicNameValuePair("__VIEWSTATEGENERATOR", loginPage.select("#__VIEWSTATEGENERATOR").val())); data.add(new BasicNameValuePair("__EVENTVALIDATION", loginPage.select("#__EVENTVALIDATION").val())); data.add(new BasicNameValuePair("ctl00$ContentPlaceHolderMain$TextBoxLoginName", account.getName())); data.add(new BasicNameValuePair("ctl00$ContentPlaceHolderMain$TextBoxLoginPassword", account.getPassword())); data.add(new BasicNameValuePair("ctl00$ContentPlaceHolderMain$ButtonLogin", "Anmelden")); String html = httpPost(opac_url + "/user/login.aspx", new UrlEncodedFormEntity(data), "UTF-8"); Document doc = Jsoup.parse(html); if (doc.select("#ctl00_ContentPlaceHolderMain_LabelLoginMessage").size() > 0) { throw new OpacErrorException( doc.select("#ctl00_ContentPlaceHolderMain_LabelLoginMessage").text()); } return doc; } @Override public void setLanguage(String language) { // TODO Auto-generated method stub } @Override public Set<String> getSupportedLanguages() throws IOException { // TODO Auto-generated method stub return null; } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // Modifications: // 2006 Aug 15: Formatting, use generics for collections, be explicit about method visibility, add support for generic indexes. - dj@opennms.org // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.collectd; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Category; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.config.DataCollectionConfigFactory; import org.opennms.netmgt.snmp.AggregateTracker; import org.opennms.netmgt.snmp.Collectable; import org.opennms.netmgt.snmp.CollectionTracker; import org.opennms.netmgt.snmp.SingleInstanceTracker; import org.opennms.netmgt.snmp.SnmpAgentConfig; import org.opennms.netmgt.snmp.SnmpInstId; import org.opennms.netmgt.snmp.SnmpObjId; import org.opennms.netmgt.snmp.SnmpUtils; import org.opennms.netmgt.snmp.SnmpValue; import org.opennms.netmgt.snmp.SnmpWalker; public class CollectionSet implements Collectable { public static class RescanNeeded { boolean rescanNeeded = false; public void rescanIndicated() { rescanNeeded = true; } public boolean rescanIsNeeded() { return rescanNeeded; } } static public final class IfNumberTracker extends SingleInstanceTracker { int m_ifNumber = -1; IfNumberTracker() { super(SnmpObjId.get(SnmpCollector.INTERFACES_IFNUMBER), SnmpInstId.INST_ZERO); } protected void storeResult(SnmpObjId base, SnmpInstId inst, SnmpValue val) { m_ifNumber = val.toInt(); } public int getIfNumber() { return m_ifNumber; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()); buffer.append("@"); buffer.append(Integer.toHexString(hashCode())); buffer.append(": ifNumber: " + m_ifNumber); return buffer.toString(); } } private CollectionAgent m_agent; private OnmsSnmpCollection m_snmpCollection; private SnmpIfCollector m_ifCollector; private CollectionSet.IfNumberTracker m_ifNumber; private SnmpNodeCollector m_nodeCollector; public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("CollectionAgent: "); buffer.append(m_agent); buffer.append("\n"); buffer.append("OnmsSnmpCollection: "); buffer.append(m_snmpCollection); buffer.append("\n"); buffer.append("SnmpIfCollector: "); buffer.append(m_ifCollector); buffer.append("\n"); buffer.append("IfNumberTracker: "); buffer.append(m_ifNumber); buffer.append("\n"); buffer.append("SnmpNodeCollector: "); buffer.append(m_nodeCollector); buffer.append("\n"); return buffer.toString(); } public CollectionSet(CollectionAgent agent, OnmsSnmpCollection snmpCollection) { m_agent = agent; m_snmpCollection = snmpCollection; } public SnmpIfCollector getIfCollector() { if (m_ifCollector == null) m_ifCollector = createIfCollector(); return m_ifCollector; } public CollectionSet.IfNumberTracker getIfNumber() { if (m_ifNumber == null) m_ifNumber = createIfNumberTracker(); return m_ifNumber; } public SnmpNodeCollector getNodeCollector() { if (m_nodeCollector == null) m_nodeCollector = createNodeCollector(); return m_nodeCollector; } private SnmpNodeCollector createNodeCollector() { SnmpNodeCollector nodeCollector = null; if (!getAttributeList().isEmpty()) { nodeCollector = new SnmpNodeCollector(m_agent.getInetAddress(), getAttributeList(), this); } return nodeCollector; } private CollectionSet.IfNumberTracker createIfNumberTracker() { CollectionSet.IfNumberTracker ifNumber = null; if (hasInterfaceDataToCollect()) { ifNumber = new CollectionSet.IfNumberTracker(); } return ifNumber; } private SnmpIfCollector createIfCollector() { SnmpIfCollector ifCollector = null; // construct the ifCollector if (hasInterfaceDataToCollect()) { ifCollector = new SnmpIfCollector(m_agent.getInetAddress(), getCombinedInterfaceAttributes(), this); } return ifCollector; } public NodeInfo getNodeInfo() { return getNodeResourceType().getNodeInfo(); } boolean hasDataToCollect() { return (getNodeResourceType().hasDataToCollect() || getIfResourceType().hasDataToCollect()); } boolean hasInterfaceDataToCollect() { return getIfResourceType().hasDataToCollect(); } public CollectionAgent getCollectionAgent() { return m_agent; } Category log() { return ThreadCategory.getInstance(getClass()); } Collection getAttributeList() { return getNodeInfo().getAttributeTypes(); } /** * @deprecated Use {@link org.opennms.netmgt.collectd.IfResourceType#getCombinedInterfaceAttributes()} instead */ List<AttributeType> getCombinedInterfaceAttributes() { List<AttributeType> attributes = new LinkedList<AttributeType>(); attributes.addAll(getIfResourceType().getCombinedInterfaceAttributes()); attributes.addAll(getIfAliasResourceType().getAttributeTypes()); attributes.addAll(getGenericIndexAttributeTypes()); return attributes; } protected Collection<AttributeType> getGenericIndexAttributeTypes() { Collection<AttributeType> attributeTypes = new LinkedList<AttributeType>(); Collection<ResourceType> resourceTypes = getGenericIndexResourceTypes(); for (ResourceType resourceType : resourceTypes) { attributeTypes.addAll(resourceType.getAttributeTypes()); } return attributeTypes; } private Collection<ResourceType> getGenericIndexResourceTypes() { Collection<org.opennms.netmgt.config.datacollection.ResourceType> configuredResourceTypes = DataCollectionConfigFactory.getInstance().getConfiguredResourceTypes().values(); List<ResourceType> resourceTypes = new LinkedList<ResourceType>(); for (org.opennms.netmgt.config.datacollection.ResourceType configuredResourceType : configuredResourceTypes) { resourceTypes.add(new GenericIndexResourceType(m_agent, m_snmpCollection, configuredResourceType)); } return resourceTypes; } /** * @deprecated Use {@link org.opennms.netmgt.collectd.IfResourceType#getIfInfos()} instead */ public Collection getIfInfos() { return getIfResourceType().getIfInfos(); } public IfInfo getIfInfo(int ifIndex) { return getIfResourceType().getIfInfo(ifIndex); } public CollectionTracker getCollectionTracker() { return new AggregateTracker(AttributeType.getCollectionTrackers(getAttributeTypes())); } private Collection<AttributeType> getAttributeTypes() { return m_snmpCollection.getAttributeTypes(m_agent); } public Collection getResources() { return m_snmpCollection.getResources(m_agent); } public void visit(CollectionSetVisitor visitor) { visitor.visitCollectionSet(this); for (Iterator iter = getResources().iterator(); iter.hasNext();) { CollectionResource resource = (CollectionResource) iter.next(); resource.visit(visitor); } visitor.completeCollectionSet(this); } CollectionTracker getTracker() { List<Collectable> trackers = new ArrayList<Collectable>(3); if (getIfNumber() != null) { trackers.add(getIfNumber()); } if (getNodeCollector() != null) { trackers.add(getNodeCollector()); } if (getIfCollector() != null) { trackers.add(getIfCollector()); } return new AggregateTracker(trackers); } protected SnmpWalker createWalker() { CollectionAgent agent = getCollectionAgent(); return SnmpUtils.createWalker(getAgentConfig(), "SnmpCollectors for " + agent.getHostAddress(), getTracker()); } void logStartedWalker() { if (log().isDebugEnabled()) { log().debug( "collect: successfully instantiated " + "SnmpNodeCollector() for " + getCollectionAgent().getHostAddress()); } } void logFinishedWalker() { log().info( "collect: node SNMP query for address " + getCollectionAgent().getHostAddress() + " complete."); } void verifySuccessfulWalk(SnmpWalker walker) throws CollectionWarning { if (walker.failed()) { // Log error and return COLLECTION_FAILED throw new CollectionWarning("collect: collection failed for " + getCollectionAgent().getHostAddress()); } } void collect() throws CollectionWarning { // XXX Should we have a call to hasDataToCollect here? try { // now collect the data SnmpWalker walker = createWalker(); walker.start(); logStartedWalker(); // wait for collection to finish walker.waitFor(); logFinishedWalker(); // Was the collection successful? verifySuccessfulWalk(walker); getCollectionAgent().setMaxVarsPerPdu(walker.getMaxVarsPerPdu()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CollectionWarning("collect: Collection of node SNMP " + "data for interface " + getCollectionAgent().getHostAddress() + " interrupted!", e); } } void checkForNewInterfaces(CollectionSet.RescanNeeded rescanNeeded) { if (!hasInterfaceDataToCollect()) return; logIfCounts(); if (ifCountHasChanged(getCollectionAgent())) { log().info("Sending rescan event because the number of interfaces on primary SNMP " + "interface " + getCollectionAgent().getHostAddress() + " has changed, generating 'ForceRescan' event."); rescanNeeded.rescanIndicated(); } getCollectionAgent().setSavedIfCount(getIfNumber().getIfNumber()); } private void logIfCounts() { CollectionAgent agent = getCollectionAgent(); log().debug("collect: nodeId: " + agent.getNodeId() + " interface: " + agent.getHostAddress() + " ifCount: " + getIfNumber().getIfNumber() + " savedIfCount: " + agent.getSavedIfCount()); } public boolean rescanNeeded() { final RescanNeeded rescanNeeded = new RescanNeeded(); visit(new ResourceVisitor() { public void visitResource(CollectionResource resource) { log().debug("rescanNeeded: Visiting resource " + resource); if (resource.rescanNeeded()) { log().debug("Sending rescan event for "+getCollectionAgent()+" because resource "+resource+" indicated it was needed"); rescanNeeded.rescanIndicated(); } } }); checkForNewInterfaces(rescanNeeded); return rescanNeeded.rescanIsNeeded(); } public SnmpAgentConfig getAgentConfig() { SnmpAgentConfig agentConfig = getCollectionAgent().getAgentConfig(); agentConfig.setMaxVarsPerPdu(computeMaxVarsPerPdu(agentConfig)); int snmpPort = m_snmpCollection.getSnmpPort(); if (snmpPort > -1) { agentConfig.setPort(snmpPort); } return agentConfig; } private int computeMaxVarsPerPdu(SnmpAgentConfig agentConfig) { int maxVarsPerPdu = getCollectionAgent().getMaxVarsPerPdu(); if (maxVarsPerPdu < 1) { maxVarsPerPdu = m_snmpCollection.getMaxVarsPerPdu(); log().info("using maxVarsPerPdu from dataCollectionConfig"); } if (maxVarsPerPdu < 1) { maxVarsPerPdu = agentConfig.getMaxVarsPerPdu(); log().info("using maxVarsPerPdu from snmpconfig"); } if (maxVarsPerPdu < 1) { log().warn("maxVarsPerPdu CANNOT BE LESS THAN 1. Using 10"); return 10; } return maxVarsPerPdu; } public void notifyIfNotFound(AttributeDefinition attrType, SnmpObjId base, SnmpInstId inst, SnmpValue val) { // Don't bother sending a rescan event in this case since localhost is not going to be there anyway //triggerRescan(); log().info("Unable to locate resource for agent "+getCollectionAgent()+" with instance id "+inst+" while collecting attribute "+attrType); } void saveAttributes(final ServiceParameters params) { BasePersister persister = createPersister(params); visit(persister); } private BasePersister createPersister(ServiceParameters params) { if (Boolean.getBoolean("org.opennms.rrd.storeByGroup")) { return new GroupPersister(params); } else { return new OneToOnePersister(params); } } private boolean ifCountHasChanged(CollectionAgent agent) { return (agent.getSavedIfCount() != -1) && (getIfNumber().getIfNumber() != agent.getSavedIfCount()); } private NodeResourceType getNodeResourceType() { return m_snmpCollection.getNodeResourceType(getCollectionAgent()); } private IfResourceType getIfResourceType() { return m_snmpCollection.getIfResourceType(getCollectionAgent()); } private IfAliasResourceType getIfAliasResourceType() { return m_snmpCollection.getIfAliasResourceType(getCollectionAgent()); } }
package org.fiteagle.adapters.openstack; import info.openmultinet.ontology.vocabulary.Omn; import info.openmultinet.ontology.vocabulary.Omn_domain_pc; import info.openmultinet.ontology.vocabulary.Omn_lifecycle; import info.openmultinet.ontology.vocabulary.Omn_monitoring; import info.openmultinet.ontology.vocabulary.Omn_resource; import info.openmultinet.ontology.vocabulary.Omn_service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.ejb.EJB; import javax.enterprise.concurrent.ManagedThreadFactory; import javax.naming.InitialContext; import javax.naming.NamingException; import org.fiteagle.abstractAdapter.AbstractAdapter; import org.fiteagle.adapters.openstack.client.IOpenstackClient; import org.fiteagle.adapters.openstack.client.OpenstackClient; import org.fiteagle.adapters.openstack.client.model.Flavors; import org.fiteagle.adapters.openstack.client.model.Images; import org.fiteagle.adapters.openstack.client.model.Servers; import org.fiteagle.adapters.openstack.dm.OpenstackAdapterMDBSender; import org.fiteagle.api.core.Config; import org.fiteagle.api.core.IMessageBus; import org.fiteagle.api.core.MessageUtil; import org.fiteagle.api.core.OntologyModelUtil; import org.jclouds.openstack.nova.v2_0.domain.Flavor; import org.jclouds.openstack.nova.v2_0.domain.FloatingIP; import org.jclouds.openstack.nova.v2_0.domain.Image; import org.jclouds.openstack.nova.v2_0.domain.Server; import org.jclouds.openstack.nova.v2_0.domain.ServerCreated; import org.jclouds.openstack.nova.v2_0.options.CreateServerOptions; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; public class OpenstackAdapter extends AbstractAdapter { Logger LOGGER = Logger.getLogger(this.getClass().getName()); protected IOpenstackClient openstackClient; private OpenstackAdapterMDBSender listener; @EJB OpenstackAdapterControl openstackAdapterControler; private Map<String,ArrayList<String>> defaultFlavours = openstackAdapterControler.instancesDefaultFlavours.get(this.uuid); private String floatingPool; private String keystone_auth_URL; private String net_name; private String nova_endpoint; private String keystone_password; private String keystone_endpoint; private String glance_endpoint; private String net_endpoint; private String tenant_name; private String keystone_username; private String default_flavor_id; private String default_image_id; private String default_region; private Flavors flavors; public OpenstackAdapter(Model adapterTBox, Resource adapterABox){ this.uuid = UUID.randomUUID().toString(); this.openstackClient = new OpenstackClient(this); this.adapterTBox = adapterTBox; this.adapterABox = adapterABox; Resource adapterType = Omn_domain_pc.VMServer; this.adapterABox.addProperty(RDF.type,adapterType); this.adapterABox.addProperty(RDFS.label, this.adapterABox.getLocalName()); this.adapterABox.addProperty(RDFS.comment, "Openstack server"); Property longitude = adapterTBox.createProperty("http://www.w3.org/2003/01/geo/wgs84_pos#long"); Property latitude = adapterTBox.createProperty("http://www.w3.org/2003/01/geo/wgs84_pos#lat"); this.adapterABox.addProperty(latitude, "52.516377"); this.adapterABox.addProperty(longitude, "13.323732"); this.adapterABox.addProperty(Omn_lifecycle.canImplement, Omn_domain_pc.VM); } public void initFlavors() { LOGGER.info("init flavors"); flavors = openstackClient.listFlavors(); LOGGER.info("read flavors"); readDefaultFlavours(); List<Resource> diskImages = getDiskImages(); for(Flavor flavor: flavors.getList()){ if(flavor.getName().startsWith("r1.")){ Resource vmResource = adapterABox.getModel().createResource(adapterABox.getNameSpace() + flavor.getName()); vmResource.addProperty(RDF.type, Omn_domain_pc.VM); vmResource.addProperty(RDFS.subClassOf, Omn.Resource); vmResource.addProperty(Omn_domain_pc.hasCPU, String.valueOf(flavor.getVcpus())); vmResource.addProperty(Omn_lifecycle.hasID,flavor.getId()); for(Resource r: diskImages){ vmResource.addProperty(Omn_domain_pc.hasDiskImage, r); r.addProperty(Omn_domain_pc.hasDiskimageLabel, r.getNameSpace()); adapterABox.addProperty(Omn_lifecycle.canImplement, r); } adapterABox.addProperty(Omn_lifecycle.canImplement, vmResource); } } } public void readDefaultFlavours(){ if(openstackAdapterControler.instancesDefaultFlavours.get(this.uuid) != null){ defaultFlavours =openstackAdapterControler.instancesDefaultFlavours.get(this.uuid); LOGGER.info("got default flavors"); for (String s : defaultFlavours.keySet()){ Resource flavourResource = adapterABox.getModel().createResource(adapterABox.getNameSpace() + s); flavourResource.addProperty(RDF.type, Omn_domain_pc.VM); flavourResource.addProperty(Omn_domain_pc.hasDiskImage, defaultFlavours.get(s).get(0)); flavourResource.addProperty(Omn_lifecycle.hasID, defaultFlavours.get(s).get(1)); flavourResource.addProperty(RDFS.subClassOf, Omn.Resource); adapterABox.addProperty(Omn_lifecycle.canImplement, flavourResource); } }else { LOGGER.log(Level.SEVERE, "Could not find default Flavours in the Config-File - Flavours from Server used instead"); } } protected List<Resource> getDiskImages() { List<Resource> diskimages = new ArrayList<>(); Images images = openstackClient.listImages(); for(Image image : images.getList()){ Resource diskImage = adapterABox.getModel().createResource(adapterABox.getNameSpace() + "diskImage/" +image.getId() ); diskImage.addProperty(RDF.type, Omn_domain_pc.DiskImage); diskImage.addProperty(Omn_domain_pc.hasDiskimageLabel,image.getName()); diskImage.addProperty(Omn_domain_pc.hasDiskimageURI, image.getId()); diskimages.add(diskImage); } return diskimages; } @Override public Model createInstance(String instanceURI, Model newInstanceModel) { Resource requestedVM = newInstanceModel.getResource(instanceURI); LOGGER.log(Level.SEVERE, MessageUtil.serializeModel(requestedVM.getModel(), IMessageBus.SERIALIZATION_NTRIPLE)); String diskImageURI = getRequestedTypeURI(requestedVM); String flavorId = getFlavorId(requestedVM); // String diskImageURI = new String(""); if(defaultFlavours == null){ defaultFlavours =openstackAdapterControler.instancesDefaultFlavours.get(this.uuid); } // for (String s : defaultFlavours.keySet()){ // diskImageURI = defaultFlavours.get(s).get(0); testFloatingIps(); if(diskImageURI.isEmpty()){ diskImageURI = getDiskImageId(requestedVM); } String username = getUsername(requestedVM); String publicKey = getPublicKey(requestedVM); Resource monitoringService = getMonitoringService(newInstanceModel); CreateServerOptions options = new CreateServerOptions(); if(username != null && publicKey != null) { String userdata_not_encoded = "#cloud-config\n" + "users:\n" + " - name: " + username + "\n" + " sudo: ALL=(ALL) NOPASSWD:ALL\n" + " shell: /bin/bash\n" + " ssh-authorized-keys:\n" + " - " + publicKey + "\n"; options.userData(userdata_not_encoded.getBytes()); } // try{ // ServerCreated serverForCreate = openstackClient.createServer(requestedVM.getLocalName(), diskImageURI, flavorId, options); // }catch(Exception e){ // e.printStackTrace(); try { CreateVM createVM = new CreateVM(instanceURI, diskImageURI, flavorId, options, this.listener, username); if(monitoringService != null){ createVM.setMonitoringService(monitoringService); } ManagedThreadFactory threadFactory = (ManagedThreadFactory) new InitialContext().lookup("java:jboss/ee/concurrency/factory/default"); Thread createVMThread = threadFactory .newThread(createVM); createVMThread.start(); } catch (NamingException e) { e.printStackTrace(); } Model returnModel = ModelFactory.createDefaultModel(); Resource resource = returnModel.createResource(requestedVM.getURI()); resource.addProperty(RDF.type, Omn_domain_pc.VM); // resource.addProperty(Omn_domain_pc.hasVMID, ) Property property = returnModel.createProperty(Omn_lifecycle.hasState.getNameSpace(), Omn_lifecycle.hasState.getLocalName()); property.addProperty(RDF.type, OWL.FunctionalProperty); resource.addProperty(property, Omn_lifecycle.Uncompleted); return returnModel; } private Resource getMonitoringService(Model newInstanceModel) { ResIterator resIterator = newInstanceModel.listSubjectsWithProperty(RDF.type, Omn_monitoring.MonitoringService); Resource omsp_service = null; while (resIterator.hasNext()){ omsp_service = resIterator.nextResource(); } return omsp_service; } private String addKeypairId(String username, String publicKey ) { String keyPairId = null; if (username != null && publicKey != null) { keyPairId = username + UUID.randomUUID(); openstackClient.addKeyPair(keyPairId, publicKey); } return keyPairId; } private String getPublicKey(Resource requestedVM) { Statement publicKeyStatement = requestedVM.getProperty(Omn_service.publickey); if(publicKeyStatement == null){ System.err.println("Warning: no public key found!"); return ""; } final RDFNode keyObject = publicKeyStatement.getObject(); if (null == keyObject) { System.err.println("Warning: no public key found!"); return ""; } else { return keyObject.toString(); } } private String getUsername(Resource requestedVM) { Statement usernameStatement = requestedVM.getProperty(Omn_service.username); if(usernameStatement != null) { String userName = usernameStatement.getObject().toString(); return userName; } return null; } // public void addListener(OpenstackAdapterMDBSender newListener) { // myListeners.add(newListener); private String getFlavorId(Resource requestedVM) { String flavorId = null; // Resource requestedFlavor = this.adapterABox.getModel().getResource(typeURI); if(requestedVM != null){ Statement statement = requestedVM.getProperty(Omn_lifecycle.hasComponentID); String tmpString = statement.getObject().asLiteral().getString(); String[] tmpArray = null; try{ tmpArray = tmpString.split(Pattern.quote("+")); } catch(Exception e){ LOGGER.log(Level.SEVERE, "Could not find FlavorId for given Flavor"); } String flavorName = tmpArray[tmpArray.length-1]; for (Flavor f : flavors.getList()){ if (f.getName().equals(flavorName)){ flavorId = f.getId(); LOGGER.log(Level.INFO, "Found FlavorID for "+flavorName+" and that is: " + flavorId); } } // Resource flavour = this.adapterABox.getModel().getResource(flavorId); // Statement blub = flavour.getProperty(Omn_lifecycle.hasID); // if(flavour != null){ // flavorId = flavour.getProperty(Omn_lifecycle.hasID).getObject().asLiteral().getString(); // flavorId = node.asLiteral().getString(); return flavorId; } LOGGER.log(Level.SEVERE, "Could not find FlavorId for given Flavor"); return null; } private String getDiskImageId(Resource requestedVM) { String diskImageURI = null; Statement requestedDiskImage = requestedVM.getProperty(Omn_domain_pc.hasDiskImage); if(requestedDiskImage != null){ Resource diskImage = this.adapterABox.getModel().getResource(requestedDiskImage.getObject().asResource().getURI()); diskImageURI = diskImage.getProperty(Omn_domain_pc.hasDiskimageURI).getString(); } return diskImageURI; } private String getRequestedTypeURI(Resource requestedVM) { StmtIterator stmtIterator = requestedVM.listProperties(RDF.type); String requestedType = null; while (stmtIterator.hasNext()){ Statement statement = stmtIterator.nextStatement(); RDFNode one = statement.getObject(); boolean isNode = one.equals(Omn_resource.Node); if(!isNode){ requestedType = statement.getObject().asResource().getURI(); break; } } return requestedType; } @Override public void deleteInstance(String instanceURI) { Server instance = null; try { instance = getServerWithName(instanceURI); } catch (InstanceNotFoundException e) { Logger.getAnonymousLogger().log(Level.SEVERE, "Resource could not be deleted"); } String id = instance.getId(); if(openstackClient.deleteServer(id)){ LOGGER.log(Level.SEVERE , "Deleted Server with ID: "+id); }else{ LOGGER.log(Level.SEVERE , "Could not delete Server with ID: " + id); } } private Server getServerWithName(String instanceURI) throws InstanceNotFoundException { Servers servers = openstackClient.listServers(); for(Server server : servers.getList()){ if(server.getName().equals(instanceURI)){ return server; } } throw new InstanceNotFoundException(instanceURI + " not found"); } @Override public void updateAdapterDescription(){ Images images = openstackClient.listImages(); if(images != null){ // openstackParser.addToAdapterInstanceDescription(images); } } @Override public Model updateInstance(String instanceURI, Model configureModel) { return configureModel; } public String getImageAssociatedFlavor(String diskImageName){ try{ return (String) openstackAdapterControler.instancesDefaultFlavours.get(this.uuid).get(diskImageName); }catch(Exception e){ LOGGER.log(Level.SEVERE, "Could not find default Flavour for "+diskImageName); return null; } } /* public Resource getImageResource(){ return adapterModel.getResource(getAdapterManagedResources().get(0).getNameSpace()+"OpenstackImage"); } */ @Override public Resource getAdapterABox() { return adapterABox; } @Override public Model getAdapterDescriptionModel() { return adapterABox.getModel(); } @Override public Model getInstance(String instanceURI) throws InstanceNotFoundException { Servers servers = openstackClient.listServers(); for(Server server : servers.getList()){ if(server.getName().equals(instanceURI)){ // TODO Why are we returning an empty model?! return ModelFactory.createDefaultModel(); } } throw new InstanceNotFoundException("Instance "+instanceURI+" not found"); } @Override public Model getAllInstances() throws InstanceNotFoundException { Model model = ModelFactory.createDefaultModel(); Servers servers = openstackClient.listServers(); for(Server server : servers.getList()){ model.add(getInstance(server.getName())); } return model; } public String getFloatingPool() { return floatingPool; } /*public void setListener(OpenstackAdapterMDBSender listener) { this.listener = listener; } */ public void setFloatingPool(String floatingPool) { this.floatingPool = floatingPool; } public String getKeystone_auth_URL() { return keystone_auth_URL; } public void setKeystone_auth_URL(String keystone_auth_URL) { this.keystone_auth_URL = keystone_auth_URL; } public String getNet_name() { return net_name; } public void setNet_name(String net_name) { this.net_name = net_name; } public String getNova_endpoint() { return nova_endpoint; } public void setNova_endpoint(String nova_endpoint) { this.nova_endpoint = nova_endpoint; } public String getKeystone_password() { return keystone_password; } public void setKeystone_password(String keystone_password) { this.keystone_password = keystone_password; } public String getKeystone_endpoint() { return keystone_endpoint; } public void setKeystone_endpoint(String keystone_endpoint) { this.keystone_endpoint = keystone_endpoint; } public String getGlance_endpoint() { return glance_endpoint; } public void setGlance_endpoint(String glance_endpoint) { this.glance_endpoint = glance_endpoint; } public String getNet_endpoint() { return net_endpoint; } public void setNet_endpoint(String net_endpoint) { this.net_endpoint = net_endpoint; } public String getTenant_name() { return tenant_name; } public void setTenant_name(String tenant_name) { this.tenant_name = tenant_name; } public String getKeystone_username() { return keystone_username; } public void setKeystone_username(String keystone_username) { this.keystone_username = keystone_username; } public String getDefault_flavor_id() { return default_flavor_id; } public void setDefault_flavor_id(String default_flavor_id) { this.default_flavor_id = default_flavor_id; } public String getDefault_image_id() { return default_image_id; } public String getDefault_region() { return default_region; } public void setDefault_image_id(String default_image_id) { this.default_image_id = default_image_id; } @Override public void refreshConfig() throws ProcessingException { // TODO Auto-generated method stub } @Override public void shutdown() { } @Override public void configure(Config configuration) { } public void setListener(OpenstackAdapterMDBSender listener) { this.listener = listener; } public void testFloatingIps(){ List<FloatingIP> floatingIps = openstackClient.listFreeFloatingIps(); LOGGER.log(Level.SEVERE, floatingIps.toString()); } private class CreateVM implements Runnable { private final OpenstackAdapterMDBSender parent; private final String username; private Resource monitoringService; private String name; private String imageId; private String flavorId; private CreateServerOptions options; public CreateVM(String name,String imageId,String flavorID,CreateServerOptions options, OpenstackAdapterMDBSender parent, String username){ this.parent = parent; this.username = username; this.name = name; this.flavorId = flavorID; this.imageId = imageId; this.options = options; } public Resource getMonitoringService() { return monitoringService; } public void setMonitoringService(Resource monitoringService) { this.monitoringService = monitoringService; } @Override public void run() { ServerCreated server = openstackClient.createServer(name,imageId,flavorId,options); List<FloatingIP> floatingIps = openstackClient.listFreeFloatingIps(); FloatingIP floatingIp = null; if(floatingIps != null){ Iterator<FloatingIP> floatingIpIterator = floatingIps.iterator(); while(floatingIpIterator.hasNext()) { FloatingIP tempfloatingIp = floatingIpIterator.next(); if (tempfloatingIp.getInstanceId() == null) { floatingIp = tempfloatingIp; break; } } } if(floatingIp == null){ LOGGER.log(Level.SEVERE , "FLOATING IP IS EMPTY"); } Model model = parseToModel(server, floatingIp); parent.publishModelUpdate(model, UUID.randomUUID().toString(), IMessageBus.TYPE_INFORM, IMessageBus.TARGET_ORCHESTRATOR); } private Model parseToModel(ServerCreated server, FloatingIP floatingIp){ //TODO: better check whether it's already an URI Model parsedServerModel = ModelFactory.createDefaultModel(); Resource parsedServer = parsedServerModel.createResource(server.getName()); Server tmpServer = openstackClient.getServerDetails(server.getId()); int retryCounter = 0; while(retryCounter < 10){ if(!"ACTIVE".equalsIgnoreCase(tmpServer.getStatus().value())){ try { Thread.sleep(1000); tmpServer = openstackClient.getServerDetails(tmpServer.getId()); } catch (InterruptedException e) { throw new RuntimeException(); } }else { break; } } try { openstackClient.allocateFloatingIpForServer(tmpServer.getId(),floatingIp.getIp()); }catch (Exception e){ e.printStackTrace(); throw new RuntimeException(); } parsedServer.addProperty(Omn_domain_pc.hasVMID,tmpServer.getId()); parsedServer.addProperty(RDF.type, Omn_domain_pc.VM); Property property = parsedServer.getModel().createProperty(Omn_lifecycle.hasState.getNameSpace(),Omn_lifecycle.hasState.getLocalName()); property.addProperty(RDF.type, OWL.FunctionalProperty); parsedServer.addProperty(property, Omn_lifecycle.Started); if(floatingIp != null){ Resource loginService = parsedServerModel.createResource(OntologyModelUtil .getResourceNamespace() + "LoginService" + UUID.randomUUID().toString()); loginService.addProperty(RDF.type, Omn_service.LoginService); loginService.addProperty(Omn_service.authentication,"ssh-keys"); loginService.addProperty(Omn_service.username, username); loginService.addProperty(Omn_service.hostname, floatingIp.getIp()); loginService.addProperty(Omn_service.port,"22"); parsedServer.addProperty(Omn.hasService, loginService); } if(monitoringService != null){ parsedServer.addProperty(Omn_lifecycle.usesService,monitoringService); parsedServer.getModel().add(monitoringService.listProperties()); } return parsedServer.getModel(); } } public IOpenstackClient getOpenstackClient() { return openstackClient; } protected void setOpenstackClient(IOpenstackClient openstackClient) { this.openstackClient = openstackClient; } public void setDefault_region(String default_region) { // TODO Auto-generated method stub this.default_region = default_region; } }
package org.jenetics.internal.util; import java.util.ListIterator; import java.util.NoSuchElementException; public class ArrayProxyIterator<T> implements ListIterator<T> { final ArrayProxy<T> _proxy; private int _pos = 0; public ArrayProxyIterator(final ArrayProxy<T> proxy) { _proxy = proxy; } @Override public boolean hasNext() { return _pos < _proxy._length; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return _proxy.uncheckedGet(_pos++); } @Override public int nextIndex() { return _pos + 1; } @Override public boolean hasPrevious() { return _pos > 0; } @Override public T previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } return _proxy.uncheckedGet(--_pos); } @Override public int previousIndex() { return _pos - 1; } @Override public void set(final T value) { throw new UnsupportedOperationException( "Iterator is immutable." ); } @Override public void add(final T value) { throw new UnsupportedOperationException( "Can't change Iteration size." ); } @Override public void remove() { throw new UnsupportedOperationException( "Can't change Iterattion size." ); } }
package sk.henrichg.phoneprofiles; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; public class LockDeviceActivity extends AppCompatActivity { private View view = null; @SuppressLint("InflateParams") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); overridePendingTransition(0, 0); PPApplication.lockDeviceActivity = this; /* View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; decorView.setSystemUiVisibility(uiOptions); setContentView(R.layout.activity_lock_device); WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness =0.005f; getWindow().setAttributes(lp); */ PPApplication.screenTimeoutBeforeDeviceLock = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000); ActivateProfileHelper.screenTimeoutUnlock(getApplicationContext()); Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000); WindowManager.LayoutParams params = new WindowManager.LayoutParams(); params.flags = 1808; //TODO Android O //if (android.os.Build.VERSION.SDK_INT < 26) params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR; //else // params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; params.gravity = Gravity.TOP; params.width = -1; params.height = -1; params.format = -1; params.screenBrightness = 0f; LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = layoutInflater.inflate(R.layout.activity_lock_device, null); view.setSystemUiVisibility(5894); view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int i) { view.setSystemUiVisibility(5894); } }); WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE); if (windowManager != null) windowManager.addView(view, params); LockDeviceActivityFinishBroadcastReceiver.setAlarm(getApplicationContext()); } @Override protected void onDestroy() { super.onDestroy(); if (view != null) { try { WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE); if (windowManager != null) windowManager.removeViewImmediate(view); } catch (Exception ignored) {} } LockDeviceActivityFinishBroadcastReceiver.removeAlarm(getApplicationContext()); PPApplication.lockDeviceActivity = null; if (Permissions.checkLockDevice(getApplicationContext())) Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, PPApplication.screenTimeoutBeforeDeviceLock); } @Override public void finish() { super.finish(); overridePendingTransition(0, 0); } }
package ua.com.fielden.platform.utils; import static java.lang.String.format; import static ua.com.fielden.platform.entity.AbstractEntity.COMMON_PROPS; import static ua.com.fielden.platform.reflection.AnnotationReflector.getKeyType; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import org.joda.time.DateTime; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.AbstractUnionEntity; import ua.com.fielden.platform.entity.ActivatableAbstractEntity; import ua.com.fielden.platform.entity.DynamicEntityKey; import ua.com.fielden.platform.entity.annotation.DescTitle; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.entity.annotation.MapEntityTo; import ua.com.fielden.platform.entity.fetch.FetchProviderFactory; import ua.com.fielden.platform.entity.fetch.IFetchProvider; import ua.com.fielden.platform.entity.meta.MetaProperty; import ua.com.fielden.platform.entity.meta.PropertyDescriptor; import ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.reflection.AnnotationReflector; import ua.com.fielden.platform.reflection.Finder; import ua.com.fielden.platform.reflection.TitlesDescsGetter; import ua.com.fielden.platform.reflection.asm.impl.DynamicEntityClassLoader; import ua.com.fielden.platform.serialisation.api.ISerialiser; import ua.com.fielden.platform.types.Money; import ua.com.fielden.platform.utils.ConverterFactory.Converter; public class EntityUtils { private final static Logger logger = Logger.getLogger(EntityUtils.class); /** Private default constructor to prevent instantiation. */ private EntityUtils() { } /** * dd/MM/yyyy format instance */ public static final String dateWithoutTimeFormat = "dd/MM/yyyy"; /** * Convenient method for value to {@link String} conversion * * @param value * @param valueType * @return */ public static String toString(final Object value, final Class<?> valueType) { if (value == null) { return ""; } if (valueType == Integer.class || valueType == int.class) { return NumberFormat.getInstance().format(value); } else if (Number.class.isAssignableFrom(valueType) || valueType == double.class) { return NumberFormat.getInstance().format(new BigDecimal(value.toString())); } else if (valueType == Date.class || valueType == DateTime.class) { final Date date = valueType == Date.class ? (Date) value : ((DateTime) value).toDate(); return new SimpleDateFormat(dateWithoutTimeFormat).format(date) + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(date); } else if (Money.class.isAssignableFrom(valueType)) { return value instanceof Number ? new Money(value.toString()).toString() : value.toString(); } else if (valueType == BigDecimalWithTwoPlaces.class) { return value instanceof Number ? String.format("%,10.2f", value) : value.toString(); } else { return value.toString(); } } /** * Invokes method {@link #toString(Object, Class)} with the second argument being assigned as value's class. * * @param value * @return */ public static String toString(final Object value) { if (value == null) { return ""; } return toString(value, value.getClass()); } /** * Null-safe comparator. * * @param o1 * @param o2 * @return */ public static int safeCompare(final Comparable c1, final Comparable c2) { if (c1 == null && c2 == null) { return 0; } else if (c1 == null) { return -1; } else if (c2 == null) { return 1; } else { return c1.compareTo(c2); } } /** * Null-safe equals based on the {@link AbstractEntity}'s id property. If id property is not present in both entities then default equals for entities will be called. * * @param entity1 * @param entity2 * @return */ public static boolean areEqual(final AbstractEntity<?> entity1, final AbstractEntity<?> entity2) { if (entity1 != null && entity2 != null) { if (entity1.getId() == null && entity2.getId() == null) { return entity1.equals(entity2); } else { return equalsEx(entity1.getId(), entity2.getId()); } } return entity1 == entity2; } /** * Returns value that indicates whether entity is among entities. The equality comparison is based on {@link #areEquals(AbstractEntity, AbstractEntity)} method * * @param entities * @param entity * @return */ public static <T extends AbstractEntity<?>> boolean containsById(final List<T> entities, final T entity) { for (final AbstractEntity<?> e : entities) { if (areEqual(e, entity)) { return true; } } return false; } /** * Returns index of the entity in the entities list. The equality comparison is based on the {@link #areEquals(AbstractEntity, AbstractEntity)} method. * * @param entities * @param entity * @return */ public static <T extends AbstractEntity<?>> int indexOfById(final List<T> entities, final T entity) { for (int index = 0; index < entities.size(); index++) { if (areEqual(entities.get(index), entity)) { return index; } } return -1; } /** * This method chooses appropriate Converter for any types of property. Even for properties of [AbstractEntity's descendant type] or List<[AbstractEntity's descendant type]> or * List<String> * * @param entity * @param propertyName * @return */ public static Converter chooseConverterBasedUponPropertyType(final AbstractEntity<?> entity, final String propertyName, final ShowingStrategy showingStrategy) { final MetaProperty metaProperty = Finder.findMetaProperty(entity, propertyName); return chooseConverterBasedUponPropertyType(metaProperty, showingStrategy); } /** * this method chooses appropriate Converter for any types of property. Even for properties of [AbstractEntity's descendant type] or List<[AbstractEntity's descendant type]> or * List<String> * * @param entity * @param propertyName * @return */ public static Converter chooseConverterBasedUponPropertyType(final Class<?> propertyType, final Class<?> collectionType, final ShowingStrategy showingStrategy) { if (propertyType.equals(String.class)) { return null; } else if (Number.class.isAssignableFrom(propertyType)) { return ConverterFactory.createNumberConverter(); } else if (Money.class.isAssignableFrom(propertyType)) { return ConverterFactory.createMoneyConverter(); } else if (Date.class.equals(propertyType) || DateTime.class.equals(propertyType)) { return ConverterFactory.createDateConverter(); } else if (AbstractEntity.class.isAssignableFrom(propertyType)) { return ConverterFactory.createAbstractEntityOrListConverter(showingStrategy); } else if (List.class.isAssignableFrom(propertyType)) { if (collectionType != null) { final Class<?> typeArgClass = collectionType; if (AbstractEntity.class.isAssignableFrom(typeArgClass)) { return ConverterFactory.createAbstractEntityOrListConverter(showingStrategy); } else if (typeArgClass.equals(String.class)) { return ConverterFactory.createStringListConverter(); } else { System.out.println(new Exception("listType actualTypeArgument is not String or descendant of AbstractEntity!")); return null; } } else { System.out.println(new Exception("listType is not Parameterized???!!")); return null; } } else if (Enum.class.isAssignableFrom(propertyType)) { return ConverterFactory.createTrivialConverter(); } else { return null; } } /** * Does the same as {@link #chooseConverterBasedUponPropertyType(AbstractEntity, String)} * * @param metaProperty * @return */ public static Converter chooseConverterBasedUponPropertyType(final MetaProperty metaProperty, final ShowingStrategy showingStrategy) { return chooseConverterBasedUponPropertyType(metaProperty.getType(), metaProperty.getPropertyAnnotationType(), showingStrategy); } /** * Obtains {@link MetaProperty} using {@link #findFirstFailedMetaProperty(AbstractEntity, String)} and returns {@link #getLabelText(MetaProperty, boolean)} * * @return the subject's text value * @throws MissingConverterException * @throws ClassCastException * if the subject value is not a String */ @SuppressWarnings("unchecked") public static String getLabelText(final AbstractEntity entity, final String propertyName, final ShowingStrategy showingStrategy) { final MetaProperty metaProperty = findFirstFailedMetaProperty(entity, propertyName); return getLabelText(metaProperty, false, showingStrategy); } public enum ShowingStrategy { KEY_ONLY, DESC_ONLY, KEY_AND_DESC } /** * Gets converter for passed {@link MetaProperty} with showKeyOnly param and returns {@link #getLabelText(MetaProperty, Converter)} * * @param metaProperty * @param showKeyOnly * @return */ public static String getLabelText(final MetaProperty metaProperty, final boolean returnEmptyStringIfInvalid, final ShowingStrategy showingStrategy) { final ConverterFactory.Converter converter = chooseConverterBasedUponPropertyType(metaProperty, showingStrategy); return getLabelText(metaProperty, returnEmptyStringIfInvalid, converter); } /** * Returns text value for passed {@link MetaProperty} using passed {@link Converter}. * * @param returnEmptyStringIfInvalid * - if {@link Boolean#TRUE} passed as this parameter, then empty string will be returned if passed {@link MetaProperty} is invalid (converter is not used at all in * this case). Otherwise {@link MetaProperty#getLastInvalidValue()} will be obtained from invalid {@link MetaProperty}, converted using passed {@link Converter} and * returned. * * @return the subject's text value * @throws MissingConverterException * @throws ClassCastException * if the subject value is not a String */ public static String getLabelText(final MetaProperty metaProperty, final boolean returnEmptyStringIfInvalid, final Converter converter) { if (metaProperty != null) { // hierarchy is valid, only the last property could be invalid final Object value = metaProperty.getLastAttemptedValue(); if (!metaProperty.isValid() && returnEmptyStringIfInvalid) { return ""; } return getLabelText(value, converter); } else { // some property (not the last) is invalid, thus showing empty string return ""; } } /** * Returns label text representation of value using specified converter. * * @param value * @param converter * @return */ public static String getLabelText(final Object value, final Converter converter) { if (value != null && !value.getClass().equals(String.class) && converter == null) { return value.toString(); } final String str = converter != null ? converter.convertToString(value) : (String) value; return str == null ? "" : str; } /** * Formats passeed value according to its type. * * @param value * @param valueType * @return */ public static String formatTooltip(final Object value, final Class<?> valueType) { if (value == null) { return ""; } if (valueType == Integer.class) { return NumberFormat.getInstance().format(value); } else if (Number.class.isAssignableFrom(valueType)) { return NumberFormat.getInstance().format(new BigDecimal(value.toString())); } else if (valueType == Date.class || valueType == DateTime.class) { final Object convertedValue = value instanceof DateTime ? ((DateTime) value).toDate() : value; return new SimpleDateFormat(dateWithoutTimeFormat).format(convertedValue) + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(convertedValue); } else { return value.toString(); } } /** * Checks and answers if the two objects are both {@code null} or equal. * * <pre> * #equals(null, null) == true * #equals(&quot;Hi&quot;, &quot;Hi&quot;) == true * #equals(&quot;Hi&quot;, null) == false * #equals(null, &quot;Hi&quot;) == false * #equals(&quot;Hi&quot;, &quot;Ho&quot;) == false * </pre> * * @param o1 * the first object to compare * @param o2 * the second object to compare * @return boolean {@code true} if and only if both objects are {@code null} or equal */ public static boolean equalsEx(final Object o1, final Object o2) { return o1 == o2 || o1 != null && o2 != null && o1.equals(o2); } /** * Returns current value(if property is valid, then its value, otherwise last incorrect value of corresponding meta-property) of property of passed entity.<br> * <br> * Note : does not support dot-notated property names. * * @param entity * @param propertyName * @return */ public static Object getCurrentValue(final AbstractEntity<?> entity, final String propertyName) { final MetaProperty metaProperty = entity.getProperty(propertyName); if (metaProperty == null) { throw new IllegalArgumentException("Couldn't find meta-property named '" + propertyName + "' in " + entity); } else { return metaProperty.isValid() ? entity.get(propertyName) : metaProperty.getLastInvalidValue(); } } /** * Returns either {@link MetaProperty} corresponding to last property in <code>propertyName</code> if all previous {@link MetaProperty}ies are valid and without warnings, or * first failed {@link MetaProperty} or one with warning. * * @param entity * @param propertyName * @return */ public static MetaProperty findFirstFailedMetaProperty(final AbstractEntity<?> entity, final String propertyName) { final List<MetaProperty> metaProperties = Finder.findMetaProperties(entity, propertyName); return findFirstFailedMetaProperty(metaProperties); } /** * Does the same as method {@link #findFirstFailedMetaProperty(AbstractEntity, String)} but already on the provided list of {@link MetaProperty}s. * * @param metaProperties * @return */ public static MetaProperty findFirstFailedMetaProperty(final List<MetaProperty> metaProperties) { MetaProperty firstFailedMetaProperty = metaProperties.get(metaProperties.size() - 1); for (int i = 0; i < metaProperties.size(); i++) { final MetaProperty metaProperty = metaProperties.get(i); if (!metaProperty.isValid() || metaProperty.hasWarnings()) { firstFailedMetaProperty = metaProperty; break; } } return firstFailedMetaProperty; } /** * This method throws Result (so can be used to specify DYNAMIC validation inside the date setters) when the specified finish/start dates are invalid together. * * @param start * @param finish * @param fieldPrefix * - the prefix for the field in the error message for e.g. "actual" or "early". * @param finishSetter * - use true if validation have to be performed inside the "finish" date setter, false - inside the "start" date setter * @throws Result */ public static void validateDateRange(final Date start, final Date finish, final MetaProperty<Date> startProperty, final MetaProperty<Date> finishProperty, final boolean finishSetter) { if (finish != null) { if (start != null) { if (start.after(finish)) { throw Result.failure(finishSetter ? format("Property [%s] (value [%s]) cannot be before property [%s] (value [%s]).", finishProperty.getTitle(), toString(finish) , startProperty.getTitle(), toString(start)) : format("Property [%s] (value [%s]) cannot be after property [%s] (value [%s]).", startProperty.getTitle(), toString(start), finishProperty.getTitle(), toString(finish))); } } else { throw Result.failure(finishSetter ? format("Property [%s] (value [%s]) cannot be specified without property [%s].", finishProperty.getTitle(), finish, startProperty.getTitle()) : format("Property [%s] cannot be empty if property [%s] (value [%s]) if specified.", startProperty.getTitle(), finishProperty.getTitle(), finish)); } } } /** * This method throws Result (so can be used to specify DYNAMIC validation inside the date setters) when the specified finish/start date times are invalid together. * * @param start * @param finish * @param fieldPrefix * - the prefix for the field in the error message for e.g. "actual" or "early". * @param finishSetter * - use true if validation have to be performed inside the "finish" date setter, false - inside the "start" date setter * @throws Result */ public static void validateDateTimeRange(final DateTime start, final DateTime finish, final MetaProperty<DateTime> startProperty, final MetaProperty<DateTime> finishProperty, final boolean finishSetter) { if (finish != null) { if (start != null) { if (start.isAfter(finish)) { throw Result.failure(finishSetter ? format("Property [%s] (value [%s]) cannot be before property [%s] (value [%s]).", finishProperty.getTitle(), toString(finish) , startProperty.getTitle(), toString(start)) : format("Property [%s] (value [%s]) cannot be after property [%s] (value [%s]).", startProperty.getTitle(), toString(start), finishProperty.getTitle(), toString(finish))); } } else { throw Result.failure(finishSetter ? format("Property [%s] (value [%s]) cannot be specified without property [%s].", finishProperty.getTitle(), finish, startProperty.getTitle()) : format("Property [%s] cannot be empty if property [%s] (value [%s]) if specified.", startProperty.getTitle(), finishProperty.getTitle(), finish)); } } } public static void validateIntegerRange(final Integer start, final Integer finish, final MetaProperty startProperty, final MetaProperty finishProperty, final boolean finishSetter) throws Result { if (finish != null) { if (start != null) { if (start.compareTo(finish) > 0) { // after(finish) throw new Result("", new Exception(finishSetter ? finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." // : startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + ".")); } } else { throw new Result("", new Exception(finishSetter ? finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() // : startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified.")); } } } /** * A convenient method for validating two double properties that form a range [from;to]. * * @param start * @param finish * @param startProperty * @param finishProperty * @param finishSetter * @throws Result */ public static void validateDoubleRange(final Double start, final Double finish, final MetaProperty startProperty, final MetaProperty finishProperty, final boolean finishSetter) throws Result { if (finish != null) { if (start != null) { if (start.compareTo(finish) > 0) { // after(finish) throw new Result("", new Exception(finishSetter ? finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." // : startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + ".")); } } else { throw new Result("", new Exception(finishSetter ? finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() // : startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified.")); } } } /** * A convenient method for validating two money properties that form a range [from;to]. * * @param start * @param finish * @param startProperty * @param finishProperty * @param finishSetter * @throws Result */ public static void validateMoneyRange(final Money start, final Money finish, final MetaProperty startProperty, final MetaProperty finishProperty, final boolean finishSetter) throws Result { if (finish != null) { if (start != null) { if (start.compareTo(finish) > 0) { // after(finish) throw new Result("", new Exception(finishSetter ? finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." // : startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + ".")); } } else { throw new Result("", new Exception(finishSetter ? finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() // : startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified.")); } } } /** * Indicates whether type represents enumeration. * * @param type * @return */ public static boolean isEnum(final Class<?> type) { return Enum.class.isAssignableFrom(type); } /** * Indicates whether type represents "rangable" values like {@link Number}, {@link Money} or {@link Date}. * * @param type * @return */ public static boolean isRangeType(final Class<?> type) { return Number.class.isAssignableFrom(type) || Money.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type); } /** * Indicates whether type represents boolean values. * * @param type * @return */ public static boolean isBoolean(final Class<?> type) { return boolean.class.isAssignableFrom(type); } /** * Indicates whether type represents date values. * * @param type * @return */ public static boolean isDate(final Class<?> type) { return Date.class.isAssignableFrom(type); } /** * Indicates whether type represents {@link DateTime} values. * * @param type * @return */ public static boolean isDateTime(final Class<?> type) { return DateTime.class.isAssignableFrom(type); } /** * Indicates whether type represents string values. * * @return */ public static boolean isString(final Class<?> type) { return String.class.isAssignableFrom(type); } /** * Indicates whether type represents {@link AbstractEntity}-typed values. * * @return */ public static boolean isEntityType(final Class<?> type) { return AbstractEntity.class.isAssignableFrom(type); } /** * Indicates whether type represents {@link ActivatableAbstractEntity}-typed values. * * @return */ public static boolean isActivatableEntityType(final Class<?> type) { return ActivatableAbstractEntity.class.isAssignableFrom(type); } /** * Indicates whether type represents {@link Integer}-typed values. * * @return */ public static boolean isInteger(final Class<?> type) { return Integer.class.isAssignableFrom(type); } /** * Indicates whether type represents either {@link BigDecimal} or {@link Money}-typed values. * * @return */ public static boolean isDecimal(final Class<?> type) { return BigDecimal.class.isAssignableFrom(type) || Money.class.isAssignableFrom(type); } public static boolean isDynamicEntityKey(final Class<?> type) { return DynamicEntityKey.class.isAssignableFrom(type); } /** * Indicates that given entity type is mapped to database. * * @return */ public static boolean isPersistedEntityType(final Class<?> type) { return type != null && isEntityType(type) && AnnotationReflector.getAnnotation(type, MapEntityTo.class) != null; } /** * Identifies whether the entity type represent a composite entity. * * @param entityType * @return */ public static <T extends AbstractEntity<?>> boolean isCompositeEntity(final Class<T> entityType) { final KeyType keyAnnotation = AnnotationReflector.getAnnotation(entityType, KeyType.class); if (keyAnnotation != null) { return DynamicEntityKey.class.isAssignableFrom(keyAnnotation.value()); } else { return false; } } /** * Indicates that given entity type is based on query model. * * @return */ public static <ET extends AbstractEntity<?>> boolean isQueryBasedEntityType(final Class<ET> type) { return type != null && isEntityType(type) && AnnotationReflector.getAnnotation(type, MapEntityTo.class) == null && getEntityModelsOfQueryBasedEntityType(type).size() > 0; } /** * Returns list of query models, which given entity type is based on (assuming it is after all). * * @param entityType * @return */ public static <ET extends AbstractEntity<?>> List<EntityResultQueryModel<ET>> getEntityModelsOfQueryBasedEntityType(final Class<ET> entityType) { final List<EntityResultQueryModel<ET>> result = new ArrayList<EntityResultQueryModel<ET>>(); try { final Field exprField = entityType.getDeclaredField("model_"); exprField.setAccessible(true); result.add((EntityResultQueryModel<ET>) exprField.get(null)); return result; } catch (final Exception e) { } try { final Field exprField = entityType.getDeclaredField("models_"); exprField.setAccessible(true); result.addAll((List<EntityResultQueryModel<ET>>) exprField.get(null)); return result; } catch (final Exception e) { } return result; } /** * Indicates whether type represents {@link Collection}-typed values. * * @return */ public static boolean isCollectional(final Class<?> type) { return Collection.class.isAssignableFrom(type); } /** * Indicates whether type represents {@link PropertyDescriptor}-typed values. * * @return */ public static boolean isPropertyDescriptor(final Class<?> type) { return PropertyDescriptor.class.isAssignableFrom(type); } /** * Indicates whether type represents {@link AbstractUnionEntity}-typed values. * * @return */ public static boolean isUnionEntityType(final Class<?> type) { return type != null && AbstractUnionEntity.class.isAssignableFrom(type); } /** * Returns a deep copy of an object (all hierarchy of properties will be copied).<br> * <br> * * <b>Important</b> : Depending on {@link ISerialiser} implementation, all classes that are used in passed object hierarchy should correspond some contract. For e.g. Kryo based * serialiser requires all the classes to be registered and to have default constructor, simple java serialiser requires all the classes to implement {@link Serializable} etc. * * @param oldObj * @param serialiser * @return -- <code>null</code> if <code>oldObj</code> is <code>null</code>, otherwise a deep copy of <code>oldObj</code>. * */ public static <T> T deepCopy(final T oldObj, final ISerialiser serialiser) { if (oldObj == null) { // obviously return null if oldObj == null return null; } try { final byte[] serialised = serialiser.serialise(oldObj); return serialiser.deserialise(serialised, (Class<T>) oldObj.getClass()); } catch (final Exception e) { throw deepCopyError(oldObj, e); } // final ObjectOutputStream oos = null; // final ObjectInputStream ois = null; // try { // final ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A // oos = new ObjectOutputStream(bos); // B // // serialize and pass the object // oos.writeObject(oldObj); // C // oos.flush(); // D // final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E // ois = new ObjectInputStream(bin); // F // // return the new object // return (T) ois.readObject(); // G // } catch (final Exception e) { // throw deepCopyError(oldObj, e); // } finally { // try { // if (oos != null) { // oos.close(); // if (ois != null) { // ois.close(); // } catch (final IOException e2) { // throw deepCopyError(oldObj, e2); } /** * Returns the not enhanced copy of the specified enhancedEntity. * * @param enhancedEntity * @return */ @SuppressWarnings("unchecked") public static <T extends AbstractEntity<?>> T makeNotEnhanced(final T enhancedEntity) { return enhancedEntity == null ? null : (T) enhancedEntity.copy(DynamicEntityClassLoader.getOriginalType(enhancedEntity.getType())); } /** * Returns the not enhanced copy of the list of enhanced entities. * * @param enhancedEntities * @return */ public static <T extends AbstractEntity<?>> List<T> makeNotEnhanced(final List<T> enhancedEntities) { if (enhancedEntities == null) { return null; } final List<T> notEnhnacedEntities = new ArrayList<>(); for (final T entry : enhancedEntities) { notEnhnacedEntities.add(makeNotEnhanced(entry)); } return notEnhnacedEntities; } protected static IllegalStateException deepCopyError(final Object oldObj, final Exception e) { final String message = "The deep copy operation has been failed for object [" + oldObj + "]. Cause = [" + e.getMessage() + "]."; e.printStackTrace(); logger.error(message); return new IllegalStateException(message); } /** * A convenient method for extracting type information from all enum value for a specified enum type. * * @param <E> * @param type * @return */ public static <E extends Enum<E>> List<Class<?>> extractTypes(final Class<E> type) { final List<Class<?>> result = new ArrayList<Class<?>>(); result.add(type); final EnumSet<E> mnemonicEnumSet = EnumSet.allOf(type); for (final E value : mnemonicEnumSet) { result.add(value.getClass()); } return result; } /** * Splits dot.notated property in two parts: first level property and the rest of subproperties. * * @param dotNotatedPropName * @return */ public static Pair<String, String> splitPropByFirstDot(final String dotNotatedPropName) { final int firstDotIndex = dotNotatedPropName.indexOf("."); if (firstDotIndex != -1) { return new Pair<String, String>(dotNotatedPropName.substring(0, firstDotIndex), dotNotatedPropName.substring(firstDotIndex + 1)); } else { return new Pair<String, String>(dotNotatedPropName, null); } } /** * Splits dot.notated property in two parts: last subproperty (as second part) and prior subproperties. * * @param dotNotatedPropName * @return */ public static Pair<String, String> splitPropByLastDot(final String dotNotatedPropName) { final int lastDotIndex = findLastDotInString(0, dotNotatedPropName); if (lastDotIndex != -1) { return new Pair<String, String>(dotNotatedPropName.substring(0, lastDotIndex - 1), dotNotatedPropName.substring(lastDotIndex)); } else { return new Pair<String, String>(null, dotNotatedPropName); } } private static int findLastDotInString(final int fromPosition, final String dotNotatedPropName) { final int nextDotIndex = dotNotatedPropName.indexOf(".", fromPosition); if (nextDotIndex != -1) { return findLastDotInString(nextDotIndex + 1, dotNotatedPropName); } else { return fromPosition; } } /** * Returns true if the provided <code>dotNotationProp</code> is a valid property in the specified entity type. * * @param type * @param dotNotationProp * @return */ public static boolean isProperty(final Class<?> type, final String dotNotationProp) { try { return AnnotationReflector.isAnnotationPresent(Finder.findFieldByName(type, dotNotationProp), IsProperty.class); } catch (final Exception ex) { return false; } } /** * Retrieves all persisted properties fields within given entity type * * @param entityType * @return */ public static List<Field> getRealProperties(final Class entityType) { final List<Field> result = new ArrayList<Field>(); for (final Field propField : Finder.findRealProperties(entityType)) { //, MapTo.class if (!(propField.getName().equals("desc") && !hasDescProperty(entityType))) { result.add(propField); } } return result; } public static <ET extends AbstractEntity<?>> boolean hasDescProperty(final Class<ET> entityType) { return AnnotationReflector.isAnnotationPresentForClass(DescTitle.class, entityType); } /** * Retrieves all collectional properties fields within given entity type * * @param entityType * @return */ public static List<Field> getCollectionalProperties(final Class entityType) { final List<Field> result = new ArrayList<Field>(); for (final Field propField : Finder.findRealProperties(entityType)) { if (Collection.class.isAssignableFrom(propField.getType()) && Finder.hasLinkProperty(entityType, propField.getName())) { result.add(propField); } } return result; } public static class BigDecimalWithTwoPlaces { }; /** * Produces list of props that should be added to order model instead of composite key. * * @param entityType * @param prefix * @return */ public static List<String> getOrderPropsFromCompositeEntityKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType, final String prefix) { final List<String> result = new ArrayList<>(); final List<Field> keyProps = Finder.getKeyMembers(entityType); for (final Field keyMemberProp : keyProps) { if (DynamicEntityKey.class.equals(getKeyType(keyMemberProp.getType()))) { result.addAll(getOrderPropsFromCompositeEntityKey((Class<AbstractEntity<DynamicEntityKey>>) keyMemberProp.getType(), (prefix != null ? prefix + "." : "") + keyMemberProp.getName())); } else if (isEntityType(keyMemberProp.getType())) { result.add((prefix != null ? prefix + "." : "") + keyMemberProp.getName() + ".key"); } else { result.add((prefix != null ? prefix + "." : "") + keyMemberProp.getName()); } } return result; } public static SortedSet<String> getFirstLevelProps(final Set<String> allProps) { final SortedSet<String> result = new TreeSet<String>(); for (final String prop : allProps) { result.add(splitPropByFirstDot(prop).getKey()); } return result; } /** * A convenient method for constructing a pair of property and its title as defined at the entity type level. * * @param entityType * @param propName * @return */ public static Pair<String, String> titleAndProp(final Class<? extends AbstractEntity<?>> entityType, final String propName) { return new Pair<>(TitlesDescsGetter.getTitleAndDesc(propName, entityType).getKey(), propName); } /** * Returns <code>true</code> if the original value is stale according to fresh value for current version of entity, <code>false</code> otherwise. * * @param originalValue * -- original value for the property of stale entity * @param freshValue * -- fresh value for the property of current (fresh) version of entity * @return */ public static boolean isStale(final Object originalValue, final Object freshValue) { return !EntityUtils.equalsEx(freshValue, originalValue); } /** * Returns <code>true</code> if the new value for stale entity conflicts with fresh value for current version of entity, <code>false</code> otherwise. * * @param staleNewValue * -- new value for the property of stale entity * @param staleOriginalValue * -- original value for the property of stale entity * @param freshValue * -- fresh value for the property of current (fresh) version of entity * @return */ public static boolean isConflicting(final Object staleNewValue, final Object staleOriginalValue, final Object freshValue) { // old implementation: // return (freshValue == null && staleOriginalValue != null && staleNewValue != null) || // (freshValue != null && staleOriginalValue == null && staleNewValue == null) || // (freshValue != null && !freshValue.equals(staleOriginalValue) && !freshValue.equals(staleNewValue)); return isStale(staleOriginalValue, freshValue) && !EntityUtils.equalsEx(staleNewValue, freshValue); } /** * Creates empty {@link IFetchProvider} for concrete <code>entityType</code> with instrumentation. * * @param entityType * @param instrumented * @return */ public static <T extends AbstractEntity<?>> IFetchProvider<T> fetch(final Class<T> entityType, final boolean instumented) { return FetchProviderFactory.createDefaultFetchProvider(entityType, instumented); } public static <T extends AbstractEntity<?>> IFetchProvider<T> fetch(final Class<T> entityType) { return FetchProviderFactory.createDefaultFetchProvider(entityType, false); } /** * Creates {@link IFetchProvider} for concrete <code>entityType</code> with 'key' and 'desc' (analog of {@link EntityQueryUtils#fetchKeyAndDescOnly(Class)}) with instrumentation. * * @param entityType * @param instrumented * @return */ public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchWithKeyAndDesc(final Class<T> entityType, final boolean instrumented) { return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, instrumented); } public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchWithKeyAndDesc(final Class<T> entityType) { return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, false); } /** * Creates empty {@link IFetchProvider} for concrete <code>entityType</code> <b>without</b> instrumentation. * * @param entityType * @return */ public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchNotInstrumented(final Class<T> entityType) { return FetchProviderFactory.createDefaultFetchProvider(entityType, false); } /** * Creates {@link IFetchProvider} for concrete <code>entityType</code> with 'key' and 'desc' (analog of {@link EntityQueryUtils#fetchKeyAndDescOnly(Class)}) <b>without</b> instrumentation. * * @param entityType * @return */ public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchNotInstrumentedWithKeyAndDesc(final Class<T> entityType) { return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, false); } /** * Tries to perform shallow copy of collectional value. If unsuccessful, returns empty {@link Optional}. * * @param value * @return */ public static <T> Optional<Optional<T>> copyCollectionalValue(final T value) { if (value == null) { return Optional.of(Optional.empty()); // return non-empty optional of empty (null) copy } try { final Collection<?> collection = (Collection<?>) value; // try to obtain empty constructor to perform shallow copying of collection final Constructor<? extends Collection> constructor = collection.getClass().getConstructor(); final Collection copy = constructor.newInstance(); copy.addAll(collection); // return non-empty optional of non-empty copy return Optional.of(Optional.of((T) copy)); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.debug(e.getMessage(), e); } return Optional.empty(); // return empty optional indicating the failure of copying } }
package com.intellij.execution.ui; import com.intellij.execution.BeforeRunTask; import com.intellij.execution.BeforeRunTaskProvider; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl; import com.intellij.execution.impl.UnknownBeforeRunTaskProvider; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.dnd.*; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.PossiblyDumbAware; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.InplaceButton; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBEmptyBorder; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.WrapLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; public final class BeforeRunComponent extends JPanel implements DnDTarget, Disposable { private final List<TaskButton> myTags = new ArrayList<>(); private final InplaceButton myAddButton; private final JPanel myAddPanel; private final LinkLabel<Object> myAddLabel; private final JLabel myDropFirst = new JLabel(AllIcons.General.DropPlace); Runnable myChangeListener; private BiConsumer<Key<? extends BeforeRunTask<?>>, Boolean> myTagListener; private RunConfiguration myConfiguration; public BeforeRunComponent(@NotNull Disposable parentDisposable) { super(new WrapLayout(FlowLayout.LEADING, 0, FragmentedSettingsBuilder.TAG_VGAP)); Disposer.register(parentDisposable, this); add(Box.createVerticalStrut(30)); JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); myDropFirst.setBorder(JBUI.Borders.empty()); panel.add(myDropFirst); panel.setPreferredSize(myDropFirst.getPreferredSize()); add(panel); myDropFirst.setVisible(false); JBEmptyBorder border = JBUI.Borders.emptyRight(5); myAddButton = new InplaceButton(ExecutionBundle.message("run.configuration.before.run.add.task"), AllIcons.General.Add, e -> showPopup()); myAddPanel = new JPanel(); myAddPanel.setBorder(border); myAddPanel.add(myAddButton); myAddLabel = new LinkLabel<>(ExecutionBundle.message("run.configuration.before.run.add.task"), null, (aSource, aLinkData) -> showPopup()); myAddLabel.setBorder(border); DnDManager.getInstance().registerTarget(this, this, this); } private List<BeforeRunTaskProvider<BeforeRunTask<?>>> getProviders() { return ContainerUtil.filter(BeforeRunTaskProvider.EP_NAME.getExtensions(myConfiguration.getProject()), provider -> provider.createTask(myConfiguration) != null); } private TaskButton createTag(BeforeRunTaskProvider<BeforeRunTask<?>> provider) { return new TaskButton(provider, (e) -> { myChangeListener.run(); updateAddLabel(); myTagListener.accept(provider.getId(), false); }); } private void updateAddLabel() { myAddLabel.setVisible(getEnabledTasks().isEmpty()); } public void showPopup() { DefaultActionGroup group = new DefaultActionGroup(); for (BeforeRunTaskProvider<BeforeRunTask<?>> provider : getProviders()) { group.add(new TagAction(provider)); } ListPopup popup = JBPopupFactory .getInstance().createActionGroupPopup(ExecutionBundle.message("add.new.before.run.task.name"), group, DataManager.getInstance().getDataContext(myAddButton), false, false, false, null, -1, Conditions.alwaysTrue()); popup.showUnderneathOf(myAddButton); } public void addOrRemove(Key<? extends BeforeRunTask<?>> providerId, boolean add) { TaskButton taskButton = ContainerUtil.find(myTags, button -> button.myProvider.getId() == providerId); if (add) { if (taskButton == null) { createTask(null, ContainerUtil.find(getProviders(), provider -> providerId == provider.getId())); } } else if (taskButton != null) { myTags.remove(taskButton); } } private void createTask(@Nullable AnActionEvent e, BeforeRunTaskProvider<BeforeRunTask<?>> myProvider) { BeforeRunTask<?> task = myProvider.createTask(myConfiguration); if (task == null) return; TaskButton tag = createTag(myProvider); if (e == null) { addTask(tag, task); return; } myProvider.configureTask(e.getDataContext(), myConfiguration, task).onSuccess(changed -> { if (!myProvider.canExecuteTask(myConfiguration, task)) { return; } addTask(tag, task); }); } private void addTask(TaskButton tag, BeforeRunTask<?> task) { task.setEnabled(true); tag.setTask(task); myTags.remove(tag); myTags.add(tag); buildPanel(); myChangeListener.run(); myTagListener.accept(tag.myProvider.getId(), true); } public void reset(@NotNull RunnerAndConfigurationSettingsImpl s) { myConfiguration = s.getConfiguration(); for (TaskButton tag : myTags) { remove(tag); } myTags.clear(); List<BeforeRunTask<?>> tasks = s.getManager().getBeforeRunTasks(s.getConfiguration()); for (BeforeRunTask<?> task : tasks) { BeforeRunTaskProvider taskProvider = ContainerUtil.find(getProviders(), provider -> task.getProviderId() == provider.getId()); if (taskProvider == null) { taskProvider = new UnknownBeforeRunTaskProvider(task.getProviderId().toString()); } TaskButton tag = createTag(taskProvider); tag.setTask(task); myTags.add(tag); } buildPanel(); } private void buildPanel() { remove(myAddPanel); remove(myAddLabel); for (TaskButton tag : myTags) { add(tag); } add(myAddPanel); add(myAddLabel); updateAddLabel(); } public void apply(RunnerAndConfigurationSettingsImpl s) { s.getManager().setBeforeRunTasks(s.getConfiguration(), getEnabledTasks()); } @NotNull private List<BeforeRunTask<?>> getEnabledTasks() { return myTags.stream() .filter(button -> button.myTask != null && button.isVisible()) .map(button -> button.myTask) .collect(Collectors.toList()); } @Override public void drop(DnDEvent event) { TagButton replaceButton = getReplaceButton(event); if (replaceButton == null ) return; TaskButton button = (TaskButton)event.getAttachedObject(); int i = myTags.indexOf(replaceButton); myTags.remove(button); myTags.add(i, button); buildPanel(); myChangeListener.run(); IdeFocusManager.getInstance(myConfiguration.getProject()).requestFocus(button, false); } @Override public void cleanUpOnLeave() { if (myTags != null) { myTags.forEach(button -> button.showDropPlace(false)); } myDropFirst.setVisible(false); } private TagButton getReplaceButton(DnDEvent event) { Object object = event.getAttachedObject(); if (!(object instanceof TaskButton)) { return null; } Rectangle area = new Rectangle(event.getPoint().x - 5, event.getPoint().y - 5, 10, 10); TaskButton button = ContainerUtil.find(myTags, tag -> tag.isVisible() && tag.getBounds().intersects(area)); if (button == null || button == object) return null; boolean left = button.getBounds().getCenterX() > event.getPoint().x; int i = myTags.indexOf(button); if (i < myTags.indexOf(object)) { if (!left) { button = ContainerUtil.find(myTags, b -> b.isVisible() && myTags.indexOf(b) > i); } } else if (left) { button = ContainerUtil.findLast(myTags, b -> b.isVisible() && myTags.indexOf(b) < i); } return button == object ? null : button; } private TagButton getDropButton(TagButton replaceButton, DnDEvent event) { int i = myTags.indexOf(replaceButton); if (i > myTags.indexOf(event.getAttachedObject())) { return replaceButton; } return ContainerUtil.findLast(myTags, button -> button.isVisible() && myTags.indexOf(button) < i); } @Override public boolean update(DnDEvent event) { TagButton replace = getReplaceButton(event); if (replace != null) { TagButton dropButton = getDropButton(replace, event); myTags.forEach(button -> button.showDropPlace(button == dropButton)); myDropFirst.setVisible(dropButton == null); event.setDropPossible(true); return false; } myTags.forEach(button -> button.showDropPlace(false)); event.setDropPossible(false); return true; } public void setTagListener(BiConsumer<Key<? extends BeforeRunTask<?>>, Boolean> tagListener) { myTagListener = tagListener; } @Override public void dispose() {} private final class TaskButton extends TagButton implements DnDSource { private final BeforeRunTaskProvider<BeforeRunTask<?>> myProvider; private final JLabel myDropPlace = new JLabel(AllIcons.General.DropPlace); private BeforeRunTask<?> myTask; private TaskButton(@NotNull BeforeRunTaskProvider<BeforeRunTask<?>> provider, Consumer<AnActionEvent> action) { super(provider.getName(), action); Disposer.register(BeforeRunComponent.this, this); add(myDropPlace, JLayeredPane.DRAG_LAYER); myProvider = provider; myDropPlace.setVisible(false); myButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (!DumbService.isDumb(myConfiguration.getProject()) || DumbService.isDumbAware(myProvider)) { myProvider.configureTask(DataManager.getInstance().getDataContext(TaskButton.this), myConfiguration, myTask) .onSuccess(aBoolean -> setTask(myTask)); } } } }); DnDManager.getInstance().registerSource(this, myButton, this); myButton.setToolTipText(ExecutionBundle.message("run.configuration.before.run.tooltip")); layoutButtons(); } @Override protected void layoutButtons() { super.layoutButtons(); if (myDropPlace == null) return; Rectangle bounds = myButton.getBounds(); Dimension size = myDropPlace.getPreferredSize(); int gap = JBUI.scale(2); setPreferredSize(new Dimension(bounds.width + size.width + 2 * gap, bounds.height)); myDropPlace.setBounds((int)(bounds.getMaxX() + gap), bounds.y + (bounds.height - size.height) / 2, size.width, size.height); } private void setTask(@Nullable BeforeRunTask<?> task) { myTask = task; setVisible(task != null); if (task != null) { updateButton(myProvider.getDescription(task), myProvider.getTaskIcon(task), !DumbService.isDumb(myConfiguration.getProject()) || DumbService.isDumbAware(myProvider)); } } private void showDropPlace(boolean show) { myDropPlace.setVisible(show); } @Override public boolean canStartDragging(DnDAction action, Point dragOrigin) { return true; } @Override public DnDDragStartBean startDragging(DnDAction action, Point dragOrigin) { return new DnDDragStartBean(this); } @Override public String toString() { return myProvider.getName(); } } private class TagAction extends AnAction implements PossiblyDumbAware { private final BeforeRunTaskProvider<BeforeRunTask<?>> myProvider; private TagAction(BeforeRunTaskProvider<BeforeRunTask<?>> provider) { super(provider.getName(), null, provider.getIcon()); myProvider = provider; } @Override public void actionPerformed(@NotNull AnActionEvent e) { createTask(e, myProvider); } @Override public boolean isDumbAware() { return DumbService.isDumbAware(myProvider); } } }
package com.intellij.openapi.vcs.actions; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPromoter; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.actions.NextWordWithSelectionAction; import com.intellij.openapi.editor.actions.PreviousWordWithSelectionAction; import com.intellij.openapi.vcs.VcsDataKeys; import com.intellij.openapi.vcs.changes.EditorTabPreviewEscapeAction; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.commit.CommitActionsPanel; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.intellij.util.containers.ContainerUtil.filter; public class VcsActionPromoter implements ActionPromoter { @Override public List<AnAction> promote(@NotNull List<? extends AnAction> actions, @NotNull DataContext context) { ActionManager am = ActionManager.getInstance(); List<AnAction> reorderedActions = new ArrayList<>(actions); List<String> reorderedIds = ContainerUtil.map(reorderedActions, it -> am.getId(it)); reorderActionPair(reorderedActions, reorderedIds, "Vcs.MoveChangedLinesToChangelist", "ChangesView.Move"); reorderActionPair(reorderedActions, reorderedIds, "Vcs.RollbackChangedLines", "ChangesView.Revert"); Set<AnAction> promoted = new HashSet<>(filter(actions, action -> action instanceof ShowMessageHistoryAction || action instanceof CommitActionsPanel.DefaultCommitAction || isCommitMessageEditor(context) && ( action instanceof PreviousWordWithSelectionAction || action instanceof NextWordWithSelectionAction ) )); Set<AnAction> demoted = new HashSet<>(filter(actions, action -> action instanceof EditorTabPreviewEscapeAction )); reorderedActions.removeAll(promoted); reorderedActions.removeAll(demoted); reorderedActions.addAll(0, promoted); reorderedActions.addAll(demoted); return reorderedActions; } private static boolean isCommitMessageEditor(@NotNull DataContext context) { return context.getData(VcsDataKeys.COMMIT_MESSAGE_CONTROL) != null; } /** * Ensures that one global action has priority over another global action. * But is not pushing it ahead of other actions (ex: of some local action with same shortcut). */ private static void reorderActionPair(List<AnAction> reorderedActions, List<String> reorderedIds, String highPriority, String lowPriority) { int highPriorityIndex = reorderedIds.indexOf(highPriority); int lowPriorityIndex = reorderedIds.indexOf(lowPriority); if (highPriorityIndex == -1 || lowPriorityIndex == -1) return; if (highPriorityIndex < lowPriorityIndex) return; String id = reorderedIds.remove(highPriorityIndex); AnAction action = reorderedActions.remove(highPriorityIndex); reorderedIds.add(lowPriorityIndex, id); reorderedActions.add(lowPriorityIndex, action); } }
package com.intellij.vcs.log.ui; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.JBColor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import com.intellij.vcs.log.ui.tables.AbstractVcsLogTableModel; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.*; import java.util.List; /** * @author Kirill Likhodedov */ public class VcsLogColorManagerImpl implements VcsLogColorManager { private static final Color REF_BORDER = JBColor.GRAY; private static final Color ROOT_INDICATOR_BORDER = JBColor.LIGHT_GRAY; private static final Logger LOG = Logger.getInstance(VcsLogColorManagerImpl.class); private static Color[] ROOT_COLORS = { JBColor.RED, JBColor.YELLOW, JBColor.LIGHT_GRAY, JBColor.BLUE, JBColor.MAGENTA, JBColor.CYAN, JBColor.GREEN, JBColor.ORANGE, JBColor.PINK}; @NotNull private final List<VirtualFile> myRoots; @NotNull private final Map<VirtualFile, Color> myRoots2Colors; public VcsLogColorManagerImpl(@NotNull Collection<VirtualFile> roots) { myRoots = new ArrayList<VirtualFile>(roots); Collections.sort(myRoots, new Comparator<VirtualFile>() { // TODO add a common util method to sort roots @Override public int compare(VirtualFile o1, VirtualFile o2) { return o1.getName().compareTo(o2.getName()); } }); myRoots2Colors = ContainerUtil.newHashMap(); int i = 0; for (VirtualFile root : roots) { myRoots2Colors.put(root, ROOT_COLORS[i]); i++; // TODO handle the case when there are more roots than colors } } @Override public boolean isMultipleRoots() { return myRoots.size() > 1; } @NotNull @Override public Color getRootColor(@NotNull VirtualFile root) { if (root == AbstractVcsLogTableModel.FAKE_ROOT) { return UIUtil.getTableBackground(); } Color color = myRoots2Colors.get(root); if (color == null) { LOG.error("No color record for root " + root + ". All roots: " + myRoots2Colors); color = UIUtil.getTableBackground(); } return color; } @NotNull @Override public Color getReferenceBorderColor() { return REF_BORDER; } @NotNull @Override public Color getRootIndicatorBorder() { return ROOT_INDICATOR_BORDER; } }
package net.mcft.copy.tweaks; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import net.mcft.copy.betterstorage.api.crafting.BetterStorageCrafting; import net.mcft.copy.betterstorage.api.crafting.ShapedStationRecipe; import net.mcft.copy.core.util.RandomUtils; import net.mcft.copy.core.util.WorldUtils; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.monster.EntityBlaze; import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.monster.EntitySkeleton; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.entity.monster.EntityWitch; import net.minecraft.entity.passive.EntityChicken; import net.minecraft.entity.passive.EntityCow; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.passive.EntityPig; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.living.LivingDropsEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.registry.GameRegistry; @Mod(modid = copyVanillaTweaks.MOD_ID, version = "@VERSION@", useMetadata = false, dependencies = "required-after:copycore;required-after:betterstorage") public class copyVanillaTweaks { public static final String MOD_ID = "copyVanillaTweaks"; public static final String MOD_NAME = "copy's Vanilla Tweaks"; @EventHandler public void postInit(FMLPostInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); // Adjust durability of tools and armor setToolDurability( 80, Items.wooden_sword, Items.wooden_pickaxe, Items.wooden_shovel, Items.wooden_axe, Items.wooden_hoe); setToolDurability( 160, Items.stone_sword, Items.stone_pickaxe, Items.stone_shovel, Items.stone_axe, Items.stone_hoe); setToolDurability( 160, Items.golden_sword, Items.golden_pickaxe, Items.golden_shovel, Items.golden_axe, Items.golden_hoe); setToolDurability( 320, Items.iron_sword, Items.iron_pickaxe, Items.iron_shovel, Items.iron_axe, Items.iron_hoe); setToolDurability(1720, Items.diamond_sword, Items.diamond_pickaxe, Items.diamond_shovel, Items.diamond_axe, Items.diamond_hoe); setArmorDurability(10, Items.leather_helmet, Items.leather_chestplate, Items.leather_leggings, Items.leather_boots); setArmorDurability(12, Items.golden_helmet, Items.golden_chestplate, Items.golden_leggings, Items.golden_boots); setArmorDurability(16, Items.iron_helmet, Items.iron_chestplate, Items.iron_leggings, Items.iron_boots); setArmorDurability(20, Items.chainmail_helmet, Items.chainmail_chestplate, Items.chainmail_leggings, Items.chainmail_boots); setArmorDurability(32, Items.diamond_helmet, Items.diamond_chestplate, Items.diamond_leggings, Items.diamond_boots); Set removeRecipesOf = new HashSet(Arrays.asList( Items.stone_sword, Items.stone_pickaxe, Items.stone_shovel, Items.stone_axe, Items.stone_hoe, Items.golden_sword, Items.golden_pickaxe, Items.golden_shovel, Items.golden_axe, Items.golden_hoe, Items.iron_sword, Items.iron_pickaxe, Items.iron_shovel, Items.iron_axe, Items.iron_hoe, Items.diamond_sword, Items.diamond_pickaxe, Items.diamond_shovel, Items.diamond_axe, Items.diamond_hoe, Items.golden_helmet, Items.golden_chestplate, Items.golden_leggings, Items.golden_boots, Items.iron_helmet, Items.iron_chestplate, Items.iron_leggings, Items.iron_boots, Items.diamond_helmet, Items.diamond_chestplate, Items.diamond_leggings, Items.diamond_boots, Items.bucket, Items.bed, Item.getItemFromBlock(Blocks.enchanting_table), Item.getItemFromBlock(Blocks.anvil) )); // Remove saw recipes if ForgeMultipart is present. if (Loader.isModLoaded("ForgeMultipart")) { removeRecipesOf.addAll(Arrays.asList( Item.itemRegistry.getObject("ForgeMicroblock:sawStone"), Item.itemRegistry.getObject("ForgeMicroblock:sawIron"), Item.itemRegistry.getObject("ForgeMicroblock:sawDiamond") )); } Set<Item> replaceCobbleWithStoneIn = new HashSet<Item>(Arrays.asList( Item.getItemFromBlock(Blocks.lever), Item.getItemFromBlock(Blocks.dispenser), Item.getItemFromBlock(Blocks.dropper), Item.getItemFromBlock(Blocks.piston), Items.brewing_stand )); ListIterator<IRecipe> recipeIterator = CraftingManager.getInstance().getRecipeList().listIterator(); while (recipeIterator.hasNext()) { IRecipe recipe = recipeIterator.next(); ItemStack output = recipe.getRecipeOutput(); if (output == null) continue; if (removeRecipesOf.contains(output.getItem())) recipeIterator.remove(); else if (replaceCobbleWithStoneIn.contains(output.getItem()) && (recipe instanceof ShapedOreRecipe)) { Object[] input = ((ShapedOreRecipe)recipe).getInput(); for (int i = 0; i < input.length; i++) if (input[i] instanceof List) { List<ItemStack> stacks = (List<ItemStack>)input[i]; for (ItemStack stack : stacks) if (stack.getItem() == Item.getItemFromBlock(Blocks.cobblestone)) { input[i] = OreDictionary.getOres("stone"); break; } } } } // Stone tools ToolMaterial.STONE.customCraftingMaterial = Items.flint; GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Items.stone_sword), " x ", " o ", "s/s", 'o', "stone", 'x', Items.flint, '/', "stickWood", 's', Items.string)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Items.stone_pickaxe), "xox", "s/s", " / ", 'o', "stone", 'x', Items.flint, '/', "stickWood", 's', Items.string)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Items.stone_shovel), " x ", "s/s", " / ", 'x', Items.flint, '/', "stickWood", 's', Items.string)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Items.stone_axe), "xo ", "x/ ", "s/s", 'o', "stone", 'x', Items.flint, '/', "stickWood", 's', Items.string)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Items.stone_hoe), "xo ", "s/s", " / ", 'o', "stone", 'x', Items.flint, '/', "stickWood", 's', Items.string)); // Gold tools and armor addStationRecipe(Items.golden_sword, 2, "o", "o", "/", 'o', "ingotGold", '/', "stickWood"); addStationRecipe(Items.golden_pickaxe, 2, "ooo", " / ", " / ", 'o', "ingotGold", '/', "stickWood"); addStationRecipe(Items.golden_shovel, 1, "o", "/", "/", 'o', "ingotGold", '/', "stickWood"); addStationRecipe(Items.golden_axe, 1, "oo", "o/", " /", 'o', "ingotGold", '/', "stickWood"); addStationRecipe(Items.golden_hoe, 1, "oo", " /", " /", 'o', "ingotGold", '/', "stickWood"); addStationRecipe(Items.golden_helmet, 2, "ooo", "oHo", 'o', "ingotGold", 'H', Items.leather_helmet); addStationRecipe(Items.golden_chestplate, 3, "oCo", "ooo", "ooo", 'o', "ingotGold", 'C', Items.leather_chestplate); addStationRecipe(Items.golden_leggings, 2, "ooo", "oLo", "o o", 'o', "ingotGold", 'L', Items.leather_leggings); addStationRecipe(Items.golden_boots, 2, "oBo", "o o", 'o', "ingotGold", 'B', Items.leather_boots); // Iron tools and armor addStationRecipe(Items.iron_sword, 6, "o", "o", "/", 'o', "ingotIron", '/', "stickWood"); addStationRecipe(Items.iron_pickaxe, 8, "ooo", " / ", " / ", 'o', "ingotIron", '/', "stickWood"); addStationRecipe(Items.iron_shovel, 4, "o", "/", "/", 'o', "ingotIron", '/', "stickWood"); addStationRecipe(Items.iron_axe, 4, "oo", "o/", " /", 'o', "ingotIron", '/', "stickWood"); addStationRecipe(Items.iron_hoe, 4, "oo", " /", " /", 'o', "ingotIron", '/', "stickWood"); addStationRecipe(Items.iron_helmet, 8, "ooo", "oHo", 'o', "ingotIron", 'H', Items.leather_helmet); addStationRecipe(Items.iron_chestplate, 12, "oCo", "ooo", "ooo", 'o', "ingotIron", 'C', Items.leather_chestplate); addStationRecipe(Items.iron_leggings, 10, "ooo", "oLo", "o o", 'o', "ingotIron", 'L', Items.leather_leggings); addStationRecipe(Items.iron_boots, 8, "oBo", "o o", 'o', "ingotIron", 'B', Items.leather_boots); // Diamond tools and armor addStationRecipe(Items.diamond_sword, 12, "o", "x", "/", 'o', "gemDiamond", 'x', "gemEmerald", '/', "stickWood"); addStationRecipe(Items.diamond_pickaxe, 16, "oxo", " / ", " / ", 'o', "gemDiamond", 'x', "gemEmerald", '/', "stickWood"); addStationRecipe(Items.diamond_shovel, 8, "o", "/", "/", 'o', "gemDiamond", '/', "stickWood"); addStationRecipe(Items.diamond_axe, 8, "ox", "o/", " /", 'o', "gemDiamond", 'x', "gemEmerald", '/', "stickWood"); addStationRecipe(Items.diamond_hoe, 8, "ox", " /", " /", 'o', "gemDiamond", 'x', "gemEmerald", '/', "stickWood"); addStationRecipe(Items.diamond_helmet, 16, "oxo", "oHo", 'o', "gemDiamond", 'x', "gemEmerald", 'H', Items.leather_helmet); addStationRecipe(Items.diamond_chestplate, 24, "oCo", "oxo", "ooo", 'o', "gemDiamond", 'x', "gemEmerald", 'C', Items.leather_chestplate); addStationRecipe(Items.diamond_leggings, 20, "oxo", "oLo", "o o", 'o', "gemDiamond", 'x', "gemEmerald", 'L', Items.leather_leggings); addStationRecipe(Items.diamond_boots, 16, "oBo", "o o", 'o', "gemDiamond", 'B', Items.leather_boots); // Other recipes addStationRecipe(Items.bucket, 2, "o o", " o ", 'o', "ingotIron"); addStationRecipe(Items.bed, 20, "WWW", "PPP", 'W', Blocks.wool, 'P', "plankWood"); addStationRecipe(Blocks.enchanting_table, 30, " B ", "o "###", 'B', Items.book, 'o', "gemDiamond", '#', Blocks.obsidian); addStationRecipe(Blocks.anvil, 20, "OOO", " o ", "ooo", 'O', "blockIron", 'o', "ingotIron"); addStationRecipe(new ItemStack(Items.leather, 4), 1, "ooo", "ooo", "ooo", 'o', Items.rotten_flesh); // ForgeMultipart saws if (Loader.isModLoaded("ForgeMultipart")) { Item stoneRod = (Item)Item.itemRegistry.getObject("ForgeMultipart:stoneRod"); Item sawStone = (Item)Item.itemRegistry.getObject("ForgeMultipart:sawStone"); Item sawIron = (Item)Item.itemRegistry.getObject("ForgeMultipart:sawIron"); Item sawDiamond = (Item)Item.itemRegistry.getObject("ForgeMultipart:sawDiamond"); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(sawStone), "/ "/oo", 'o', Items.flint, '/', "stickWood", '-', stoneRod)); addStationRecipe(sawIron, 3, "/ "/oo", 'o', "ingotIron", '/', "stickWood", '-', stoneRod); addStationRecipe(sawDiamond, 6, "/ "/oo", 'o', "gemDiamond", '/', "stickWood", '-', stoneRod); } } private static void setToolDurability(int durability, Item... items) { for (Item item : items) item.setMaxDamage(durability); } private static final int[] maxDamageArray = new int[]{ 11, 16, 15, 13 }; private static void setArmorDurability(int durability, ItemArmor... items) { for (ItemArmor item : items) item.setMaxDamage(durability * maxDamageArray[item.armorType]); } private static void addStationRecipe(ItemStack output, int experience, Object... input) { BetterStorageCrafting.addStationRecipe(new ShapedStationRecipe( new ItemStack[]{ null, null, null, null, output }, input ).setRequiredExperience(experience)); } private static void addStationRecipe(Item output, int experience, Object... input) { addStationRecipe(new ItemStack(output), experience, input); } private static void addStationRecipe(Block output, int experience, Object... input) { addStationRecipe(new ItemStack(output), experience, input); } @SubscribeEvent public void onHarvestDrops(HarvestDropsEvent event) { // Change gravel drops so it always drops gravel not using a shovel. // Chance of getting flint is different depending on the shovel tier: // Wood & Gold: 35%, Stone: 20%, Iron: 5%, Diamond: 0%. if ((event.block == Blocks.gravel) && !event.isSilkTouching) { ItemStack holding = ((event.harvester != null) ? event.harvester.getCurrentEquippedItem() : null); ItemTool tool = (((holding != null) && (holding.getItem() instanceof ItemTool)) ? (ItemTool)holding.getItem() : null); boolean dropsFlint = ((tool != null) && tool.getToolClasses(holding).contains("shovel") && RandomUtils.getBoolean(0.35 - tool.getHarvestLevel(holding, "shovel") * 0.15)); event.drops.clear(); event.drops.add(dropsFlint ? new ItemStack(Items.flint) : new ItemStack(Blocks.gravel)); } } @SubscribeEvent public void onLivingDrops(LivingDropsEvent event) { // Don't drop any extras if the entity is a child. if (event.entityLiving.isChild()) return; // Chickens drop 3 extra feathers. if (event.entity instanceof EntityChicken) event.drops.add(makeItemToDrop(event.entity, Items.feather, 3)); // Pigs drop 2 extra porkchops. else if (event.entity instanceof EntityPig) event.drops.add(makeItemToDrop(event.entity, Items.porkchop, 1)); // Cows drop 1 extra leather and 1 extra beef. else if (event.entity instanceof EntityCow) { event.drops.add(makeItemToDrop(event.entity, Items.leather, 1)); event.drops.add(makeItemToDrop(event.entity, Items.beef, 1)); // Horses drop 1-2 extra leather. } else if (event.entity instanceof EntityHorse) event.drops.add(makeItemToDrop(event.entity, Items.leather, RandomUtils.getInt(1, 3))); // Spiders drop 1 extra string. else if (event.entity instanceof EntitySpider) event.drops.add(makeItemToDrop(event.entity, Items.string, 1)); // Skeletons drop 1 extra bones. else if (event.entity instanceof EntitySkeleton) event.drops.add(makeItemToDrop(event.entity, Items.bone, 1)); // Creepers drop 1 extra gunpowder. else if (event.entity instanceof EntityCreeper) event.drops.add(makeItemToDrop(event.entity, Items.gunpowder, 1)); // Endermen drop 0-1 extra enderpearls. else if ((event.entity instanceof EntityEnderman) && RandomUtils.getBoolean(0.5)) event.drops.add(makeItemToDrop(event.entity, Items.ender_pearl, 1)); // Blaze drop 1 extra blazerod. else if (event.entity instanceof EntityBlaze) event.drops.add(makeItemToDrop(event.entity, Items.blaze_rod, 1)); // Witches have a 25% chance to drop a random potion. else if ((event.entity instanceof EntityWitch) && RandomUtils.getBoolean(0.25)) { int[] damageValues = { 8197, 8194, 8205, 8195, // Healing, Swiftness, Water Breathing, Fire Resistance, 16396, 16388, 16394, 16392 // Harming, Poison, Slowness, Weakness }; int damage = damageValues[RandomUtils.getInt(damageValues.length)]; event.drops.add(makeItemToDrop(event.entity, new ItemStack(Items.potionitem, 1, damage))); } } public static EntityItem makeItemToDrop(Entity entity, ItemStack stack) { EntityItem item = new EntityItem(entity.worldObj, entity.posX, entity.posY, entity.posZ, stack); item.motionX = RandomUtils.getGaussian() * 0.05F; item.motionY = RandomUtils.getGaussian() * 0.05F + 0.2F; item.motionZ = RandomUtils.getGaussian() * 0.05F; return item; } public static EntityItem makeItemToDrop(Entity entity, Item item, int amount) { return makeItemToDrop(entity, new ItemStack(item, amount)); } private static int agingSlowdownDefault = 4; private static Map<Class<? extends EntityAgeable>, Integer> agingSlowdownMap = new HashMap<Class<? extends EntityAgeable>, Integer>(); static { agingSlowdownMap.put(EntityChicken.class, 2); agingSlowdownMap.put(EntityVillager.class, 3); } private static int getAgingSlowdown(EntityAgeable entity) { Integer agingSlowdown = agingSlowdownMap.get(entity.getClass()); return ((agingSlowdown != null) ? agingSlowdown : agingSlowdownDefault); } @SubscribeEvent public void onLivingUpdate(LivingUpdateEvent event) { if (event.entity.worldObj.isRemote) return; // Adult chickens have a 25% chance drop a feather every 8 minutes. if ((event.entity instanceof EntityChicken) && !event.entityLiving.isChild() && ((event.entity.ticksExisted % (8 * 60 * 20)) == 0) && RandomUtils.getBoolean(0.5)) WorldUtils.dropStackFromEntity(event.entity, new ItemStack(Items.feather), 1.5F); if (event.entity instanceof EntityAgeable) { EntityAgeable entity = (EntityAgeable)event.entity; int age = entity.getGrowingAge(); int agingSlowdown = getAgingSlowdown(entity); if (age == -24000) onChildEntityBred(entity); else if ((age != 0) && ((entity.ticksExisted % agingSlowdown) != 0)) entity.setGrowingAge(age + ((age > 0) ? 1 : -1)); } } public void onChildEntityBred(EntityAgeable entity) { // Drop additional experience. int agingSlowdown = getAgingSlowdown(entity); int experience = (agingSlowdown - 1) * 2 + RandomUtils.getInt(3); while (experience > 0) { int xp = EntityXPOrb.getXPSplit(experience); entity.worldObj.spawnEntityInWorld(new EntityXPOrb(entity.worldObj, entity.posX, entity.posY, entity.posZ, xp)); experience -= xp; } // Spawn additional pigs. if (entity instanceof EntityPig) { int num = (RandomUtils.getBoolean(1.0 / 200) ? 3 : 1); for (int i = 0; i < num; i++) { EntityAgeable newEntity = entity.createChild(entity); newEntity.setGrowingAge(-23999); newEntity.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, RandomUtils.getFloat(360), 0); entity.worldObj.spawnEntityInWorld(newEntity); } } } }
package com.mapzen.tangram; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.PointF; import android.graphics.Rect; import android.opengl.GLSurfaceView.Renderer; import android.os.Build; import android.os.Handler; import android.support.annotation.IntRange; import android.support.annotation.Keep; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.ArrayMap; import android.util.DisplayMetrics; import android.util.Log; import android.util.LongSparseArray; import android.view.MotionEvent; import android.view.View; import com.mapzen.tangram.TouchInput.Gestures; import com.mapzen.tangram.viewholder.GLViewHolder; import com.mapzen.tangram.networking.DefaultHttpHandler; import com.mapzen.tangram.networking.HttpHandler; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * {@code MapController} is the main class for interacting with a Tangram map. */ public class MapController { public boolean handleGesture(View mapView, MotionEvent ev) { return touchInput.onTouch(mapView, ev); } /** * Options for interpolating map parameters */ @Keep public enum EaseType { LINEAR, CUBIC, QUINT, SINE, } /** * Options for changing the appearance of 3D geometry */ public enum CameraType { PERSPECTIVE, ISOMETRIC, FLAT, } /** * Options representing an error generated after from the map controller */ public enum Error { NONE, SCENE_UPDATE_PATH_NOT_FOUND, SCENE_UPDATE_PATH_YAML_SYNTAX_ERROR, SCENE_UPDATE_VALUE_YAML_SYNTAX_ERROR, NO_VALID_SCENE, } protected static EaseType DEFAULT_EASE_TYPE = EaseType.CUBIC; /** * Options for enabling debug rendering features */ public enum DebugFlag { FREEZE_TILES, PROXY_COLORS, TILE_BOUNDS, TILE_INFOS, LABELS, TANGRAM_INFOS, DRAW_ALL_LABELS, TANGRAM_STATS, SELECTION_BUFFER, } enum MapRegionChangeState { IDLE, JUMPING, ANIMATING, } /** * Interface for listening to scene load status information. * Triggered after a call of {@link #updateSceneAsync(List<SceneUpdate>)} or * {@link #loadSceneFileAsync(String, List<SceneUpdate>)} or {@link #loadSceneFile(String, List<SceneUpdate>)} * Listener should be set with {@link #setSceneLoadListener(SceneLoadListener)} * The callbacks will be run on the main (UI) thread. */ @Keep public interface SceneLoadListener { /** * Received when a scene load or update finishes. If sceneError is not null then the operation did not succeed. * @param sceneId The identifier returned by {@link #updateSceneAsync(List<SceneUpdate>)} or * {@link #loadSceneFileAsync(String, List<SceneUpdate>)}. * @param sceneError A {@link SceneError} holding error information, or null if no error occurred. */ void onSceneReady(final int sceneId, final SceneError sceneError); } public interface CameraAnimationCallback { void onFinish(); void onCancel(); } /** * Callback for {@link #captureFrame(FrameCaptureCallback, boolean) } */ public interface FrameCaptureCallback { /** * Called on the ui-thread when a frame was captured. */ void onCaptured(@NonNull final Bitmap bitmap); } /** * Capture MapView as Bitmap. * @param waitForCompleteView Delay the capture until the view is fully loaded and * no ease- or label-animation is running. */ public void captureFrame(@NonNull final FrameCaptureCallback callback, final boolean waitForCompleteView) { mapRenderer.captureFrame(callback, waitForCompleteView); requestRender(); } /** * Construct a MapController * @param context The application Context in which the map will function; the asset * bundle for this activity must contain all the local files that the map * will need. */ protected MapController(@NonNull Context context) { if (Build.VERSION.SDK_INT > 18) { clientTileSources = new ArrayMap<>(); } else { clientTileSources = new HashMap<>(); } markers = new LongSparseArray<>(); // Get configuration info from application displayMetrics = context.getResources().getDisplayMetrics(); assetManager = context.getAssets(); // Parse font file description fontFileParser = new FontFileParser(); fontFileParser.parse(); mapPointer = nativeInit(assetManager); if (mapPointer <= 0) { throw new RuntimeException("Unable to create a native Map object! There may be insufficient memory available."); } nativeSetPixelScale(mapPointer, displayMetrics.density); } /** * Responsible to configure {@link MapController} configuration on the ui thread. * Must be called from the ui thread post instantiation of {@link MapController} * @param viewHolder GLViewHolder for the map display * @param handler {@link HttpHandler} to initialize httpHandler for network handling */ void UIThreadInit(@NonNull final GLViewHolder viewHolder, @Nullable final HttpHandler handler) { // Use the DefaultHttpHandler if none is provided if (handler == null) { httpHandler = new DefaultHttpHandler(); } else { httpHandler = handler; } Context context = viewHolder.getView().getContext(); uiThreadHandler = new Handler(context.getMainLooper()); mapRenderer = new MapRenderer(this, uiThreadHandler); // Set up MapView this.viewHolder = viewHolder; viewHolder.setRenderer(mapRenderer); isGLRendererSet = true; viewHolder.setRenderMode(GLViewHolder.RenderMode.RENDER_WHEN_DIRTY); touchInput = new TouchInput(context); touchInput.setPanResponder(getPanResponder()); touchInput.setScaleResponder(getScaleResponder()); touchInput.setRotateResponder(getRotateResponder()); touchInput.setShoveResponder(getShoveResponder()); touchInput.setSimultaneousDetectionDisabled(Gestures.SHOVE, Gestures.ROTATE); touchInput.setSimultaneousDetectionDisabled(Gestures.ROTATE, Gestures.SHOVE); touchInput.setSimultaneousDetectionDisabled(Gestures.SHOVE, Gestures.SCALE); touchInput.setSimultaneousDetectionDisabled(Gestures.SHOVE, Gestures.PAN); touchInput.setSimultaneousDetectionDisabled(Gestures.SCALE, Gestures.LONG_PRESS); } /** * Responsible to dispose internals of MapController during Map teardown. * If client code extends MapController and overrides this method, then it must call super.dispose() */ protected synchronized void dispose() { if (mapPointer == 0) { return; } Log.e("TANGRAM", ">>> dispose"); nativeShutdown(mapPointer); Log.e("TANGRAM", "<<< http requests: " + httpRequestHandles.size()); for (MapData mapData : clientTileSources.values()) { mapData.remove(); } Log.e("TANGRAM", "<<< 1"); clientTileSources.clear(); Log.e("TANGRAM", "<<< 2"); markers.clear(); Log.e("TANGRAM", "<<< 3"); // Dispose all listener and callbacks associated with mapController // This will help prevent leaks of references from the client code, possibly used in these // listener/callbacks touchInput = null; mapChangeListener = null; featurePickListener = null; sceneLoadListener = null; labelPickListener = null; markerPickListener = null; cameraAnimationCallback = null; frameCaptureCallback = null; // Prevent any calls to native functions - except dispose. final long pointer = mapPointer; mapPointer = 0; // NOTE: It is possible for the MapView held by a ViewGroup to be removed, calling detachFromWindow which // stops the Render Thread associated with GLSurfaceView, possibly resulting in leaks from render thread // queue. Because of the above, destruction lifecycle of the GLSurfaceView will not be triggered. // To avoid the above senario, nativeDispose is called from the UIThread. // Since all gl resources will be freed when GLSurfaceView is deleted this is safe until // we support sharing gl contexts. nativeDispose(pointer); Log.e("TANGRAM", "<<< disposed"); } /** * Returns the {@link GLViewHolder} instance for the client application, which can be further used to get the underlying * GLSurfaceView or Client provided implementation for GLViewHolder, to forward any explicit view controls, example Transformations, etc. * @return GLViewHolder used by the Map Renderer */ @Nullable public GLViewHolder getGLViewHolder() { return viewHolder; } /** * Load a new scene file synchronously. * Use {@link #setSceneLoadListener(SceneLoadListener)} for notification when the new scene is * ready. * @param path Location of the YAML scene file within the application assets * @return Scene ID An identifier for the scene being loaded, the same value will be passed to * {@link SceneLoadListener#onSceneReady(int sceneId, SceneError sceneError)} when loading is complete. */ public int loadSceneFile(final String path) { return loadSceneFile(path, null); } /** * Load a new scene file asynchronously. * Use {@link #setSceneLoadListener(SceneLoadListener)} for notification when the new scene is * ready. * @param path Location of the YAML scene file within the application assets * @return Scene ID An identifier for the scene being loaded, the same value will be passed to * {@link SceneLoadListener#onSceneReady(int sceneId, SceneError sceneError)} when loading is complete. */ public int loadSceneFileAsync(final String path) { return loadSceneFileAsync(path, null); } /** * Load a new scene file synchronously. * If scene updates triggers an error, they won't be applied. * Use {@link #setSceneLoadListener(SceneLoadListener)} for notification when the new scene is * ready. * @param path Location of the YAML scene file within the application assets * @param sceneUpdates List of {@code SceneUpdate} * @return Scene ID An identifier for the scene being loaded, the same value will be passed to * {@link SceneLoadListener#onSceneReady(int sceneId, SceneError sceneError)} when loading is complete. */ public int loadSceneFile(final String path, @Nullable final List<SceneUpdate> sceneUpdates) { checkPointer(mapPointer); final String[] updateStrings = bundleSceneUpdates(sceneUpdates); final int sceneId = nativeLoadScene(mapPointer, path, updateStrings); removeAllMarkers(); requestRender(); return sceneId; } /** * Load a new scene file asynchronously. * If scene updates triggers an error, they won't be applied. * Use {@link #setSceneLoadListener(SceneLoadListener)} for notification when the new scene is * ready. * @param path Location of the YAML scene file within the application assets * @param sceneUpdates List of {@code SceneUpdate} * @return Scene ID An identifier for the scene being loaded, the same value will be passed to * {@link SceneLoadListener#onSceneReady(int sceneId, SceneError sceneError)} when loading is complete. */ public int loadSceneFileAsync(final String path, @Nullable final List<SceneUpdate> sceneUpdates) { checkPointer(mapPointer); final String[] updateStrings = bundleSceneUpdates(sceneUpdates); final int sceneId = nativeLoadSceneAsync(mapPointer, path, updateStrings); removeAllMarkers(); requestRender(); return sceneId; } /** * Load a new scene synchronously, provided an explicit yaml scene string to load * If scene updates triggers an error, they won't be applied. * Use {@link #setSceneLoadListener(SceneLoadListener)} for notification when the new scene is * ready. * @param yaml YAML scene String * @param resourceRoot base path to resolve relative URLs * @param sceneUpdates List of {@code SceneUpdate} * @return Scene ID An identifier for the scene being loaded, the same value will be passed to */ public int loadSceneYaml(final String yaml, final String resourceRoot, @Nullable final List<SceneUpdate> sceneUpdates) { checkPointer(mapPointer); final String[] updateStrings = bundleSceneUpdates(sceneUpdates); final int sceneId = nativeLoadSceneYaml(mapPointer, yaml, resourceRoot, updateStrings); removeAllMarkers(); requestRender(); return sceneId; } /** * Load a new scene asynchronously, provided an explicit yaml scene string to load * If scene updates triggers an error, they won't be applied. * Use {@link #setSceneLoadListener(SceneLoadListener)} for notification when the new scene is * ready. * @param yaml YAML scene String * @param resourceRoot base path to resolve relative URLs * @param sceneUpdates List of {@code SceneUpdate} * @return Scene ID An identifier for the scene being loaded, the same value will be passed to */ public int loadSceneYamlAsync(final String yaml, final String resourceRoot, @Nullable final List<SceneUpdate> sceneUpdates) { checkPointer(mapPointer); final String[] updateStrings = bundleSceneUpdates(sceneUpdates); final int sceneId = nativeLoadSceneYamlAsync(mapPointer, yaml, resourceRoot, updateStrings); removeAllMarkers(); requestRender(); return sceneId; } /** * Apply SceneUpdates to the current scene asyncronously * If a updates trigger an error, scene updates won't be applied. * Use {@link #setSceneLoadListener(SceneLoadListener)} for notification when the new scene is * ready. * @param sceneUpdates List of {@code SceneUpdate} * @return new scene ID */ public int updateSceneAsync(@NonNull final List<SceneUpdate> sceneUpdates) { checkPointer(mapPointer); if (sceneUpdates == null || sceneUpdates.size() == 0) { throw new IllegalArgumentException("sceneUpdates can not be null or empty in queueSceneUpdates"); } removeAllMarkers(); final String[] updateStrings = bundleSceneUpdates(sceneUpdates); return nativeUpdateScene(mapPointer, updateStrings); } /** * Set the camera position of the map view * @param update CameraUpdate to modify current camera position */ public void updateCameraPosition(@NonNull final CameraUpdate update) { updateCameraPosition(update, 0, DEFAULT_EASE_TYPE,null); } /** * Animate the camera position of the map view with the default easing function * @param update CameraUpdate to update current camera position * @param duration Time in milliseconds to ease to the updated position */ public void updateCameraPosition(@NonNull final CameraUpdate update, final int duration) { updateCameraPosition(update, duration, DEFAULT_EASE_TYPE, null); } /** * Animate the camera position of the map view with an easing function * @param update CameraUpdate to update current camera position * @param duration Time in milliseconds to ease to the updated position * @param ease Type of easing to use */ public void updateCameraPosition(@NonNull final CameraUpdate update, final int duration, @NonNull final EaseType ease) { updateCameraPosition(update, duration, ease, null); } /** * Animate the camera position of the map view and run a callback when the animation completes * @param update CameraUpdate to update current camera position * @param duration Time in milliseconds to ease to the updated position * @param cb Callback that will run when the animation is finished or canceled */ public void updateCameraPosition(@NonNull final CameraUpdate update, final int duration, @NonNull final CameraAnimationCallback cb) { updateCameraPosition(update, duration, DEFAULT_EASE_TYPE, cb); } /** * Animate the camera position of the map view with an easing function and run a callback when * the animation completes * @param update CameraUpdate to update current camera position * @param duration Time in milliseconds to ease to the updated position * @param ease Type of easing to use * @param cb Callback that will run when the animation is finished or canceled */ public void updateCameraPosition(@NonNull final CameraUpdate update, final int duration, @NonNull final EaseType ease, @Nullable final CameraAnimationCallback cb) { checkPointer(mapPointer); if (duration > 0) { setMapRegionState(MapRegionChangeState.ANIMATING); } else { setMapRegionState(MapRegionChangeState.JUMPING); } setPendingCameraAnimationCallback(cb); final float seconds = duration / 1000.f; nativeUpdateCameraPosition(mapPointer, update.set, update.longitude, update.latitude, update.zoom, update.zoomBy, update.rotation, update.rotationBy, update.tilt, update.tiltBy, update.boundsLon1, update.boundsLat1, update.boundsLon2, update.boundsLat2, update.padding, seconds, ease.ordinal()); } /** * Smoothly animate over an arc to a new camera position for the map view * FlyTo duration is calculated assuming speed of 1 unit and distance between the current and new positions * @param position CameraPosition of the destination * @param callback Callback that will run when the animation is finished or canceled */ public void flyToCameraPosition(@NonNull CameraPosition position, @Nullable final CameraAnimationCallback callback) { flyToCameraPosition(position, 0, callback); } /** * Smoothly animate over an arc to a new camera position for the map view in provided time duration * @param position CameraPosition of the destination * @param duration Time in milliseconds of the animation * @param callback Callback that will run when the animation is finished or canceled */ public void flyToCameraPosition(@NonNull final CameraPosition position, final int duration, @Nullable final CameraAnimationCallback callback) { flyToCameraPosition(position, duration, callback, 1); } /** * Smoothly animate over an arc to a new camera position for the map view * FlyTo duration is calculated using speed and distance between the current and new positions * @param position CameraPosition of the destination * @param callback Callback that will run when the animation is finished or canceled * @param speed Scaling factor for animation duration (recommended range is 0.1 - 10) */ public void flyToCameraPosition(@NonNull final CameraPosition position, @Nullable final CameraAnimationCallback callback, final float speed) { flyToCameraPosition(position, -1, callback, speed); } private void flyToCameraPosition(@NonNull final CameraPosition position, final int duration, @Nullable final CameraAnimationCallback callback, final float speed) { checkPointer(mapPointer); // TODO: Make sense to have mark animating for flyTo irrespective of duration/speed? setMapRegionState(MapRegionChangeState.ANIMATING); setPendingCameraAnimationCallback(callback); final float seconds = duration / 1000.f; nativeFlyTo(mapPointer, position.longitude, position.latitude, position.zoom, seconds, speed); } private void setPendingCameraAnimationCallback(final CameraAnimationCallback callback) { synchronized (cameraAnimationCallbackLock) { // Wrap the callback to run corresponding map change events. pendingCameraAnimationCallback = new CameraAnimationCallback() { @Override public void onFinish() { setMapRegionState(MapRegionChangeState.IDLE); if (callback != null) { callback.onFinish(); } } @Override public void onCancel() { // Possible camera update was cancelled in between, so should account for this map change setMapRegionState(MapRegionChangeState.IDLE); if (callback != null) { callback.onCancel(); } } }; } } /** * Get the {@link CameraPosition} of the map view * @return The current camera position */ @NonNull public CameraPosition getCameraPosition() { return getCameraPosition(new CameraPosition()); } /** * Get the {@link CameraPosition} of the map view * @param out CameraPosition to be reused as the output * @return the current camera position of the map view */ @NonNull public CameraPosition getCameraPosition(@NonNull final CameraPosition out) { checkPointer(mapPointer); final double[] pos = { 0, 0 }; final float[] zrt = { 0, 0, 0 }; nativeGetCameraPosition(mapPointer, pos, zrt); out.longitude = pos[0]; out.latitude = pos[1]; out.zoom = zrt[0]; out.rotation = zrt[1]; out.tilt = zrt[2]; return out; } /** * Cancel current camera animation */ public void cancelCameraAnimation() { checkPointer(mapPointer); nativeCancelCameraAnimation(mapPointer); } /** * Get the {@link CameraPosition} that that encloses the given bounds with at least the given amount of padding on each side. * @param sw south-west coordinate * @param ne northwest coordinate * @param padding The minimum distance to keep between the bounds and the edges of the view * @return The enclosing camera position */ @NonNull public CameraPosition getEnclosingCameraPosition(@NonNull LngLat sw, @NonNull LngLat ne, @NonNull Rect padding) { return getEnclosingCameraPosition(sw, ne, padding, new CameraPosition()); } /** * Get the {@link CameraPosition} that that encloses the given bounds with at least the given amount of padding on each side. * @param sw south-west coordinate * @param ne northwest coordinate * @param padding The minimum distance to keep between the bounds and the edges of the view * @param out CameraPosition to be reused as the output * @return The enclosing camera position */ @NonNull public CameraPosition getEnclosingCameraPosition(@NonNull LngLat sw, @NonNull LngLat ne, @NonNull Rect padding, @NonNull final CameraPosition out) { int pad[] = new int[]{padding.left, padding.top, padding.right, padding.bottom}; double lngLatZoom[] = new double[3]; nativeGetEnclosingCameraPosition(mapPointer, sw.longitude, sw.latitude, ne.longitude, ne.latitude, pad, lngLatZoom); out.longitude = lngLatZoom[0]; out.latitude = lngLatZoom[1]; out.zoom = (float)lngLatZoom[2]; out.rotation = 0.f; out.tilt = 0.f; return out; } /** * Set the camera type for the map view * @param type A {@code CameraType} */ public void setCameraType(@NonNull final CameraType type) { checkPointer(mapPointer); nativeSetCameraType(mapPointer, type.ordinal()); } /** * Get the camera type currently in use for the map view * @return A {@code CameraType} */ public CameraType getCameraType() { checkPointer(mapPointer); return CameraType.values()[nativeGetCameraType(mapPointer)]; } /** * Get the minimum zoom level of the map view. The default minimum zoom is 0. * @return The zoom level */ public float getMinimumZoomLevel() { checkPointer(mapPointer); return nativeGetMinZoom(mapPointer); } /** * Set the minimum zoom level of the map view. * * Values less than the default minimum zoom will be clamped. Assigning a value greater than the * current maximum zoom will set the maximum zoom to this value. * @param minimumZoom The zoom level */ public void setMinimumZoomLevel(float minimumZoom) { checkPointer(mapPointer); nativeSetMinZoom(mapPointer, minimumZoom); } /** * Get the maximum zoom level of the map view. The default maximum zoom is 20.5. * @return The zoom level */ public float getMaximumZoomLevel() { checkPointer(mapPointer); return nativeGetMaxZoom(mapPointer); } /** * Set the maximum zoom level of the map view. * * Values greater than the default maximum zoom will be clamped. Assigning a value less than the * current minimum zoom will set the minimum zoom to this value. * @param maximumZoom The zoom level */ public void setMaximumZoomLevel(float maximumZoom) { checkPointer(mapPointer); nativeSetMaxZoom(mapPointer, maximumZoom); } /** * Find the geographic coordinates corresponding to the given position on screen * @param screenPosition Position in pixels from the top-left corner of the map area * @return LngLat corresponding to the given point, or null if the screen position * does not intersect a geographic location (this can happen at high tilt angles). */ @Nullable public LngLat screenPositionToLngLat(@NonNull final PointF screenPosition) { checkPointer(mapPointer); final double[] tmp = { screenPosition.x, screenPosition.y }; if (nativeScreenPositionToLngLat(mapPointer, tmp)) { return new LngLat(tmp[0], tmp[1]); } return null; } /** * Find the position on screen corresponding to the given geographic coordinates * @param lngLat Geographic coordinates * @return Position in pixels from the top-left corner of the map area (the point * may not lie within the viewable screen area) */ @NonNull public PointF lngLatToScreenPosition(@NonNull final LngLat lngLat) { checkPointer(mapPointer); final double[] tmp = { lngLat.longitude, lngLat.latitude }; nativeLngLatToScreenPosition(mapPointer, tmp); return new PointF((float)tmp[0], (float)tmp[1]); } /** * Construct a collection of drawable map features. * @param name The name of the data collection. Once added to a map, features from this * {@code MapData} will be available from a data source with this name, just like a data source * specified in a scene file. You cannot create more than one data source with the same name. * If you call {@code addDataLayer} with the same name more than once, the same {@code MapData} * object will be returned. */ public MapData addDataLayer(final String name) { return addDataLayer(name, false); } @NonNull public MapData addDataLayer(final String name, final boolean generateCentroid) { MapData mapData = clientTileSources.get(name); if (mapData != null) { return mapData; } checkPointer(mapPointer); final long pointer = nativeAddTileSource(mapPointer, name, generateCentroid); if (pointer <= 0) { throw new RuntimeException("Unable to create new data source"); } mapData = new MapData(name, pointer, this); clientTileSources.put(name, mapData); return mapData; } /** * For package-internal use only; remove a {@code MapData} from this map * @param mapData The {@code MapData} to remove */ void removeDataLayer(@NonNull final MapData mapData) { clientTileSources.remove(mapData.name); checkPointer(mapPointer); checkPointer(mapData.pointer); nativeRemoveTileSource(mapPointer, mapData.pointer); } /** * Manually trigger a re-draw of the map view * * Typically this does not need to be called from outside Tangram, see {@link #setRenderMode(int)}. */ @Keep public void requestRender() { viewHolder.requestRender(); } /** * Set whether the map view re-draws continuously * * Typically this does not need to be called from outside Tangram. The map automatically re-renders when the view * changes or when any animation in the map requires rendering. * @param renderMode Either 1, to render continuously, or 0, to render only when needed. */ @Keep public void setRenderMode(@IntRange(from=0,to=1) final int renderMode) { switch (renderMode) { case 0: viewHolder.setRenderMode(GLViewHolder.RenderMode.RENDER_WHEN_DIRTY); break; case 1: viewHolder.setRenderMode(GLViewHolder.RenderMode.RENDER_CONTINUOUSLY); break; default: } } /** * Get the {@link TouchInput} for this map. * * {@code TouchInput} allows you to configure how gestures can move the map. You can set custom * responders for any gesture type in {@code TouchInput} to override or extend the default * behavior. * * Note that {@code MapController} assigns the default gesture responders for the pan, rotate, * scale, and shove gestures. If you set custom responders for these gestures, the default * responders will be replaced and those gestures will no longer move the map. To customize * these gesture responders and preserve the default map movement behavior: create a new gesture * responder, get the responder for that gesture from the {@code MapController}, and then in the * new responder call the corresponding methods on the {@code MapController} gesture responder. * @return The {@code TouchInput}. */ public TouchInput getTouchInput() { return touchInput; } /** * Get a responder for pan gestures */ public TouchInput.PanResponder getPanResponder() { return new TouchInput.PanResponder() { @Override public boolean onPanBegin() { setMapRegionState(MapRegionChangeState.JUMPING); return true; } @Override public boolean onPan(final float startX, final float startY, final float endX, final float endY) { setMapRegionState(MapRegionChangeState.JUMPING); nativeHandlePanGesture(mapPointer, startX, startY, endX, endY); return true; } @Override public boolean onPanEnd() { setMapRegionState(MapRegionChangeState.IDLE); return true; } @Override public boolean onFling(final float posX, final float posY, final float velocityX, final float velocityY) { nativeHandleFlingGesture(mapPointer, posX, posY, velocityX, velocityY); return true; } @Override public boolean onCancelFling() { cancelCameraAnimation(); return true; } }; } /** * Get a responder for rotate gestures */ public TouchInput.RotateResponder getRotateResponder() { return new TouchInput.RotateResponder() { @Override public boolean onRotateBegin() { setMapRegionState(MapRegionChangeState.JUMPING); return true; } @Override public boolean onRotate(final float x, final float y, final float rotation) { setMapRegionState(MapRegionChangeState.JUMPING); nativeHandleRotateGesture(mapPointer, x, y, rotation); return true; } @Override public boolean onRotateEnd() { setMapRegionState(MapRegionChangeState.IDLE); return true; } }; } /** * Get a responder for scale gestures */ public TouchInput.ScaleResponder getScaleResponder() { return new TouchInput.ScaleResponder() { @Override public boolean onScaleBegin() { setMapRegionState(MapRegionChangeState.JUMPING); return true; } @Override public boolean onScale(final float x, final float y, final float scale, final float velocity) { setMapRegionState(MapRegionChangeState.JUMPING); nativeHandlePinchGesture(mapPointer, x, y, scale, velocity); return true; } @Override public boolean onScaleEnd() { setMapRegionState(MapRegionChangeState.IDLE); return true; } }; } /** * Get a responder for shove (vertical two-finger drag) gestures */ public TouchInput.ShoveResponder getShoveResponder() { return new TouchInput.ShoveResponder() { @Override public boolean onShoveBegin() { setMapRegionState(MapRegionChangeState.JUMPING); return true; } @Override public boolean onShove(final float distance) { setMapRegionState(MapRegionChangeState.JUMPING); nativeHandleShoveGesture(mapPointer, distance); return true; } @Override public boolean onShoveEnd() { setMapRegionState(MapRegionChangeState.IDLE); return true; } }; } /** * Set the radius to use when picking features on the map. The default radius is 0.5 dp. * @param radius The radius in dp (density-independent pixels). */ public void setPickRadius(final float radius) { checkPointer(mapPointer); nativeSetPickRadius(mapPointer, radius); } /** * Set a listener for feature pick events * @param listener The {@link FeaturePickListener} to call */ public void setFeaturePickListener(@Nullable final FeaturePickListener listener) { featurePickListener = listener; } /** * Set a listener for scene update error statuses * @param listener The {@link SceneLoadListener} to call after scene has loaded */ public void setSceneLoadListener(@Nullable final SceneLoadListener listener) { sceneLoadListener = listener; } /** * Set a listener for label pick events * @param listener The {@link LabelPickListener} to call */ public void setLabelPickListener(@Nullable final LabelPickListener listener) { labelPickListener = (listener == null) ? null : new LabelPickListener() { @Override public void onLabelPick(final LabelPickResult labelPickResult, final float positionX, final float positionY) { uiThreadHandler.post(new Runnable() { @Override public void run() { listener.onLabelPick(labelPickResult, positionX, positionY); } }); } }; } /** * Set a listener for marker pick events * @param listener The {@link MarkerPickListener} to call */ public void setMarkerPickListener(@Nullable final MarkerPickListener listener) { markerPickListener = (listener == null) ? null : new MarkerPickListener() { @Override public void onMarkerPick(final MarkerPickResult markerPickResult, final float positionX, final float positionY) { uiThreadHandler.post(new Runnable() { @Override public void run() { listener.onMarkerPick(markerPickResult, positionX, positionY); } }); } }; } /** * Query the map for geometry features at the given screen coordinates; results will be returned * in a callback to the object set by {@link #setFeaturePickListener(FeaturePickListener)} * @param posX The horizontal screen coordinate * @param posY The vertical screen coordinate */ public void pickFeature(final float posX, final float posY) { if (featurePickListener != null) { checkPointer(mapPointer); nativePickFeature(mapPointer, posX, posY); } } /** * Query the map for labeled features at the given screen coordinates; results will be returned * in a callback to the object set by {@link #setLabelPickListener(LabelPickListener)} * @param posX The horizontal screen coordinate * @param posY The vertical screen coordinate */ public void pickLabel(final float posX, final float posY) { if (labelPickListener != null) { checkPointer(mapPointer); nativePickLabel(mapPointer, posX, posY); } } /** * Query the map for a {@link Marker} at the given screen coordinates; results will be returned * in a callback to the object set by {@link #setMarkerPickListener(MarkerPickListener)} * @param posX The horizontal screen coordinate * @param posY The vertical screen coordinate */ public void pickMarker(final float posX, final float posY) { if (markerPickListener != null) { checkPointer(mapPointer); nativePickMarker(mapPointer, posX, posY); } } /** * Adds a {@link Marker} to the map which can be used to dynamically add points and polylines * to the map. * @return Newly created {@link Marker} object. */ @NonNull public Marker addMarker() { checkPointer(mapPointer); final long markerId = nativeMarkerAdd(mapPointer); final Marker marker = new Marker(viewHolder.getView().getContext(), markerId, this); markers.put(markerId, marker); return marker; } /** * Removes the passed in {@link Marker} from the map. * Alias of Marker{@link #removeMarker(long)} * @param marker to remove from the map. * @return whether or not the marker was removed */ public boolean removeMarker(@NonNull final Marker marker) { return this.removeMarker(marker.getMarkerId()); } /** * Removes the passed in {@link Marker} from the map. * @param markerId to remove from the map. * @return whether or not the marker was removed */ public boolean removeMarker(final long markerId) { checkPointer(mapPointer); checkId(markerId); markers.remove(markerId); return nativeMarkerRemove(mapPointer, markerId); } /** * Remove all the {@link Marker} objects from the map. */ public void removeAllMarkers() { checkPointer(mapPointer); nativeMarkerRemoveAll(mapPointer); // Invalidate all markers so their ids are unusable for (int i = 0; i < markers.size(); i++) { final Marker marker = markers.valueAt(i); marker.invalidate(); } markers.clear(); } /** * Set a listener for map change events * @param listener The {@link MapChangeListener} to call when the map change events occur * due to camera updates or user interaction */ public void setMapChangeListener(@Nullable final MapChangeListener listener) { mapChangeListener = listener; } void setMapRegionState(MapRegionChangeState state) { if (mapChangeListener != null) { switch (currentState) { case IDLE: if (state == MapRegionChangeState.JUMPING) { mapChangeListener.onRegionWillChange(false); } else if (state == MapRegionChangeState.ANIMATING){ mapChangeListener.onRegionWillChange(true); } break; case JUMPING: if (state == MapRegionChangeState.IDLE) { mapChangeListener.onRegionDidChange(false); } else if (state == MapRegionChangeState.JUMPING) { mapChangeListener.onRegionIsChanging(); } break; case ANIMATING: if (state == MapRegionChangeState.IDLE) { mapChangeListener.onRegionDidChange(true); } else if (state == MapRegionChangeState.ANIMATING) { mapChangeListener.onRegionIsChanging(); } break; } } currentState = state; } /** * Enqueue a Runnable to be executed synchronously on the rendering thread * @param r Runnable to run */ public void queueEvent(@NonNull final Runnable r) { viewHolder.queueEvent(r); } /** * Make a debugging feature active or inactive * @param flag The feature to set * @param on True to activate the feature, false to deactivate */ public void setDebugFlag(@NonNull final DebugFlag flag, final boolean on) { nativeSetDebugFlag(flag.ordinal(), on); } /** * Set whether the OpenGL state will be cached between subsequent frames. This improves * rendering efficiency, but can cause errors if your application code makes OpenGL calls. * @param use Whether to use a cached OpenGL state; false by default */ public void useCachedGlState(final boolean use) { checkPointer(mapPointer); nativeUseCachedGlState(mapPointer, use); } /** * Sets an opaque background color used as default color when a scene is being loaded * @param red red component of the background color * @param green green component of the background color * @param blue blue component of the background color */ public void setDefaultBackgroundColor(final float red, final float green, final float blue) { checkPointer(mapPointer); nativeSetDefaultBackgroundColor(mapPointer, red, green, blue); } // Package private methods void onLowMemory() { checkPointer(mapPointer); nativeOnLowMemory(mapPointer); } void removeTileSource(final long sourcePtr) { checkPointer(mapPointer); checkPointer(sourcePtr); nativeRemoveTileSource(mapPointer, sourcePtr); } void clearTileSource(final long sourcePtr) { checkPointer(mapPointer); checkPointer(sourcePtr); nativeClearTileSource(mapPointer, sourcePtr); } void addFeature(final long sourcePtr, final double[] coordinates, final int[] rings, final String[] properties) { checkPointer(mapPointer); checkPointer(sourcePtr); nativeAddFeature(mapPointer, sourcePtr, coordinates, rings, properties); } void addGeoJson(final long sourcePtr, final String geoJson) { checkPointer(mapPointer); checkPointer(sourcePtr); nativeAddGeoJson(mapPointer, sourcePtr, geoJson); } void checkPointer(final long ptr) { if (ptr <= 0) { throw new RuntimeException("Tried to perform an operation on an invalid pointer!" + " This means you may have used an object that has been disposed and is no" + " longer valid."); } } void checkId(final long id) { if (id <= 0) { throw new RuntimeException("Tried to perform an operation on an invalid id!" + " This means you may have used an object that has been disposed and is no" + " longer valid."); } } @Nullable private String[] bundleSceneUpdates(@Nullable final List<SceneUpdate> sceneUpdates) { if (sceneUpdates == null) { return null; } final String[] updateStrings = new String[sceneUpdates.size() * 2]; int index = 0; for (final SceneUpdate sceneUpdate : sceneUpdates) { updateStrings[index++] = sceneUpdate.getPath(); updateStrings[index++] = sceneUpdate.getValue(); } return updateStrings; } boolean setMarkerStylingFromString(final long markerId, final String styleString) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetStylingFromString(mapPointer, markerId, styleString); } boolean setMarkerStylingFromPath(final long markerId, final String path) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetStylingFromPath(mapPointer, markerId, path); } boolean setMarkerBitmap(final long markerId, Bitmap bitmap, float density) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetBitmap(mapPointer, markerId, bitmap, density); } boolean setMarkerPoint(final long markerId, final double lng, final double lat) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetPoint(mapPointer, markerId, lng, lat); } boolean setMarkerPointEased(final long markerId, final double lng, final double lat, final int duration, @NonNull final EaseType ease) { checkPointer(mapPointer); checkId(markerId); final float seconds = duration / 1000.f; return nativeMarkerSetPointEased(mapPointer, markerId, lng, lat, seconds, ease.ordinal()); } boolean setMarkerPolyline(final long markerId, final double[] coordinates, final int count) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetPolyline(mapPointer, markerId, coordinates, count); } boolean setMarkerPolygon(final long markerId, final double[] coordinates, final int[] rings, final int count) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetPolygon(mapPointer, markerId, coordinates, rings, count); } boolean setMarkerVisible(final long markerId, final boolean visible) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetVisible(mapPointer, markerId, visible); } boolean setMarkerDrawOrder(final long markerId, final int drawOrder) { checkPointer(mapPointer); checkId(markerId); return nativeMarkerSetDrawOrder(mapPointer, markerId, drawOrder); } // Networking methods @Keep void cancelUrlRequest(final long requestHandle) { Object request = httpRequestHandles.remove(requestHandle); if (request != null) { httpHandler.cancelRequest(request); } } @Keep void startUrlRequest(@NonNull final String url, final long requestHandle) { final HttpHandler.Callback callback = new HttpHandler.Callback() { @Override public void onFailure(@Nullable final IOException e) { if (httpRequestHandles.remove(requestHandle) == null) { return; } String msg = (e == null) ? "" : e.getMessage(); nativeOnUrlComplete(mapPointer, requestHandle, null, msg); } @Override public void onResponse(final int code, @Nullable final byte[] rawDataBytes) { if (httpRequestHandles.remove(requestHandle) == null) { return; } if (code >= 200 && code < 300) { nativeOnUrlComplete(mapPointer, requestHandle, rawDataBytes, null); } else { nativeOnUrlComplete(mapPointer, requestHandle, null, "Unexpected response code: " + code + " for URL: " + url); } } @Override public void onCancel() { if (httpRequestHandles.remove(requestHandle) == null) { return; } nativeOnUrlComplete(mapPointer, requestHandle, null, null); } }; Object request = httpHandler.startRequest(url, callback); if (request != null) { httpRequestHandles.put(requestHandle, request); } } // Called from JNI on worker or render-thread. @Keep void sceneReadyCallback(final int sceneId, final int errorType, final String updatePath, final String updateValue) { final SceneLoadListener listener = sceneLoadListener; if (listener != null) { uiThreadHandler.post(new Runnable() { @Override public void run() { SceneError error = null; if (errorType >= 0) { error = new SceneError(updatePath, updateValue, errorType); } listener.onSceneReady(sceneId, error); } }); } } // Called from JNI on render-thread. @Keep void cameraAnimationCallback(final boolean finished) { final CameraAnimationCallback callback = cameraAnimationCallback; synchronized (cameraAnimationCallbackLock) { cameraAnimationCallback = pendingCameraAnimationCallback; pendingCameraAnimationCallback = null; } if (callback != null) { uiThreadHandler.post(new Runnable() { @Override public void run() { if (finished) { callback.onFinish(); } else { callback.onCancel(); } } }); } } @Keep void featurePickCallback(final Map<String, String> properties, final float x, final float y) { final FeaturePickListener listener = featurePickListener; if (listener != null) { uiThreadHandler.post(new Runnable() { @Override public void run() { listener.onFeaturePick(properties, x, y); } }); } } @Keep void labelPickCallback(final Map<String, String> properties, final float x, final float y, final int type, final double lng, final double lat) { final LabelPickListener listener = labelPickListener; if (listener != null) { uiThreadHandler.post(new Runnable() { @Override public void run() { LabelPickResult result = null; if (properties != null) { result = new LabelPickResult(lng, lat, type, properties); } listener.onLabelPick(result, x, y); } }); } } @Keep void markerPickCallback(final long markerId, final float x, final float y, final double lng, final double lat) { final MarkerPickListener listener = markerPickListener; if (listener != null) { uiThreadHandler.post(new Runnable() { @Override public void run() { final Marker marker = markers.get(markerId); MarkerPickResult result = null; if (marker != null) { result = new MarkerPickResult(marker, lng, lat); } listener.onMarkerPick(result, x, y); } }); } } // Font Fetching @Keep String getFontFilePath(final String key) { return fontFileParser.getFontFile(key); } @Keep String getFontFallbackFilePath(final int importance, final int weightHint) { return fontFileParser.getFontFallback(importance, weightHint); } // Private members long mapPointer; private MapRenderer mapRenderer; private GLViewHolder viewHolder; private MapRegionChangeState currentState = MapRegionChangeState.IDLE; private AssetManager assetManager; private TouchInput touchInput; private FontFileParser fontFileParser; private DisplayMetrics displayMetrics = new DisplayMetrics(); private HttpHandler httpHandler; private final Map<Long, Object> httpRequestHandles = Collections.synchronizedMap(new HashMap()); MapChangeListener mapChangeListener; private FeaturePickListener featurePickListener; private SceneLoadListener sceneLoadListener; private LabelPickListener labelPickListener; private MarkerPickListener markerPickListener; private FrameCaptureCallback frameCaptureCallback; private boolean frameCaptureAwaitCompleteView; private Map<String, MapData> clientTileSources; private LongSparseArray<Marker> markers; private Handler uiThreadHandler; private CameraAnimationCallback cameraAnimationCallback; private CameraAnimationCallback pendingCameraAnimationCallback; private final Object cameraAnimationCallbackLock = new Object(); private boolean isGLRendererSet = false; // Native methods private synchronized native void nativeOnLowMemory(long mapPtr); private synchronized native long nativeInit(AssetManager assetManager); private synchronized native void nativeDispose(long mapPtr); private synchronized native void nativeShutdown(long mapPtr); private synchronized native int nativeLoadScene(long mapPtr, String path, String[] updateStrings); private synchronized native int nativeLoadSceneAsync(long mapPtr, String path, String[] updateStrings); private synchronized native int nativeLoadSceneYaml(long mapPtr, String yaml, String resourceRoot, String[] updateStrings); private synchronized native int nativeLoadSceneYamlAsync(long mapPtr, String yaml, String resourceRoot, String[] updateStrings); private synchronized native void nativeGetCameraPosition(long mapPtr, double[] lonLatOut, float[] zoomRotationTiltOut); private synchronized native void nativeUpdateCameraPosition(long mapPtr, int set, double lon, double lat, float zoom, float zoomBy, float rotation, float rotateBy, float tilt, float tiltBy, double b1lon, double b1lat, double b2lon, double b2lat, int[] padding, float duration, int ease); private synchronized native void nativeFlyTo(long mapPtr, double lon, double lat, float zoom, float duration, float speed); private synchronized native void nativeGetEnclosingCameraPosition(long mapPtr, double aLng, double aLat, double bLng, double bLat, int[] buffer, double[] lngLatZoom); private synchronized native void nativeCancelCameraAnimation(long mapPtr); private synchronized native boolean nativeScreenPositionToLngLat(long mapPtr, double[] coordinates); private synchronized native boolean nativeLngLatToScreenPosition(long mapPtr, double[] coordinates); private synchronized native void nativeSetPixelScale(long mapPtr, float scale); private synchronized native void nativeSetCameraType(long mapPtr, int type); private synchronized native int nativeGetCameraType(long mapPtr); private synchronized native float nativeGetMinZoom(long mapPtr); private synchronized native void nativeSetMinZoom(long mapPtr, float minZoom); private synchronized native float nativeGetMaxZoom(long mapPtr); private synchronized native void nativeSetMaxZoom(long mapPtr, float maxZoom); private synchronized native void nativeHandleTapGesture(long mapPtr, float posX, float posY); private synchronized native void nativeHandleDoubleTapGesture(long mapPtr, float posX, float posY); private synchronized native void nativeHandlePanGesture(long mapPtr, float startX, float startY, float endX, float endY); private synchronized native void nativeHandleFlingGesture(long mapPtr, float posX, float posY, float velocityX, float velocityY); private synchronized native void nativeHandlePinchGesture(long mapPtr, float posX, float posY, float scale, float velocity); private synchronized native void nativeHandleRotateGesture(long mapPtr, float posX, float posY, float rotation); private synchronized native void nativeHandleShoveGesture(long mapPtr, float distance); private synchronized native int nativeUpdateScene(long mapPtr, String[] updateStrings); private synchronized native void nativeSetPickRadius(long mapPtr, float radius); private synchronized native void nativePickFeature(long mapPtr, float posX, float posY); private synchronized native void nativePickLabel(long mapPtr, float posX, float posY); private synchronized native void nativePickMarker(long mapPtr, float posX, float posY); private synchronized native long nativeMarkerAdd(long mapPtr); private synchronized native boolean nativeMarkerRemove(long mapPtr, long markerID); private synchronized native boolean nativeMarkerSetStylingFromString(long mapPtr, long markerID, String styling); private synchronized native boolean nativeMarkerSetStylingFromPath(long mapPtr, long markerID, String path); private synchronized native boolean nativeMarkerSetBitmap(long mapPtr, long markerID, Bitmap bitmap, float density); private synchronized native boolean nativeMarkerSetPoint(long mapPtr, long markerID, double lng, double lat); private synchronized native boolean nativeMarkerSetPointEased(long mapPtr, long markerID, double lng, double lat, float duration, int ease); private synchronized native boolean nativeMarkerSetPolyline(long mapPtr, long markerID, double[] coordinates, int count); private synchronized native boolean nativeMarkerSetPolygon(long mapPtr, long markerID, double[] coordinates, int[] rings, int count); private synchronized native boolean nativeMarkerSetVisible(long mapPtr, long markerID, boolean visible); private synchronized native boolean nativeMarkerSetDrawOrder(long mapPtr, long markerID, int drawOrder); private synchronized native void nativeMarkerRemoveAll(long mapPtr); private synchronized native void nativeUseCachedGlState(long mapPtr, boolean use); private synchronized native void nativeSetDefaultBackgroundColor(long mapPtr, float r, float g, float b); private native void nativeOnUrlComplete(long mapPtr, long requestHandle, byte[] rawDataBytes, String errorMessage); synchronized native long nativeAddTileSource(long mapPtr, String name, boolean generateCentroid); synchronized native void nativeRemoveTileSource(long mapPtr, long sourcePtr); synchronized native void nativeClearTileSource(long mapPtr, long sourcePtr); synchronized native void nativeAddFeature(long mapPtr, long sourcePtr, double[] coordinates, int[] rings, String[] properties); synchronized native void nativeAddGeoJson(long mapPtr, long sourcePtr, String geoJson); native void nativeSetDebugFlag(int flag, boolean on); }
package net.milkycraft.Listeners; import java.util.List; import net.milkycraft.Spawnegg; import org.bukkit.entity.CaveSpider; import org.bukkit.entity.Chicken; import org.bukkit.entity.Cow; import org.bukkit.entity.Creeper; import org.bukkit.entity.Enderman; import org.bukkit.entity.Ghast; import org.bukkit.entity.IronGolem; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.MagmaCube; import org.bukkit.entity.MushroomCow; import org.bukkit.entity.Ocelot; import org.bukkit.entity.Pig; import org.bukkit.entity.PigZombie; import org.bukkit.entity.Sheep; import org.bukkit.entity.Silverfish; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Slime; import org.bukkit.entity.Snowman; import org.bukkit.entity.Spider; import org.bukkit.entity.Villager; import org.bukkit.entity.Wolf; import org.bukkit.entity.Zombie; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityTargetEvent; public class SpawnListener implements Listener{ private boolean cancelled = true; Spawnegg plugin; public SpawnListener(Spawnegg instance) { plugin = instance; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onSpawn(CreatureSpawnEvent e) { if(e.isCancelled()) { return; } List<String> worldz = plugin.getConfig().getStringList( "World.Worldname"); for (String worldname : worldz) { if (e.getEntity().getWorld().getName().equals(worldname)) { if(e.getEntity() instanceof LivingEntity) { if(e.getEntity() instanceof Creeper) { if(plugin.getConfig().getBoolean("disabled.mobs.creeper")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity()instanceof Skeleton) { if(plugin.getConfig().getBoolean("disabled.mobs.skeleton")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Spider) { if(plugin.getConfig().getBoolean("disabled.mobs.spider")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Zombie) { if(plugin.getConfig().getBoolean("disabled.mobs.zombie")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Slime) { if(plugin.getConfig().getBoolean("disabled.mobs.slime")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Ghast) { if(plugin.getConfig().getBoolean("disabled.mobs.ghast")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof PigZombie) { if(plugin.getConfig().getBoolean("disabled.mobs.pigman")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Enderman) { if(plugin.getConfig().getBoolean("disabled.mobs.enderman")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof CaveSpider) { if(plugin.getConfig().getBoolean("disabled.mobs.cavespider")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Silverfish) { if(plugin.getConfig().getBoolean("disabled.mobs.silverfish")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Ghast) { if(plugin.getConfig().getBoolean("disabled.mobs.blaze")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof MagmaCube) { if(plugin.getConfig().getBoolean("disabled.mobs.magmacube")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Pig) { if(plugin.getConfig().getBoolean("disabled.mobs.pig")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Sheep) { if(plugin.getConfig().getBoolean("disabled.mobs.sheep")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Cow) { if(plugin.getConfig().getBoolean("disabled.mobs.cow")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Chicken) { if(plugin.getConfig().getBoolean("disabled.mobs.chicken")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Ghast) { if(plugin.getConfig().getBoolean("disabled.mobs.squid")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Wolf) { if(plugin.getConfig().getBoolean("disabled.mobs.wolf")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof MushroomCow) { if(plugin.getConfig().getBoolean("disabled.mobs.mooshroom")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Snowman) { if(plugin.getConfig().getBoolean("disabled.mobs.snowgolem")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Ocelot) { if(plugin.getConfig().getBoolean("disabled.mobs.ocelot")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof IronGolem) { if(plugin.getConfig().getBoolean("disabled.mobs.irongolem")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Villager) { if(plugin.getConfig().getBoolean("disabled.mobs.villager")) { e.setCancelled(true); blocked(e); return; } } else if(e.getEntity() instanceof Villager) { if(plugin.getConfig().getBoolean("disabled.mobs.villager")) { e.setCancelled(true); blocked(e); return; } } } } } } @EventHandler(priority = EventPriority.HIGH) public void onTarget(EntityTargetEvent ev, CreatureSpawnEvent e) { if(this.blocked(e)) { ev.getEntity().remove(); Spawnegg.log.warning("Blocked Mob was forcibly removed on target"); return; } } public boolean blocked(CreatureSpawnEvent e) { return cancelled; } }
package netspy.components.mailing; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import netspy.NetSpy; import netspy.components.config.ConfigPropertiesManager; import netspy.components.filehandling.lists.Blacklist; import netspy.components.filehandling.manager.FileManager; import netspy.components.logging.LogManager; import netspy.components.util.StringHelper; /** * The Class EmailHandler. */ public class EmailHandler { /** The Constant SECURITY_LEVEL. */ public static final int SECURITY_LEVEL = 6; /** The Constant EML_FILE_EXTENSION. */ public static final String EML_FILE_EXTENSION = ".eml"; /** The Constant HTML_MAIL_PART_START_IDENTIFIER. */ private static final String HTML_MAIL_PART_START_IDENTIFIER = "Content-Type: text/html;"; /** The Constant MAIL_SENDER_IDENTIFIER. */ private static final String MAIL_SENDER_IDENTIFIER = "from:"; /** The Constant MAIL_RECEIVER_IDENTIFIER. */ private static final String MAIL_RECEIVER_IDENTIFIER = "to:"; /** The Constant MAIL_SUBJECT_IDENTIFIER. */ private static final String MAIL_SUBJECT_IDENTIFIER = "subject:"; /** The Constant MAIL_SENDING_DATE_IDENTIFIER. */ private static final String MAIL_SENDING_DATE_IDENTIFIER = "date:"; /** The mail containers. */ private EmailContainer mailContainer = new EmailContainer(); /** * Check mailbox. * * @return true, if successful */ public boolean checkMailbox() { return !getEmlFiles().isEmpty(); } /** * Gets the eml files. * * @return the eml files */ public List<File> getEmlFiles() { return new FileManager().getFilesByExtension(EML_FILE_EXTENSION, new ConfigPropertiesManager().getInboxPath()); } /** * Extract email properties. * * @param email the email * @return the email */ private Email extractEmailProperties(Email email) { for (String line: email.getLines()) { if (line.startsWith(MAIL_SENDER_IDENTIFIER)) { email.setSender(this.extractSender(line)); } if (line.startsWith(MAIL_RECEIVER_IDENTIFIER)) { email.setReceiver(this.extractReceiver(line)); } if (line.startsWith(MAIL_SUBJECT_IDENTIFIER)) { email.setSubject(this.extractSubject(line)); } if (line.startsWith(MAIL_SENDING_DATE_IDENTIFIER)) { email.setSendingDate(this.extractSendingDate(line)); } } return email; } /** * Extract sending date. * * @param line the line * @return the string */ private String extractSendingDate(String line) { String date = new StringHelper().splitString(line, ": ").get(1).trim(); // set "Nicht definiert" if property is not defined if (date.length() <= 0 || date == null) { return "Nicht definiert"; } return date; } /** * Extract subject. * * @param line the line * @return the string */ private String extractSubject(String line) { String subject = new StringHelper().splitString(line, ": ").get(1).trim(); // set "Nicht definiert" if property is not defined if (subject.length() <= 0 || subject == null) { return "Nicht definiert"; } return subject; } /** * Extract sender. * * @param line the line * @return the string */ private String extractSender(String line) { String sender = new StringHelper().splitString(line, ": ").get(1).trim(); sender = sender.substring(sender.indexOf("<") + 1, sender.indexOf(">")); // set "Nicht definiert" if property is not defined if (sender.length() <= 0 || sender == null) { return "Nicht definiert"; } return sender; } /** * Extract receiver. * * @param line the line * @return the string receiver */ private String extractReceiver(String line) { String receiver = new StringHelper().splitString(line, ": ").get(1).trim(); receiver = receiver.substring(receiver.indexOf("<") + 1, receiver.indexOf(">")); // set "Nicht definiert" if property is not defined if (receiver.length() <= 0 || receiver == null) { return "Nicht definiert"; } return receiver; } /** * Gets the mail container. * * @return the mail container */ public EmailContainer getMailContainer() { return this.mailContainer; } /** * Sets the mail container. * * @param mailContainer the new mail container */ public void setMailContainer(EmailContainer mailContainer) { this.mailContainer = mailContainer; } /** * Scan mails. */ public void scanMails() { for (Email email: this.getMailContainer().getMails()) { List<String> mailContent = null; mailContent = email.getLines(); // replace ascii, then to lower case mailContent = new StringHelper().toLowerCase(new StringHelper().replaceAscii(mailContent)); email.setLines(mailContent); email = this.checkAgainstBlacklist(email); email = this.extractEmailProperties(email); // just if mail is suspicious, get its properties, // else remove mail and go to next mail if (!email.isSuspicious()) { continue; } } } /** * Put mails into quarantine. */ public void putMailsIntoQuarantine() { int counterSuspiciousMails = 0; for (Email email: this.getMailContainer().getMails()) { if (email.isSuspicious()) { new LogManager().log(email); new FileManager().moveFile(email.getRelativePath(), new ConfigPropertiesManager().getQuarantinePath()); counterSuspiciousMails++; } } // clear mail container after files are moved this.mailContainer = new EmailContainer(); String msg = "Es wurden " + counterSuspiciousMails + " verdächtige Email(s) gefunden."; if (counterSuspiciousMails >= 1) { msg += System.lineSeparator(); msg += "Weitere Details dazu befinden sich in der Logdatei."; } NetSpy.mainFrame.getLogBox().append(msg); } /** * Check against blacklist. * * @param email the email * @return the email */ private Email checkAgainstBlacklist(Email email) { Map<String, Integer> hitMap = new HashMap<>(); int hitsInLine = 0; int totalHits = 0; int hitsBefore = 0; for (String line: email.getLines()) { for (String blacklistWord: this.getBlacklist()) { // convert to lower case before checking blacklistWord = blacklistWord.toLowerCase(); if (line.contains(blacklistWord)) { // count hits in current line hitsInLine = new StringHelper().countOccurrences(line, blacklistWord); // add it to total hits totalHits += hitsInLine; // if the word was not found yet if (!hitMap.keySet().contains(blacklistWord)) { // add it to the hitmap hitMap.put(blacklistWord, hitsInLine); } else { // add hits to existing amount hitsBefore = hitMap.get(blacklistWord); hitMap.remove(blacklistWord); hitMap.put(blacklistWord, (hitsBefore + hitsInLine)); } } } // set suspicious flag to an email if amount of hits // has passed a specific limit if (totalHits >= SECURITY_LEVEL && !email.isSuspicious()) { email.setSuspicious(true); } } email.setHitMap(hitMap); return email; } /** * Log results. */ public void logResults() { } /** * Gets the blacklist. * * @return the blacklist */ private List<String> getBlacklist() { return new Blacklist(new FileManager().getBlacklist()).getBlacklist(); } /** * Gets the mail content. * * @param file the file * @return the mail content * @throws IOException Signals that an I/O exception has occurred. */ public List<String> getMailContent(File file) throws IOException { return new FileManager().readFile(file.getPath(), "UTF-8", HTML_MAIL_PART_START_IDENTIFIER); } }
package nl.tudelft.selfcompileapp; import java.io.File; import java.io.InputStream; import java.io.PrintWriter; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import com.android.dex.Dex; import com.android.dx.merge.CollisionPolicy; import com.android.dx.merge.DexMerger; import com.android.sdklib.build.ApkBuilder; public class MainActivity extends Activity { private final String target_platform = "android-18"; private final String proj_name = "SelfCompileApp"; private final String[] proj_libs = { "kellinwood-logging-lib-1.1.jar", "zipio-lib-1.8.jar", "zipsigner-lib-1.17.jar", "sdklib-24.3.3.jar", "dx-22.0.1.jar", "ecj-4.5-A.jar", "ecj-4.5-B.jar", "ecj-4.5-C.jar" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void clean(View btnClean) { btnClean.setEnabled(false); new CleanBuild().execute(); } public void aidl(View btnAidl) { btnAidl.setEnabled(false); new ConvertAidl().execute(); } public void aapt(View btnAapt) { btnAapt.setEnabled(false); new PackAssets().execute(); } public void compile(View btnCompile) { btnCompile.setEnabled(false); new CompileJava().execute(); } public void dexlibs(View btnDexLibs) { btnDexLibs.setEnabled(false); new DexLibs().execute(); } public void dex(View btnDex) { btnDex.setEnabled(false); new DexMerge().execute(); } public void apk(View btnPack) { btnPack.setEnabled(false); new BuildApk().execute(); } public void sign(View btnSign) { btnSign.setEnabled(false); new SignApk().execute(); } public void align(View btnAlign) { btnAlign.setEnabled(false); new AlignApk().execute(); } public void install(View btnInstall) { btnInstall.setEnabled(false); new InstallApk().execute(); } private class CleanBuild extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnClean = (Button) findViewById(R.id.btnClean); btnClean.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirSrc = new File(dirProj, "src"); File dirRes = new File(dirProj, "res"); File dirLibs = new File(dirProj, "libs"); File dirAssets = new File(dirProj, "assets"); File dirBin = new File(dirProj, "bin"); File dirDexedLibs = new File(dirBin, "dexedLibs"); File xmlMan = new File(dirProj, "AndroidManifest.xml"); File jarAndroid = new File(dirAssets, target_platform + ".jar"); System.out.println("// DELETE PROJECT FOLDER"); Util.deleteRecursive(dirProj); // DEBUG Util.listRecursive(dirRoot); System.out.println("// EXTRACT PROJECT"); dirSrc.mkdirs(); dirRes.mkdirs(); dirLibs.mkdirs(); dirAssets.mkdirs(); dirBin.mkdirs(); dirDexedLibs.mkdirs(); Util.copy(getAssets().open(xmlMan.getName()), xmlMan); Util.copy(getAssets().open(jarAndroid.getName()), jarAndroid); InputStream zipSrc = getAssets().open("src.zip"); Util.unzip(zipSrc, dirSrc); InputStream zipRes = getAssets().open("res.zip"); Util.unzip(zipRes, dirRes); InputStream zipLibs = getAssets().open("libs.zip"); Util.unzip(zipLibs, dirLibs); InputStream zipDexedLibs = getAssets().open("dexedLibs.zip"); Util.unzip(zipDexedLibs, dirDexedLibs); // DEBUG Util.listRecursive(dirProj); } catch (Exception e) { e.printStackTrace(); } return null; } } private class ConvertAidl extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnAidl = (Button) findViewById(R.id.btnAidl); btnAidl.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { System.out.println("// RUN AIDL"); // TODO } catch (Exception e) { e.printStackTrace(); } return null; } } private class PackAssets extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnAapt = (Button) findViewById(R.id.btnAapt); btnAapt.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirAssets = new File(dirProj, "assets"); File dirGen = new File(dirProj, "gen"); File dirRes = new File(dirProj, "res"); File dirBin = new File(dirProj, "bin"); // File dirBinRes = new File(dirBin, "res"); // File dirCrunch = new File(dirBinRes, "crunch"); // File xmlBinMan = new File(dirBin, "AndroidManifest.xml"); File xmlMan = new File(dirProj, "AndroidManifest.xml"); File jarAndroid = new File(dirAssets, target_platform + ".jar"); File ap_Resources = new File(dirBin, "resources.ap_"); dirGen.mkdirs(); System.out.println("// DELETE xxhdpi"); // TODO update aapt Util.deleteRecursive(new File(dirRes, "drawable-xxhdpi")); Aapt aapt = new Aapt(); int exitCode; System.out.println("// RUN AAPT & CREATE R.JAVA"); exitCode = aapt .fnExecute("aapt p -f -v -M " + xmlMan.getPath() + " -F " + ap_Resources.getPath() + " -I " + jarAndroid.getPath() + " -A " + dirAssets.getPath() + " -S " + dirRes.getPath() + " -J " + dirGen.getPath()); System.out.println(exitCode); // System.out.println("// CREATE R.JAVA"); // exitCode = aapt.fnExecute("aapt p -m -v -J " + // dirGen.getPath() // + " -M " + xmlMan.getPath() + " -S " + dirRes.getPath() // System.out.println(exitCode); // System.out.println("// CRUNCH PNG"); // exitCode = aapt.fnExecute("aapt c -v -S " + dirRes.getPath() // + " -C " + dirCrunch.getPath()); // System.out.println(exitCode); // System.out.println("// RUN AAPT"); // exitCode = aapt // .fnExecute("aapt p -v -S " // + dirCrunch.getPath() // + dirRes.getPath() // " -f --no-crunch --auto-add-overlay --debug-mode -0 apk -M " // + xmlBinMan.getPath() + " -A " // + dirAssets.getPath() + " -I " // + jarAndroid.getPath() + " -F " // + ap_Resources.getPath()); // System.out.println(exitCode); // DEBUG Util.listRecursive(dirProj); } catch (Exception e) { e.printStackTrace(); } return null; } } private class CompileJava extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnCompile = (Button) findViewById(R.id.btnCompile); btnCompile.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirSrc = new File(dirProj, "src"); File dirGen = new File(dirProj, "gen"); File dirLibs = new File(dirProj, "libs"); File dirBin = new File(dirProj, "bin"); File dirClasses = new File(dirBin, "classes"); File jarAndroid = new File(dirRoot, target_platform + ".jar"); dirClasses.mkdirs(); String strBootCP = jarAndroid.getPath(); String strClassPath = ""; for (String lib : proj_libs) { strClassPath += File.pathSeparator + new File(dirLibs, lib).getPath(); } Locale.setDefault(Locale.ROOT); System.out.println("// COMPILE SOURCE RECURSIVE"); org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile( new String[] { "-1.5", "-showversion", "-verbose", "-deprecation", "-bootclasspath", strBootCP, "-cp", strClassPath, "-d", dirClasses.getPath(), dirGen.getPath(), dirSrc.getPath() }, new PrintWriter(System.out), new PrintWriter(System.err), new CompileProgress()); // DEBUG Util.listRecursive(dirGen); Util.listRecursive(dirBin); } catch (Exception e) { e.printStackTrace(); } return null; } } private class CompileProgress extends org.eclipse.jdt.core.compiler.CompilationProgress { @Override public void begin(int arg0) { } @Override public void done() { } @Override public boolean isCanceled() { // TODO Auto-generated method stub return false; } @Override public void setTaskName(String arg0) { } @Override public void worked(int arg0, int arg1) { } } private class DexLibs extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnDexLibs = (Button) findViewById(R.id.btnDexLibs); btnDexLibs.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirLibs = new File(dirProj, "libs"); File dirBin = new File(dirProj, "bin"); File dirDexedLibs = new File(dirBin, "dexedLibs"); dirDexedLibs.mkdirs(); System.out.println("// PRE-DEX LIBS"); for (String lib : proj_libs) { File jarLib = new File(dirLibs, lib); File dexLib = new File(dirDexedLibs, lib); if (!dexLib.exists()) { com.android.dx.command.dexer.Main.main(new String[] { "--verbose", "--output=" + dexLib.getPath(), jarLib.getPath() }); } } // DEBUG Util.listRecursive(dirBin); } catch (Exception e) { e.printStackTrace(); } return null; } } private class DexMerge extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnDex = (Button) findViewById(R.id.btnDex); btnDex.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirBin = new File(dirProj, "bin"); File dirClasses = new File(dirBin, "classes"); File dirDexedLibs = new File(dirBin, "dexedLibs"); File dexClasses = new File(dirBin, "classes.dex"); System.out.println("// DEX CLASSES"); com.android.dx.command.dexer.Main.main(new String[] { "--verbose", "--output=" + dexClasses.getPath(), dirClasses.getPath() }); System.out.println("// MERGE DEXED LIBS"); for (String lib : proj_libs) { File dexLib = new File(dirDexedLibs, lib); Dex merged = new DexMerger(new Dex(dexClasses), new Dex( dexLib), CollisionPolicy.FAIL).merge(); merged.writeTo(dexClasses); } // DEBUG Util.listRecursive(dirBin); } catch (Exception e) { e.printStackTrace(); } return null; } } private class BuildApk extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnApk = (Button) findViewById(R.id.btnApk); btnApk.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirAssets = new File(dirProj, "assets"); File dirSrc = new File(dirProj, "src"); File dirRes = new File(dirProj, "res"); File dirLibs = new File(dirProj, "libs"); File dirBin = new File(dirProj, "bin"); File dirDexedLibs = new File(dirBin, "dexedLibs"); File dirDist = new File(dirProj, "dist"); File apkUnsigned = new File(dirDist, proj_name + ".unsigned.apk"); File ap_Resources = new File(dirBin, "resources.ap_"); File dexClasses = new File(dirBin, "classes.dex"); File xmlMan = new File(dirProj, "AndroidManifest.xml"); File zipSrc = new File(dirAssets, "src.zip"); File zipRes = new File(dirAssets, "res.zip"); File zipLibs = new File(dirAssets, "libs.zip"); File zipDexedLibs = new File(dirAssets, "dexedLibs.zip"); dirDist.mkdirs(); // Do NOT use embedded JarSigner PrivateKey privateKey = null; X509Certificate x509Cert = null; System.out.println("// RUN APK BUILDER"); ApkBuilder apkbuilder = new ApkBuilder(apkUnsigned, ap_Resources, dexClasses, privateKey, x509Cert, System.out); System.out.println("// ADD NATIVE LIBS"); apkbuilder.addNativeLibraries(dirLibs); System.out.println("// ADD LIB RESOURCES"); for (String lib : proj_libs) { File jarLib = new File(dirLibs, lib); apkbuilder.addResourcesFromJar(jarLib); } System.out.println("// ZIP & ADD ASSETS"); // android.jar already packed by aapt String strAssets = "assets" + File.separator; apkbuilder.addFile(xmlMan, strAssets + xmlMan.getName()); Util.zip(dirSrc, zipSrc); apkbuilder.addFile(zipSrc, strAssets + zipSrc.getName()); Util.zip(dirRes, zipRes); apkbuilder.addFile(zipRes, strAssets + zipRes.getName()); Util.zip(dirLibs, zipLibs); apkbuilder.addFile(zipLibs, strAssets + zipLibs.getName()); Util.zip(dirDexedLibs, zipDexedLibs); apkbuilder.addFile(zipDexedLibs, strAssets + zipDexedLibs.getName()); apkbuilder.setDebugMode(true); apkbuilder.sealApk(); // DEBUG Util.listRecursive(dirDist); } catch (Exception e) { e.printStackTrace(); } return null; } } private class SignApk extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnSign = (Button) findViewById(R.id.btnSign); btnSign.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirDist = new File(dirProj, "dist"); File apkUnsigned = new File(dirDist, proj_name + ".unsigned.apk"); File apkSigned = new File(dirDist, proj_name + ".unaligned.apk"); System.out.println("// RUN ZIP SIGNER"); kellinwood.security.zipsigner.ZipSigner zipsigner = new kellinwood.security.zipsigner.ZipSigner(); zipsigner.setKeymode("testkey"); // TODO zipsigner.signZip(apkUnsigned.getPath(), apkSigned.getPath()); // DEBUG Util.listRecursive(dirDist); } catch (Exception e) { e.printStackTrace(); } return null; } } private class AlignApk extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnAlign = (Button) findViewById(R.id.btnAlign); btnAlign.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirDist = new File(dirProj, "dist"); System.out.println("// RUN ZIP ALIGN"); // TODO // DEBUG Util.listRecursive(dirDist); } catch (Exception e) { e.printStackTrace(); } return null; } } private class InstallApk extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnInstall = (Button) findViewById(R.id.btnInstall); btnInstall.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, proj_name); File dirDist = new File(dirProj, "dist"); File apkSigned = new File(dirDist, proj_name + ".unaligned.apk"); System.out.println("// INSTALL APK"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(apkSigned), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } return null; } } }
package openblocks.common.entity; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.ai.EntityAIFollowOwner; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import openblocks.OpenBlocks; import openblocks.common.GenericInventory; import openblocks.common.entity.ai.EntityAICollectItem; import openblocks.utils.BlockUtils; public class EntityLuggage extends EntityTameable implements IEntityAdditionalSpawnData { protected GenericInventory inventory = new GenericInventory("luggage", false, 27); private boolean special; public int lastSound = 0; public EntityLuggage(World world) { super(world); this.texture = OpenBlocks.getTexturesPath("models/luggage.png"); this.setSize(0.5F, 0.5F); this.moveSpeed = 0.4F; setTamed(true); this.getNavigator().setAvoidsWater(true); this.getNavigator().setCanSwim(true); this.tasks.addTask(1, new EntityAISwimming(this)); this.tasks.addTask(2, new EntityAIFollowOwner(this, this.moveSpeed, 10.0F, 2.0F)); this.tasks.addTask(3, new EntityAICollectItem(this)); this.dataWatcher.addObject(18, Integer.valueOf(inventory.getSizeInventory())); // inventory size } protected void setSpecial() { if(special) return; special = true; GenericInventory inventory = new GenericInventory("luggage", false, 54); inventory.copyFrom(this.inventory); if (this.dataWatcher != null) { this.dataWatcher.updateObject(18, Integer.valueOf(inventory.getSizeInventory())); } this.inventory = inventory; } public boolean isSpecial() { return special; } public void onLivingUpdate() { super.onLivingUpdate(); if (worldObj.isRemote) { int inventorySize = dataWatcher.getWatchableObjectInt(18); if (inventory.getSizeInventory() != inventorySize) { inventory = new GenericInventory("luggage", false, inventorySize); } this.texture = OpenBlocks.getTexturesPath(inventorySize == 27 ? "models/luggage.png" : "models/luggage_special.png"); } lastSound++; } public boolean isAIEnabled() { return true; } @Override public int getMaxHealth() { return 100; } public GenericInventory getInventory() { return inventory; } @Override public EntityAgeable createChild(EntityAgeable entityageable) { return null; } @Override public boolean interact(EntityPlayer player) { if (!worldObj.isRemote) { if (player.isSneaking()) { ItemStack luggageItem = new ItemStack(OpenBlocks.Items.luggage); NBTTagCompound tag = new NBTTagCompound(); inventory.writeToNBT(tag); luggageItem.setTagCompound(tag); BlockUtils.dropItemStackInWorld(worldObj, posX, posY, posZ, luggageItem); setDead(); } else { player.openGui(OpenBlocks.instance, OpenBlocks.Gui.Luggage.ordinal(), player.worldObj, entityId, 0, 0); } } return true; } public boolean canConsumeStackPartially(ItemStack stack) { return BlockUtils.testInventoryInsertion(inventory, stack) > 0; } protected void playStepSound(int par1, int par2, int par3, int par4) { this.playSound("openblocks.feet", 0.3F, 0.7F + (worldObj.rand.nextFloat() * 0.5f)); } @Override public void writeEntityToNBT(NBTTagCompound tag) { super.writeEntityToNBT(tag); tag.setBoolean("shiny", special); inventory.writeToNBT(tag); } @Override public void readEntityFromNBT(NBTTagCompound tag) { super.readEntityFromNBT(tag); if(tag.hasKey("shiny") && tag.getBoolean("shiny")) setSpecial(); inventory.readFromNBT(tag); } @Override public void onStruckByLightning(EntityLightningBolt lightning) { setSpecial(); } @Override public boolean isEntityInvulnerable() { return true; } @Override public void writeSpawnData(ByteArrayDataOutput data) { data.writeInt(inventory.getSizeInventory()); } @Override public void readSpawnData(ByteArrayDataInput data) { inventory = new GenericInventory("luggage", false, data.readInt()); } }
package org.apache.xerces.readers; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.xml.sax.Locator; import org.xml.sax.InputSource; import java.io.IOException; /** * Reader for processing internal entity replacement text. * <p> * This reader processes data contained within strings kept * in the string pool. It provides the support for both * general and parameter entities. The location support * as we are processing the replacement text is somewhat * poor and needs to be updated when "nested locations" * have been implemented. * <p> * For efficiency, we return instances of this class to a * free list and reuse those instances to process other * strings. * * @version $id$ */ final class StringReader extends XMLEntityReader { /** * Allocate a string reader * * @param entityHandler The current entity handler. * @param errorReporter The current error reporter. * @param sendCharDataAsCharArray true if char data should be reported using * char arrays instead of string handles. * @param lineNumber The line number to return as our position. * @param columnNumber The column number to return as our position. * @param stringHandle The StringPool handle for the data to process. * @param stringPool The string pool. * @param addEnclosingSpaces If true, treat the data to process as if * there were a leading and trailing space * character enclosing the string data. * @return The reader that will process the string data. */ public static StringReader createStringReader(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, int lineNumber, int columnNumber, int stringHandle, StringPool stringPool, boolean addEnclosingSpaces) { StringReader reader = null; synchronized (StringReader.class) { reader = fgFreeReaders; if (reader == null) { return new StringReader(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber, stringHandle, stringPool, addEnclosingSpaces); } fgFreeReaders = reader.fNextFreeReader; } reader.init(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber, stringHandle, stringPool, addEnclosingSpaces); return reader; } private StringReader(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, int lineNumber, int columnNumber, int stringHandle, StringPool stringPool, boolean addEnclosingSpaces) { super(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber); fStringPool = stringPool; fData = fStringPool.toString(stringHandle); fCurrentOffset = 0; fEndOffset = fData.length(); if (addEnclosingSpaces) { fMostRecentChar = ' '; fCurrentOffset oweTrailingSpace = hadTrailingSpace = true; } else { fMostRecentChar = fEndOffset == 0 ? -1 : fData.charAt(0); } } private void init(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, int lineNumber, int columnNumber, int stringHandle, StringPool stringPool, boolean addEnclosingSpaces) { super.init(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber); fStringPool = stringPool; fData = fStringPool.toString(stringHandle); fCurrentOffset = 0; fEndOffset = fData.length(); fNextFreeReader = null; if (addEnclosingSpaces) { fMostRecentChar = ' '; fCurrentOffset oweTrailingSpace = hadTrailingSpace = true; } else { fMostRecentChar = fEndOffset == 0 ? -1 : fData.charAt(0); oweTrailingSpace = hadTrailingSpace = false; } } public int addString(int offset, int length) { if (length == 0) return 0; return fStringPool.addString(fData.substring(offset, offset + length)); } public int addSymbol(int offset, int length) { if (length == 0) return 0; return fStringPool.addSymbol(fData.substring(offset, offset + length)); } public void append(XMLEntityHandler.CharBuffer charBuffer, int offset, int length) { boolean addSpace = false; for (int i = 0; i < length; i++) { try { charBuffer.append(fData.charAt(offset++)); } catch (StringIndexOutOfBoundsException ex) { if (offset == fEndOffset + 1 && hadTrailingSpace) { charBuffer.append(' '); } else { System.err.println("StringReader.append()"); throw ex; } } } } private int loadNextChar() { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } return fMostRecentChar; } public XMLEntityHandler.EntityReader changeReaders() throws Exception { XMLEntityHandler.EntityReader nextReader = super.changeReaders(); synchronized (StringReader.class) { fNextFreeReader = fgFreeReaders; fgFreeReaders = this; } return nextReader; } public boolean lookingAtChar(char chr, boolean skipPastChar) throws Exception { int ch = fMostRecentChar; if (ch != chr) { if (ch == -1) { return changeReaders().lookingAtChar(chr, skipPastChar); } return false; } if (skipPastChar) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } } return true; } public boolean lookingAtValidChar(boolean skipPastChar) throws Exception { int ch = fMostRecentChar; if (ch < 0xD800) { if (ch < 0x20 && ch != 0x09 && ch != 0x0A && ch != 0x0D) { if (ch == -1) return changeReaders().lookingAtValidChar(skipPastChar); return false; } if (skipPastChar) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } } return true; } if (ch > 0xFFFD) { return false; } if (ch < 0xDC00) { if (fCurrentOffset + 1 >= fEndOffset) { return false; } ch = fData.charAt(fCurrentOffset + 1); if (ch < 0xDC00 || ch >= 0xE000) { return false; } else if (!skipPastChar) { return true; } else { fCurrentOffset++; } } else if (ch < 0xE000) { return false; } if (skipPastChar) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } } return true; } public boolean lookingAtSpace(boolean skipPastChar) throws Exception { int ch = fMostRecentChar; if (ch > 0x20) return false; if (ch == 0x20 || ch == 0x0A || ch == 0x0D || ch == 0x09) { if (skipPastChar) { loadNextChar(); } return true; } if (ch == -1) { return changeReaders().lookingAtSpace(skipPastChar); } return false; } public void skipToChar(char chr) throws Exception { // REVISIT - this will skip invalid characters without reporting them. int ch = fMostRecentChar; while (true) { if (ch == chr) return; if (ch == -1) { changeReaders().skipToChar(chr); return; } ch = loadNextChar(); } } public void skipPastSpaces() throws Exception { int ch = fMostRecentChar; if (ch == -1) { changeReaders().skipPastSpaces(); return; } while (true) { if (ch > 0x20 || (ch != 0x20 && ch != 0x0A && ch != 0x09 && ch != 0x0D)) { fMostRecentChar = ch; return; } if (++fCurrentOffset >= fEndOffset) { changeReaders().skipPastSpaces(); return; } ch = fData.charAt(fCurrentOffset); } } public void skipPastName(char fastcheck) throws Exception { int ch = fMostRecentChar; if (ch < 0x80) { if (ch == -1 || XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) return; } while (true) { ch = loadNextChar(); if (fastcheck == ch) return; if (ch < 0x80) { if (ch == -1 || XMLCharacterProperties.fgAsciiNameChar[ch] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) return; } } } public void skipPastNmtoken(char fastcheck) throws Exception { int ch = fMostRecentChar; while (true) { if (fastcheck == ch) return; if (ch < 0x80) { if (ch == -1 || XMLCharacterProperties.fgAsciiNameChar[ch] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) return; } ch = loadNextChar(); } } public boolean skippedString(char[] s) throws Exception { int ch = fMostRecentChar; if (ch != s[0]) { if (ch == -1) return changeReaders().skippedString(s); return false; } if (fCurrentOffset + s.length > fEndOffset) return false; for (int i = 1; i < s.length; i++) { if (fData.charAt(fCurrentOffset + i) != s[i]) return false; } fCurrentOffset += (s.length - 1); loadNextChar(); return true; } public int scanInvalidChar() throws Exception { int ch = fMostRecentChar; if (ch == -1) return changeReaders().scanInvalidChar(); loadNextChar(); return ch; } public int scanCharRef(boolean hex) throws Exception { int ch = fMostRecentChar; if (ch == -1) return changeReaders().scanCharRef(hex); int num = 0; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); } else { if (ch < '0' || ch > '9') return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - '0'; } boolean toobig = false; while (true) { ch = loadNextChar(); if (ch == -1) return XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) break; } else { if (ch < '0' || ch > '9') break; } if (hex) { int dig = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); num = (num << 4) + dig; } else { int dig = ch - '0'; num = (num * 10) + dig; } if (num > 0x10FFFF) { toobig = true; num = 0; } } if (ch != ';') return XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED; loadNextChar(); if (toobig) return XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE; return num; } public int scanStringLiteral() throws Exception { boolean single; if (!(single = lookingAtChar('\'', true)) && !lookingAtChar('\"', true)) { return XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED; } int offset = fCurrentOffset; char qchar = single ? '\'' : '\"'; while (!lookingAtChar(qchar, false)) { if (!lookingAtValidChar(true)) { return XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR; } } int stringIndex = addString(offset, fCurrentOffset - offset); lookingAtChar(qchar, true); // move past qchar return stringIndex; } // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' // | "'" ([^<&'] | Reference)* "'" public int scanAttValue(char qchar, boolean asSymbol) throws Exception { int offset = fCurrentOffset; while (true) { if (lookingAtChar(qchar, false)) { break; } if (lookingAtChar(' ', true)) { continue; } if (lookingAtSpace(false)) { return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX; } if (lookingAtChar('&', false)) { return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX; } if (lookingAtChar('<', false)) { return XMLEntityHandler.ATTVALUE_RESULT_LESSTHAN; } if (!lookingAtValidChar(true)) { return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR; } } int result = asSymbol ? addSymbol(offset, fCurrentOffset - offset) : addString(offset, fCurrentOffset - offset); lookingAtChar(qchar, true); return result; } // [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' // | "'" ([^%&'] | PEReference | Reference)* "'" // The values in the following table are defined as: // 0 - not special // 1 - quote character // 2 - reference // 3 - peref // 4 - invalid public static final byte fgAsciiEntityValueChar[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 0, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int scanEntityValue(int qchar, boolean createString) throws Exception { int offset = fCurrentOffset; int ch = fMostRecentChar; while (true) { if (ch == -1) { changeReaders(); // do not call next reader, our caller may need to change the parameters return XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT; } if (ch < 0x80) { switch (fgAsciiEntityValueChar[ch]) { case 1: // quote char if (ch == qchar) { if (!createString) return XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED; int length = fCurrentOffset - offset; int result = length == 0 ? StringPool.EMPTY_STRING : addString(offset, length); loadNextChar(); return result; } // the other quote character is not special // fall through case 0: // non-special char if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; ch = fMostRecentChar = ' '; } else { ch = fMostRecentChar = -1; } } else { ch = fMostRecentChar = fData.charAt(fCurrentOffset); } continue; case 2: // reference return XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE; case 3: // peref return XMLEntityHandler.ENTITYVALUE_RESULT_PEREF; case 4: // invalid return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; } } else if (ch < 0xD800) { ch = loadNextChar(); } else if (ch >= 0xE000 && (ch <= 0xFFFD || (ch >= 0x10000 && ch <= 0x10FFFF))) { // REVISIT - needs more code to check surrogates. ch = loadNextChar(); } else { return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; } } } public boolean scanExpectedName(char fastcheck, StringPool.CharArrayRange expectedName) throws Exception { int ch = fMostRecentChar; if (ch == -1) { return changeReaders().scanExpectedName(fastcheck, expectedName); } if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int nameOffset = fCurrentOffset; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) return false; while (true) { ch = loadNextChar(); if (fastcheck == ch) break; if (ch == -1) break; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } int nameIndex = fStringPool.addSymbol(fData.substring(nameOffset, fCurrentOffset)); // DEFECT !! check name against expected name return true; } public void scanQName(char fastcheck, QName qname) throws Exception { int ch = fMostRecentChar; if (ch == -1) { changeReaders().scanQName(fastcheck, qname); return; } if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int nameOffset = fCurrentOffset; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { qname.clear(); return; } while (true) { ch = loadNextChar(); if (fastcheck == ch) break; if (ch == -1) break; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } qname.clear(); qname.rawname = fStringPool.addSymbol(fData.substring(nameOffset, fCurrentOffset)); int index = fData.indexOf(':', nameOffset); if (index != -1 && index < fCurrentOffset) { qname.prefix = fStringPool.addSymbol(fData.substring(nameOffset, index)); int indexOfSpaceChar = fData.indexOf( ' ', index + 1 );//one past : look for blank String localPart; if( indexOfSpaceChar != -1 ){//found one localPart = fData.substring(index+1, indexOfSpaceChar ); qname.localpart = fStringPool.addSymbol(localPart); } else{//then get up to end of String int lenfData = fData.length(); localPart = fData.substring( index + 1, lenfData ); qname.localpart = fStringPool.addSymbol(localPart); } qname.localpart = fStringPool.addSymbol(localPart); } else { qname.localpart = qname.rawname; } } // scanQName(char,QName) public int scanName(char fastcheck) throws Exception { int ch = fMostRecentChar; if (ch == -1) { return changeReaders().scanName(fastcheck); } if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int nameOffset = fCurrentOffset; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) return -1; while (true) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } break; } ch = fMostRecentChar = fData.charAt(fCurrentOffset); if (fastcheck == ch) break; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } int nameIndex = fStringPool.addSymbol(fData.substring(nameOffset, fCurrentOffset)); return nameIndex; } // There are no leading/trailing space checks here because scanContent cannot // be called on a parameter entity reference value. private int recognizeMarkup(int ch) throws Exception { if (ch == -1) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } switch (ch) { case '?': loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_PI; case '!': ch = loadNextChar(); if (ch == -1) { fCurrentOffset -= 2; loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (ch == '-') { ch = loadNextChar(); if (ch == -1) { fCurrentOffset -= 3; loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (ch == '-') { loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_COMMENT; } break; } if (ch == '[') { for (int i = 0; i < 6; i++) { ch = loadNextChar(); if (ch == -1) { fCurrentOffset -= (3 + i); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (ch != cdata_string[i]) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } } loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CDSECT; } break; case '/': loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_ETAG; default: return XMLEntityHandler.CONTENT_RESULT_START_OF_ELEMENT; } return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } private int recognizeReference(int ch) throws Exception { if (ch == -1) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } // [67] Reference ::= EntityRef | CharRef // [68] EntityRef ::= '&' Name ';' // [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' if (ch == ' loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CHARREF; } else { return XMLEntityHandler.CONTENT_RESULT_START_OF_ENTITYREF; } } public int scanContent(QName element) throws Exception { int ch = fMostRecentChar; if (ch == -1) { return changeReaders().scanContent(element); } int offset = fCurrentOffset; if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiWSCharData[ch]) { case 0: ch = loadNextChar(); break; case 1: ch = loadNextChar(); if (!fInCDSect) { return recognizeMarkup(ch); } break; case 2: ch = loadNextChar(); if (!fInCDSect) { return recognizeReference(ch); } break; case 3: ch = loadNextChar(); if (ch == ']' && fCurrentOffset + 1 < fEndOffset && fData.charAt(fCurrentOffset + 1) == '>') { loadNextChar(); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; } break; case 4: return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; case 5: do { ch = loadNextChar(); if (ch == -1) { callCharDataHandler(offset, fEndOffset, true); return changeReaders().scanContent(element); } } while (ch == 0x20 || ch == 0x0A || ch == 0x0D || ch == 0x09); if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: ch = loadNextChar(); break; case 1: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, true); return recognizeMarkup(ch); } break; case 2: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, true); return recognizeReference(ch); } break; case 3: ch = loadNextChar(); if (ch == ']' && fCurrentOffset + 1 < fEndOffset && fData.charAt(fCurrentOffset + 1) == '>') { callCharDataHandler(offset, fCurrentOffset - 1, true); loadNextChar(); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; } break; case 4: callCharDataHandler(offset, fCurrentOffset, true); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (ch == 0xFFFE || ch == 0xFFFF) { callCharDataHandler(offset, fCurrentOffset, true); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = loadNextChar(); } } } else { if (ch == 0xFFFE || ch == 0xFFFF) { callCharDataHandler(offset, fCurrentOffset, false); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = loadNextChar(); } while (true) { if (ch == -1) { callCharDataHandler(offset, fEndOffset, false); return changeReaders().scanContent(element); } if (ch >= 0x80) break; if (XMLCharacterProperties.fgAsciiCharData[ch] != 0) break; ch = loadNextChar(); } while (true) { // REVISIT - EOF check ? if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: ch = loadNextChar(); break; case 1: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, false); return recognizeMarkup(ch); } break; case 2: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, false); return recognizeReference(ch); } break; case 3: ch = loadNextChar(); if (ch == ']' && fCurrentOffset + 1 < fEndOffset && fData.charAt(fCurrentOffset + 1) == '>') { callCharDataHandler(offset, fCurrentOffset - 1, false); loadNextChar(); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; } break; case 4: callCharDataHandler(offset, fCurrentOffset, false); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (ch == 0xFFFE || ch == 0xFFFF) { callCharDataHandler(offset, fCurrentOffset, false); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = loadNextChar(); } if (ch == -1) { callCharDataHandler(offset, fCurrentOffset, false); return changeReaders().scanContent(element); } } } private void callCharDataHandler(int offset, int endOffset, boolean isWhitespace) throws Exception { int length = endOffset - offset; if (!fSendCharDataAsCharArray) { int stringIndex = addString(offset, length); if (isWhitespace) fCharDataHandler.processWhitespace(stringIndex); else fCharDataHandler.processCharacters(stringIndex); return; } if (isWhitespace) fCharDataHandler.processWhitespace(fData.toCharArray(), offset, length); else fCharDataHandler.processCharacters(fData.toCharArray(), offset, length); } private static final char[] cdata_string = { 'C','D','A','T','A','[' }; private StringPool fStringPool = null; private String fData = null; private int fEndOffset; private boolean hadTrailingSpace = false; private boolean oweTrailingSpace = false; private int fMostRecentChar; private StringReader fNextFreeReader = null; private static StringReader fgFreeReaders = null; private boolean fCalledCharPropInit = false; }
// Sep 14, 2000: // Fixed problem with namespace handling. Contributed by // David Blondeau <blondeau@intalio.com> // Sep 14, 2000: // Fixed serializer to report IO exception directly, instead at // the end of document processing. // Reported by Patrick Higgins <phiggins@transzap.com> // Aug 21, 2000: // Fixed bug in startDocument not calling prepare. // Reported by Mikael Staldal <d96-mst-ingen-reklam@d.kth.se> // Aug 21, 2000: // Added ability to omit DOCTYPE declaration. package org.apache.xml.serialize; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.OutputStream; import java.io.Writer; import java.util.Enumeration; import org.w3c.dom.*; import org.xml.sax.DocumentHandler; import org.xml.sax.ContentHandler; import org.xml.sax.AttributeList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.util.NamespaceSupport; import org.apache.xerces.util.XMLChar; import org.apache.xerces.dom.DOMMessageFormatter; /** * Implements an XML serializer supporting both DOM and SAX pretty * serializing. For usage instructions see {@link Serializer}. * <p> * If an output stream is used, the encoding is taken from the * output format (defaults to <tt>UTF-8</tt>). If a writer is * used, make sure the writer uses the same encoding (if applies) * as specified in the output format. * <p> * The serializer supports both DOM and SAX. SAX serializing is done by firing * SAX events and using the serializer as a document handler. DOM serializing is done * by calling {@link #serialize(Document)} or by using DOM Level 3 * {@link org.w3c.dom.ls.DOMWriter} and * serializing with {@link org.w3c.dom.ls.DOMWriter#writeNode}, * {@link org.w3c.dom.ls.DOMWriter#writeToString}. * <p> * If an I/O exception occurs while serializing, the serializer * will not throw an exception directly, but only throw it * at the end of serializing (either DOM or SAX's {@link * org.xml.sax.DocumentHandler#endDocument}. * <p> * For elements that are not specified as whitespace preserving, * the serializer will potentially break long text lines at space * boundaries, indent lines, and serialize elements on separate * lines. Line terminators will be regarded as spaces, and * spaces at beginning of line will be stripped. * @author <a href="mailto:arkin@intalio.com">Assaf Arkin</a> * @author <a href="mailto:rahul.srivastava@sun.com">Rahul Srivastava</a> * @author Elena Litani IBM * @version $Revision$ $Date$ * @see Serializer */ public class XMLSerializer extends BaseMarkupSerializer { // constants protected static final boolean DEBUG = false; // data // DOM Level 3 implementation: variables intialized in DOMWriterImpl /** stores namespaces in scope */ protected NamespaceSupport fNSBinder; /** stores all namespace bindings on the current element */ protected NamespaceSupport fLocalNSBinder; /** symbol table for serialization */ protected SymbolTable fSymbolTable; // is node dom level 1 node? protected boolean fDOML1 = false; // counter for new prefix names protected int fNamespaceCounter = 1; protected final static String PREFIX = "NS"; /** * Controls whether namespace fixup should be performed during * the serialization. * NOTE: if this field is set to true the following * fields need to be initialized: fNSBinder, fLocalNSBinder, fSymbolTable, * XMLSymbols.EMPTY_STRING, fXmlSymbol, fXmlnsSymbol, fNamespaceCounter. */ protected boolean fNamespaces = false; private boolean fPreserveSpace; /** * Constructs a new serializer. The serializer cannot be used without * calling {@link #setOutputCharStream} or {@link #setOutputByteStream} * first. */ public XMLSerializer() { super( new OutputFormat( Method.XML, null, false ) ); } /** * Constructs a new serializer. The serializer cannot be used without * calling {@link #setOutputCharStream} or {@link #setOutputByteStream} * first. */ public XMLSerializer( OutputFormat format ) { super( format != null ? format : new OutputFormat( Method.XML, null, false ) ); _format.setMethod( Method.XML ); } /** * Constructs a new serializer that writes to the specified writer * using the specified output format. If <tt>format</tt> is null, * will use a default output format. * * @param writer The writer to use * @param format The output format to use, null for the default */ public XMLSerializer( Writer writer, OutputFormat format ) { super( format != null ? format : new OutputFormat( Method.XML, null, false ) ); _format.setMethod( Method.XML ); setOutputCharStream( writer ); } /** * Constructs a new serializer that writes to the specified output * stream using the specified output format. If <tt>format</tt> * is null, will use a default output format. * * @param output The output stream to use * @param format The output format to use, null for the default */ public XMLSerializer( OutputStream output, OutputFormat format ) { super( format != null ? format : new OutputFormat( Method.XML, null, false ) ); _format.setMethod( Method.XML ); setOutputByteStream( output ); } public void setOutputFormat( OutputFormat format ) { super.setOutputFormat( format != null ? format : new OutputFormat( Method.XML, null, false ) ); } /** * This methods turns on namespace fixup algorithm during * DOM serialization. * @deprecated -- functionality could be removed * @see org.w3c.dom.ls.DOMWriter * * @param namespaces */ public void setNamespaces (boolean namespaces){ fNamespaces = namespaces; } // SAX content handler serializing methods // public void startElement( String namespaceURI, String localName, String rawName, Attributes attrs ) throws SAXException { int i; boolean preserveSpace; ElementState state; String name; String value; boolean addNSAttr = false; if (DEBUG) { System.out.println("==>startElement("+namespaceURI+","+localName+ ","+rawName+")"); } try { if (_printer == null) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.SERIALIZER_DOMAIN, "NoWriterSupplied", null); throw new IllegalStateException(msg); } state = getElementState(); if (isDocumentState()) { // If this is the root element handle it differently. // If the first root element in the document, serialize // the document's DOCTYPE. Space preserving defaults // to that of the output format. if (! _started) startDocument( ( localName == null || localName.length() == 0 ) ? rawName : localName ); } else { // For any other element, if first in parent, then // close parent's opening tag and use the parnet's // space preserving. if (state.empty) _printer.printText( '>' ); // Must leave CData section first if (state.inCData) { _printer.printText( "]]>" ); state.inCData = false; } // Indent this element on a new line if the first // content of the parent element or immediately // following an element or a comment if (_indenting && ! state.preserveSpace && ( state.empty || state.afterElement || state.afterComment)) _printer.breakLine(); } preserveSpace = state.preserveSpace; //We remove the namespaces from the attributes list so that they will //be in _prefixes attrs = extractNamespaces(attrs); // Do not change the current element state yet. // This only happens in endElement(). if (rawName == null || rawName.length() == 0) { if (localName == null) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.SERIALIZER_DOMAIN, "NoName", null); throw new SAXException(msg); } if (namespaceURI != null && ! namespaceURI.equals( "" )) { String prefix; prefix = getPrefix( namespaceURI ); if (prefix != null && prefix.length() > 0) rawName = prefix + ":" + localName; else rawName = localName; } else rawName = localName; addNSAttr = true; } _printer.printText( '<' ); _printer.printText( rawName ); _printer.indent(); // For each attribute print it's name and value as one part, // separated with a space so the element can be broken on // multiple lines. if (attrs != null) { for (i = 0 ; i < attrs.getLength() ; ++i) { _printer.printSpace(); name = attrs.getQName( i ); if (name != null && name.length() == 0) { String prefix; String attrURI; name = attrs.getLocalName( i ); attrURI = attrs.getURI( i ); if (( attrURI != null && attrURI.length() != 0 ) && ( namespaceURI == null || namespaceURI.length() == 0 || ! attrURI.equals( namespaceURI ) )) { prefix = getPrefix( attrURI ); if (prefix != null && prefix.length() > 0) name = prefix + ":" + name; } } value = attrs.getValue( i ); if (value == null) value = ""; _printer.printText( name ); _printer.printText( "=\"" ); printEscaped( value ); _printer.printText( '"' ); // If the attribute xml:space exists, determine whether // to preserve spaces in this and child nodes based on // its value. if (name.equals( "xml:space" )) { if (value.equals( "preserve" )) preserveSpace = true; else preserveSpace = _format.getPreserveSpace(); } } } if (_prefixes != null) { Enumeration enum; enum = _prefixes.keys(); while (enum.hasMoreElements()) { _printer.printSpace(); value = (String) enum.nextElement(); name = (String) _prefixes.get( value ); if (name.length() == 0) { _printer.printText( "xmlns=\"" ); printEscaped( value ); _printer.printText( '"' ); } else { _printer.printText( "xmlns:" ); _printer.printText( name ); _printer.printText( "=\"" ); printEscaped( value ); _printer.printText( '"' ); } } } // Now it's time to enter a new element state // with the tag name and space preserving. // We still do not change the curent element state. state = enterElementState( namespaceURI, localName, rawName, preserveSpace ); name = ( localName == null || localName.length() == 0 ) ? rawName : namespaceURI + "^" + localName; state.doCData = _format.isCDataElement( name ); state.unescaped = _format.isNonEscapingElement( name ); } catch (IOException except) { throw new SAXException( except ); } } public void endElement( String namespaceURI, String localName, String rawName ) throws SAXException { try { endElementIO( namespaceURI, localName, rawName ); } catch (IOException except) { throw new SAXException( except ); } } public void endElementIO( String namespaceURI, String localName, String rawName ) throws IOException { ElementState state; if (DEBUG) { System.out.println("==>endElement: " +rawName); } // Works much like content() with additions for closing // an element. Note the different checks for the closed // element's state and the parent element's state. _printer.unindent(); state = getElementState(); if (state.empty) { _printer.printText( "/>" ); } else { // Must leave CData section first if (state.inCData) _printer.printText( "]]>" ); // This element is not empty and that last content was // another element, so print a line break before that // last element and this element's closing tag. if (_indenting && ! state.preserveSpace && (state.afterElement || state.afterComment)) _printer.breakLine(); _printer.printText( "</" ); _printer.printText( state.rawName ); _printer.printText( '>' ); } // Leave the element state and update that of the parent // (if we're not root) to not empty and after element. state = leaveElementState(); state.afterElement = true; state.afterComment = false; state.empty = false; if (isDocumentState()) _printer.flush(); } // SAX document handler serializing methods // public void startElement( String tagName, AttributeList attrs ) throws SAXException { int i; boolean preserveSpace; ElementState state; String name; String value; if (DEBUG) { System.out.println("==>startElement("+tagName+")"); } try { if (_printer == null) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.SERIALIZER_DOMAIN, "NoWriterSupplied", null); throw new IllegalStateException(msg); } state = getElementState(); if (isDocumentState()) { // If this is the root element handle it differently. // If the first root element in the document, serialize // the document's DOCTYPE. Space preserving defaults // to that of the output format. if (! _started) startDocument( tagName ); } else { // For any other element, if first in parent, then // close parent's opening tag and use the parnet's // space preserving. if (state.empty) _printer.printText( '>' ); // Must leave CData section first if (state.inCData) { _printer.printText( "]]>" ); state.inCData = false; } // Indent this element on a new line if the first // content of the parent element or immediately // following an element. if (_indenting && ! state.preserveSpace && ( state.empty || state.afterElement || state.afterComment)) _printer.breakLine(); } preserveSpace = state.preserveSpace; // Do not change the current element state yet. // This only happens in endElement(). _printer.printText( '<' ); _printer.printText( tagName ); _printer.indent(); // For each attribute print it's name and value as one part, // separated with a space so the element can be broken on // multiple lines. if (attrs != null) { for (i = 0 ; i < attrs.getLength() ; ++i) { _printer.printSpace(); name = attrs.getName( i ); value = attrs.getValue( i ); if (value != null) { _printer.printText( name ); _printer.printText( "=\"" ); printEscaped( value ); _printer.printText( '"' ); } // If the attribute xml:space exists, determine whether // to preserve spaces in this and child nodes based on // its value. if (name.equals( "xml:space" )) { if (value.equals( "preserve" )) preserveSpace = true; else preserveSpace = _format.getPreserveSpace(); } } } // Now it's time to enter a new element state // with the tag name and space preserving. // We still do not change the curent element state. state = enterElementState( null, null, tagName, preserveSpace ); state.doCData = _format.isCDataElement( tagName ); state.unescaped = _format.isNonEscapingElement( tagName ); } catch (IOException except) { throw new SAXException( except ); } } public void endElement( String tagName ) throws SAXException { endElement( null, null, tagName ); } // Generic node serializing methods methods // /** * Called to serialize the document's DOCTYPE by the root element. * The document type declaration must name the root element, * but the root element is only known when that element is serialized, * and not at the start of the document. * <p> * This method will check if it has not been called before ({@link #_started}), * will serialize the document type declaration, and will serialize all * pre-root comments and PIs that were accumulated in the document * (see {@link #serializePreRoot}). Pre-root will be serialized even if * this is not the first root element of the document. */ protected void startDocument( String rootTagName ) throws IOException { int i; String dtd; dtd = _printer.leaveDTD(); if (! _started) { if (! _format.getOmitXMLDeclaration()) { StringBuffer buffer; // Serialize the document declaration appreaing at the head // of very XML document (unless asked not to). buffer = new StringBuffer( "<?xml version=\"" ); if (_format.getVersion() != null) buffer.append( _format.getVersion() ); else buffer.append( "1.0" ); buffer.append( '"' ); String format_encoding = _format.getEncoding(); if (format_encoding != null) { buffer.append( " encoding=\"" ); buffer.append( format_encoding ); buffer.append( '"' ); } if (_format.getStandalone() && _docTypeSystemId == null && _docTypePublicId == null) buffer.append( " standalone=\"yes\"" ); buffer.append( "?>" ); _printer.printText( buffer ); _printer.breakLine(); } if (! _format.getOmitDocumentType()) { if (_docTypeSystemId != null) { // System identifier must be specified to print DOCTYPE. // If public identifier is specified print 'PUBLIC // <public> <system>', if not, print 'SYSTEM <system>'. _printer.printText( "<!DOCTYPE " ); _printer.printText( rootTagName ); if (_docTypePublicId != null) { _printer.printText( " PUBLIC " ); printDoctypeURL( _docTypePublicId ); if (_indenting) { _printer.breakLine(); for (i = 0 ; i < 18 + rootTagName.length() ; ++i) _printer.printText( " " ); } else _printer.printText( " " ); printDoctypeURL( _docTypeSystemId ); } else { _printer.printText( " SYSTEM " ); printDoctypeURL( _docTypeSystemId ); } // If we accumulated any DTD contents while printing. // this would be the place to print it. if (dtd != null && dtd.length() > 0) { _printer.printText( " [" ); printText( dtd, true, true ); _printer.printText( ']' ); } _printer.printText( ">" ); _printer.breakLine(); } else if (dtd != null && dtd.length() > 0) { _printer.printText( "<!DOCTYPE " ); _printer.printText( rootTagName ); _printer.printText( " [" ); printText( dtd, true, true ); _printer.printText( "]>" ); _printer.breakLine(); } } } _started = true; // Always serialize these, even if not te first root element. serializePreRoot(); } /** * Called to serialize a DOM element. Equivalent to calling {@link * #startElement}, {@link #endElement} and serializing everything * inbetween, but better optimized. */ protected void serializeElement( Element elem ) throws IOException { Attr attr; NamedNodeMap attrMap; int i; Node child; ElementState state; String name; String value; String tagName; String prefix, localUri; String uri; if (fNamespaces) { // reset local binder fLocalNSBinder.reset(); // note: the values that added to namespace binder // must be already be added to the symbol table fLocalNSBinder.pushContext(); // add new namespace context fNSBinder.pushContext(); } if (DEBUG) { System.out.println("==>startElement: " +elem.getNodeName() +" ns="+elem.getNamespaceURI()); } tagName = elem.getTagName(); state = getElementState(); if (isDocumentState()) { // If this is the root element handle it differently. // If the first root element in the document, serialize // the document's DOCTYPE. Space preserving defaults // to that of the output format. // check if document is DOM L1 document fDOML1 = (elem.getLocalName() == null)? true: false; if (! _started) { startDocument( tagName); } } else { // For any other element, if first in parent, then // close parent's opening tag and use the parent's // space preserving. if (state.empty) _printer.printText( '>' ); // Must leave CData section first if (state.inCData) { _printer.printText( "]]>" ); state.inCData = false; } // Indent this element on a new line if the first // content of the parent element or immediately // following an element. if (_indenting && ! state.preserveSpace && ( state.empty || state.afterElement || state.afterComment)) _printer.breakLine(); } // Do not change the current element state yet. // This only happens in endElement(). fPreserveSpace = state.preserveSpace; int length = 0; attrMap = null; // retrieve attributes if (elem.hasAttributes()) { attrMap = elem.getAttributes(); length = attrMap.getLength(); } if (!fNamespaces) { // no namespace fixup should be perform // serialize element name _printer.printText( '<' ); _printer.printText( tagName ); _printer.indent(); // For each attribute print it's name and value as one part, // separated with a space so the element can be broken on // multiple lines. for ( i = 0 ; i < length ; ++i ) { attr = (Attr) attrMap.item( i ); name = attr.getName(); value = attr.getValue(); if ( value == null ) value = ""; if ( attr.getSpecified()) { _printer.printSpace(); _printer.printText( name ); _printer.printText( "=\"" ); printEscaped( value ); _printer.printText( '"' ); } // If the attribute xml:space exists, determine whether // to preserve spaces in this and child nodes based on // its value. if ( name.equals( "xml:space" ) ) { if ( value.equals( "preserve" ) ) fPreserveSpace = true; else fPreserveSpace = _format.getPreserveSpace(); } } } else { // do namespace fixup // REVISIT: some optimization could probably be done to avoid traversing // attributes twice. // record all valid namespace declarations // before attempting to fix element's namespace for (i = 0;i < length;i++) { attr = (Attr) attrMap.item( i ); uri = attr.getNamespaceURI(); // check if attribute is a namespace decl if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) { value = attr.getNodeValue(); if (value == null) { value=XMLSymbols.EMPTY_STRING; } if (value.equals(NamespaceSupport.XMLNS_URI)) { if (fDOMErrorHandler != null) { modifyDOMError("No prefix other than 'xmlns' can be bound to 'http: DOMError.SEVERITY_ERROR, attr); boolean continueProcess = fDOMErrorHandler.handleError(fDOMError); if (!continueProcess) { // stop the namespace fixup and validation throw new RuntimeException("Stopped at user request"); } } } else { prefix = attr.getPrefix(); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); String localpart = fSymbolTable.addSymbol( attr.getLocalName()); if (prefix == XMLSymbols.PREFIX_XMLNS) { //xmlns:prefix value = fSymbolTable.addSymbol(value); // record valid decl if (value.length() != 0) { fNSBinder.declarePrefix(localpart, value); } else { // REVISIT: issue error on invalid declarations // xmlns:foo = "" } continue; } else { // xmlns // empty prefix is always bound ("" or some string) value = fSymbolTable.addSymbol(value); fNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value); continue; } } // end-else: valid declaration } // end-if: namespace declaration } // end-for // get element uri/prefix uri = elem.getNamespaceURI(); prefix = elem.getPrefix(); // output element name // REVISIT: this could be removed if we always convert empty string to null // for the namespaces. if ((uri !=null && prefix !=null ) && uri.length() == 0 && prefix.length()!=0) { // uri is an empty string and element has some prefix // the namespace alg later will fix up the namespace attributes // remove element prefix prefix = null; _printer.printText( '<' ); _printer.printText( elem.getLocalName() ); _printer.indent(); } else { _printer.printText( '<' ); _printer.printText( tagName ); _printer.indent(); } // Fix up namespaces for element: per DOM L3 // Need to consider the following cases: // case 1: <foo:elem xmlns:ns1="myURI" xmlns="default"/> // Assume "foo", "ns1" are declared on the parent. We should not miss // redeclaration for both "ns1" and default namespace. To solve this // we add a local binder that stores declaration only for current element. // This way we avoid outputing duplicate declarations for the same element // as well as we are not omitting redeclarations. // case 2: <elem xmlns="" xmlns="default"/> // We need to bind default namespace to empty string, to be able to // omit duplicate declarations for the same element // as well as namespace attribute rebounding xsl to another namespace. // Need to make sure that the new namespace decl value is changed to // check if prefix/namespace is correct for current element if (uri != null) { // Element has a namespace uri = fSymbolTable.addSymbol(uri); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); if (fNSBinder.getURI(prefix) == uri) { // The xmlns:prefix=namespace or xmlns="default" was declared at parent. // The binder always stores mapping of empty prefix to "". // (NOTE: local binder does not store this kind of binding!) // Thus the case where element was declared with uri="" (with or without a prefix) // will be covered here. } else { // the prefix is either undeclared // conflict: the prefix is bound to another URI printNamespaceAttr(prefix, uri); fLocalNSBinder.declarePrefix(prefix, uri); //fNSBinder.declarePrefix(prefix, uri); } } else { // Element has no namespace int colon = tagName.indexOf(':'); if (colon > -1) { // DOM Level 1 node! if (fDOMErrorHandler != null) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.SERIALIZER_DOMAIN, "ElementQName", new Object[]{tagName}); modifyDOMError(msg, DOMError.SEVERITY_ERROR, elem); boolean continueProcess = fDOMErrorHandler.handleError(fDOMError); // REVISIT: should we terminate upon request? if (!continueProcess) { throw new RuntimeException("Process stoped at user request"); } } } else { // uri=null and no colon (DOM L2 node) uri = fNSBinder.getURI(XMLSymbols.EMPTY_STRING); if (uri !=null && uri.length() > 0) { // there is a default namespace decl that is bound to // non-zero length uri, output xmlns="" printNamespaceAttr(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING); fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING); //fNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING); } } } // Fix up namespaces for attributes: per DOM L3 // check if prefix/namespace is correct the attributes for (i = 0; i < length; i++) { attr = (Attr) attrMap.item( i ); value = attr.getValue(); name = attr.getNodeName(); uri = attr.getNamespaceURI(); // Fix attribute that was declared with a prefix and namespace="" if (uri !=null && uri.length() == 0) { uri=null; // we must remove prefix for this attribute name=attr.getLocalName(); } if (DEBUG) { System.out.println("==>process attribute: "+attr.getNodeName()); } // make sure that value is never null. if (value == null) { value=XMLSymbols.EMPTY_STRING; } if (uri != null) { // attribute has namespace !=null prefix = attr.getPrefix(); prefix = prefix == null ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); String localpart = fSymbolTable.addSymbol( attr.getLocalName()); // print namespace declarations namespace declarations if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) { // check if we need to output this declaration prefix = attr.getPrefix(); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); localpart = fSymbolTable.addSymbol( attr.getLocalName()); if (prefix == XMLSymbols.PREFIX_XMLNS) { //xmlns:prefix localUri = fLocalNSBinder.getURI(localpart); // local prefix mapping value = fSymbolTable.addSymbol(value); if (value.length() != 0 ) { // add declaration to the global binder. if (localUri != null) { // declaration was redeclared and printed above fNSBinder.declarePrefix(localpart, localUri); } else { printNamespaceAttr(localpart, value); } } else { // REVISIT: issue error on invalid declarations // xmlns:foo = "" } continue; } else { // xmlns // empty prefix is always bound ("" or some string) uri = fNSBinder.getURI(XMLSymbols.EMPTY_STRING); localUri=fLocalNSBinder.getURI(XMLSymbols.EMPTY_STRING); value = fSymbolTable.addSymbol(value); if (localUri != null) { // declaration was redeclared and printed above fNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value); } else { printNamespaceAttr(XMLSymbols.EMPTY_STRING, value); } continue; } } uri = fSymbolTable.addSymbol(uri); // find if for this prefix a URI was already declared String declaredURI = fNSBinder.getURI(prefix); if (prefix == XMLSymbols.EMPTY_STRING || declaredURI != uri) { // attribute has no prefix (default namespace decl does not apply to attributes) // attribute prefix is not declared // conflict: attr URI does not match the prefix in scope name = attr.getNodeName(); // Find if any prefix for attributes namespace URI is available // in the scope String declaredPrefix = fLocalNSBinder.getPrefix(uri); if (declaredPrefix == null) { declaredPrefix = fNSBinder.getPrefix(uri); } if (declaredPrefix !=null && declaredPrefix !=XMLSymbols.EMPTY_STRING) { // use the prefix that was found prefix = declaredPrefix; name=prefix+":"+localpart; } else { if (DEBUG) { System.out.println("==> cound not find prefix for the attribute: " +prefix); } if (prefix != XMLSymbols.EMPTY_STRING && fLocalNSBinder.getURI(prefix) == null) { // the current prefix is not null and it has no in scope declaration // use this prefix } else { // find a prefix following the pattern "NS" +index (starting at 1) // make sure this prefix is not declared in the current scope. prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++); while (fLocalNSBinder.getURI(prefix)!=null) { prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++); } name=prefix+":"+localpart; } // add declaration for the new prefix printNamespaceAttr(prefix, uri); value = fSymbolTable.addSymbol(value); fLocalNSBinder.declarePrefix(prefix, value); fNSBinder.declarePrefix(prefix, uri); } // change prefix for this attribute } printAttribute (name, (value==null)?XMLSymbols.EMPTY_STRING:value, attr.getSpecified()); } else { // attribute uri == null // data int colon = name.indexOf(':'); if (colon > -1 ) { if (fDOMErrorHandler != null) { modifyDOMError("DOM Level 1 Node: "+name, DOMError.SEVERITY_ERROR, attr); boolean continueProcess = fDOMErrorHandler.handleError(fDOMError); if (!continueProcess) { // stop the namespace fixup and validation throw new RuntimeException("Stopped at user request"); } } printAttribute (name, value, attr.getSpecified()); } else { // uri=null and no colon // no fix up is needed: default namespace decl does not // apply to attributes printAttribute (name, value, attr.getSpecified()); } } } // end loop for attributes }// end namespace fixup algorithm // If element has children, then serialize them, otherwise // serialize en empty tag. if (elem.hasChildNodes()) { // Enter an element state, and serialize the children // one by one. Finally, end the element. state = enterElementState( null, null, tagName, fPreserveSpace ); state.doCData = _format.isCDataElement( tagName ); state.unescaped = _format.isNonEscapingElement( tagName ); child = elem.getFirstChild(); while (child != null) { serializeNode( child ); child = child.getNextSibling(); } if (fNamespaces) { fNSBinder.popContext(); } endElementIO( null, null, tagName ); } else { if (DEBUG) { System.out.println("==>endElement: " +elem.getNodeName()); } if (fNamespaces) { fNSBinder.popContext(); } _printer.unindent(); _printer.printText( "/>" ); // After element but parent element is no longer empty. state.afterElement = true; state.afterComment = false; state.empty = false; if (isDocumentState()) _printer.flush(); } } /** * Serializes a namespace attribute with the given prefix and value for URI. * In case prefix is empty will serialize default namespace declaration. * * @param prefix * @param uri * @exception IOException */ private void printNamespaceAttr(String prefix, String uri) throws IOException{ _printer.printSpace(); if (prefix == XMLSymbols.EMPTY_STRING) { if (DEBUG) { System.out.println("=>add xmlns=\""+uri+"\" declaration"); } _printer.printText( XMLSymbols.PREFIX_XMLNS ); } else { if (DEBUG) { System.out.println("=>add xmlns:"+prefix+"=\""+uri+"\" declaration"); } _printer.printText( "xmlns:"+prefix ); } _printer.printText( "=\"" ); printEscaped( uri ); _printer.printText( '"' ); } /** * Prints attribute. * NOTE: xml:space attribute modifies output format * * @param name * @param value * @param isSpecified * @exception IOException */ private void printAttribute (String name, String value, boolean isSpecified) throws IOException{ if (isSpecified || (fFeatures != null && !((Boolean)fFeatures.get("discard-default-content")).booleanValue())) { _printer.printSpace(); _printer.printText( name ); _printer.printText( "=\"" ); printEscaped( value ); _printer.printText( '"' ); } // If the attribute xml:space exists, determine whether // to preserve spaces in this and child nodes based on // its value. if (name.equals( "xml:space" )) { if (value.equals( "preserve" )) fPreserveSpace = true; else fPreserveSpace = _format.getPreserveSpace(); } } protected String getEntityRef( int ch ) { // Encode special XML characters into the equivalent character references. // These five are defined by default for all XML documents. switch (ch) { case '<': return "lt"; case '>': return "gt"; case '"': return "quot"; case '\'': return "apos"; case '&': return "amp"; } return null; } /** Retrieve and remove the namespaces declarations from the list of attributes. * */ private Attributes extractNamespaces( Attributes attrs ) throws SAXException { AttributesImpl attrsOnly; String rawName; int i; int indexColon; String prefix; int length; if (attrs == null) { return null; } length = attrs.getLength(); attrsOnly = new AttributesImpl( attrs ); for (i = length - 1 ; i >= 0 ; --i) { rawName = attrsOnly.getQName( i ); //We have to exclude the namespaces declarations from the attributes //is TRUE if (rawName.startsWith( "xmlns" )) { if (rawName.length() == 5) { startPrefixMapping( "", attrs.getValue( i ) ); attrsOnly.removeAttribute( i ); } else if (rawName.charAt(5) == ':') { startPrefixMapping(rawName.substring(6), attrs.getValue(i)); attrsOnly.removeAttribute( i ); } } } return attrsOnly; } // overwrite printing functions to make sure serializer prints out valid XML protected void printEscaped( String source ) throws IOException { int length = source.length(); for ( int i = 0 ; i < length ; ++i ) { int ch = source.charAt(i); if (!XMLChar.isValid(ch)) { if (++i <length) { surrogates(ch, source.charAt(i)); } else { fatalError("The character '"+(char)ch+"' is an invalid XML character"); } continue; } printXMLChar(ch); } } protected final void printXMLChar( int ch ) throws IOException { if ( ch == '<') { _printer.printText("&lt;"); } else if (ch == '&') { _printer.printText("&amp;"); } else if ( ch == '"') { // REVISIT: for character data we should not convert this into // char reference _printer.printText("&quot;"); } else if ( ( ch >= ' ' && _encodingInfo.isPrintable(ch)) || ch == '\n' || ch == '\r' || ch == '\t' ) { _printer.printText((char)ch); } else { // The character is not printable, print as character reference. _printer.printText( "& _printer.printText(Integer.toHexString(ch)); _printer.printText( ';' ); } } protected void printText( String text, boolean preserveSpace, boolean unescaped ) throws IOException { int index; char ch; int length = text.length(); if ( preserveSpace ) { // Preserving spaces: the text must print exactly as it is, // without breaking when spaces appear in the text and without // consolidating spaces. If a line terminator is used, a line // break will occur. for ( index = 0 ; index < length ; ++index ) { ch = text.charAt( index ); if (!XMLChar.isValid(ch)) { // check if it is surrogate if (++index <length) { surrogates(ch, text.charAt(index)); } else { fatalError("The character '"+(char)ch+"' is an invalid XML character"); } continue; } if ( unescaped ) { _printer.printText( ch ); } else printXMLChar( ch ); } } else { // Not preserving spaces: print one part at a time, and // use spaces between parts to break them into different // lines. Spaces at beginning of line will be stripped // by printing mechanism. Line terminator is treated // no different than other text part. for ( index = 0 ; index < length ; ++index ) { ch = text.charAt( index ); if (!XMLChar.isValid(ch)) { // check if it is surrogate if (++index <length) { surrogates(ch, text.charAt(index)); } else { fatalError("The character '"+(char)ch+"' is an invalid XML character"); } continue; } if ( XMLChar.isSpace(ch)) _printer.printSpace(); else if ( unescaped ) _printer.printText( ch ); else printXMLChar( ch ); } } } protected void printText( char[] chars, int start, int length, boolean preserveSpace, boolean unescaped ) throws IOException { int index; char ch; if ( preserveSpace ) { // Preserving spaces: the text must print exactly as it is, // without breaking when spaces appear in the text and without // consolidating spaces. If a line terminator is used, a line // break will occur. while ( length ch = chars[ start ]; ++start; if (!XMLChar.isValid(ch)) { // check if it is surrogate if (++start <length) { surrogates(ch, chars[start]); } else { fatalError("The character '"+(char)ch+"' is an invalid XML character"); } continue; } if ( unescaped ) _printer.printText( ch ); else printXMLChar( ch ); } } else { // Not preserving spaces: print one part at a time, and // use spaces between parts to break them into different // lines. Spaces at beginning of line will be stripped // by printing mechanism. Line terminator is treated // no different than other text part. while ( length ch = chars[ start ]; ++start; if (!XMLChar.isValid(ch)) { // check if it is surrogate if (++start <length) { surrogates(ch, chars[start]); } else { fatalError("The character '"+(char)ch+"' is an invalid XML character"); } continue; } if ( XMLChar.isSpace(ch)) _printer.printSpace(); else if ( unescaped ) _printer.printText( ch ); else printXMLChar( ch ); } } } public boolean reset() { super.reset(); return true; } }
package org.biojava.bio.program.abi; import java.io.DataInput; import java.io.DataInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.biojava.bio.seq.DNATools; import org.biojava.bio.symbol.IllegalSymbolException; import org.biojava.bio.symbol.Symbol; import org.biojava.utils.io.CachingInputStream; import org.biojava.utils.io.Seekable; public class ABIFParser { private ABIFParser.DataAccess din; private boolean parsed = false; private Map records; private final int RECORD_COUNT_OFFSET = 18; private final int RECORD_OFFSET_OFFSET = 26; /** Creates a new ABIFParser for a file. */ public ABIFParser(File f) throws IOException { this(new ABIFParser.RandomAccessFile(f)); } /** * Creates a new ABIFParser for an input stream. Note that the stream * will be wrapped in a {@link CachingInputStream} if it isn't one already. * If it is, it will be seeked to 0. */ public ABIFParser(InputStream in) throws IOException { this(new ABIFParser.DataStream(in)); } /** * Creates a new ABIFParser for the specified {@link DataAccess} object. * If you need to read from something other than a file or a stream, you'll * have to implement a {@link DataAccess}-implementing class wrapping your * source and then pass an instance to this constructor. */ public ABIFParser(ABIFParser.DataAccess toParse) throws IOException { din = toParse; readDataRecords(); } /** * Returns the accessor for the raw data being parsed by this parser. */ public final ABIFParser.DataAccess getDataAccess() { return din; } private final void readDataRecords() throws IOException { parsed = false; din.seek(RECORD_COUNT_OFFSET); long recordCount = 0xffffffff & din.readInt(); din.seek(RECORD_OFFSET_OFFSET); long recordOffset = 0xffffffff & din.readInt(); din.seek(recordOffset); TaggedDataRecord tdr; StringBuffer label; records = new HashMap(); for (int i = 0 ; i < recordCount ; i++) { tdr = new TaggedDataRecord(din); label = new StringBuffer(6).append(tdr.tagName).append(tdr.tagNumber); records.put(label.substring(0), tdr); } for (Iterator i = records.values().iterator(); i.hasNext(); ) { TaggedDataRecord record = (TaggedDataRecord)i.next(); if (record.hasOffsetData) { din.seek(record.dataRecord); din.readFully(record.offsetData); } } parsed = true; din.finishedReading(); } public static Symbol decodeDNAToken(char token) throws IllegalSymbolException { switch (token) { case 'a': case 'A': return DNATools.a(); case 'c': case 'C': return DNATools.c(); case 'g': case 'G': return DNATools.g(); case 't': case 'T': return DNATools.t(); case 'n': case 'N': return DNATools.n(); case '-': return DNATools.getDNA().getGapSymbol(); default: throw new IllegalSymbolException("Can't decode token " + token + " into DNA"); } } public ABIFParser.TaggedDataRecord getDataRecord(String tagName, int tagNumber) throws IllegalArgumentException, IllegalStateException { if (!parsed) throw new IllegalStateException("parsing is not complete"); if (tagNumber < 1) throw new IllegalArgumentException("tagNumber must be positive"); if (tagName.length() != 4) throw new IllegalArgumentException("tagName must be 4 characters long"); return (ABIFParser.TaggedDataRecord) records.get(tagName + tagNumber); } /** * An aggregate immutable type for an ABIF tagged data record. See the * Tibbets paper (referenced in the javadoc for {@link ABIFParser}) for * more information. */ public static class TaggedDataRecord { public static final int DATA_TYPE_ASCII_ARRAY = 2; public static final int DATA_TYPE_INTEGER = 4; public static final int DATA_TYPE_FLOAT = 7; public static final int DATA_TYPE_DATE = 10; public static final int DATA_TYPE_TIME = 11; public static final int DATA_TYPE_PSTRING = 18; public final char[] tagName; public final long tagNumber; public final int dataType; public final int elementLength; public final long numberOfElements; public final long recordLength; public final long dataRecord; public final long crypticVariable; public final boolean hasOffsetData; public final byte[] offsetData; /** * Creates a new TaggedDataRecord from the next 28 bytes of * <code>din</code>. * @param din the source of the raw data to be parsed * @throws IOException if there's a problem with <code>din</code> */ public TaggedDataRecord(ABIFParser.DataAccess din) throws IOException { tagName = new char[4]; tagName[0] = (char) din.readByte(); tagName[1] = (char) din.readByte(); tagName[2] = (char) din.readByte(); tagName[3] = (char) din.readByte(); tagNumber = 0xffffffff & din.readInt(); dataType = 0xffff & din.readShort(); elementLength = 0xffff & din.readShort(); numberOfElements = 0xffffffff & din.readInt(); recordLength = 0xffffffff & din.readInt(); dataRecord = 0xffffffff & din.readInt(); crypticVariable = 0xffffffff & din.readInt(); hasOffsetData = recordLength>4L; if (hasOffsetData) offsetData = new byte[(int)recordLength]; else offsetData = new byte[0]; } /** * A very verbose <code>toString</code> that dumps all of the * data in this record in a human-readable format. */ public String toString() { StringBuffer sb = new StringBuffer(super.toString()).append("[\n"); sb.append(" tagName = ").append(tagName).append('\n'); sb.append(" tagNumber = ").append(tagNumber).append('\n'); sb.append(" dataType = "); switch (dataType) { case DATA_TYPE_ASCII_ARRAY: sb.append("ASCII"); break; case DATA_TYPE_INTEGER: sb.append("INTEGER"); break; case DATA_TYPE_FLOAT: sb.append("FLOAT"); break; case DATA_TYPE_DATE: sb.append("DATE"); break; case DATA_TYPE_TIME: sb.append("TIME"); break; case DATA_TYPE_PSTRING: sb.append("PSTRING"); break; default: sb.append(dataType); } sb.append('\n'); sb.append(" elementLength = ").append(elementLength).append('\n'); sb.append(" numberOfElements= ").append(numberOfElements).append('\n'); sb.append(" recordLength = ").append(recordLength).append('\n'); sb.append(" dataRecord = "); if (recordLength <= 4) { switch (dataType) { case DATA_TYPE_ASCII_ARRAY: if (elementLength > 3) sb.append((char) ((dataRecord >>> 24) & 0xFF)); if (elementLength > 2) sb.append((char) ((dataRecord >>> 16) & 0xFF)); if (elementLength > 1) sb.append((char) ((dataRecord >>> 8 ) & 0xFF)); sb.append((char) ((dataRecord) & 0xFF)); break; case DATA_TYPE_DATE: sb.append((dataRecord >>> 16) & 0xffff).append('/'); sb.append((dataRecord >>> 8 ) & 0xff).append('/'); sb.append((dataRecord) & 0xff); break; case DATA_TYPE_TIME: sb.append((dataRecord >>> 24) & 0xff).append(':'); sb.append((dataRecord >>> 16) & 0xff).append(':'); sb.append((dataRecord >>> 8 ) & 0xff); break; case DATA_TYPE_INTEGER: sb.append(dataRecord >>> (4 - recordLength)*8); break; default: hexStringify((int)dataRecord, sb); } } else { hexStringify((int)dataRecord, sb); } sb.append(" hasOffsetData = ").append(hasOffsetData).append('\n'); sb.append('\n'); sb.append(" crypticVariable = ").append(crypticVariable).append('\n'); sb.append(']'); return sb.toString(); } private void hexStringify(int l, StringBuffer sb) { sb.append("0x"); String hex = Integer.toHexString(l).toUpperCase(); for (int i = 8 ; i > hex.length() ; i sb.append('0'); sb.append(hex); } } /** * Concatenation of the {@link Seekable} and {@link DataInput} interfaces. */ public static interface DataAccess extends Seekable, DataInput { /** * Called when the parser has finished reading. The access * may choose to close itself at this point, e.g. if it is * using a RandomAccessFile. * @throws IOException if it could not do what it needs to. */ public void finishedReading() throws IOException; } private static class RandomAccessFile extends java.io.RandomAccessFile implements DataAccess { public RandomAccessFile(File f) throws FileNotFoundException { super(f, "r"); } public void finishedReading() throws IOException { this.close(); } } /** Implements DataAccess by delegating to a CachingStream and a * DataInputStream */ private static class DataStream implements DataAccess { CachingInputStream cin; DataInputStream din; public DataStream(InputStream src) throws IOException { if (src instanceof CachingInputStream) cin = (CachingInputStream) src; else cin = new CachingInputStream(src); cin.seek(0); din = new DataInputStream(cin); } public DataStream(CachingInputStream cin) throws IOException { this((InputStream) cin); } public void finishedReading() throws IOException { // We don't care. } public boolean readBoolean() throws IOException { return din.readBoolean(); } public byte readByte() throws IOException { return din.readByte(); } public char readChar() throws IOException { return din.readChar(); } public short readShort() throws IOException { return din.readShort(); } public int readInt() throws IOException { return din.readInt(); } public long readLong() throws IOException { return din.readLong(); } public float readFloat() throws IOException { return din.readFloat(); } public double readDouble() throws IOException { return din.readDouble(); } public String readUTF() throws IOException { return din.readUTF(); } public int readUnsignedByte() throws IOException { return din.readUnsignedByte(); } public int readUnsignedShort() throws IOException { return din.readUnsignedShort(); } public void readFully(byte[] values) throws IOException { din.readFully(values); } public void readFully(byte[] values, int start, int len) throws IOException { din.readFully(values, start, len); } public String readLine() throws IOException { throw new UnsupportedOperationException("DataInputStream#readLine is deprecated. Use readUTF instead"); } public int skipBytes(int count) throws IOException { return din.skipBytes(count); } public void seek(long pos) throws IOException { cin.seek(pos); } } }
package kawa.lang; import gnu.lists.*; import java.io.*; import gnu.mapping.*; import gnu.expr.*; import java.util.*; /** The translated form of a <code>(syntax <var>template</var>)</code>. */ public class SyntaxTemplate implements Externalizable { /** A <code>syntax</code> or <code>syntax-rules</code> template is * translated into a "template program." * The template program is a simple bytecode stored in a string. * The encoding is designed so that instructions are normally * in the range 1..127, which makes the <code>CONSTANT_Utf8</code> encoding * used in <code>.class</code> files compact. * The folowing <code>BUILD_XXX</code> are the "opcode" of the encoding, * stored in the low-order 3 bits of a <code>char</code>. */ String template_program; /** Template instructions that don't have an operand value. */ static final int BUILD_MISC = 0; /** Make following operand into a 1-element list. */ static final int BUILD_LIST1 = (1<<3)+BUILD_MISC; static final int BUILD_NIL = (2<<3)+BUILD_MISC; /** Wrap following sub-expression in a SyntaxForm. */ static final int BUILD_SYNTAX = (3<<3)+BUILD_MISC; /** Build a vector (an <code>FVector</code>) from following sub-expression. * The latter must evaluate to a list. */ static final int BUILD_VECTOR = (5<<3)+BUILD_MISC; /** Instruction to creat a <code>Pair</code> from sub-expressions. * Instruction <code>BUILD_CONS+4*delta</code> is followed by a * sub-expression for the <code>car</code> * (whose length is <code>delta</code> chars), * followed by the expression for the <code>cdr</code>. */ static final int BUILD_CONS = 1; /** Instruction BUILD_VAR+8*i pushes vars[i]. * This array contains the values of pattern variables. */ final static int BUILD_VAR = 2; // Must be an even number. /** Instruction BUILD_VAR_CAR+8*i pushes car(vars[i]). * It assumes that vars[i] is actually a pair whose car was the * matched pattern variable. (This is done so we can preserve * <code>PairWithPosition</code> source positions). */ final static int BUILD_VAR_CAR = BUILD_VAR+1; /** Instruction BUILD_LITERAL+8*i pushes literal_values[i]. */ final static int BUILD_LITERAL = 4; /** Instruction <code>BUILD_DOTS+8*i</code> repeats a sub-expression. * The value <code>i</code> is a variable index of a pattern variable * of at least the needed depth. The result is spliced in. */ final static int BUILD_DOTS = 5; /** Unfinished support for "operand" values that need more tahn 13 bits. */ final static int BUILD_WIDE = 7; /** Map variable to ellipsis nesting depth. * The nesting depth of the <code>i</code>'th pattern variable * is <code>(int) patternNesting.charAt(i)/2</code>. * The low-order bit indicates that if matched value is the <code>car</code> * of the value saved in the <code>vars</code> array. * (We use a <code>String</code> because it is compact both at runtime * and in <code>.class</code> files. */ String patternNesting; int max_nesting; Object[] literal_values; static final String dots3 = "..."; /** The lexical context of template definition. */ private ScopeExp currentScope; /* DEBUGGING: void print_template_program (java.util.Vector patternNames, java.io.PrintWriter ps) { print_template_program(patternNames, ps, 0, template_program.length()); ps.flush(); } void print_template_program (java.util.Vector patternNames, java.io.PrintWriter ps, int start, int limit) { for (int i = start; i < limit; i++) { char ch = template_program.charAt(i); ps.print(" " + i + ": " + (int)ch); if (ch == BUILD_LIST1) ps.println (" - LIST1"); else if (ch == BUILD_NIL) ps.println (" - NIL"); else if (ch == BUILD_SYNTAX) ps.println (" - SYNTAX"); else if ((ch & 7) == BUILD_DOTS) { int var_num = ch >> 3; ps.print(" - DOTS (var: "); ps.print(var_num); if (patternNames != null && var_num >= 0 && var_num < patternNames.size()) { ps.print(" = "); ps.print(patternNames.elementAt(var_num)); } ps.println(')'); } else if (ch == BUILD_VECTOR) ps.println (" - VECTOR"); else if ((ch & 7) == BUILD_CONS) ps.println (" - CONS "+(ch >> 3)); else if ((ch & 7) == BUILD_LITERAL) { int lit_num = ch >> 3; ps.print (" - literal[" + lit_num + "]: "); if (literal_values == null || literal_values.length <= lit_num || lit_num < 0) ps.print("??"); else kawa.standard.Scheme.writeFormat.writeObject(literal_values [lit_num], (Consumer) ps); ps.println(); } else if ((ch & 6) == BUILD_VAR) // Also catches BUILD_VAR_CAR. { int var_num = ch >> 3; ps.print(((ch & 7) == BUILD_VAR ? " - VAR[" : " - VAR_CAR[") + var_num + "]"); if (patternNames != null && var_num >= 0 && var_num < patternNames.size()) ps.print(": " + patternNames.elementAt(var_num)); ps.println(); } else ps.println (" - ???"); } } END DEBUGGING */ protected SyntaxTemplate () { } public SyntaxTemplate (String patternNesting, String template_program, Object[] literal_values, int max_nesting) { this.patternNesting = patternNesting; this.template_program = template_program; this.literal_values = literal_values; this.max_nesting = max_nesting; } public SyntaxTemplate (Object template, SyntaxForm syntax, Translator tr) { this.currentScope = tr.currentScope(); this.patternNesting = tr == null || tr.patternScope == null ? "" : tr.patternScope.patternNesting.toString(); StringBuffer program = new StringBuffer (); java.util.Vector literals_vector = new java.util.Vector (); /* #ifdef use:java.util.IdentityHashMap */ IdentityHashMap seen = new IdentityHashMap(); /* #else */ // Object seen = null; /* #endif */ convert_template(template, syntax, program, 0, literals_vector, seen, false, tr); this.template_program = program.toString(); this.literal_values = new Object[literals_vector.size ()]; literals_vector.copyInto (this.literal_values); /* DEBUGGING: OutPort err = OutPort.errDefault(); err.print("{translated template"); Macro macro = tr.currentMacroDefinition; err.print(" scope: "); err.print(currentScope); if (macro != null) { err.print(" for "); err.print(macro); } if (tr != null && tr.patternScope != null) { err.println(" - "); print_template_program (tr.patternScope.pattern_names, err); } err.println ('}'); */ } /** Recursively translate a syntax-rule template to a template program. * @param form the template from the syntax-rule * @param syntax if non-null, the closest surrounding <code>SyntaxForm</code> * @param template_program (output) the translated template * @param nesting the depth of ... we are inside * @param literals_vector (output) the literal data in the template * @param tr the current Translator * @return the index of a pattern variable (in <code>pattern_names</code>) * that is nested at least as much as <code>nesting</code>; * if there is none such, -1 if there is any pattern variable or elipsis; * and -2 if the is no pattern variable or elipsis. */ public int convert_template (Object form, SyntaxForm syntax, StringBuffer template_program, int nesting, java.util.Vector literals_vector, Object seen, boolean isVector, Translator tr) { while (form instanceof SyntaxForm) { syntax = (SyntaxForm) form; form = syntax.form; } /* #ifdef use:java.util.IdentityHashMap */ if (form instanceof Pair || form instanceof FVector) { IdentityHashMap seen_map = (IdentityHashMap) seen; if (seen_map.containsKey(form)) { /* FIXME cycles are OK if data are literal. */ tr.syntaxError("self-referential (cyclic) syntax template"); return -2; } seen_map.put(form, form); } /* #endif */ check_form: if (form instanceof Pair) { Pair pair = (Pair) form; int ret_cdr = -2;; int save_pc = template_program.length(); Object car = pair.car; // Look for (... ...) and translate that to ... if (tr.matches(car, dots3)) { Object cdr = tr.stripSyntax(pair.cdr); if (cdr instanceof Pair) { Pair cdr_pair = (Pair) cdr; if (cdr_pair.car == dots3 && cdr_pair.cdr == LList.Empty) { form = dots3; break check_form; } } } int save_literals = literals_vector.size(); // This may get patched to a BUILD_CONS. template_program.append((char) BUILD_LIST1); int num_dots3 = 0; Object rest = pair.cdr; while (rest instanceof Pair) { Pair p = (Pair) rest; if (! tr.matches(p.car, dots3)) break; num_dots3++; rest = p.cdr; template_program.append((char) BUILD_DOTS); // to be patched. } int ret_car = convert_template(car, syntax, template_program, nesting + num_dots3, literals_vector, seen, false, tr); if (rest != LList.Empty) { int delta = template_program.length() - save_pc - 1; template_program.setCharAt(save_pc, (char)((delta<<3)+BUILD_CONS)); ret_cdr = convert_template (rest, syntax, template_program, nesting, literals_vector, seen, isVector, tr); } if (num_dots3 > 0) { if (ret_car < 0) tr.syntaxError ("... follows template with no suitably-nested pattern variable"); for (int i = num_dots3; --i >= 0; ) { char op = (char) ((ret_car << 3) + BUILD_DOTS); template_program.setCharAt(save_pc+i + 1, op); int n = nesting+num_dots3; if (n >= max_nesting) max_nesting = n; } } if (ret_car >= 0) return ret_car; if (ret_cdr >= 0) return ret_cdr; if (ret_car == -1 || ret_cdr == -1) return -1; if (isVector) return -2; // There is no pattern variable in 'form', so treat it as literal. // This is optimization to group non-substrituted "chunks" // as a single literal and a single SyntaxForm value. literals_vector.setSize(save_literals); template_program.setLength(save_pc); } else if (form instanceof FVector) { template_program.append((char) BUILD_VECTOR); return convert_template(LList.makeList((FVector) form), syntax, template_program, nesting, literals_vector, seen, true, tr); } else if (form == LList.Empty) { template_program.append((char) BUILD_NIL); return -2; } else if (form instanceof String && tr != null && tr.patternScope != null) { int pattern_var_num = indexOf(tr.patternScope.pattern_names, form); if (pattern_var_num >= 0) { int var_nesting = patternNesting.charAt(pattern_var_num); int op = (var_nesting & 1) != 0 ? BUILD_VAR_CAR : BUILD_VAR; var_nesting >>= 1; // R4RS requires that the nesting be equal. // We allow an extension here, since it allows potentially-useful // rules like (x (y ...) ...) => (((x y) ...) ...) if (var_nesting > nesting) tr.syntaxError ("inconsistent ... nesting of " + form); template_program.append((char) (op + 8 * pattern_var_num)); return var_nesting == nesting ? pattern_var_num : -1; } // else treated quoted symbol as literal: } int literals_index = indexOf(literals_vector, form); if (literals_index < 0) { literals_index = literals_vector.size (); literals_vector.addElement(form); } if (form instanceof String || form instanceof Symbol) tr.noteAccess(form, tr.currentScope()); if (! (form instanceof SyntaxForm) && form != dots3) template_program.append((char) (BUILD_SYNTAX)); template_program.append((char) (BUILD_LITERAL + 8 * literals_index)); return form == dots3 ? -1 : -2; } /** Similar to vec.indexOf(elem), but uses == (not equals) to compare. */ static int indexOf(java.util.Vector vec, Object elem) { int len = vec.size(); for (int i = 0; i < len; i++) { if (vec.elementAt(i) == elem) return i; } return -1; } /** The the current repeat count. */ private int get_count (Object var, int nesting, int[] indexes) { for (int level = 0; level < nesting; level++) var = ((Object[]) var) [indexes[level]]; Object[] var_array = (Object[]) var; return var_array.length; } /** Expand this template * The compiler translates <code>(syntax <var>template</var>)</code> * to a call to this method. */ public Object execute (Object[] vars, TemplateScope templateScope) { if (false) // DEBUGGING { OutPort err = OutPort.errDefault(); err.print("{Expand template in "); err.print(((Translator) Compilation.getCurrent()).getCurrentSyntax()); err.print(" tscope: "); err.print(templateScope); if (vars != null) { err.print(" vars: "); for (int i = 0; i < vars.length; i++) { err.println(); err.print(" " + i +" : "); kawa.standard.Scheme.writeFormat.writeObject(vars[i], err); } } err.println('}'); } Object result = execute(0, vars, 0, new int[max_nesting], (Translator) Compilation.getCurrent(), templateScope); if (false) // DEBUGGING: { OutPort err = OutPort.errDefault(); err.startLogicalBlock("", false, "}"); err.print("{Expansion of syntax template "); err.print(((Translator) Compilation.getCurrent()).getCurrentSyntax()); err.print(": "); err.writeBreakLinear(); kawa.standard.Scheme.writeFormat.writeObject(result, err); err.endLogicalBlock("}"); err.println(); err.flush(); } return result; } public Object execute (Object[] vars, Translator tr, TemplateScope templateScope) { return execute(0, vars, 0, new int[max_nesting], tr, templateScope); } Object get_var (int var_num, Object[] vars, int[] indexes) { Object var = vars [var_num]; if (var_num < patternNesting.length()) { int var_nesting = (int) patternNesting.charAt(var_num) >> 1; for (int level = 0; level < var_nesting; level++) var = ((Object[]) var) [indexes[level]]; } return var; } /** Similar to execute, but return is wrapped in a list. * Normally the result is a single Pair, BUILD_DOTS can return zero * or many Pairs. */ LList executeToList (int pc, Object[] vars, int nesting, int[] indexes, Translator tr, TemplateScope templateScope) { int pc0 = pc; int ch = template_program.charAt(pc); while ((ch & 7) == BUILD_WIDE) ch = ((ch - BUILD_WIDE) << 13) | template_program.charAt(++pc); if ((ch & 7) == BUILD_VAR_CAR) { Pair p = (Pair) get_var(ch >> 3, vars, indexes); return Translator.makePair(p, p.car, LList.Empty); } else if ((ch & 7) == BUILD_DOTS) { int var_num = (int) (ch >> 3); Object var = vars[var_num]; int count = get_count(var, nesting, indexes); LList result = LList.Empty; Pair last = null; // Final Pair of result list, or null. pc++; for (int j = 0; j < count; j++) { indexes[nesting] = j; LList list = executeToList(pc, vars, nesting + 1, indexes, tr, templateScope); if (last == null) result = list; else last.cdr = list; // Normally list is a single Pair, but if it is multiple Pairs, // find the last Pair so we can properly splice everything. while (list instanceof Pair) { last = (Pair) list; list = (LList) last.cdr; } } return result; } Object v = execute(pc0, vars, nesting, indexes, tr, templateScope); return new Pair(v, LList.Empty); } /** * @param nesting number of levels of ... we are nested inside * @param indexes element i (where i in [0 .. nesting-1] specifies * the iteration index for the i'level of nesting */ Object execute (int pc, Object[] vars, int nesting, int[] indexes, Translator tr, TemplateScope templateScope) { int ch = template_program.charAt(pc); /* DEBUGGING: System.err.print ("{execute template pc:"+pc + " ch:"+(int)ch+" nesting:["); for (int level=0; level < nesting; level++) System.err.print ((level > 0 ? " " : "") + indexes[level]); System.err.println("]}"); */ while ((ch & 7) == BUILD_WIDE) ch = ((ch - BUILD_WIDE) << 13) | template_program.charAt(++pc); if (ch == BUILD_LIST1) { return executeToList(pc+1, vars, nesting, indexes, tr, templateScope); } else if (ch == BUILD_NIL) return LList.Empty; else if (ch == BUILD_SYNTAX) { Object v = execute(pc+1, vars, nesting, indexes, tr, templateScope); return v == LList.Empty ? v : SyntaxForm.make(v, templateScope); } else if ((ch & 7) == BUILD_CONS) { Pair p = null; Object result = null; int pc0=pc, pc1=pc; for (;;) { pc++; pc1=pc; Object q = executeToList(pc, vars, nesting, indexes, tr, templateScope); if (p == null) result = q; else p.cdr = q; while (q instanceof Pair) { p = (Pair) q; q = p.cdr; } pc += ch >> 3; ch = template_program.charAt(pc); if ((ch & 7) != BUILD_CONS) break; } Object cdr = execute(pc, vars, nesting, indexes, tr, templateScope); if (p == null) result = cdr; else p.cdr = cdr; return result; } else if (ch == BUILD_VECTOR) { Object el = execute(pc+1, vars, nesting, indexes, tr, templateScope); return new FVector((LList) el); } else if ((ch & 7) == BUILD_LITERAL) { int lit_no = ch >> 3; /* DEBUGGING: System.err.println("-- insert literal#"+lit_no +": "+literal_values[lit_no]); */ return literal_values[lit_no]; } else if ((ch & 6) == BUILD_VAR) // Also handles BUILD_VAR_CAR. { Object var = get_var(ch >> 3, vars, indexes); if ((ch & 7) == BUILD_VAR_CAR) var = ((Pair) var).car; return var; } else throw new Error("unknown template code: "+((int) ch)+" at "+pc); } /** * @serialData */ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(patternNesting); out.writeObject(template_program); out.writeObject(literal_values); out.writeInt(max_nesting); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { patternNesting = (String) in.readObject(); template_program = (String) in.readObject(); literal_values = (Object[]) in.readObject(); max_nesting = in.readInt(); } }
package de.independit.scheduler.server.repository; import java.io.*; import java.util.*; import java.lang.*; import java.sql.*; import de.independit.scheduler.server.*; import de.independit.scheduler.server.util.*; import de.independit.scheduler.server.exception.*; public class SDMSParameterDefinition extends SDMSParameterDefinitionProxyGeneric { public final static String __version = "SDMSParameterDefinition $Revision: 2.2.6.1 $ / @(#) $Id: SDMSParameterDefinition.java,v 2.2.6.1 2013/03/14 10:25:21 ronald Exp $"; protected SDMSParameterDefinition(SDMSObject p_object) { super(p_object); } private void deleteExtents(SystemEnvironment env) throws SDMSException { Long id = getId(env); Vector v = SDMSVersionedExtentsTable.idx_oId.getVector(env, getId(env)); for(int i = 0; i < v.size(); i++) { SDMSVersionedExtents e = (SDMSVersionedExtents) v.get(i); e.delete(env); } } public void delete(SystemEnvironment env) throws SDMSException { HashSet<Long> s = new HashSet<Long>(); s.add(getSeId(env)); delete(env, s, false); } public void delete(SystemEnvironment env, HashSet<Long> seIds, boolean force) throws SDMSException { Long id = getId(env); Vector v = SDMSParameterDefinitionTable.idx_linkPdId.getVector(env, id); for(int i = 0; i < v.size(); i++) { SDMSParameterDefinition pd = (SDMSParameterDefinition) v.get(i); if (seIds.contains(pd.getSeId(env))) continue; throw new CommonErrorException( new SDMSMessage(env, "03402082327", "The parameter $1 is referenced by $2", getName(env), pd.getURL(env) ) ); } if (getIsLong(env).booleanValue()) deleteExtents(env); super.delete(env); } public String getDefaultValue (SystemEnvironment env) throws SDMSException { String val = super.getDefaultValue (env); if (getIsLong(env).booleanValue()) { Vector v = SDMSVersionedExtentsTable.idx_oId.getVector(env, getId(env)); for (int s = 1; s <= v.size(); s ++) { for (int i = 0; i < v.size(); i ++) { SDMSVersionedExtents e = (SDMSVersionedExtents) v.get(i); if (s == e.getSequence(env).intValue()) { val = val + e.getExtent(env); } } } } return (val); } private void createExtents(SystemEnvironment env, String p_value) throws SDMSException { int e = 1; while (p_value.length() > 0) { if (p_value.length() > SDMSVersionedExtentsProxyGeneric.getExtentMaxLength()) { SDMSVersionedExtentsTable.table.create(env, getId(env), new Integer(e), p_value.substring(0, SDMSVersionedExtentsProxyGeneric.getExtentMaxLength())); p_value = p_value.substring(SDMSVersionedExtentsProxyGeneric.getExtentMaxLength()); } else { SDMSVersionedExtentsTable.table.create(env, getId(env), new Integer(e), p_value); break; } e ++; } } public void setDefaultValue (SystemEnvironment env, String p_defaultValue) throws SDMSException { String oldValue = getDefaultValue(env); if(p_defaultValue != null && p_defaultValue.equals(oldValue)) return; if(p_defaultValue == null && oldValue == null) return; if (p_defaultValue != null) { if (getIsLong(env).booleanValue()) deleteExtents(env); if (p_defaultValue.length() > getDefaultValueMaxLength()) { createExtents(env, p_defaultValue.substring(getDefaultValueMaxLength())); p_defaultValue = p_defaultValue.substring(0, getDefaultValueMaxLength()); setIsLong(env, Boolean.TRUE); } else setIsLong(env, Boolean.FALSE); } super.setDefaultValue(env, p_defaultValue); return ; } public String getURLName(SystemEnvironment env) throws SDMSException { SDMSProxy p = null; final Long seId = getSeId(env); try { p = SDMSSchedulingEntityTable.getObject(env, seId); } catch (NotFoundException nfe1) { try { p = SDMSScopeTable.getObject(env, seId); } catch (NotFoundException nfe2) { try { p = SDMSNamedResourceTable.getObject(env, seId); } catch (NotFoundException nfe3) { p = SDMSNamedResourceTable.getObject(env, seId); } } } return getName(env) + " of " + p.getURL(env); } public String getURL(SystemEnvironment env) throws SDMSException { return "parameter " + getURLName(env); } public void setLinkPdId (SystemEnvironment env, Long p_linkPdId) throws SDMSException { super.setLinkPdId(env, p_linkPdId); checkRefCycle(env); } protected void checkRefCycle(SystemEnvironment env) throws SDMSException { checkRefCycle(env, new HashSet<Long>()); } protected void checkRefCycle(SystemEnvironment env, HashSet<Long> pdIds) throws SDMSException { Long linkPdId = getLinkPdId(env); if (linkPdId == null) return; pdIds.add(getId(env)); if (pdIds.contains(linkPdId)) throw new CommonErrorException(new SDMSMessage(env, "03507140909", "Cyclic Parameter References detected")); SDMSParameterDefinition pd = SDMSParameterDefinitionTable.getObject(env, linkPdId); pd.checkRefCycle(env, pdIds); } }
package org.inaturalist.android; import java.io.Serializable; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.inaturalist.android.R; import org.inaturalist.android.INaturalistService.LoginType; import android.app.Activity; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.ImageView; public class INaturalistApp extends Application { private final static String TAG = "INAT: Application"; private SharedPreferences mPrefs; private NotificationManager mNotificationManager; private boolean mIsSyncing = false; public static Integer VERSION = 1; public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); public static SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd h:mm:ss a z"); public static SimpleDateFormat SHORT_DATE_FORMAT = new SimpleDateFormat("d MMM yyyy"); public static SimpleDateFormat SHORT_TIME_FORMAT = new SimpleDateFormat("h:mm a z"); private static Integer SYNC_NOTIFICATION = 3; private static Context context; private Locale locale = null; private Locale deviceLocale = null; @Override public void onCreate() { super.onCreate(); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); INaturalistApp.context = getApplicationContext(); deviceLocale = getResources().getConfiguration().locale; applyLocaleSettings(); } /* Used for accessing iNat service results - since passing large amounts of intent data * is impossible (for example, returning a huge list of projects/guides won't work via intents) */ private Map<String, Serializable> mServiceResults = new HashMap<String, Serializable>(); public void setServiceResult(String key, Serializable value) { mServiceResults.put(key, value); } public Serializable getServiceResult(String key) { return mServiceResults.get(key); } /** * Get ISO 3166-1 alpha-2 country code for this device (or null if not available) * @param context Context reference to get the TelephonyManager instance from * @return country code or null */ public static String getUserCountry(Context context) { ActivityHelper helper; helper = new ActivityHelper(context); try { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final String simCountry = tm.getSimCountryIso(); if (simCountry != null && simCountry.length() == 2) { // SIM country code is available return simCountry.toLowerCase(Locale.US); } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable) String networkCountry = tm.getNetworkCountryIso(); if (networkCountry != null && networkCountry.length() == 2) { // network country code is available return networkCountry.toLowerCase(Locale.US); } } } catch (Exception e) { } return null; } /** Returns the set inat network member */ public String getInaturalistNetworkMember() { SharedPreferences settings = getPrefs(); return settings.getString("pref_network_member", null); } /** Set the inat network member */ public void setInaturalistNetworkMember(String memberNetwork) { SharedPreferences settings = getPrefs(); Editor settingsEditor = settings.edit(); settingsEditor.putString("pref_network_member", memberNetwork); settingsEditor.apply(); } private void updateUIAccordingToNetworkMember() { String networkMember = getInaturalistNetworkMember(); String newLocale; Resources res = getBaseContext().getResources(); newLocale = getStringResourceByName("inat_network_language_" + networkMember); // Change locale settings in the app DisplayMetrics dm = res.getDisplayMetrics(); android.content.res.Configuration conf = res.getConfiguration(); String parts[] = newLocale.split("-r"); if (parts.length > 1) { // Language + country code conf.locale = new Locale(parts[0], parts[1]); } else { // Just the language code conf.locale = new Locale(newLocale); } res.updateConfiguration(conf, dm); SharedPreferences settings = getPrefs(); Editor settingsEditor = settings.edit(); settingsEditor.putString("pref_locale", newLocale); settingsEditor.apply(); restart(); } public void detectUserCountryAndUpdateNetwork(Context context) { // Don't ask the user again to switch to another network (if he's been asked before) if (getInaturalistNetworkMember() != null) return; ActivityHelper helper; helper = new ActivityHelper(context); Resources res = getBaseContext().getResources(); LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View titleBarView = inflater.inflate(R.layout.change_network_title_bar, null); ImageView titleBarLogo = (ImageView) titleBarView.findViewById(R.id.title_bar_logo); String country = getUserCountry(context); Log.d(TAG, "Detected country: " + country); final String[] inatNetworks = getINatNetworks(); if (country == null) { // Couldn't detect country - set default iNat network setInaturalistNetworkMember(inatNetworks[0]); return; } String detectedNetwork = inatNetworks[0]; // Select default iNaturalist network for (int i = 0; i < inatNetworks.length; i++) { if (country.equalsIgnoreCase(getStringResourceByName("inat_country_" + inatNetworks[i]))) { detectedNetwork = inatNetworks[i]; break; } } // Don't ask the user again to switch if it's the default iNat network if (!detectedNetwork.equals(inatNetworks[0])) { // Set the logo in the title bar according to network type String logoName = getStringResourceByName("inat_logo_" + detectedNetwork); String packageName = getPackageName(); int resId = getResources().getIdentifier(logoName, "drawable", packageName); titleBarLogo.setImageResource(resId); final String selectedNetwork = detectedNetwork; helper.confirm( titleBarView, getStringResourceByName("alert_message_use_" + detectedNetwork), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setInaturalistNetworkMember(selectedNetwork); updateUIAccordingToNetworkMember(); } }, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Set default iNaturalist network setInaturalistNetworkMember(inatNetworks[0]); } }); } else { // Set default iNaturalist network setInaturalistNetworkMember(inatNetworks[0]); } } public String getFormattedDeviceLocale(){ if(deviceLocale!=null){ return deviceLocale.getDisplayLanguage(); } return ""; } public String[] getINatNetworks() { Resources res = getResources(); return res.getStringArray(R.array.inat_networks); } public String[] getStringArrayResourceByName(String aString) { String packageName = getPackageName(); int resId = getResources().getIdentifier(aString, "array", packageName); if (resId == 0) { return new String[] { aString }; } else { return getResources().getStringArray(resId); } } public String getStringResourceByName(String aString) { String packageName = getPackageName(); int resId = getResources().getIdentifier(aString, "string", packageName); if (resId == 0) { return aString; } else { return getString(resId); } } public void applyLocaleSettings(){ SharedPreferences settings = getPrefs(); Configuration config = getBaseContext().getResources().getConfiguration(); String lang = settings.getString("pref_locale", ""); if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) { String parts[] = lang.split("-r"); if (parts.length > 1) { // Language + country code locale = new Locale(parts[0], parts[1]); } else { // Just the language code locale = new Locale(lang); } }else{ locale = deviceLocale; } Locale.setDefault(locale); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } public void restart(){ Intent i = getBaseContext().getPackageManager() .getLaunchIntentForPackage( getBaseContext().getPackageName() ); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Configuration config = new Configuration(newConfig); if (locale != null) { config.locale = locale; Locale.setDefault(locale); getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } } public static Context getAppContext() { return INaturalistApp.context; } public void setIsSyncing(boolean isSyncing) { mIsSyncing = isSyncing; } public void checkSyncNeeded() { Cursor oCursor = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_synced_at IS NULL OR (_updated_at > _synced_at)", null, Observation.DEFAULT_SORT_ORDER); Cursor opCursor = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_synced_at IS NULL OR (_updated_at > _synced_at)", null, ObservationPhoto.DEFAULT_SORT_ORDER); if (!mIsSyncing) { mNotificationManager.cancel(SYNC_NOTIFICATION); } else { Resources res = getResources(); serviceNotify(SYNC_NOTIFICATION, res.getString(R.string.sync_required), String.format(res.getString(R.string.sync_required_message), oCursor.getCount(), opCursor.getCount()), null, new Intent(INaturalistService.ACTION_SYNC, null, this, INaturalistService.class)); } } public boolean loggedIn() { return getPrefs().contains("credentials"); } public LoginType getLoginType() { return LoginType.valueOf(getPrefs().getString("login_type", LoginType.PASSWORD.toString())); } public String currentUserLogin() { return getPrefs().getString("username", null); } public SharedPreferences getPrefs() { if (mPrefs == null) { mPrefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); } return mPrefs; } public void notify(Integer id, String title, String content) { notify(id, title, content, null); } public void notify(Integer id, String title, String content, String ticker) { Intent intent = new Intent(this, ObservationListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); notify(id, title, content, ticker, intent); } public void sweepingNotify(Integer id, String title, String content, String ticker, Intent intent) { if (mNotificationManager != null) { mNotificationManager.cancelAll(); } notify(id, title, content, ticker, intent); } public void sweepingNotify(Integer id, String title, String content, String ticker) { if (mNotificationManager != null) { mNotificationManager.cancelAll(); } notify(id, title, content, ticker); } public void notify(Integer id, String title, String content, String ticker, Intent intent) { PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); notify(id, title, content, ticker, pendingIntent); } public void serviceNotify(Integer id, String title, String content, String ticker, Intent intent) { PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); notify(id, title, content, ticker, pendingIntent); } public void notify(Integer id, String title, String content, String ticker, PendingIntent pendingIntent) { if (mNotificationManager == null) { mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } Notification notification = new Notification(R.drawable.ic_stat_inaturalist, ticker, System.currentTimeMillis()); notification.setLatestEventInfo(getApplicationContext(), title, content, pendingIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(id, notification); } public String formatDate(Timestamp date) { return DATE_FORMAT.format(date); } public String formatDatetime(Timestamp date) { return DATETIME_FORMAT.format(date); } public String shortFormatDate(Timestamp date) { SimpleDateFormat f; if (Locale.getDefault().getCountry().equals("US")) { f = new SimpleDateFormat("MMM d, yyyy"); } else { f = SHORT_DATE_FORMAT; } return f.format(date); } public String shortFormatTime(Timestamp date) { return SHORT_TIME_FORMAT.format(date); } }
package soot.jimple.internal; import soot.*; import soot.jimple.*; import java.util.*; public class JInterfaceInvokeExpr extends AbstractInterfaceInvokeExpr { public JInterfaceInvokeExpr(Value base, SootMethodRef methodRef, List args) { super(Jimple.v().newLocalBox(base), methodRef, new ValueBox[args.size()]); if(!methodRef.declaringClass().isInterface() && !methodRef.declaringClass().isPhantom()) { throw new RuntimeException("Trying to create interface invoke expression for non-interface type: " + methodRef.declaringClass() + " Use JVirtualInvokeExpr or JSpecialInvokeExpr instead!"); } for(int i = 0; i < args.size(); i++) this.argBoxes[i] = Jimple.v().newImmediateBox((Value) args.get(i)); } public Object clone() { List argList = new ArrayList(getArgCount()); for(int i = 0; i < getArgCount(); i++) { argList.add(i, Jimple.cloneIfNecessary(getArg(i))); } return new JInterfaceInvokeExpr(Jimple.cloneIfNecessary(getBase()), methodRef, argList); } }
package org.jetbrains.plugins.groovy.util; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.Nls; import javax.swing.*; import java.awt.*; /** * @author peter */ public abstract class SdkHomeConfigurable implements Configurable { private JPanel myPanel; private TextFieldWithBrowseButton myPathField; protected final Project myProject; protected final String myFrameworkName; public SdkHomeConfigurable(Project project, final String frameworkName) { myProject = project; myFrameworkName = frameworkName; } @Nls public String getDisplayName() { return myFrameworkName; } public JComponent createComponent() { if (myPanel != null) { return myPanel; } myPanel = new JPanel(new BorderLayout()); final JPanel contentPanel = new JPanel(new BorderLayout()); myPanel.add(contentPanel, BorderLayout.NORTH); contentPanel.add(new JLabel(myFrameworkName + " home:"), BorderLayout.WEST); myPathField = new TextFieldWithBrowseButton(); contentPanel.add(myPathField); myPathField .addBrowseFolderListener("Select " + myFrameworkName + " home", "", myProject, new FileChooserDescriptor(false, true, false, false, false, false) { @Override public boolean isFileSelectable(VirtualFile file) { return isSdkHome(file); } }); return myPanel; } protected abstract boolean isSdkHome(VirtualFile file); public boolean isModified() { return !myPathField.getText().equals(getStateText()); } public void apply() throws ConfigurationException { final SdkHomeSettings state = new SdkHomeSettings(); state.SDK_HOME = FileUtil.toSystemIndependentName(myPathField.getText()); getFrameworkSettings().loadState(state); } protected abstract PersistentStateComponent<SdkHomeSettings> getFrameworkSettings(); public void reset() { myPathField.setText(getStateText()); } private String getStateText() { final SdkHomeSettings state = getFrameworkSettings().getState(); final String stateText = state == null ? "" : state.SDK_HOME; return StringUtil.notNullize(FileUtil.toSystemDependentName(stateText)); } public void disposeUIResources() { } public static class SdkHomeSettings { public String SDK_HOME; } }
package org.jstrava.entities.activity; import org.jstrava.entities.segment.SegmentEffort; import org.jstrava.entities.athlete.Athlete; import java.util.List; import com.google.gson.annotations.SerializedName; public class Activity { private int id; private int resource_state; private String external_id; private int upload_id; private Athlete athlete;/*Simple Athlete representation with just id*/ private String name; private float distance; private int moving_time; private int elapsed_time; private float total_elevation_gain; private String type; private String start_date; private String start_date_local; private String timezone; private String[] start_latlng; private String[] end_latlng; private String location_city; private String location_state; private int achievement_count; private int kudos_count; private int comment_count; private int athlete_count; private int photo_count; private Polyline map; private boolean trainer; private boolean commute; private boolean manual; @SerializedName("private") private boolean PRIVATE; private boolean flagged; private String gear_id; private float average_speed; private float max_speed; private float average_cadence; private int average_temp; private float average_watts; private float kilojoules; private float average_heartrate; private float max_heartrate; private float calories; private int truncated; private boolean has_kudoed; private List<SegmentEffort> segment_efforts; private List<SplitsMetric> splits_metric; private List<SplitsStandard> splits_standard; private List<SegmentEffort> best_efforts; @Override public String toString() { return name; } public Activity() { } public Activity(int id) { this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getResource_state() { return resource_state; } public void setResource_state(int resource_state) { this.resource_state = resource_state; } public String getExternal_id() { return external_id; } public void setExternal_id(String external_id) { this.external_id = external_id; } public Athlete getAthlete() { return athlete; } public void setAthlete(Athlete athlete) { this.athlete = athlete; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getDistance() { return distance; } public void setDistance(float distance) { this.distance = distance; } public int getMoving_time() { return moving_time; } public void setMoving_time(int moving_time) { this.moving_time = moving_time; } public int getElapsed_time() { return elapsed_time; } public void setElapsed_time(int elapsed_time) { this.elapsed_time = elapsed_time; } public float getTotal_elevation_gain() { return total_elevation_gain; } public void setTotal_elevation_gain(float total_elevation_gain) { this.total_elevation_gain = total_elevation_gain; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public boolean isTrainer() { return trainer; } public boolean isCommute() { return commute; } public boolean isManual() { return manual; } public boolean isPRIVATE() { return PRIVATE; } public boolean isFlagged() { return flagged; } public boolean isHas_kudoed() { return has_kudoed; } public String getStart_date_local() { return start_date_local; } public void setStart_date_local(String start_date_local) { this.start_date_local = start_date_local; } public String getTime_zone() { return timezone; } public void setTime_zone(String timezone) { this.timezone = timezone; } public String[] getStart_latlng() { return start_latlng; } public void setStart_latlng(String[] start_latlng) { this.start_latlng = start_latlng; } public String[] getEnd_latlng() { return end_latlng; } public void setEnd_latlng(String[] end_latlng) { this.end_latlng = end_latlng; } public String getLocation_city() { return location_city; } public void setLocation_city(String location_city) { this.location_city = location_city; } public String getLocation_state() { return location_state; } public void setLocation_state(String location_state) { this.location_state = location_state; } public int getAchievement_count() { return achievement_count; } public void setAchievement_count(int achievement_count) { this.achievement_count = achievement_count; } public int getKudos_count() { return kudos_count; } public void setKudos_count(int kudos_count) { this.kudos_count = kudos_count; } public int getComment_count() { return comment_count; } public void setComment_count(int comment_count) { this.comment_count = comment_count; } public int getAthlete_count() { return athlete_count; } public void setAthlete_count(int athlete_count) { this.athlete_count = athlete_count; } public int getPhoto_count() { return photo_count; } public void setPhoto_count(int photo_count) { this.photo_count = photo_count; } public Polyline getMap() { return map; } public void setMap(Polyline map) { this.map = map; } public boolean getTrainer() { return trainer; } public void setTrainer(boolean trainer) { this.trainer = trainer; } public boolean getCommute() { return commute; } public void setCommute(boolean commute) { this.commute = commute; } public boolean getManual() { return manual; } public void setManual(boolean manual) { this.manual = manual; } public boolean getPRIVATE() { return PRIVATE; } public void setPRIVATE(boolean PRIVATE) { this.PRIVATE = PRIVATE; } public boolean getFlagged() { return flagged; } public void setFlagged(boolean flagged) { this.flagged = flagged; } public String getGear_id() { return gear_id; } public void setGear_id(String gear_id) { this.gear_id = gear_id; } public float getAverage_speed() { return average_speed; } public void setAverage_speed(float average_speed) { this.average_speed = average_speed; } public float getMax_speed() { return max_speed; } public void setMax_speed(float max_speed) { this.max_speed = max_speed; } public float getAverage_cadence() { return average_cadence; } public void setAverage_cadence(float average_cadence) { this.average_cadence = average_cadence; } public int getAverage_temp() { return average_temp; } public void setAverage_temp(int average_temp) { this.average_temp = average_temp; } public float getAverage_watts() { return average_watts; } public void setAverage_watts(float average_watts) { this.average_watts = average_watts; } public float getKilojoules() { return kilojoules; } public void setKilojoules(float kilojoules) { this.kilojoules = kilojoules; } public float getAverage_heartrate() { return average_heartrate; } public void setAverage_heartrate(float average_heartrate) { this.average_heartrate = average_heartrate; } public float getMax_heartrate() { return max_heartrate; } public void setMax_heartrate(float max_heartrate) { this.max_heartrate = max_heartrate; } public float getCalories() { return calories; } public void setCalories(float calories) { this.calories = calories; } public int getTruncated() { return truncated; } public void setTruncated(int truncated) { this.truncated = truncated; } public boolean getHas_kudoed() { return has_kudoed; } public void setHas_kudoed(boolean has_kudoed) { this.has_kudoed = has_kudoed; } public List<SegmentEffort> getSegment_efforts() { return segment_efforts; } public void setSegment_efforts(List<SegmentEffort> segment_efforts) { this.segment_efforts = segment_efforts; } public List<SplitsMetric> getSplits_metric() { return splits_metric; } public void setSplits_metric(List<SplitsMetric> splits_metric) { this.splits_metric = splits_metric; } public List<SplitsStandard> getSplits_standard() { return splits_standard; } public void setSplits_standard(List<SplitsStandard> splits_standard) { this.splits_standard = splits_standard; } public List<SegmentEffort> getBest_efforts() { return best_efforts; } public void setBest_efforts(List<SegmentEffort> best_efforts) { this.best_efforts = best_efforts; } public int getUpload_id() { return upload_id; } public void setUpload_id(int upload_id) { this.upload_id = upload_id; } }
package org.mozilla.mozstumbler; import android.net.wifi.ScanResult; import android.util.Log; import java.util.Locale; import java.util.regex.Pattern; final class BSSIDBlockList { private static final String LOGTAG = BSSIDBlockList.class.getName(); private static final String NULL_BSSID = "000000000000"; private static final String WILDCARD_BSSID = "ffffffffffff"; private static final Pattern BSSID_PATTERN = Pattern.compile("([0-9a-f]{12})"); private static final String[] OUI_LIST = { // Some iPad and iPhone OUIs: "001b63", "0021e9", "74e2f5", "78d6f0", "7c6d62", "7cc537", "88c663", "8c7712", // Motorola Mobility OUIs: "1430c6", "34bb26", "60beb5", "b07994", "ccc3ea", "e0757d", "f8e079", "f8f1b6", // Adelaide Metro WiFi Network OUIs: "a854b2", }; private BSSIDBlockList() { } static boolean contains(ScanResult scanResult) { String BSSID = scanResult.BSSID; if (BSSID == null || NULL_BSSID.equals(BSSID) || WILDCARD_BSSID.equals(BSSID)) { return true; // blocked! } if (!isCanonicalBSSID(BSSID)) { Log.w(LOGTAG, "", new IllegalArgumentException("Unexpected BSSID format: " + BSSID)); return true; // blocked! } for (String oui : OUI_LIST) { if (BSSID.startsWith(oui)) { return true; // blocked! } } return false; } static String canonicalizeBSSID(String BSSID) { if (BSSID == null) { return ""; } if (isCanonicalBSSID(BSSID)) { return BSSID; } // Some devices may return BSSIDs with '-' or '.' delimiters. BSSID = BSSID.toLowerCase(Locale.US).replace(":", "") .replace("-", "") .replace(".", ""); return isCanonicalBSSID(BSSID) ? BSSID : ""; } private static boolean isCanonicalBSSID(String BSSID) { return BSSID_PATTERN.matcher(BSSID).matches(); } }
package org.newdawn.slick.state; import java.util.HashMap; import java.util.Iterator; import org.newdawn.slick.Game; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.InputListener; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.transition.EmptyTransition; import org.newdawn.slick.state.transition.Transition; /** * A state based game isolated different stages of the game (menu, ingame, hiscores, etc) into * different states so they can be easily managed and maintained. * * @author kevin * * * A class extendion was impossible so the class had to modificated * because all variables are private. */ public abstract class StateBasedGame implements Game, InputListener { /** The list of states making up this game */ private HashMap states = new HashMap(); /** The current state */ private GameState currentState; /** The Last state */ private GameState lastState; /** The next state we're moving into */ private GameState nextState; /** The container holding this game */ private GameContainer container; /** The title of the game */ private String title; /** The transition being used to enter the state */ private Transition enterTransition; /** The transition being used to leave the state */ private Transition leaveTransition; /** * Create a new state based game * * @param name The name of the game */ public StateBasedGame(String name) { this.title = name; currentState = new BasicGameState() { public int getID() { return -1; } public void init(GameContainer container, StateBasedGame game) throws SlickException { } public void render(StateBasedGame game, Graphics g) throws SlickException { } public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { } public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { } }; } /** * @see org.newdawn.slick.ControlledInputReciever#inputStarted() */ public void inputStarted() { } /** * Get the number of states that have been added to this game * * @return The number of states that have been added to this game */ public int getStateCount() { return states.keySet().size(); } /** * Get the ID of the state the game is currently in * * @return The ID of the state the game is currently in */ public int getCurrentStateID() { return currentState.getID(); } /** * Get the state the game is currently in * * @return The state the game is currently in */ public GameState getCurrentState() { return currentState; } /** * @see org.newdawn.slick.InputListener#setInput(org.newdawn.slick.Input) */ public void setInput(Input input) { } /** * Add a state to the game. The state will be updated and maintained * by the game * * @param state The state to be added */ public void addState(GameState state) { states.put(new Integer(state.getID()), state); if (currentState.getID() == -1) { currentState = state; } } /** * Get a state based on it's identifier * * @param id The ID of the state to retrieve * @return The state requested or null if no state with the specified ID exists */ public GameState getState(int id) { return (GameState) states.get(new Integer(id)); } /** * Enter a particular game state with no transition * Modification: Saves the last state * * @param id The ID of the state to enter */ public void enterState(int id) { enterState(id, new EmptyTransition(), new EmptyTransition()); } /** * Enter a particular game state with the transitions provided * * @param id The ID of the state to enter * @param leave The transition to use when leaving the current state * @param enter The transition to use when entering the new state */ public void enterState(int id, Transition leave, Transition enter) { if (leave == null) { leave = new EmptyTransition(); } if (enter == null) { enter = new EmptyTransition(); } leaveTransition = leave; enterTransition = enter; // All inputs only in the current state container.getInput().clearControlPressedRecord(); container.getInput().clearKeyPressedRecord(); container.getInput().clearMousePressedRecord(); lastState = currentState; nextState = getState(id); if (nextState == null) { throw new RuntimeException("No game state registered with the ID: "+id); } leaveTransition.init(currentState, nextState); } /** * @see org.newdawn.slick.BasicGame#init(org.newdawn.slick.GameContainer) */ public final void init(GameContainer container) throws SlickException { this.container = container; initStatesList(container); Iterator gameStates = states.values().iterator(); while (gameStates.hasNext()) { GameState state = (GameState) gameStates.next(); state.init(container, this); } if (currentState != null) { currentState.enter(container, this); } } /** * Initialise the list of states making up this game * * @param container The container holding the game * @throws SlickException Indicates a failure to initialise the state based game resources */ public abstract void initStatesList(GameContainer container) throws SlickException; /** * @see org.newdawn.slick.Game#render(org.newdawn.slick.GameContainer, org.newdawn.slick.Graphics) */ public final void render(GameContainer container, Graphics g) throws SlickException { preRenderState(container, g); if (leaveTransition != null) { leaveTransition.preRender(this, container, g); } else if (enterTransition != null) { enterTransition.preRender(this, container, g); } currentState.render(container, this, g); if (leaveTransition != null) { leaveTransition.postRender(this, container, g); } else if (enterTransition != null) { enterTransition.postRender(this, container, g); } postRenderState(container, g); } /** * User hook for rendering at the before the current state * and/or transition have been rendered * * @param container The container in which the game is hosted * @param g The graphics context on which to draw * @throws SlickException Indicates a failure within render */ protected void preRenderState(GameContainer container, Graphics g) throws SlickException { // NO-OP } /** * User hook for rendering at the game level after the current state * and/or transition have been rendered * * @param container The container in which the game is hosted * @param g The graphics context on which to draw * @throws SlickException Indicates a failure within render */ protected void postRenderState(GameContainer container, Graphics g) throws SlickException { // NO-OP } /** * @see org.newdawn.slick.BasicGame#update(org.newdawn.slick.GameContainer, int) */ public final void update(GameContainer container, int delta) throws SlickException { preUpdateState(container, delta); if (leaveTransition != null) { leaveTransition.update(this, container, delta); if (leaveTransition.isComplete()) { currentState.leave(container, this); GameState prevState = currentState; currentState = nextState; nextState = null; leaveTransition = null; if (enterTransition == null) { currentState.enter(container, this); } else { enterTransition.init(currentState, prevState); } } else { return; } } if (enterTransition != null) { enterTransition.update(this, container, delta); if (enterTransition.isComplete()) { currentState.enter(container, this); enterTransition = null; } else { return; } } currentState.update(container, this, delta); postUpdateState(container, delta); } /** * User hook for updating at the game before the current state * and/or transition have been updated * * @param container The container in which the game is hosted * @param delta The amount of time in milliseconds since last update * @throws SlickException Indicates a failure within render */ protected void preUpdateState(GameContainer container, int delta) throws SlickException { // NO-OP } /** * User hook for rendering at the game level after the current state * and/or transition have been updated * * @param container The container in which the game is hosted * @param delta The amount of time in milliseconds since last update * @throws SlickException Indicates a failure within render */ protected void postUpdateState(GameContainer container, int delta) throws SlickException { // NO-OP } /** * Check if the game is transitioning between states * * @return True if we're transitioning between states */ private boolean transitioning() { return (leaveTransition != null) || (enterTransition != null); } /** * @see org.newdawn.slick.Game#closeRequested() */ public boolean closeRequested() { return true; } /** * @see org.newdawn.slick.Game#getTitle() */ public String getTitle() { return title; } /** * Get the container holding this game * * @return The game container holding this game */ public GameContainer getContainer() { return container; } /** * @see org.newdawn.slick.InputListener#controllerButtonPressed(int, int) */ public void controllerButtonPressed(int controller, int button) { if (transitioning()) { return; } currentState.controllerButtonPressed(controller, button); } /** * @see org.newdawn.slick.InputListener#controllerButtonReleased(int, int) */ public void controllerButtonReleased(int controller, int button) { if (transitioning()) { return; } currentState.controllerButtonReleased(controller, button); } /** * @see org.newdawn.slick.InputListener#controllerDownPressed(int) */ public void controllerDownPressed(int controller) { if (transitioning()) { return; } currentState.controllerDownPressed(controller); } /** * @see org.newdawn.slick.InputListener#controllerDownReleased(int) */ public void controllerDownReleased(int controller) { if (transitioning()) { return; } currentState.controllerDownReleased(controller); } /** * @see org.newdawn.slick.InputListener#controllerLeftPressed(int) */ public void controllerLeftPressed(int controller) { if (transitioning()) { return; } currentState.controllerLeftPressed(controller); } /** * @see org.newdawn.slick.InputListener#controllerLeftReleased(int) */ public void controllerLeftReleased(int controller) { if (transitioning()) { return; } currentState.controllerLeftReleased(controller); } /** * @see org.newdawn.slick.InputListener#controllerRightPressed(int) */ public void controllerRightPressed(int controller) { if (transitioning()) { return; } currentState.controllerRightPressed(controller); } /** * @see org.newdawn.slick.InputListener#controllerRightReleased(int) */ public void controllerRightReleased(int controller) { if (transitioning()) { return; } currentState.controllerRightReleased(controller); } /** * @see org.newdawn.slick.InputListener#controllerUpPressed(int) */ public void controllerUpPressed(int controller) { if (transitioning()) { return; } currentState.controllerUpPressed(controller); } /** * @see org.newdawn.slick.InputListener#controllerUpReleased(int) */ public void controllerUpReleased(int controller) { if (transitioning()) { return; } currentState.controllerUpReleased(controller); } /** * @see org.newdawn.slick.InputListener#keyPressed(int, char) */ public void keyPressed(int key, char c) { if (transitioning()) { return; } currentState.keyPressed(key, c); } /** * @see org.newdawn.slick.InputListener#keyReleased(int, char) */ public void keyReleased(int key, char c) { if (transitioning()) { return; } currentState.keyReleased(key, c); } /** * @see org.newdawn.slick.InputListener#mouseMoved(int, int, int, int) */ public void mouseMoved(int oldx, int oldy, int newx, int newy) { if (transitioning()) { return; } currentState.mouseMoved(oldx, oldy, newx, newy); } /** * @see org.newdawn.slick.InputListener#mouseDragged(int, int, int, int) */ public void mouseDragged(int oldx, int oldy, int newx, int newy) { if (transitioning()) { return; } currentState.mouseDragged(oldx, oldy, newx, newy); } /** * @see org.newdawn.slick.InputListener#mouseClicked(int, int, int, int) */ public void mouseClicked(int button, int x, int y, int clickCount) { if (transitioning()) { return; } currentState.mouseClicked(button, x, y, clickCount); } /** * @see org.newdawn.slick.InputListener#mousePressed(int, int, int) */ public void mousePressed(int button, int x, int y) { if (transitioning()) { return; } currentState.mousePressed(button, x, y); } /** * @see org.newdawn.slick.InputListener#mouseReleased(int, int, int) */ public void mouseReleased(int button, int x, int y) { if (transitioning()) { return; } currentState.mouseReleased(button, x, y); } /** * @see org.newdawn.slick.InputListener#isAcceptingInput() */ public boolean isAcceptingInput() { if (transitioning()) { return false; } return currentState.isAcceptingInput(); } /** * @see org.newdawn.slick.InputListener#inputEnded() */ public void inputEnded() { } /** * @see org.newdawn.slick.InputListener#mouseWheelMoved(int) */ public void mouseWheelMoved(int newValue) { if (transitioning()) { return; } currentState.mouseWheelMoved(newValue); } /** * Returns the state before the current state */ public GameState getLastState() { return lastState; } /** * Returns the id of the state before the current state */ public int getLastStateID() { return lastState.getID(); } /** * Enters to the LastState-State */ public void enterLastState() { enterState(getLastStateID()); } }
package org.jkiss.dbeaver.model.sql; import org.eclipse.core.resources.IFile; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPObject; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.DBCLogicalOperator; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect; import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration; import org.jkiss.dbeaver.model.sql.format.tokenized.SQLTokenizedFormatter; import org.jkiss.dbeaver.model.struct.DBSAttributeBase; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.DBSTypedObject; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.Pair; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SQL Utils */ public final class SQLUtils { private static final Log log = Log.getLog(SQLUtils.class); public static final Pattern PATTERN_OUT_PARAM = Pattern.compile("((\\?)|(:[a-z0-9]+))\\s*:="); public static final Pattern CREATE_PREFIX_PATTERN = Pattern.compile("(CREATE (:OR REPLACE)?).+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public static final int MIN_SQL_DESCRIPTION_LENGTH = 512; public static final int MAX_SQL_DESCRIPTION_LENGTH = 500; public static String stripTransformations(String query) { return query; // if (!query.contains(TOKEN_TRANSFORM_START)) { // return query; // } else { // return PATTERN_XFORM.matcher(query).replaceAll(""); } public static String stripComments(SQLDialect dialect, String query) { Pair<String, String> multiLineComments = dialect.getMultiLineComments(); return stripComments( query, multiLineComments == null ? null : multiLineComments.getFirst(), multiLineComments == null ? null : multiLineComments.getSecond(), dialect.getSingleLineComments()); } public static String stripComments(String query, @Nullable String mlCommentStart, @Nullable String mlCommentEnd, String[] slComments) { String leading = "", trailing = ""; { int startPos, endPos; for (startPos = 0; startPos < query.length(); startPos++) { if (!Character.isWhitespace(query.charAt(startPos))) { break; } } for (endPos = query.length() - 1; endPos > startPos; endPos if (!Character.isWhitespace(query.charAt(endPos))) { break; } } if (startPos > 0) { leading = query.substring(0, startPos); } if (endPos < query.length() - 1) { trailing = query.substring(endPos + 1); } } query = query.trim(); if (mlCommentStart != null && mlCommentEnd != null) { Pattern stripPattern = Pattern.compile( "(\\s*" + Pattern.quote(mlCommentStart) + "[^" + Pattern.quote(mlCommentEnd) + "]*" + Pattern.quote(mlCommentEnd) + "\\s*)[^" + Pattern.quote(mlCommentStart) + "]*"); Matcher matcher = stripPattern.matcher(query); if (matcher.matches()) { query = query.substring(matcher.end(1)); } } for (String slComment : slComments) { while (query.startsWith(slComment)) { int crPos = query.indexOf('\n'); if (crPos == -1) { break; } else { query = query.substring(crPos).trim(); } } } return leading + query + trailing; } public static List<String> splitFilter(String filter) { if (CommonUtils.isEmpty(filter)) { return Collections.emptyList(); } return CommonUtils.splitString(filter, ','); } public static boolean matchesAnyLike(String string, Collection<String> likes) { for (String like : likes) { if (matchesLike(string, like)) { return true; } } return false; } public static String makeLikePattern(String like) { return like.replace("%", ".*").replace("_", ".?"); } public static boolean matchesLike(String string, String like) { Pattern pattern = Pattern.compile(makeLikePattern(like), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); return pattern.matcher(string).matches(); } public static void appendValue(StringBuilder buffer, DBSTypedObject type, Object value) { if (type.getDataKind() == DBPDataKind.NUMERIC || type.getDataKind() == DBPDataKind.BOOLEAN) { buffer.append(value); } else { buffer.append('\'').append(value).append('\''); } } public static String quoteString(String string) { return "'" + string.replaceAll("'", "''") + "'"; } public static String escapeString(String string) { return string.replaceAll("'", "\\'"); } public static String getFirstKeyword(String query) { int startPos = 0, endPos = -1; for (int i = 0; i < query.length(); i++) { if (Character.isLetterOrDigit(query.charAt(i))) { startPos = i; break; } } for (int i = startPos; i < query.length(); i++) { if (Character.isWhitespace(query.charAt(i))) { endPos = i; break; } } if (endPos == -1) { return query; } return query.substring(startPos, endPos); } @Nullable public static String getQueryOutputParameter(DBCSession session, String query) { final Matcher matcher = PATTERN_OUT_PARAM.matcher(query); if (matcher.find()) { return matcher.group(1); } return null; } /** * Removes \\r characters from query. * Actually this is done specially for Oracle due to some bug in it's driver * * @param query query * @return normalized query */ public static String makeUnifiedLineFeeds(String query) { if (query.indexOf('\r') == -1) { return query; } StringBuilder result = new StringBuilder(query.length()); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if (c == '\r') { continue; } result.append(c); } return result.toString(); } public static String formatSQL(SQLDataSource dataSource, String query) { SQLSyntaxManager syntaxManager = new SQLSyntaxManager(); syntaxManager.init(dataSource.getSQLDialect(), dataSource.getContainer().getPreferenceStore()); SQLFormatterConfiguration configuration = new SQLFormatterConfiguration(syntaxManager); return new SQLTokenizedFormatter().format(query, configuration); } public static void appendLikeCondition(StringBuilder sql, String value, boolean not) { if (value.contains("%") || value.contains("_")) { if (not) sql.append(" NOT"); sql.append(" LIKE ?"); } else { sql.append(not ? "<>?": "=?"); } } public static boolean appendFirstClause(StringBuilder sql, boolean firstClause) { if (firstClause) { sql.append(" WHERE "); } else { sql.append(" AND "); } return false; } public static String trimQueryStatement(SQLSyntaxManager syntaxManager, String sql) { sql = sql.trim(); for (String statementDelimiter : syntaxManager.getStatementDelimiters()) { if (sql.endsWith(statementDelimiter) && sql.length() > statementDelimiter.length()) { if (Character.isAlphabetic(statementDelimiter.charAt(0))) { // Delimiter is alphabetic (e.g. "GO") so it must be prefixed with whitespace char lastChar = sql.charAt(sql.length() - statementDelimiter.length() - 1); if (Character.isUnicodeIdentifierPart(lastChar)) { return sql; } } // Remove trailing delimiter only if it is not block end String trimmed = sql.substring(0, sql.length() - statementDelimiter.length()); String test = trimmed.toUpperCase().trim(); if (!test.endsWith(SQLConstants.BLOCK_END)) { sql = trimmed; } } } return sql; } @NotNull public static SQLDialect getDialectFromObject(DBPObject object) { if (object instanceof DBSObject) { DBPDataSource dataSource = ((DBSObject)object).getDataSource(); if (dataSource instanceof SQLDataSource) { return ((SQLDataSource) dataSource).getSQLDialect(); } } return BasicSQLDialect.INSTANCE; } public static void appendConditionString( @NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query, boolean inlineCriteria) { String operator = filter.isAnyConstraint() ? " OR " : " AND "; //$NON-NLS-1$ $NON-NLS-2$ boolean hasWhere = false; for (DBDAttributeConstraint constraint : filter.getConstraints()) { String condition = getConstraintCondition(dataSource, constraint, inlineCriteria); if (condition == null) { continue; } if (hasWhere) query.append(operator); hasWhere = true; if (conditionTable != null) { query.append(conditionTable).append('.'); } query.append(DBUtils.getObjectFullName(dataSource, constraint.getAttribute())); query.append(' ').append(condition); } if (!CommonUtils.isEmpty(filter.getWhere())) { if (hasWhere) query.append(operator); query.append(filter.getWhere()); } } public static void appendOrderString(@NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query) { // Construct ORDER BY boolean hasOrder = false; for (DBDAttributeConstraint co : filter.getOrderConstraints()) { if (hasOrder) query.append(','); if (conditionTable != null) { query.append(conditionTable).append('.'); } query.append(DBUtils.getObjectFullName(co.getAttribute())); if (co.isOrderDescending()) { query.append(" DESC"); //$NON-NLS-1$ } hasOrder = true; } if (!CommonUtils.isEmpty(filter.getOrder())) { if (hasOrder) query.append(','); query.append(filter.getOrder()); } } @Nullable public static String getConstraintCondition(DBPDataSource dataSource, DBDAttributeConstraint constraint, boolean inlineCriteria) { String criteria = constraint.getCriteria(); if (!CommonUtils.isEmpty(criteria)) { final char firstChar = criteria.trim().charAt(0); if (!Character.isLetter(firstChar) && firstChar != '=' && firstChar != '>' && firstChar != '<' && firstChar != '!') { return '=' + criteria; } else { return criteria; } } else if (constraint.getOperator() != null) { DBCLogicalOperator operator = constraint.getOperator(); StringBuilder conString = new StringBuilder(); if (constraint.isReverseOperator()) { conString.append("NOT "); } conString.append(operator.getStringValue()); if (operator.getArgumentCount() > 0) { for (int i = 0; i < operator.getArgumentCount(); i++) { if (i > 0) { conString.append(" AND"); } if (inlineCriteria) { conString.append(' ').append(convertValueToSQL(dataSource, constraint.getAttribute(), constraint.getValue())); } else { conString.append(" ?"); } } } return conString.toString(); } else { return null; } } public static String convertValueToSQL(DBPDataSource dataSource, DBSAttributeBase attribute, @Nullable Object value) { if (DBUtils.isNullValue(value)) { return SQLConstants.NULL_VALUE; } DBDValueHandler valueHandler = DBUtils.findValueHandler(dataSource, attribute); String strValue = valueHandler.getValueDisplayString(attribute, value, DBDDisplayFormat.NATIVE); SQLDialect sqlDialect = null; if (dataSource instanceof SQLDataSource) { sqlDialect = ((SQLDataSource) dataSource).getSQLDialect(); } if (value instanceof Number) { return strValue; } switch (attribute.getDataKind()) { case BOOLEAN: case NUMERIC: return strValue; case CONTENT: if (value instanceof DBDContent) { if (!ContentUtils.isTextContent((DBDContent) value)) { return "[BLOB]"; } } case STRING: case ROWID: if (sqlDialect != null) { strValue = sqlDialect.escapeString(strValue); } return '\'' + strValue + '\''; default: if (sqlDialect != null) { return sqlDialect.escapeScriptValue(attribute, value, strValue); } return strValue; } } public static String getColumnTypeModifiers(DBSAttributeBase column, String typeName, DBPDataKind dataKind) { if (dataKind == DBPDataKind.STRING) { if (typeName.indexOf('(') == -1) { final long maxLength = column.getMaxLength(); if (maxLength > 0) { return "(" + maxLength + ")"; } } } else if (dataKind == DBPDataKind.CONTENT) { final long maxLength = column.getMaxLength(); if (maxLength > 0) { return "(" + maxLength + ')'; } } else if (dataKind == DBPDataKind.NUMERIC) { if (typeName.equalsIgnoreCase("DECIMAL") || typeName.equalsIgnoreCase("NUMERIC") || typeName.equalsIgnoreCase("NUMBER")) { int scale = column.getScale(); int precision = column.getPrecision(); if (scale >= 0 && precision >= 0 && !(scale == 0 && precision == 0)) { return "(" + precision + ',' + scale + ')'; } } } return null; } public static boolean isExecQuery(@NotNull SQLDialect dialect, String query) { // Check for EXEC query final Collection<String> executeKeywords = dialect.getExecuteKeywords(); if (!CommonUtils.isEmpty(executeKeywords)) { final String queryStart = getFirstKeyword(query); for (String keyword : executeKeywords) { if (keyword.equalsIgnoreCase(queryStart)) { return true; } } } return false; } public static String getScriptDescripion(String sql) { sql = stripComments(BasicSQLDialect.INSTANCE, sql); Matcher matcher = CREATE_PREFIX_PATTERN.matcher(sql); if (matcher.find() && matcher.start(0) == 0) { sql = sql.substring(matcher.end(1)); } sql = sql.replaceAll(" +", " "); if (sql.length() > MAX_SQL_DESCRIPTION_LENGTH) { sql = sql.substring(0, MAX_SQL_DESCRIPTION_LENGTH) + " ..."; } return sql; } @Nullable public static String getScriptDescription(@NotNull IFile sqlScript) { try { //log.debug("Read script '" + sqlScript.getName() + "' description"); StringBuilder sql = new StringBuilder(); try (BufferedReader is = new BufferedReader(new InputStreamReader(sqlScript.getContents()))) { for (;;) { String line = is.readLine(); if (line == null) { break; } line = line.trim(); if (line.startsWith(" line.startsWith("Rem") || line.startsWith("rem") || line.startsWith("REM") ) { continue; } sql.append(line).append('\n'); if (sql.length() > MIN_SQL_DESCRIPTION_LENGTH) { break; } } } return SQLUtils.getScriptDescripion(sql.toString()); } catch (Exception e) { log.warn("", e); } return null; } }
package org.nutz.lang.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.nutz.aop.ClassDefiner; import org.nutz.aop.DefaultClassDefiner; import org.nutz.lang.Mirror; import org.nutz.repo.org.objectweb.asm.ClassWriter; import org.nutz.repo.org.objectweb.asm.MethodVisitor; import org.nutz.repo.org.objectweb.asm.Opcodes; import org.nutz.repo.org.objectweb.asm.Type; public final class FastClassFactory implements Opcodes { private static ClassDefiner classDefiner = new DefaultClassDefiner(FastClassFactory.class.getClassLoader()); private static AtomicInteger count = new AtomicInteger(); public static final String MethodArray_FieldName = "_$$Fast_methodArray"; public static final String ConstructorArray_FieldName = "_$$Fast_constructorArray"; public static final String SrcClass_FieldName = "_$$Fast_srcClass"; public static final String FieldNameArray_FieldName = "_$$Fast_fieldNames"; public static Map<String, FastClass> cache = new ConcurrentHashMap<String, FastClass>(); private static final Object lock = new Object(); public static FastClass get(Class<?> klass) { String cacheKey = klass.getName() + "_" + klass.getClassLoader(); FastClass fastClass = cache.get(cacheKey); if (fastClass != null) { return fastClass; } synchronized (lock) { fastClass = cache.get(cacheKey); if (fastClass != null) { return fastClass; } Class<?> fclass = create(klass); try { fastClass = (FastClass) fclass.newInstance(); cache.put(cacheKey, fastClass); return fastClass; } catch (Exception e) { throw new IllegalArgumentException("Fail to create FastClass for " + cacheKey, e); } } } protected static synchronized Class<?> create(Class<?> classZ) { String myName = FastClass.CLASSNAME + count.getAndIncrement(); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(V1_6, ACC_PUBLIC, myName, null, "org/nutz/lang/reflect/AbstractFastClass", null); { MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "org/nutz/lang/reflect/AbstractFastClass", "<init>", "()V"); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } { cw.visitField(ACC_PUBLIC + ACC_STATIC, FastClassFactory.MethodArray_FieldName, "[Ljava/lang/reflect/Method;", null, null).visitEnd(); cw.visitField(ACC_PUBLIC + ACC_STATIC, ConstructorArray_FieldName, "[Ljava/lang/reflect/Constructor;", null, null).visitEnd(); cw.visitField(ACC_PUBLIC + ACC_STATIC, SrcClass_FieldName, "Ljava/lang/Class;", "Ljava/lang/Class<*>;", null).visitEnd(); } // getter { MethodVisitor mv = cw.visitMethod(ACC_PROTECTED, "getMethods", "()[Ljava/lang/reflect/Method;", null, null); mv.visitCode(); mv.visitFieldInsn(GETSTATIC, myName, FastClassFactory.MethodArray_FieldName, "[Ljava/lang/reflect/Method;"); mv.visitInsn(ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(ACC_PROTECTED, "getConstructors", "()[Ljava/lang/reflect/Constructor;", "()[Ljava/lang/reflect/Constructor<*>;", null); mv.visitCode(); mv.visitFieldInsn(GETSTATIC, myName, ConstructorArray_FieldName, "[Ljava/lang/reflect/Constructor;"); mv.visitInsn(ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(ACC_PROTECTED, "getSrcClass", "()Ljava/lang/Class;", "()Ljava/lang/Class<*>;", null); mv.visitCode(); mv.visitFieldInsn(GETSTATIC, myName, SrcClass_FieldName, "Ljava/lang/Class;"); mv.visitInsn(ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } Method[] methods = classZ.getMethods(); Arrays.sort(methods, new MethodComparator()); // _invoke { String[] methodNames = new String[methods.length]; String[] descs = new String[methods.length]; int[] modifies = new int[methods.length]; int[] invokeOps = new int[methods.length]; for (int i = 0; i < methods.length; i++) { methodNames[i] = methods[i].getName(); descs[i] = Type.getMethodDescriptor(methods[i]); modifies[i] = methods[i].getModifiers(); if (classZ.isInterface()) invokeOps[i] = INVOKEINTERFACE; else if (Modifier.isAbstract(methods[i].getModifiers())) invokeOps[i] = INVOKESPECIAL; else if (Modifier.isStatic(methods[i].getModifiers())) invokeOps[i] = INVOKESTATIC; else invokeOps[i] = INVOKEVIRTUAL; } FastClassAdpter.createInokeMethod(cw.visitMethod(ACC_PUBLIC + ACC_VARARGS, "_invoke", "(Ljava/lang/Object;I[Ljava/lang/Object;)Ljava/lang/Object;", null, null), methodNames, descs, modifies, invokeOps, classZ.getName() .replace('.', '/')); } // _born Constructor<?>[] constructors = classZ.getConstructors(); Arrays.sort(constructors, new ConstructorComparator()); if (constructors.length > 0) { FastClassAdpter.createInokeConstructor(cw.visitMethod(ACC_PROTECTED + ACC_VARARGS, "_born", "(I[Ljava/lang/Object;)Ljava/lang/Object;", null, null), classZ.getName() .replace('.', '/'), constructors); } cw.visitEnd(); Class<?> xClass = classDefiner.define(myName.replace('/', '.'), cw.toByteArray()); try { xClass.getField(SrcClass_FieldName).set(null, classZ); xClass.getField(MethodArray_FieldName).set(null, methods); xClass.getField(ConstructorArray_FieldName).set(null, constructors); } catch (Throwable e) { e.printStackTrace(); } return xClass; } // public static void main(String[] args) throws Throwable { // ASMifierClassVisitor.main(new String[]{"org.nutz.lang.reflect.XXX"}); // System.out.println(Type.getObjectType(AbstractFastClass.class.getName().replace('.', } class Util { public static int compara(Class<?>[] mps1, Class<?>[] mps2) { if (mps1.length > mps2.length) return 1; if (mps1.length < mps2.length) return -1; for (int i = 0; i < mps1.length; i++) { if (mps1[i] == mps2[i]) continue; if (mps1[i].isPrimitive() && (!mps2[i].isPrimitive())) return -1; else if (mps2[i].isPrimitive() && (!mps1[i].isPrimitive())) return 1; if (mps1[i].isPrimitive() || mps2[i].isPrimitive()) if (Mirror.me(mps1[i]).getWrapper() == Mirror.me(mps2[i]) .getWrapper()) { if (mps1[i].isPrimitive()) return -1; else return 1; } if (mps2[i].isAssignableFrom(mps1[i])) return 1; } return 0; } } class ConstructorComparator implements Comparator<Constructor<?>> { public int compare(Constructor<?> c1, Constructor<?> c2) { if (c1 == c2) return 0; if (!c1.getName().equals(c2.getName())) return c1.getName().compareTo(c2.getName()); return Util.compara(c1.getParameterTypes(), c2.getParameterTypes()); } } class MethodComparator implements Comparator<Method> { public int compare(Method m1, Method m2) { if (m1 == m2) return 0; if (!m1.getName().equals(m2.getName())) return m1.getName().compareTo(m2.getName()); return Util.compara(m1.getParameterTypes(), m2.getParameterTypes()); } }
package org.jkiss.dbeaver.model.sql; import org.eclipse.core.resources.IFile; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPObject; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.DBCLogicalOperator; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect; import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration; import org.jkiss.dbeaver.model.sql.format.tokenized.SQLTokenizedFormatter; import org.jkiss.dbeaver.model.struct.DBSAttributeBase; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.DBSTypedObject; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.Pair; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SQL Utils */ public final class SQLUtils { static final Log log = Log.getLog(SQLUtils.class); public static final Pattern PATTERN_OUT_PARAM = Pattern.compile("((\\?)|(:[a-z0-9]+))\\s*:="); public static final Pattern CREATE_PREFIX_PATTERN = Pattern.compile("(CREATE (:OR REPLACE)?).+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public static final int MIN_SQL_DESCRIPTION_LENGTH = 512; public static final int MAX_SQL_DESCRIPTION_LENGTH = 500; public static String stripTransformations(String query) { return query; // if (!query.contains(TOKEN_TRANSFORM_START)) { // return query; // } else { // return PATTERN_XFORM.matcher(query).replaceAll(""); } public static String stripComments(SQLDialect dialect, String query) { Pair<String, String> multiLineComments = dialect.getMultiLineComments(); return stripComments( query, multiLineComments == null ? null : multiLineComments.getFirst(), multiLineComments == null ? null : multiLineComments.getSecond(), dialect.getSingleLineComments()); } public static String stripComments(String query, @Nullable String mlCommentStart, @Nullable String mlCommentEnd, String[] slComments) { query = query.trim(); if (mlCommentStart != null && mlCommentEnd != null) { Pattern stripPattern = Pattern.compile( "(\\s*" + Pattern.quote(mlCommentStart) + "[^" + Pattern.quote(mlCommentEnd) + "]*" + Pattern.quote(mlCommentEnd) + "\\s*)[^" + Pattern.quote(mlCommentStart) + "]*"); Matcher matcher = stripPattern.matcher(query); if (matcher.matches()) { query = query.substring(matcher.end(1)); } } for (String slComment : slComments) { while (query.startsWith(slComment)) { int crPos = query.indexOf('\n'); if (crPos == -1) { break; } else { query = query.substring(crPos).trim(); } } } return query; } public static List<String> splitFilter(String filter) { if (CommonUtils.isEmpty(filter)) { return Collections.emptyList(); } return CommonUtils.splitString(filter, ','); } public static boolean matchesAnyLike(String string, Collection<String> likes) { for (String like : likes) { if (matchesLike(string, like)) { return true; } } return false; } public static String makeLikePattern(String like) { return like.replace("%", ".*").replace("_", ".?"); } public static boolean matchesLike(String string, String like) { Pattern pattern = Pattern.compile(makeLikePattern(like), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); return pattern.matcher(string).matches(); } public static void appendValue(StringBuilder buffer, DBSTypedObject type, Object value) { if (type.getDataKind() == DBPDataKind.NUMERIC || type.getDataKind() == DBPDataKind.BOOLEAN) { buffer.append(value); } else { buffer.append('\'').append(value).append('\''); } } public static String quoteString(String string) { return "'" + string.replaceAll("'", "''") + "'"; } public static String escapeString(String string) { return string.replaceAll("'", "\\'"); } public static String getFirstKeyword(String query) { int startPos = 0, endPos = -1; for (int i = 0; i < query.length(); i++) { if (Character.isLetterOrDigit(query.charAt(i))) { startPos = i; break; } } for (int i = startPos; i < query.length(); i++) { if (Character.isWhitespace(query.charAt(i))) { endPos = i; break; } } if (endPos == -1) { return query; } return query.substring(startPos, endPos); } @Nullable public static String getQueryOutputParameter(DBCSession session, String query) { final Matcher matcher = PATTERN_OUT_PARAM.matcher(query); if (matcher.find()) { return matcher.group(1); } return null; } /** * Removes \\r characters from query. * Actually this is done specially for Oracle due to some bug in it's driver * * @param query query * @return normalized query */ public static String makeUnifiedLineFeeds(String query) { if (query.indexOf('\r') == -1) { return query; } StringBuilder result = new StringBuilder(query.length()); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if (c == '\r') { continue; } result.append(c); } return result.toString(); } public static String formatSQL(SQLDataSource dataSource, String query) { SQLSyntaxManager syntaxManager = new SQLSyntaxManager(); syntaxManager.init(dataSource.getSQLDialect(), dataSource.getContainer().getPreferenceStore()); SQLFormatterConfiguration configuration = new SQLFormatterConfiguration(syntaxManager); configuration.setKeywordCase(SQLFormatterConfiguration.KEYWORD_UPPER_CASE); return new SQLTokenizedFormatter().format(query, configuration); } public static void appendLikeCondition(StringBuilder sql, String value, boolean not) { if (value.contains("%") || value.contains("_")) { if (not) sql.append(" NOT"); sql.append(" LIKE ?"); } else { sql.append(not ? "<>?": "=?"); } } public static boolean appendFirstClause(StringBuilder sql, boolean firstClause) { if (firstClause) { sql.append(" WHERE "); } else { sql.append(" AND "); } return false; } public static String trimQueryStatement(SQLSyntaxManager syntaxManager, String sql) { sql = sql.trim(); for (String statementDelimiter : syntaxManager.getStatementDelimiters()) { if (sql.endsWith(statementDelimiter) && sql.length() > statementDelimiter.length()) { if (Character.isAlphabetic(statementDelimiter.charAt(0))) { // Delimiter is alphabetic (e.g. "GO") so it must be prefixed with whitespace char lastChar = sql.charAt(sql.length() - statementDelimiter.length() - 1); if (Character.isUnicodeIdentifierPart(lastChar)) { return sql; } } // Remove trailing delimiter only if it is not block end String trimmed = sql.substring(0, sql.length() - statementDelimiter.length()); String test = trimmed.toUpperCase().trim(); if (!test.endsWith(SQLConstants.BLOCK_END)) { sql = trimmed; } } } return sql; } @NotNull public static SQLDialect getDialectFromObject(DBPObject object) { if (object instanceof DBSObject) { DBPDataSource dataSource = ((DBSObject)object).getDataSource(); if (dataSource instanceof SQLDataSource) { return ((SQLDataSource) dataSource).getSQLDialect(); } } return BasicSQLDialect.INSTANCE; } public static void appendConditionString( @NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query, boolean inlineCriteria) { String operator = filter.isAnyConstraint() ? " OR " : " AND "; //$NON-NLS-1$ $NON-NLS-2$ boolean hasWhere = false; for (DBDAttributeConstraint constraint : filter.getConstraints()) { String condition = getConstraintCondition(dataSource, constraint, inlineCriteria); if (condition == null) { continue; } if (hasWhere) query.append(operator); hasWhere = true; if (conditionTable != null) { query.append(conditionTable).append('.'); } query.append(DBUtils.getObjectFullName(dataSource, constraint.getAttribute())); query.append(' ').append(condition); } if (!CommonUtils.isEmpty(filter.getWhere())) { if (hasWhere) query.append(operator); query.append(filter.getWhere()); } } public static void appendOrderString(@NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query) { // Construct ORDER BY boolean hasOrder = false; for (DBDAttributeConstraint co : filter.getOrderConstraints()) { if (hasOrder) query.append(','); if (conditionTable != null) { query.append(conditionTable).append('.'); } query.append(DBUtils.getObjectFullName(co.getAttribute())); if (co.isOrderDescending()) { query.append(" DESC"); //$NON-NLS-1$ } hasOrder = true; } if (!CommonUtils.isEmpty(filter.getOrder())) { if (hasOrder) query.append(','); query.append(filter.getOrder()); } } @Nullable public static String getConstraintCondition(DBPDataSource dataSource, DBDAttributeConstraint constraint, boolean inlineCriteria) { String criteria = constraint.getCriteria(); if (!CommonUtils.isEmpty(criteria)) { final char firstChar = criteria.trim().charAt(0); if (!Character.isLetter(firstChar) && firstChar != '=' && firstChar != '>' && firstChar != '<' && firstChar != '!') { return '=' + criteria; } else { return criteria; } } else if (constraint.getOperator() != null) { DBCLogicalOperator operator = constraint.getOperator(); StringBuilder conString = new StringBuilder(); if (constraint.isReverseOperator()) { conString.append("NOT "); } conString.append(operator.getStringValue()); if (operator.getArgumentCount() > 0) { for (int i = 0; i < operator.getArgumentCount(); i++) { if (i > 0) { conString.append(" AND"); } if (inlineCriteria) { conString.append(' ').append(convertValueToSQL(dataSource, constraint.getAttribute(), constraint.getValue())); } else { conString.append(" ?"); } } } return conString.toString(); } else { return null; } } public static String convertValueToSQL(DBPDataSource dataSource, DBSAttributeBase attribute, @Nullable Object value) { if (DBUtils.isNullValue(value)) { return SQLConstants.NULL_VALUE; } DBDValueHandler valueHandler = DBUtils.findValueHandler(dataSource, attribute); String strValue = valueHandler.getValueDisplayString(attribute, value, DBDDisplayFormat.NATIVE); SQLDialect sqlDialect = null; if (dataSource instanceof SQLDataSource) { sqlDialect = ((SQLDataSource) dataSource).getSQLDialect(); } if (value instanceof Number) { return strValue; } switch (attribute.getDataKind()) { case BOOLEAN: case NUMERIC: case DATETIME: return strValue; case CONTENT: if (value instanceof DBDContent) { if (!ContentUtils.isTextContent((DBDContent) value)) { return "[BLOB]"; } } case STRING: case ROWID: if (sqlDialect != null) { strValue = sqlDialect.escapeString(strValue); } return '\'' + strValue + '\''; default: return strValue; } } public static String getColumnTypeModifiers(DBSAttributeBase column, String typeName, DBPDataKind dataKind) { if (dataKind == DBPDataKind.STRING) { if (typeName.indexOf('(') == -1) { final long maxLength = column.getMaxLength(); if (maxLength > 0) { return "(" + maxLength + ")"; } } } else if (dataKind == DBPDataKind.NUMERIC) { if (typeName.equalsIgnoreCase("DECIMAL") || typeName.equalsIgnoreCase("NUMERIC") || typeName.equalsIgnoreCase("NUMBER")) { int scale = column.getScale(); int precision = column.getPrecision(); if (scale >= 0 && precision >= 0 && !(scale == 0 && precision == 0)) { return "(" + precision + ',' + scale + ')'; } } } return null; } public static boolean isExecQuery(@NotNull SQLDialect dialect, String query) { // Check for EXEC query final Collection<String> executeKeywords = dialect.getExecuteKeywords(); if (!CommonUtils.isEmpty(executeKeywords)) { final String queryStart = getFirstKeyword(query); for (String keyword : executeKeywords) { if (keyword.equalsIgnoreCase(queryStart)) { return true; } } } return false; } public static String getScriptDescripion(String sql) { sql = stripComments(BasicSQLDialect.INSTANCE, sql); Matcher matcher = CREATE_PREFIX_PATTERN.matcher(sql); if (matcher.find() && matcher.start(0) == 0) { sql = sql.substring(matcher.end(1)); } sql = sql.replaceAll(" +", " "); if (sql.length() > MAX_SQL_DESCRIPTION_LENGTH) { sql = sql.substring(0, MAX_SQL_DESCRIPTION_LENGTH) + " ..."; } return sql; } @Nullable public static String getScriptDescription(@NotNull IFile sqlScript) { try { //log.debug("Read script '" + sqlScript.getName() + "' description"); StringBuilder sql = new StringBuilder(); try (BufferedReader is = new BufferedReader(new InputStreamReader(sqlScript.getContents()))) { for (;;) { String line = is.readLine(); if (line == null) { break; } line = line.trim(); if (line.startsWith(" line.startsWith("Rem") || line.startsWith("rem") || line.startsWith("REM") ) { continue; } sql.append(line).append('\n'); if (sql.length() > MIN_SQL_DESCRIPTION_LENGTH) { break; } } } return SQLUtils.getScriptDescripion(sql.toString()); } catch (Exception e) { log.warn("", e); } return null; } }
package org.nwapw.abacus.plugin; import org.nwapw.abacus.function.Function; import org.nwapw.abacus.number.NaiveNumber; import org.nwapw.abacus.number.NumberInterface; import javax.print.attribute.standard.MediaSize; import java.util.function.BiFunction; /** * The plugin providing standard functions such as addition and subtraction to * the calculator. */ public class StandardPlugin extends Plugin { public StandardPlugin(PluginManager manager) { super(manager); } @Override public void load() { registerFunction("+", new Function() { @Override protected boolean matchesParams(NumberInterface[] params) { return params.length >= 1; } @Override protected NumberInterface applyInternal(NumberInterface[] params) { NumberInterface sum = params[0]; for(int i = 1; i < params.length; i++){ sum = sum.add(params[i]); } return sum; } }); registerFunction("-", new Function() { @Override protected boolean matchesParams(NumberInterface[] params) { return params.length == 2; } @Override protected NumberInterface applyInternal(NumberInterface[] params) { return params[0].subtract(params[1]); } }); registerFunction("*", new Function() { @Override protected boolean matchesParams(NumberInterface[] params) { return params.length >= 1; } @Override protected NumberInterface applyInternal(NumberInterface[] params) { NumberInterface product = params[0]; for(int i = 1; i < params.length; i++){ product = product.multiply(params[i]); } return product; } }); registerFunction("/", new Function() { @Override protected boolean matchesParams(NumberInterface[] params) { return params.length == 2; } @Override protected NumberInterface applyInternal(NumberInterface[] params) { return params[0].divide(params[1]); } }); registerFunction("!", new Function() { //private ArrayLi @Override protected boolean matchesParams(NumberInterface[] params) { return params.length == 1; } @Override protected NumberInterface applyInternal(NumberInterface[] params) { if(params[0].signum() == 0){ return (new NaiveNumber(1)).promoteTo(params[0].getClass()); } NumberInterface factorial = params[0]; NumberInterface multiplier = params[0]; //It is necessary to later prevent calls of factorial on anything but non-negative integers. while((multiplier = multiplier.subtract(NaiveNumber.ONE.promoteTo(multiplier.getClass()))).signum() == 1){ factorial = factorial.multiply(multiplier); } return factorial; } }); registerFunction("abs", new Function() { @Override protected boolean matchesParams(NumberInterface[] params) { return params.length == 1; } @Override protected NumberInterface applyInternal(NumberInterface[] params) { return params[0].multiply((new NaiveNumber(params[0].signum())).promoteTo(params[0].getClass())); } }); registerFunction("exp", new Function() { @Override protected boolean matchesParams(NumberInterface[] params) { return params.length == 1; } @Override protected NumberInterface applyInternal(NumberInterface[] params) { boolean takeReciprocal = params[0].signum() == -1; params[0] = StandardPlugin.this.getFunction("abs").apply(params[0]); NumberInterface sum = sumSeries(params[0], StandardPlugin.this::getExpSeriesTerm, getNTermsExp(getMaxError(params[0]), params[0])); if(takeReciprocal){ sum = NaiveNumber.ONE.promoteTo(sum.getClass()).divide(sum); } return sum; } }); } /** * Returns the nth term of the Taylor series (centered at 0) of e^x * @param n the term required (n >= 0). * @param x the real number at which the series is evaluated. * @return */ private NumberInterface getExpSeriesTerm(int n, NumberInterface x){ return x.intPow(n).divide(this.getFunction("!").apply((new NaiveNumber(n)).promoteTo(x.getClass()))); } /** * Returns the number of terms needed to evaluate the exponential function (at x) * such that the error is at most maxError. * @param maxError Maximum error permissible (This should probably be positive.) * @param x where the function is evaluated. * @return */ private int getNTermsExp(NumberInterface maxError, NumberInterface x){ //We need n such that |x^(n+1)| <= (n+1)! * maxError //The variables LHS and RHS refer to the above inequality. int n = 0; x = this.getFunction("abs").apply(x); NumberInterface LHS = x, RHS = maxError; while(LHS.compareTo(RHS) > 0){ n++; LHS = LHS.multiply(x); RHS = RHS.multiply(new NaiveNumber(n+1).promoteTo(RHS.getClass())); } return n; } /** * Returns a partial sum of a series whose terms are given by the nthTermFunction, evaluated at x. * @param x the value at which the series is evaluated. * @param nthTermFunction the function that returns the nth term of the series, in the format term(x, n). * @param n the number of terms in the partial sum. * @return the value of the partial sum that has the same class as x. */ private NumberInterface sumSeries(NumberInterface x, BiFunction<Integer, NumberInterface, NumberInterface> nthTermFunction, int n){ NumberInterface sum = NaiveNumber.ZERO.promoteTo(x.getClass()); for(int i = 0; i <= n; i++){ sum = sum.add(nthTermFunction.apply(i, x)); } return sum; } /** * Returns the maximum error based on the precision of the class of number. * @param number Any instance of the NumberInterface in question (should return an appropriate precision). * @return */ private NumberInterface getMaxError(NumberInterface number){ return (new NaiveNumber(10)).promoteTo(number.getClass()).intPow(-number.precision()); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.olentangyfrc.subsystems; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; import org.olentangyfrc.RobotMap; /** * * @author Bindernews */ public class DriveTrain extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. private Victor lowerLeft; private Victor lowerRight; private Victor upperLeft; private Victor upperRight; public DriveTrain() { super("Drive Train"); lowerRight = new Victor(RobotMap.LOW_RIGHT_MOTOR); lowerLeft = new Victor(RobotMap.LOW_LEFT_MOTOR); upperRight = new Victor(RobotMap.TOP_RIGHT_MOTOR); upperLeft = new Victor(RobotMap.TOP_LEFT_MOTOR); } public void setLowerLeft(double spd) { lowerLeft.set(spd); } public void setLowerRight(double spd) { lowerRight.set(spd); } public void setUpperRight(double spd) { upperRight.set(spd); } public void setUpperLeft(double spd) { upperLeft.set(spd); } public void setAllSpeed(double spd) { upperLeft.set(spd); upperRight.set(spd); lowerLeft.set(spd); lowerRight.set(spd); } public void setFrontSpeed(double spd) { upperLeft.set(spd); upperRight.set(spd); } public void setBackSpeed(double spd) { lowerLeft.set(spd); lowerRight.set(spd); } public void setLeftSpeed(double spd) { upperLeft.set(spd); lowerLeft.set(spd); } public void setRightSpeed(double spd) { upperRight.set(spd); lowerRight.set(spd); } public void stopLowerLeft() { lowerLeft.stopMotor(); } public void stopLowerRight() { lowerRight.stopMotor(); } public void stopUpperLeft() { upperLeft.stopMotor(); } public void stopUpperRight() { upperRight.stopMotor(); } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } }
package org.sugr.gearshift; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentManager; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.text.Html; import android.text.Spanned; import android.util.SparseBooleanArray; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.Filter; import android.widget.Filter.FilterListener; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SearchView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.sugr.gearshift.G.FilterBy; import org.sugr.gearshift.G.SortBy; import org.sugr.gearshift.G.SortOrder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Locale; /** * A list fragment representing a list of Torrents. This fragment * also supports tablet devices by allowing list items to be given an * 'activated' state upon selection. This helps indicate which item is * currently being viewed in a {@link TorrentDetailFragment}. * <p> * Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class TorrentListFragment extends ListFragment { /** * The serialization (saved instance state) Bundle key representing the * activated item position. Only used on tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; private static final String STATE_FIND_SHOWN = "find_shown"; private static final String STATE_FIND_QUERY = "find_query"; private static final String STATE_CURRENT_PROFILE = "current_profile"; private static final String STATE_TORRENTS = "torrents"; /** * The fragment's current callback object, which is notified of list item * clicks. */ private Callbacks mCallbacks = sDummyCallbacks; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = ListView.INVALID_POSITION; private boolean mAltSpeed = false; private boolean mRefreshing = true; private ActionMode mActionMode; private int mChoiceMode = ListView.CHOICE_MODE_NONE; private TransmissionProfileListAdapter mProfileAdapter; private TorrentListAdapter mTorrentListAdapter; private TransmissionProfile mProfile; private TransmissionSession mSession; // private TransmissionSessionStats mSessionStats; private boolean mScrollToTop = false; private boolean mFindShown = false; private String mFindQuery; private boolean mPreventRefreshIndicator; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callbacks { /** * Callback for when an item has been selected. */ public void onItemSelected(Torrent torrent); } /** * A dummy implementation of the {@link Callbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(Torrent torrent) { } }; private LoaderCallbacks<TransmissionProfile[]> mProfileLoaderCallbacks = new LoaderCallbacks<TransmissionProfile[]>() { @Override public android.support.v4.content.Loader<TransmissionProfile[]> onCreateLoader( int id, Bundle args) { return new TransmissionProfileSupportLoader(getActivity()); } @Override public void onLoadFinished( android.support.v4.content.Loader<TransmissionProfile[]> loader, TransmissionProfile[] profiles) { TransmissionProfile oldProfile = mProfile; mProfile = null; mProfileAdapter.clear(); if (profiles.length > 0) { mProfileAdapter.addAll(profiles); } else { mProfileAdapter.add(TransmissionProfileListAdapter.EMPTY_PROFILE); setEmptyText(R.string.no_profiles_empty_list); mRefreshing = false; getActivity().invalidateOptionsMenu(); } String currentId = TransmissionProfile.getCurrentProfileId(getActivity()); int index = 0; for (TransmissionProfile prof : profiles) { if (prof.getId().equals(currentId)) { ActionBar actionBar = getActivity().getActionBar(); if (actionBar != null) actionBar.setSelectedNavigationItem(index); mProfile = prof; break; } index++; } if (mProfile == null && profiles.length > 0) { mProfile = profiles[0]; } ((TransmissionSessionInterface) getActivity()).setProfile(mProfile); if (mProfile == null) { getActivity().getSupportLoaderManager().destroyLoader(G.TORRENTS_LOADER_ID); } else { /* The torrents might be loaded before the navigation * callback fires, which will cause the refresh indicator to * appear until the next server request */ mPreventRefreshIndicator = true; if (oldProfile != null && oldProfile.getId() == mProfile.getId()) { getActivity().getSupportLoaderManager().initLoader( G.TORRENTS_LOADER_ID, null, mTorrentLoaderCallbacks); } else { getActivity().getSupportLoaderManager().restartLoader( G.TORRENTS_LOADER_ID, null, mTorrentLoaderCallbacks); } } } @Override public void onLoaderReset( android.support.v4.content.Loader<TransmissionProfile[]> loader) { mProfileAdapter.clear(); } }; private LoaderCallbacks<TransmissionData> mTorrentLoaderCallbacks = new LoaderCallbacks<TransmissionData>() { @Override public android.support.v4.content.Loader<TransmissionData> onCreateLoader( int id, Bundle args) { G.logD("Starting the torrents loader with profile " + mProfile); if (mProfile == null) return null; TransmissionDataLoader loader = new TransmissionDataLoader(getActivity(), mProfile); return loader; } @Override public void onLoadFinished( android.support.v4.content.Loader<TransmissionData> loader, TransmissionData data) { boolean invalidateMenu = false; G.logD("Data loaded: " + data.torrents.size() + " torrents, error: " + data.error + " , removed: " + data.hasRemoved + ", added: " + data.hasAdded + ", changed: " + data.hasStatusChanged + ", metadata: " + data.hasMetadataNeeded); mSession = data.session; ((TransmissionSessionInterface) getActivity()).setSession(data.session); /* if (data.stats != null) mSessionStats = data.stats;*/ if (mSession != null && mAltSpeed != mSession.isAltSpeedLimitEnabled()) { mAltSpeed = mSession.isAltSpeedLimitEnabled(); invalidateMenu = true; } boolean filtered = false; View error = getView().findViewById(R.id.fatal_error_layer); if (data.error == 0 && error.getVisibility() != View.GONE) { error.setVisibility(View.GONE); ((TransmissionSessionInterface) getActivity()).setProfile(mProfile); } if (data.torrents.size() > 0 || data.error > 0 || mTorrentListAdapter.getUnfilteredCount() > 0) { /* The notifyDataSetChanged method sets this to true */ mTorrentListAdapter.setNotifyOnChange(false); boolean notifyChange = true; if (data.error == 0) { if (data.hasRemoved || data.hasAdded || data.hasStatusChanged || data.hasMetadataNeeded || mTorrentListAdapter.getUnfilteredCount() == 0) { notifyChange = false; if (data.hasRemoved || data.hasAdded) { ((TransmissionSessionInterface) getActivity()).setTorrents(data.torrents); } mTorrentListAdapter.clear(); mTorrentListAdapter.addAll(data.torrents); mTorrentListAdapter.repeatFilter(); filtered = true; } } else { if (data.error == TransmissionData.Errors.DUPLICATE_TORRENT) { Toast.makeText(getActivity(), R.string.duplicate_torrent, Toast.LENGTH_SHORT).show(); } else if (data.error == TransmissionData.Errors.INVALID_TORRENT) { Toast.makeText(getActivity(), R.string.invalid_torrent, Toast.LENGTH_SHORT).show(); } else { error.setVisibility(View.VISIBLE); TextView text = (TextView) getView().findViewById(R.id.transmission_error); ((TransmissionSessionInterface) getActivity()).setProfile(null); if (mActionMode != null) { mActionMode.finish(); mActionMode = null; } if (data.error == TransmissionData.Errors.NO_CONNECTIVITY) { text.setText(Html.fromHtml(getString(R.string.no_connectivity_empty_list))); } else if (data.error == TransmissionData.Errors.ACCESS_DENIED) { text.setText(Html.fromHtml(getString(R.string.access_denied_empty_list))); } else if (data.error == TransmissionData.Errors.NO_JSON) { text.setText(Html.fromHtml(getString(R.string.no_json_empty_list))); } else if (data.error == TransmissionData.Errors.NO_CONNECTION) { text.setText(Html.fromHtml(getString(R.string.no_connection_empty_list))); } else if (data.error == TransmissionData.Errors.THREAD_ERROR) { text.setText(Html.fromHtml(getString(R.string.thread_error_empty_list))); } else if (data.error == TransmissionData.Errors.RESPONSE_ERROR) { text.setText(Html.fromHtml(getString(R.string.response_error_empty_list))); } else if (data.error == TransmissionData.Errors.TIMEOUT) { text.setText(Html.fromHtml(getString(R.string.timeout_empty_list))); } } } if (data.torrents.size() > 0) { if (notifyChange) { mTorrentListAdapter.notifyDataSetChanged(); } } else { mTorrentListAdapter.notifyDataSetInvalidated(); } if (data.error == 0) { FragmentManager manager = getActivity().getSupportFragmentManager(); TorrentListMenuFragment menu = (TorrentListMenuFragment) manager.findFragmentById(R.id.torrent_list_menu); if (menu != null) { menu.notifyTorrentListUpdate(data.torrents, data.session); } if (!filtered) { TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag( TorrentDetailFragment.TAG); if (detail != null) { detail.notifyTorrentListChanged(data.hasRemoved, data.hasAdded, data.hasStatusChanged); if (data.hasStatusChanged) { invalidateMenu = true; } } } } } if (mRefreshing) { mRefreshing = false; invalidateMenu = true; } if (invalidateMenu) getActivity().invalidateOptionsMenu(); } @Override public void onLoaderReset( android.support.v4.content.Loader<TransmissionData> loader) { mTorrentListAdapter.clear(); } }; private SharedPreferences.OnSharedPreferenceChangeListener mProfileChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (getActivity() == null || mProfile == null) return; Loader<TransmissionData> loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); mProfile.load(prefs); TransmissionProfile.setCurrentProfile(mProfile, getActivity()); ((TransmissionSessionInterface) getActivity()).setProfile(mProfile); ((TransmissionDataLoader) loader).setProfile(mProfile); } }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public TorrentListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); getActivity().setProgressBarIndeterminateVisibility(true); ActionBar actionBar = getActivity().getActionBar(); if (actionBar != null) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); mProfileAdapter = new TransmissionProfileListAdapter(getActivity()); actionBar.setListNavigationCallbacks(mProfileAdapter, new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int pos, long id) { TransmissionProfile profile = mProfileAdapter.getItem(pos); if (profile != TransmissionProfileListAdapter.EMPTY_PROFILE) { final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (mProfile != null) { SharedPreferences prefs = mProfile.getPreferences(getActivity()); if (prefs != null) prefs.unregisterOnSharedPreferenceChangeListener(mProfileChangeListener); } mProfile = profile; TransmissionProfile.setCurrentProfile(profile, getActivity()); ((TransmissionSessionInterface) getActivity()).setProfile(profile); ((TransmissionDataLoader) loader).setProfile(profile); SharedPreferences prefs = mProfile.getPreferences(getActivity()); if (prefs != null) prefs.registerOnSharedPreferenceChangeListener(mProfileChangeListener); if (mPreventRefreshIndicator) { mPreventRefreshIndicator = false; } else { mRefreshing = true; getActivity().invalidateOptionsMenu(); } } return false; } }); actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); } if (savedInstanceState != null && savedInstanceState.containsKey(STATE_CURRENT_PROFILE)) { mProfile = savedInstanceState.getParcelable(STATE_CURRENT_PROFILE); } getActivity().getSupportLoaderManager().initLoader(G.PROFILES_LOADER_ID, null, mProfileLoaderCallbacks); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Restore the previously serialized activated item position. if (savedInstanceState != null) { if (savedInstanceState.containsKey(STATE_FIND_SHOWN)) { mFindShown = savedInstanceState.getBoolean(STATE_FIND_SHOWN); if (savedInstanceState.containsKey(STATE_FIND_QUERY)) { mFindQuery = savedInstanceState.getString(STATE_FIND_QUERY); } } mRefreshing = false; } mTorrentListAdapter = new TorrentListAdapter(getActivity()); setListAdapter(mTorrentListAdapter); if (savedInstanceState != null) { if (savedInstanceState.containsKey(STATE_TORRENTS)) { mTorrentListAdapter.setNotifyOnChange(false); mTorrentListAdapter.clear(); ArrayList<Torrent> torrents = savedInstanceState.getParcelableArrayList(STATE_TORRENTS); mTorrentListAdapter.addAll(torrents); mTorrentListAdapter.repeatFilter(); } if (savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)){ setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION)); } } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final ListView list = getListView(); list.setChoiceMode(mChoiceMode); list.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (!((TorrentListActivity) getActivity()).isDetailPanelShown()) { list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); setActivatedPosition(position); return true; } return false; }}); list.setMultiChoiceModeListener(new MultiChoiceModeListener() { private HashSet<Integer> mSelectedTorrentIds; @Override public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader == null) return false; final int[] ids = new int[mSelectedTorrentIds.size()]; int index = 0; for (Integer id : mSelectedTorrentIds) ids[index++] = id; AlertDialog.Builder builder; switch (item.getItemId()) { case R.id.select_all: ListView v = getListView(); for (int i = 0; i < mTorrentListAdapter.getCount(); i++) { if (!v.isItemChecked(i)) { v.setItemChecked(i, true); } } return true; case R.id.remove: case R.id.delete: builder = new AlertDialog.Builder(getActivity()) .setCancelable(false) .setNegativeButton(android.R.string.no, null); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { ((TransmissionDataLoader) loader).setTorrentsRemove(ids, item.getItemId() == R.id.delete); mRefreshing = true; getActivity().invalidateOptionsMenu(); mode.finish(); } }) .setMessage(item.getItemId() == R.id.delete ? R.string.delete_selected_confirmation : R.string.remove_selected_confirmation) .show(); return true; case R.id.resume: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-start", ids); break; case R.id.pause: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-stop", ids); break; case R.id.move: return showMoveDialog(ids); case R.id.verify: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-verify", ids); break; case R.id.reannounce: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-reannounce", ids); break; default: return true; } mRefreshing = true; getActivity().invalidateOptionsMenu(); mode.finish(); return true; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.torrent_list_multiselect, menu); mSelectedTorrentIds = new HashSet<Integer>(); mActionMode = mode; return true; } @Override public void onDestroyActionMode(ActionMode mode) { G.logD("Destroying context menu"); mActionMode = null; mSelectedTorrentIds = null; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if (checked) mSelectedTorrentIds.add(mTorrentListAdapter.getItem(position).getId()); else mSelectedTorrentIds.remove(mTorrentListAdapter.getItem(position).getId()); ArrayList<Torrent> torrents = ((TransmissionSessionInterface) getActivity()).getTorrents(); boolean hasPaused = false; boolean hasRunning = false; for (Torrent t : torrents) { if (mSelectedTorrentIds.contains(t.getId())) { if (t.getStatus() == Torrent.Status.STOPPED) { hasPaused = true; } else { hasRunning = true; } } } Menu menu = mode.getMenu(); MenuItem item = menu.findItem(R.id.resume); item.setVisible(hasPaused).setEnabled(hasPaused); item = menu.findItem(R.id.pause); item.setVisible(hasRunning).setEnabled(hasRunning); }}); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. mCallbacks = sDummyCallbacks; } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); if (mActionMode == null) listView.setChoiceMode(mChoiceMode); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mCallbacks.onItemSelected(mTorrentListAdapter.getItem(position)); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(STATE_CURRENT_PROFILE, mProfile); if (mActivatedPosition != ListView.INVALID_POSITION) { // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } outState.putBoolean(STATE_FIND_SHOWN, mFindShown); outState.putString(STATE_FIND_QUERY, mFindQuery); outState.putParcelableArrayList(STATE_TORRENTS, mTorrentListAdapter.getUnfilteredItems()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_torrent_list, container, false); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.torrent_list_options, menu); MenuItem item = menu.findItem(R.id.menu_refresh); if (mRefreshing) item.setActionView(R.layout.action_progress_bar); else item.setActionView(null); item = menu.findItem(R.id.menu_alt_speed); if (mSession == null) { item.setVisible(false); } else { item.setVisible(true); if (mAltSpeed) { item.setIcon(R.drawable.ic_menu_alt_speed_on); item.setTitle(R.string.alt_speed_label_off); } else { item.setIcon(R.drawable.ic_menu_alt_speed_off); item.setTitle(R.string.alt_speed_label_on); } } item = menu.findItem(R.id.menu_find); if (mFindShown) { item.expandActionView(); item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { mFindShown = false; mFindQuery = null; setListFilter((String) null); return true; } }); SearchView searchView = (SearchView) menu.findItem(R.id.menu_find).getActionView(); searchView.setQueryHint(getActivity().getString(R.string.filter)); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { G.logD("Search query " + newText); mFindQuery = newText; setListFilter(newText); return false; } }); if (mFindQuery == null) { searchView.setQuery("", false); } else { searchView.setQuery(mFindQuery, true); } } else { item.collapseActionView(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { Loader<TransmissionData> loader; switch (item.getItemId()) { case R.id.menu_alt_speed: loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { mAltSpeed = !mAltSpeed; mSession.setAltSpeedLimitEnabled(mAltSpeed); ((TransmissionDataLoader) loader).setSession(mSession, "alt-speed-enabled"); getActivity().invalidateOptionsMenu(); } return true; case R.id.menu_refresh: loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { loader.onContentChanged(); mRefreshing = !mRefreshing; getActivity().invalidateOptionsMenu(); } return true; default: return super.onOptionsItemSelected(item); } } public void setEmptyText(int stringId) { Spanned text = Html.fromHtml(getString(stringId)); ((TextView) getListView().getEmptyView()).setText(text); } public void setEmptyText(String text) { ((TextView) getListView().getEmptyView()).setText(text); } /** * Turns on activate-on-click mode. When this mode is on, list items will be * given the 'activated' state when touched. */ public void setActivateOnItemClick(boolean activateOnItemClick) { // When setting CHOICE_MODE_SINGLE, ListView will automatically // give items the 'activated' state when touched. mChoiceMode = activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE; getListView().setChoiceMode(mChoiceMode); } public void setListFilter(String query) { mTorrentListAdapter.filter(query); mScrollToTop = true; } public void setListFilter(FilterBy e) { mTorrentListAdapter.filter(e); mScrollToTop = true; } public void setListFilter(SortBy e) { mTorrentListAdapter.filter(e); mScrollToTop = true; } public void setListFilter(SortOrder e) { mTorrentListAdapter.filter(e); mScrollToTop = true; } public void setListDirectoryFilter(String e) { mTorrentListAdapter.filterDirectory(e); mScrollToTop = true; } public void setRefreshing(boolean refreshing) { mRefreshing = refreshing; getActivity().invalidateOptionsMenu(); } public void showFind() { mFindShown = true; mFindQuery = null; if (mActionMode != null) { mActionMode.finish(); } getActivity().invalidateOptionsMenu(); } public boolean isFindShown() { return mFindShown; } private void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { getListView().setItemChecked(mActivatedPosition, false); } else { getListView().setItemChecked(position, true); } mActivatedPosition = position; } private boolean showMoveDialog(final int[] ids) { LayoutInflater inflater = getActivity().getLayoutInflater(); final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) .setTitle(R.string.set_location) .setCancelable(false) .setNegativeButton(android.R.string.no, null) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Spinner location = (Spinner) ((AlertDialog) dialog).findViewById(R.id.location_choice); CheckBox move = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.move); String dir = (String) location.getSelectedItem(); ((TransmissionDataLoader) loader).setTorrentsLocation( ids, dir, move.isChecked()); mRefreshing = true; getActivity().invalidateOptionsMenu(); if (mActionMode != null) { mActionMode.finish(); } } }).setView(inflater.inflate(R.layout.torrent_location_dialog, null)); if (mSession == null) { return true; } AlertDialog dialog = builder.create(); dialog.show(); TransmissionProfileDirectoryAdapter adapter = new TransmissionProfileDirectoryAdapter( getActivity(), android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapter.addAll(mSession.getDownloadDirectories()); adapter.sort(); Spinner location = (Spinner) dialog.findViewById(R.id.location_choice); location.setAdapter(adapter); if (mProfile.getLastDownloadDirectory() != null) { int position = adapter.getPosition(mProfile.getLastDownloadDirectory()); if (position > -1) { location.setSelection(position); } } return true; } private static class TransmissionProfileListAdapter extends ArrayAdapter<TransmissionProfile> { public static final TransmissionProfile EMPTY_PROFILE = new TransmissionProfile(null); public TransmissionProfileListAdapter(Context context) { super(context, 0); add(EMPTY_PROFILE); } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; TransmissionProfile profile = getItem(position); if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector, null); } TextView name = (TextView) rowView.findViewById(R.id.name); TextView summary = (TextView) rowView.findViewById(R.id.summary); if (profile == EMPTY_PROFILE) { name.setText(R.string.no_profiles); if (summary != null) summary.setText(R.string.create_profile_in_settings); } else { name.setText(profile.getName()); if (summary != null) summary.setText((profile.getUsername().length() > 0 ? profile.getUsername() + "@" : "") + profile.getHost() + ":" + profile.getPort()); } return rowView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector_dropdown, null); } return getView(position, rowView, parent); } } private class TorrentListAdapter extends ArrayAdapter<Torrent> { private final Object mLock = new Object(); private ArrayList<Torrent> mObjects = new ArrayList<Torrent>(); private ArrayList<Torrent> mOriginalValues; private TorrentFilter mFilter; private CharSequence mCurrentConstraint; private FilterListener mCurrentFilterListener; private TorrentComparator mTorrentComparator = new TorrentComparator(); private FilterBy mFilterBy = FilterBy.ALL; private SortBy mSortBy = mTorrentComparator.getSortBy(); private SortBy mBaseSort = mTorrentComparator.getBaseSort(); private SortOrder mSortOrder = mTorrentComparator.getSortOrder(); private String mDirectory; private SparseBooleanArray mTorrentAdded = new SparseBooleanArray(); private SharedPreferences mSharedPrefs; public TorrentListAdapter(Context context) { super(context, R.layout.torrent_list_item, R.id.name); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); /* if (mSharedPrefs.contains(G.PREF_LIST_SEARCH)) { mCurrentConstraint = mSharedPrefs.getString( G.PREF_LIST_SEARCH, null); } */ if (mSharedPrefs.contains(G.PREF_LIST_FILTER)) { try { mFilterBy = FilterBy.valueOf( mSharedPrefs.getString(G.PREF_LIST_FILTER, "") ); } catch (Exception e) { mFilterBy = FilterBy.ALL; } } if (mSharedPrefs.contains(G.PREF_LIST_DIRECTORY)) { mDirectory = mSharedPrefs.getString(G.PREF_LIST_DIRECTORY, null); } if (mSharedPrefs.contains(G.PREF_LIST_SORT_BY)) { try { mSortBy = SortBy.valueOf( mSharedPrefs.getString(G.PREF_LIST_SORT_BY, "") ); } catch (Exception e) { mSortBy = mTorrentComparator.getSortBy(); } } if (mSharedPrefs.contains(G.PREF_BASE_SORT)) { try { mBaseSort = SortBy.valueOf( mSharedPrefs.getString(G.PREF_BASE_SORT, "") ); } catch (Exception e) { mBaseSort = mTorrentComparator.getBaseSort(); } } if (mSharedPrefs.contains(G.PREF_LIST_SORT_ORDER)) { try { mSortOrder = SortOrder.valueOf( mSharedPrefs.getString(G.PREF_LIST_SORT_ORDER, "") ); } catch (Exception e) { mSortOrder = mTorrentComparator.getSortOrder(); } } mTorrentComparator.setSortingMethod(mSortBy, mSortOrder); mTorrentComparator.setBaseSort(mBaseSort); } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; Torrent torrent = getItem(position); if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_list_item, parent, false); } TextView name = (TextView) rowView.findViewById(R.id.name); TextView traffic = (TextView) rowView.findViewById(R.id.traffic); ProgressBar progress = (ProgressBar) rowView.findViewById(R.id.progress); TextView status = (TextView) rowView.findViewById(R.id.status); TextView errorText = (TextView) rowView.findViewById(R.id.error_text); name.setText(torrent.getName()); if (torrent.getMetadataPercentComplete() < 1) { progress.setSecondaryProgress((int) (torrent.getMetadataPercentComplete() * 100)); progress.setProgress(0); } else if (torrent.getPercentDone() < 1) { progress.setSecondaryProgress((int) (torrent.getPercentDone() * 100)); progress.setProgress(0); } else { progress.setSecondaryProgress(100); float limit = torrent.getActiveSeedRatioLimit(); float current = torrent.getUploadRatio(); if (limit == -1) { progress.setProgress(100); } else { if (current >= limit) { progress.setProgress(100); } else { progress.setProgress((int) (current / limit * 100)); } } } traffic.setText(torrent.getTrafficText()); status.setText(torrent.getStatusText()); boolean enabled = torrent.isActive(); name.setEnabled(enabled); traffic.setEnabled(enabled); status.setEnabled(enabled); errorText.setEnabled(enabled); if (torrent.getError() == Torrent.Error.OK) { errorText.setVisibility(View.GONE); } else { errorText.setVisibility(View.VISIBLE); errorText.setText(torrent.getErrorString()); } if (!mTorrentAdded.get(torrent.getId(), false)) { rowView.setTranslationY(100); rowView.setAlpha((float) 0.3); rowView.setRotationX(10); rowView.animate().setDuration(300).translationY(0).alpha(1).rotationX(0).start(); mTorrentAdded.append(torrent.getId(), true); } return rowView; } @Override public void addAll(Collection<? extends Torrent> collection) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.addAll(collection); } else { mObjects.addAll(collection); } super.addAll(collection); } } @Override public void clear() { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues = null; } if (mObjects != null) { mObjects.clear(); } super.clear(); } } @Override public int getCount() { synchronized(mLock) { return mObjects == null ? 0 : mObjects.size(); } } public int getUnfilteredCount() { synchronized(mLock) { if (mOriginalValues != null) { return mOriginalValues.size(); } else { return mObjects.size(); } } } public ArrayList<Torrent> getUnfilteredItems() { synchronized(mLock) { if (mOriginalValues != null) { return mOriginalValues; } else { return mObjects; } } } @Override public Torrent getItem(int position) { return mObjects.get(position); } @Override public int getPosition(Torrent item) { return mObjects.indexOf(item); } @Override public Filter getFilter() { if (mFilter == null) mFilter = new TorrentFilter(); return mFilter; } public void filter(String query) { mCurrentConstraint = query; applyFilter(query, G.PREF_LIST_SEARCH, false); } public void filter(FilterBy by) { mFilterBy = by; applyFilter(by.name(), G.PREF_LIST_FILTER); } public void filter(SortBy by) { mSortBy = by; applyFilter(by.name(), G.PREF_LIST_SORT_BY); } public void filter(SortOrder order) { mSortOrder = order; applyFilter(order.name(), G.PREF_LIST_SORT_ORDER); } public void filterDirectory(String directory) { mDirectory = directory; applyFilter(directory, G.PREF_LIST_DIRECTORY); } public void repeatFilter() { if (mProfile != null) { getFilter().filter(mCurrentConstraint, mCurrentFilterListener); } } private void applyFilter(String value, String pref, boolean animate) { if (mActionMode != null) { mActionMode.finish(); } if (pref != null) { Editor e = mSharedPrefs.edit(); e.putString(pref, value); e.apply(); } mTorrentComparator.setSortingMethod(mSortBy, mSortOrder); repeatFilter(); if (animate) { mTorrentAdded = new SparseBooleanArray(); } } private void applyFilter(String value, String pref) { applyFilter(value, pref, true); } private class TorrentFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); ArrayList<Torrent> resultList; if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<Torrent>(mObjects); } } if (prefix == null) { prefix = ""; } if (prefix.length() == 0 && mFilterBy == FilterBy.ALL && mDirectory == null) { ArrayList<Torrent> list; synchronized (mLock) { list = new ArrayList<Torrent>(mOriginalValues); } resultList = list; } else { ArrayList<Torrent> values; synchronized (mLock) { values = new ArrayList<Torrent>(mOriginalValues); } final int count = values.size(); final ArrayList<Torrent> newValues = new ArrayList<Torrent>(); String prefixString = prefix.toString().toLowerCase(Locale.getDefault()); for (int i = 0; i < count; i++) { final Torrent torrent = values.get(i); if (mFilterBy == FilterBy.DOWNLOADING) { if (torrent.getStatus() != Torrent.Status.DOWNLOADING) continue; } else if (mFilterBy == FilterBy.SEEDING) { if (torrent.getStatus() != Torrent.Status.SEEDING) continue; } else if (mFilterBy == FilterBy.PAUSED) { if (torrent.getStatus() != Torrent.Status.STOPPED) continue; } else if (mFilterBy == FilterBy.COMPLETE) { if (torrent.getPercentDone() != 1) continue; } else if (mFilterBy == FilterBy.INCOMPLETE) { if (torrent.getPercentDone() >= 1) continue; } else if (mFilterBy == FilterBy.ACTIVE) { if (torrent.isStalled() || torrent.isFinished() || ( torrent.getStatus() != Torrent.Status.DOWNLOADING && torrent.getStatus() != Torrent.Status.SEEDING )) continue; } else if (mFilterBy == FilterBy.CHECKING) { if (torrent.getStatus() != Torrent.Status.CHECKING) continue; } if (mDirectory != null) { if (torrent.getDownloadDir() == null || !torrent.getDownloadDir().equals(mDirectory)) continue; } if (prefix.length() == 0) { newValues.add(torrent); } else if (prefix.length() > 0) { final String valueText = torrent.getName().toLowerCase(Locale.getDefault()); int lastIndex = -1; boolean match = false; for (int j = 0; j < prefixString.length(); ++j) { char c = prefixString.charAt(j); if (Character.isWhitespace(c)) { continue; } int newIndex = valueText.indexOf(c, lastIndex); if (newIndex > -1 && (lastIndex == -1 || newIndex - lastIndex < 3)) { lastIndex = newIndex + 1; if (j == prefixString.length() - 1) { match = true; } } else { break; } } if (match) { newValues.add(torrent); } } } resultList = newValues; } Collections.sort(resultList, mTorrentComparator); results.values = resultList; results.count = resultList.size(); return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { mObjects = (ArrayList<Torrent>) results.values; TransmissionSessionInterface context = (TransmissionSessionInterface) getActivity(); if (context == null) { return; } if (results.count > 0) { context.setTorrents((ArrayList<Torrent>) results.values); FragmentManager manager = getActivity().getSupportFragmentManager(); TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag( TorrentDetailFragment.TAG); if (detail != null) { detail.notifyTorrentListChanged(true, true, false); } notifyDataSetChanged(); } else { if (mTorrentListAdapter.getUnfilteredCount() == 0) { setEmptyText(R.string.no_torrents_empty_list); } else if (mTorrentListAdapter.getCount() == 0) { ((TransmissionSessionInterface) getActivity()) .setTorrents(null); setEmptyText(R.string.no_filtered_torrents_empty_list); } notifyDataSetInvalidated(); } if (mScrollToTop) { mScrollToTop = false; getListView().setSelectionAfterHeaderView(); } } } } }
package org.sylvani.bot.universal; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sylvani.bot.ActivityType; import org.sylvani.bot.ContextBase; import org.sylvani.bot.IActivity; import org.sylvani.bot.IBot; import org.sylvani.bot.IBotConfig; import org.sylvani.bot.IConnector; import org.sylvani.bot.IHandler; import org.sylvani.bot.IInterceptor; import org.sylvani.bot.ISession; import org.sylvani.bot.dialogs.IDialog; import org.sylvani.bot.recognize.IRecognizer; import io.rincl.Rincled; /** * General purpose bot implementation * * @author Harald Kuhn */ public class UniversalBot extends ContextBase implements IBot, Rincled { private Logger logger = LoggerFactory.getLogger(UniversalBot.class); private IDialog welcomeDialog; private Map<IRecognizer, IDialog> globalCommands; private Map<IRecognizer, IDialog> dialogs; private IConnector connector; private IBotConfig botConfig; private Stack<IHandler> inInterceptorChain; private Stack<IHandler> outInterceptorChain; public UniversalBot(IConnector connector) { this.connector = connector; this.dialogs = new HashMap<>(); this.globalCommands = new HashMap<>(); try { this.botConfig = new UniversalBotConfig(); } catch (IOException e) { throw new RuntimeException("config failed", e); } this.connector.listen(this); inInterceptorChain = new Stack<>(); inInterceptorChain.push(this); // the bot is the final in handler if (botConfig.getArchive() != null) { inInterceptorChain.push(botConfig.getArchive()); } if (!botConfig.getInInterceptors().isEmpty()) { for (IInterceptor interceptor : botConfig.getInInterceptors()) { interceptor.chain(inInterceptorChain.peek()); inInterceptorChain.push(interceptor); } } outInterceptorChain = new Stack<>(); outInterceptorChain.push(this); // the bot is the final out handler, too if (botConfig.getArchive() != null) { outInterceptorChain.push(botConfig.getArchive()); } if (!botConfig.getOutInterceptors().isEmpty()) { for (IInterceptor interceptor : botConfig.getOutInterceptors()) { interceptor.chain(outInterceptorChain.peek()); outInterceptorChain.push(interceptor); } } } @Override public void receive(IActivity activity) { String convId = activity.getConversation().getId(); ISession session = botConfig.getSessionStore().find(convId); logger.debug("receive activity of type " + activity.getType() + " " + activity.getText()); if (session == null) { logger.debug("new session"); session = new UniversalSession(convId, this, connector); botConfig.getSessionStore().add(convId, session); } handle(session, activity); } @Override public void handle(ISession session, IActivity activity) { if (ActivityType.MESSAGE == activity.getType()) { IDialog dialog = findDialog(session, activity); ((UniversalSession) session).setActiveDialog(dialog); dialog.handle(session, activity); } } private IDialog findDialog(ISession session, IActivity activity) { for (IRecognizer recognizer : globalCommands.keySet()) { if (recognizer.recognize(session, activity) > 0) { IDialog dialog = globalCommands.get(recognizer); logger.debug("delegating message to global " + dialog.getClass().getName()); return dialog; } } if (session.getActiveDialog() != null) { logger.debug("delegating message to active " + session.getActiveDialog().getClass().getName()); return session.getActiveDialog(); } for (IRecognizer recognizer : dialogs.keySet()) { if (recognizer.recognize(session, activity) > 0) { IDialog dialog = dialogs.get(recognizer); logger.debug("delegating message to " + dialog.getClass().getSimpleName()); return dialog; } } logger.debug("coult not find match, delegating to welcome"); return welcomeDialog; } public void addDialog(IRecognizer recognizer, IDialog dialog) { dialogs.put(recognizer, dialog); } public void addGlobalCommand(IRecognizer recognizer, IDialog dialog) { globalCommands.put(recognizer, dialog); } @Override public void send(IActivity activity) { logger.debug("send from " + activity.getFrom().getName() + " to " + activity.getRecipient().getName()); connector.send(activity); } public void setWelcomeDialog(IDialog welcomeDialog) { this.welcomeDialog = welcomeDialog; } @Override public IBotConfig getBotConfig() { return botConfig; } @Override public void invalidate(ISession session) { botConfig.getSessionStore().remove(session); } }
package org.treetank.utils; public final class FastByteArrayReader { private final byte[] mBuffer; private int mPosition; /**F * Constructor. * */ public FastByteArrayReader(final byte[] buffer) { mBuffer = buffer; mPosition = 0; } public final boolean setOffset(int offset) { if (offset < mBuffer.length) { mPosition = offset; return true; } return false; } public final boolean readBoolean() { return (mBuffer[mPosition++] == 1 ? true : false); } public final byte readByte() { return mBuffer[mPosition++]; } public final int readInt() { return ((mBuffer[mPosition++] & 0xFF) << 24) | ((mBuffer[mPosition++] & 0xFF) << 16) | ((mBuffer[mPosition++] & 0xFF) << 8) | (mBuffer[mPosition++] & 0xFF); } public final int readVarInt() { int value = ((mBuffer[mPosition++] & 127)); if ((mBuffer[mPosition - 1] & 128) != 0) { value |= ((mBuffer[mPosition++] & 127)) << 7; if ((mBuffer[mPosition - 1] & 128) != 0) { value |= ((mBuffer[mPosition++] & 127)) << 14; if ((mBuffer[mPosition - 1] & 128) != 0) { value |= ((mBuffer[mPosition++] & 127)) << 21; if ((mBuffer[mPosition - 1] & 128) != 0) { value |= ((mBuffer[mPosition++] & 255)) << 28; } else if ((mBuffer[mPosition - 1] & 64) != 0) value |= 0xF0000000; } else if ((mBuffer[mPosition - 1] & 64) != 0) value |= 0xFFF00000; } else if ((mBuffer[mPosition - 1] & 64) != 0) value |= 0xFFFFE000; } else if ((mBuffer[mPosition - 1] & 64) != 0) value |= 0xFFFFFFC0; return value; } public final long readVarLong() { mPosition++; long value = (long) (mBuffer[mPosition++] & 255); if (mBuffer[mPosition - 2] > 1) { value += ((long) (mBuffer[mPosition++] & 255) << 8); if (mBuffer[mPosition - 3] > 2) { value += ((long) (mBuffer[mPosition++] & 255) << 16); if (mBuffer[mPosition - 4] > 3) { value += ((long) (mBuffer[mPosition++] & 255) << 24); if (mBuffer[mPosition - 5] > 4) { value += ((long) (mBuffer[mPosition++] & 255) << 32); if (mBuffer[mPosition - 6] > 5) { value += ((long) (mBuffer[mPosition++] & 255) << 40); if (mBuffer[mPosition - 7] > 6) { value += ((long) (mBuffer[mPosition++] & 255) << 48); if (mBuffer[mPosition - 8] > 7) { value += ((long) mBuffer[mPosition++] << 56); } else if ((mBuffer[mPosition - 1] & 128) != 0) value |= 0xFF000000000000L; } else if ((mBuffer[mPosition - 1] & 128) != 0) value |= 0xFFFF000000000000L; } else if ((mBuffer[mPosition - 1] & 128) != 0) value |= 0xFFFFFF0000000000L; } else if ((mBuffer[mPosition - 1] & 128) != 0) value |= 0xFFFFFFFF00000000L; } else if ((mBuffer[mPosition - 1] & 128) != 0) value |= 0xFFFFFFFFFF000000L; } else if ((mBuffer[mPosition - 1] & 128) != 0) value |= 0xFFFFFFFFFFFF0000L; } else if ((mBuffer[mPosition - 1] & 128) != 0) value |= 0xFFFFFFFFFFFFFF00L; return value; } public final long readLong() { return (((long) mBuffer[mPosition++] << 56) + ((long) (mBuffer[mPosition++] & 255) << 48) + ((long) (mBuffer[mPosition++] & 255) << 40) + ((long) (mBuffer[mPosition++] & 255) << 32) + ((long) (mBuffer[mPosition++] & 255) << 24) + ((mBuffer[mPosition++] & 255) << 16) + ((mBuffer[mPosition++] & 255) << 8) + (mBuffer[mPosition++] & 255)); } public final byte[] readByteArray() { final int size = ((mBuffer[mPosition++] & 0xFF) << 16) | ((mBuffer[mPosition++] & 0xFF) << 8) | (mBuffer[mPosition++] & 0xFF); final byte[] byteArray = new byte[size]; System.arraycopy(mBuffer, mPosition, byteArray, 0, size); mPosition += size; return byteArray; } }
package org.treetank.utils; import java.math.BigInteger; public final class FastByteArrayWriter { private byte[] mBuffer; private int mSize; /** * Constructor. * */ public FastByteArrayWriter() throws Exception { mBuffer = new byte[32]; mSize = 0; } public final void writeBoolean(final boolean value) throws Exception { assertSize(1); mBuffer[mSize++] = (byte) (value ? 1 : 0); } public final void writeByte(final byte value) throws Exception { assertSize(1); mBuffer[mSize++] = value; } public final void writePseudoInt(final int value) throws Exception { assertSize(3); mBuffer[mSize++] = (byte) (value >> 16); mBuffer[mSize++] = (byte) (value >> 8); mBuffer[mSize++] = (byte) value; } public final void writeInt(final int value) throws Exception { assertSize(4); mBuffer[mSize++] = (byte) (value >> 24); mBuffer[mSize++] = (byte) (value >> 16); mBuffer[mSize++] = (byte) (value >> 8); mBuffer[mSize++] = (byte) value; } public final void writePseudoVarSizeInt(final int value) throws Exception { assertSize(4); mBuffer[mSize++] = (byte) (value); if (value > 127/*63 || value < -64*/) { mBuffer[mSize-1] |= 128; mBuffer[mSize++] = (byte) (value >> 7); if (value > 16383/*8191 || value < -8192*/) { mBuffer[mSize-1] |= 128; mBuffer[mSize++] = (byte) (value >> 14); if (value > 2097151/*1048575 || value < -1048576*/) { mBuffer[mSize-1] |= 128; mBuffer[mSize++] = (byte) (value >> 21); } else mBuffer[mSize-1] &= 127; } else mBuffer[mSize-1] &= 127; } else mBuffer[mSize-1] &= 127; } public final void writePseudoLong(final long value) throws Exception { assertSize(6); mBuffer[mSize++] = (byte) (value >>> 40); mBuffer[mSize++] = (byte) (value >>> 32); mBuffer[mSize++] = (byte) (value >>> 24); mBuffer[mSize++] = (byte) (value >>> 16); mBuffer[mSize++] = (byte) (value >> 8); mBuffer[mSize++] = (byte) value; } public final void writeLong(final long value) throws Exception { assertSize(8); mBuffer[mSize++] = (byte) (value >>> 56); mBuffer[mSize++] = (byte) (value >>> 48); mBuffer[mSize++] = (byte) (value >>> 40); mBuffer[mSize++] = (byte) (value >>> 32); mBuffer[mSize++] = (byte) (value >>> 24); mBuffer[mSize++] = (byte) (value >>> 16); mBuffer[mSize++] = (byte) (value >> 8); mBuffer[mSize++] = (byte) value; } public final void writeByteArray(final byte[] value) throws Exception { assertSize(value.length + 3); // Size of byte array. mBuffer[mSize++] = (byte) (value.length >> 16); mBuffer[mSize++] = (byte) (value.length >> 8); mBuffer[mSize++] = (byte) value.length; // Byte array. System.arraycopy(value, 0, mBuffer, mSize, value.length); mSize += value.length; } public final byte[] getBytes() throws Exception { return mBuffer; } public final int size() { return mSize; } public final void reset() { mSize = 0; } private final void assertSize(final int sizeDifference) { final int requestedSize = mSize + sizeDifference; if (requestedSize > mBuffer.length) { final byte[] biggerBuffer = new byte[requestedSize << 1]; System.arraycopy(mBuffer, 0, biggerBuffer, 0, mBuffer.length); mBuffer = biggerBuffer; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.trie.spellchecker; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Leandro Ordonez <leandro.ordone.ante@gmail.com> */ public class TrieSpellChecker { public static final List<String> DICT = new ArrayList<>(); public static void initialize() { try { InputStream dictStream = TrieSpellChecker.class.getResourceAsStream("/org/trie/util/american-english"); BufferedReader br = new BufferedReader(new InputStreamReader(dictStream)); String line; while ((line = br.readLine()) != null) { DICT.add(line); } // System.out.println(DICT); } catch (FileNotFoundException ex) { Logger.getLogger(TrieSpellChecker.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(TrieSpellChecker.class.getName()).log(Level.SEVERE, null, ex); } } public static String compoundSplitter(String concatenatedWord) { return compoundSplitter(concatenatedWord, 0); } private static String compoundSplitter(String concatenatedWord, int level) { if (DICT.isEmpty()) { initialize(); } if (DICT.contains(concatenatedWord) || DICT.contains(concatenatedWord.toLowerCase())) { return concatenatedWord; } else { String firstTerm, secondTerm, lastGoodFirst = "#none"; int i = 2; while (i <= concatenatedWord.length()) { firstTerm = concatenatedWord.substring(0, i); secondTerm = concatenatedWord.substring(i); if (DICT.contains(firstTerm)) { lastGoodFirst = firstTerm; if (DICT.contains(secondTerm)) { return firstTerm + " " + secondTerm; } else { i++; } //return firstTerm + " " + secondTerm; } else { if (firstTerm.equals(concatenatedWord)) { if(level < 1 && !lastGoodFirst.equals("#none")){ return lastGoodFirst + " " + compoundSplitter(concatenatedWord.substring(lastGoodFirst.length()), level+1); } else { return (level > 0)? "\b" + concatenatedWord : concatenatedWord; } } else { i++; } } } // System.out.println(lastFirstCorrect); } return concatenatedWord; } public static void main(String[] args) { System.out.println(TrieSpellChecker.compoundSplitter("housenumbernumeric")); // -> house number numeric System.out.println(TrieSpellChecker.compoundSplitter("wickedweather")); // -> wicked weather System.out.println(TrieSpellChecker.compoundSplitter("liquidweather")); // -> liquid weather System.out.println(TrieSpellChecker.compoundSplitter("driveourtrucks")); // -> drive our trucks System.out.println(TrieSpellChecker.compoundSplitter("gocompact")); // -> go compact System.out.println(TrieSpellChecker.compoundSplitter("slimprojector")); // -> slim projector System.out.println(TrieSpellChecker.compoundSplitter("orcore")); // -> or core System.out.println(TrieSpellChecker.compoundSplitter("zipcode")); // -> zip code System.out.println(TrieSpellChecker.compoundSplitter("asdkjkeerver")); // -> asdkjkeerver } }
package biweekly.io.json; import static biweekly.util.TestUtils.assertDateEquals; import static biweekly.util.TestUtils.assertIntEquals; import static biweekly.util.TestUtils.assertWarnings; import static biweekly.util.TestUtils.buildTimezone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import java.util.TimeZone; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import biweekly.ICalendar; import biweekly.component.DaylightSavingsTime; import biweekly.component.ICalComponent; import biweekly.component.RawComponent; import biweekly.component.StandardTime; import biweekly.component.VEvent; import biweekly.component.VTimezone; import biweekly.component.marshaller.ICalComponentMarshaller; import biweekly.io.CannotParseException; import biweekly.io.SkipMeException; import biweekly.parameter.ICalParameters; import biweekly.parameter.Value; import biweekly.property.ICalProperty; import biweekly.property.RawProperty; import biweekly.property.RecurrenceDates; import biweekly.property.RecurrenceRule; import biweekly.property.RecurrenceRule.DayOfWeek; import biweekly.property.RecurrenceRule.Frequency; import biweekly.property.Summary; import biweekly.property.marshaller.ICalPropertyMarshaller; import biweekly.util.Duration; import biweekly.util.Period; /** * @author Michael Angstadt */ public class JCalReaderTest { private static TimeZone defaultTz; private final String NEWLINE = System.getProperty("line.separator"); @BeforeClass public static void beforeClass() { //change the default timezone because my timezone is "US/Eastern", which is what the example jCal documents use defaultTz = TimeZone.getDefault(); TimeZone.setDefault(buildTimezone(1, 0)); } @AfterClass public static void afterClass() { TimeZone.setDefault(defaultTz); } @Test public void read_single() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "[\"prodid\", {}, \"text\", \"-//xyz Corp//NONSGML PDA Calendar Version 1.0//EN\"]," + "[\"version\", {}, \"text\", \"2.0\"]" + "]," + "[" + "[\"vevent\"," + "[" + "[\"summary\", {}, \"text\", \"Networld+Interop Conference\"]," + "[\"description\", {}, \"text\", \"Networld+Interop Conference\\nand Exhibit\\nAtlanta World Congress Center\\nAtlanta, Georgia\"]" + "]," + "[" + "]" + "]" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); ICalendar ical = reader.readNext(); assertEquals(2, ical.getProperties().size()); assertEquals("-//xyz Corp//NONSGML PDA Calendar Version 1.0//EN", ical.getProductId().getValue()); assertEquals("2.0", ical.getVersion().getMaxVersion()); assertEquals(1, ical.getComponents().size()); VEvent event = ical.getEvents().get(0); assertEquals(2, event.getProperties().size()); assertEquals("Networld+Interop Conference", event.getSummary().getValue()); assertEquals("Networld+Interop Conference" + NEWLINE + "and Exhibit" + NEWLINE + "Atlanta World Congress Center" + NEWLINE + "Atlanta, Georgia", event.getDescription().getValue()); assertNull(reader.readNext()); assertWarnings(0, reader.getWarnings()); } @Test public void read_multiple() throws Throwable { //@formatter:off String json = "[" + "[\"vcalendar\"," + "[" + "[\"prodid\", {}, \"text\", \"prodid1\"]," + "[\"version\", {}, \"text\", \"2.0\"]" + "]," + "[" + "[\"vevent\"," + "[" + "[\"summary\", {}, \"text\", \"summary1\"]," + "[\"description\", {}, \"text\", \"description1\"]" + "]," + "[" + "]" + "]" + "]" + "]," + "[\"vcalendar\"," + "[" + "[\"prodid\", {}, \"text\", \"prodid2\"]," + "[\"version\", {}, \"text\", \"2.0\"]" + "]," + "[" + "[\"vevent\"," + "[" + "[\"summary\", {}, \"text\", \"summary2\"]," + "[\"description\", {}, \"text\", \"description2\"]" + "]," + "[" + "]" + "]" + "]" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); { ICalendar ical = reader.readNext(); assertEquals(2, ical.getProperties().size()); assertEquals("prodid1", ical.getProductId().getValue()); assertEquals("2.0", ical.getVersion().getMaxVersion()); assertEquals(1, ical.getComponents().size()); VEvent event = ical.getEvents().get(0); assertEquals(2, event.getProperties().size()); assertEquals("summary1", event.getSummary().getValue()); assertEquals("description1", event.getDescription().getValue()); assertWarnings(0, reader.getWarnings()); } { ICalendar ical = reader.readNext(); assertEquals(2, ical.getProperties().size()); assertEquals("prodid2", ical.getProductId().getValue()); assertEquals("2.0", ical.getVersion().getMaxVersion()); assertEquals(1, ical.getComponents().size()); VEvent event = ical.getEvents().get(0); assertEquals(2, event.getProperties().size()); assertEquals("summary2", event.getSummary().getValue()); assertEquals("description2", event.getDescription().getValue()); assertWarnings(0, reader.getWarnings()); } assertNull(reader.readNext()); } @Test public void no_properties() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "]," + "[" + "[\"vevent\"," + "[" + "[\"summary\", {}, \"text\", \"summary\"]" + "]," + "[" + "]" + "]" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); ICalendar ical = reader.readNext(); assertEquals(0, ical.getProperties().size()); assertEquals(1, ical.getComponents().size()); VEvent event = ical.getEvents().get(0); assertEquals(1, event.getProperties().size()); assertEquals("summary", event.getSummary().getValue()); assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void no_components() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "[\"prodid\", {}, \"text\", \"prodid\"]" + "]," + "[" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); ICalendar ical = reader.readNext(); assertEquals(1, ical.getProperties().size()); assertEquals("prodid", ical.getProductId().getValue()); assertEquals(0, ical.getComponents().size()); assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void no_properties_or_components() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "]," + "[" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); ICalendar ical = reader.readNext(); assertEquals(0, ical.getProperties().size()); assertEquals(0, ical.getComponents().size()); assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void experimental_component() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "]," + "[" + "[\"x-party\"," + "[" + "[\"summary\", {}, \"text\", \"summary\"]" + "]," + "[" + "]" + "]" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); ICalendar ical = reader.readNext(); assertEquals(0, ical.getProperties().size()); assertEquals(1, ical.getComponents().size()); RawComponent party = ical.getExperimentalComponent("x-party"); assertEquals(1, party.getProperties().size()); assertEquals("summary", party.getProperty(Summary.class).getValue()); assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void experimental_component_registered() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "]," + "[" + "[\"x-party\"," + "[" + "[\"summary\", {}, \"text\", \"summary\"]" + "]," + "[" + "]" + "]" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); reader.registerMarshaller(new PartyMarshaller()); ICalendar ical = reader.readNext(); assertEquals(0, ical.getProperties().size()); assertEquals(1, ical.getComponents().size()); Party party = ical.getComponent(Party.class); assertEquals(1, party.getProperties().size()); assertEquals("summary", party.getProperty(Summary.class).getValue()); assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void experimental_property() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "[\"x-company\", {}, \"text\", \"value\"]," + "[\"x-company2\", {}, \"unknown\", \"value\"]" + "]," + "[" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); ICalendar ical = reader.readNext(); assertEquals(2, ical.getProperties().size()); RawProperty company = ical.getExperimentalProperty("x-company"); assertEquals(Value.TEXT, company.getParameters().getValue()); assertEquals("value", company.getValue()); company = ical.getExperimentalProperty("x-company2"); assertNull(company.getParameters().getValue()); assertEquals("value", company.getValue()); assertEquals(0, ical.getComponents().size()); assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void experimental_property_registered() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "[\"x-company\", {}, \"text\", \"value\"]" + "]," + "[" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); reader.registerMarshaller(new CompanyMarshaller()); ICalendar ical = reader.readNext(); assertEquals(1, ical.getProperties().size()); Company company = ical.getProperty(Company.class); assertEquals("value", company.getBoss()); assertEquals(0, ical.getComponents().size()); assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void skipMeException() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "[\"x-company\", {}, \"text\", \"skip-me\"]" + "]," + "[" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); reader.registerMarshaller(new CompanyMarshaller()); ICalendar ical = reader.readNext(); assertEquals(0, ical.getProperties().size()); assertEquals(0, ical.getComponents().size()); assertWarnings(1, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void cannotParseException() throws Throwable { //@formatter:off String json = "[\"vcalendar\"," + "[" + "[\"x-company\", {}, \"text\", \"don't-parse-me-bro\"]" + "]," + "[" + "]" + "]"; //@formatter:on JCalReader reader = new JCalReader(json); reader.registerMarshaller(new CompanyMarshaller()); ICalendar ical = reader.readNext(); assertEquals(1, ical.getProperties().size()); assertNull(ical.getProperty(Company.class)); RawProperty company = ical.getExperimentalProperty("x-company"); assertEquals(Value.TEXT, company.getParameters().getValue()); assertEquals("don't-parse-me-bro", company.getValue()); assertEquals(0, ical.getComponents().size()); assertWarnings(1, reader.getWarnings()); assertNull(reader.readNext()); } @Test public void empty() throws Throwable { //@formatter:off String json = ""; //@formatter:on JCalReader reader = new JCalReader(json); assertNull(reader.readNext()); } @Test public void jcal_draft_example1() throws Throwable { JCalReader reader = new JCalReader(getClass().getResourceAsStream("jcal-draft-example1.json")); ICalendar ical = reader.readNext(); assertEquals(3, ical.getProperties().size()); assertEquals("-//Example Inc.//Example Calendar//EN", ical.getProductId().getValue()); assertEquals("2.0", ical.getVersion().getMaxVersion()); assertTrue(ical.getCalendarScale().isGregorian()); assertEquals(1, ical.getComponents().size()); { VEvent event = ical.getEvents().get(0); assertEquals(4, event.getProperties().size()); assertDateEquals("20080205T191224Z", event.getDateTimeStamp().getValue()); assertDateEquals("20081006", event.getDateStart().getValue()); assertFalse(event.getDateStart().hasTime()); assertEquals("Planning meeting", event.getSummary().getValue()); assertEquals("4088E990AD89CB3DBB484909", event.getUid().getValue()); assertEquals(0, event.getComponents().size()); } assertNull(reader.readNext()); } @Test public void jcal_draft_example2() throws Throwable { JCalReader reader = new JCalReader(getClass().getResourceAsStream("jcal-draft-example2.json")); ICalendar ical = reader.readNext(); DateFormat usEastern = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); usEastern.setTimeZone(TimeZone.getTimeZone("US/Eastern")); assertEquals(2, ical.getProperties().size()); assertEquals("-//Example Corp.//Example Client//EN", ical.getProductId().getValue()); assertEquals("2.0", ical.getVersion().getMaxVersion()); assertEquals(3, ical.getComponents().size()); { VTimezone timezone = ical.getTimezones().get(0); assertEquals(2, timezone.getProperties().size()); assertDateEquals("20040110T032845Z", timezone.getLastModified().getValue()); assertEquals("US/Eastern", timezone.getTimezoneId().getValue()); assertEquals(2, timezone.getComponents().size()); { DaylightSavingsTime daylight = timezone.getDaylightSavingsTime().get(0); assertEquals(5, daylight.getProperties().size()); assertDateEquals("20000404T020000", daylight.getDateStart().getValue()); RecurrenceRule rrule = daylight.getRecurrenceRule(); assertEquals(Frequency.YEARLY, rrule.getFrequency()); assertEquals(Arrays.asList(DayOfWeek.SUNDAY), rrule.getByDay()); assertEquals(Arrays.asList(1), rrule.getByDayPrefixes()); assertEquals(Arrays.asList(4), rrule.getByMonth()); assertEquals("EDT", daylight.getTimezoneNames().get(0).getValue()); assertIntEquals(-5, daylight.getTimezoneOffsetFrom().getHourOffset()); assertIntEquals(0, daylight.getTimezoneOffsetFrom().getMinuteOffset()); assertIntEquals(-4, daylight.getTimezoneOffsetTo().getHourOffset()); assertIntEquals(0, daylight.getTimezoneOffsetTo().getMinuteOffset()); } { StandardTime standard = timezone.getStandardTimes().get(0); assertEquals(5, standard.getProperties().size()); assertDateEquals("20001026T020000", standard.getDateStart().getValue()); RecurrenceRule rrule = standard.getRecurrenceRule(); assertEquals(Frequency.YEARLY, rrule.getFrequency()); assertEquals(Arrays.asList(DayOfWeek.SUNDAY), rrule.getByDay()); assertEquals(Arrays.asList(1), rrule.getByDayPrefixes()); assertEquals(Arrays.asList(10), rrule.getByMonth()); assertEquals("EST", standard.getTimezoneNames().get(0).getValue()); assertIntEquals(-4, standard.getTimezoneOffsetFrom().getHourOffset()); assertIntEquals(0, standard.getTimezoneOffsetFrom().getMinuteOffset()); assertIntEquals(-5, standard.getTimezoneOffsetTo().getHourOffset()); assertIntEquals(0, standard.getTimezoneOffsetTo().getMinuteOffset()); } } { VEvent event = ical.getEvents().get(0); assertEquals(8, event.getProperties().size()); assertDateEquals("20060206T001121Z", event.getDateTimeStamp().getValue()); assertEquals(usEastern.parse("2006-01-02T12:00:00"), event.getDateStart().getValue()); assertEquals("US/Eastern", event.getDateStart().getTimezoneId()); assertEquals(new Duration.Builder().hours(1).build(), event.getDuration().getValue()); RecurrenceRule rrule = event.getRecurrenceRule(); assertEquals(Frequency.DAILY, rrule.getFrequency()); assertIntEquals(5, rrule.getCount()); RecurrenceDates rdate = event.getRecurrenceDates().get(0); assertNull(rdate.getDates()); assertEquals(1, rdate.getPeriods().size()); assertEquals(new Period(usEastern.parse("2006-01-02T15:00:00"), new Duration.Builder().hours(2).build()), rdate.getPeriods().get(0)); assertEquals("US/Eastern", rdate.getTimezoneId()); assertEquals("Event #2", event.getSummary().getValue()); assertEquals("We are having a meeting all this week at 12 pm for one hour, with an additional meeting on the first day 2 hours long." + NEWLINE + "Please bring your own lunch for the 12 pm meetings.", event.getDescription().getValue()); assertEquals("00959BC664CA650E933C892C@example.com", event.getUid().getValue()); } { VEvent event = ical.getEvents().get(1); assertEquals(6, event.getProperties().size()); assertDateEquals("20060206T001121Z", event.getDateTimeStamp().getValue()); assertEquals(usEastern.parse("2006-01-02T14:00:00"), event.getDateStart().getValue()); assertEquals("US/Eastern", event.getDateStart().getTimezoneId()); assertEquals(new Duration.Builder().hours(1).build(), event.getDuration().getValue()); assertEquals(usEastern.parse("2006-01-04T12:00:00"), event.getRecurrenceId().getValue()); assertEquals("US/Eastern", event.getRecurrenceId().getTimezoneId()); assertEquals("Event #2", event.getSummary().getValue()); assertEquals("00959BC664CA650E933C892C@example.com", event.getUid().getValue()); } assertNull(reader.readNext()); } private class CompanyMarshaller extends ICalPropertyMarshaller<Company> { public CompanyMarshaller() { super(Company.class, "X-COMPANY"); } @Override protected String _writeText(Company property) { return property.getBoss(); } @Override protected Company _parseText(String value, ICalParameters parameters, List<String> warnings) { return new Company(value); } @Override protected Company _parseJson(JCalValue value, ICalParameters parameters, List<String> warnings) { String boss = value.getSingleValued(); if (boss.equals("skip-me")) { throw new SkipMeException(); } if (boss.equals("don't-parse-me-bro")) { throw new CannotParseException(); } return new Company(boss); } } private class Company extends ICalProperty { private String boss; public Company(String boss) { this.boss = boss; } public String getBoss() { return boss; } } private class PartyMarshaller extends ICalComponentMarshaller<Party> { public PartyMarshaller() { super(Party.class, "X-PARTY"); } @Override protected Party _newInstance() { return new Party(); } } private class Party extends ICalComponent { //empty } }
package com.adyen; import com.adyen.httpclient.ClientInterface; import com.adyen.httpclient.HTTPClientException; import com.adyen.model.checkout.CreateCheckoutSessionRequest; import com.adyen.model.checkout.CreatePaymentLinkRequest; import com.adyen.model.checkout.PaymentSessionRequest; import com.adyen.model.checkout.PaymentsRequest; import com.adyen.service.Checkout; import com.adyen.service.PaymentLinks; import com.adyen.service.exception.ApiException; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.util.Calendar; import java.util.Date; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.verify; public class DateSerializationTest extends BaseTest { /* Tests for checking if all models in the Checkout classes are actually serializing Date objects as ISO8601 strings (note: dateOfBirth also gets serialized to ISO8601 which is fine one API side) */ private Date date() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 2023); cal.set(Calendar.MONTH, 5); cal.set(Calendar.DAY_OF_MONTH, 2); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } @Test public void TestCheckoutSessionDate() throws IOException, ApiException, HTTPClientException { Client client = createMockClientFromFile("mocks/checkout/sessions-success.json"); Checkout checkout = new Checkout(client); CreateCheckoutSessionRequest sessionsRequest = new CreateCheckoutSessionRequest(); sessionsRequest.setDeliverAt(date()); checkout.sessions(sessionsRequest); ClientInterface http = client.getHttpClient(); String expected = "\"deliverAt\":\"2023-06-02T12:00:00"; verify(http).request(anyString(), Mockito.contains(expected), any(), eq(true), isNull(), any()); } @Test public void TestCreatePaymentLinkDate() throws IOException, ApiException, HTTPClientException { Client client = createMockClientFromFile("mocks/checkout/sessions-success.json"); PaymentLinks payment = new PaymentLinks(client); CreatePaymentLinkRequest paymentLinkRequest = new CreatePaymentLinkRequest(); paymentLinkRequest.setDeliverAt(date()); paymentLinkRequest.setDateOfBirth(date()); payment.create(paymentLinkRequest); ClientInterface http = client.getHttpClient(); String expected1 = "\"deliverAt\":\"2023-06-02T12:00:00"; String expected2 = "\"dateOfBirth\":\"2023-06-02T12:00:00"; verify(http).request(anyString(), Mockito.contains(expected1), any(), eq(true), isNull(), any()); verify(http).request(anyString(), Mockito.contains(expected2), any(), eq(true), isNull(), any()); } @Test public void TestPaymentSessionDate() throws IOException, ApiException, HTTPClientException { Client client = createMockClientFromFile("mocks/checkout/sessions-success.json"); Checkout checkout = new Checkout(client); PaymentSessionRequest request = new PaymentSessionRequest(); request.setDateOfBirth(date()); request.setDeliveryDate(date()); checkout.paymentSession(request); ClientInterface http = client.getHttpClient(); String expected1 = "\"deliveryDate\":\"2023-06-02T12:00:00"; String expected2 = "\"dateOfBirth\":\"2023-06-02T12:00:00"; verify(http).request(anyString(), Mockito.contains(expected1), any(), eq(true), isNull(), any()); verify(http).request(anyString(), Mockito.contains(expected2), any(), eq(true), isNull(), any()); } @Test public void TestCheckoutPaymentsDate() throws IOException, ApiException, HTTPClientException { Client client = createMockClientFromFile("mocks/checkout/sessions-success.json"); Checkout checkout = new Checkout(client); PaymentsRequest request = new PaymentsRequest(); request.setDateOfBirth(date()); request.setDeliveryDate(date()); checkout.payments(request); ClientInterface http = client.getHttpClient(); String expected1 = "\"deliveryDate\":\"2023-06-02T12:00:00"; String expected2 = "\"dateOfBirth\":\"2023-06-02T12:00:00"; verify(http).request(anyString(), Mockito.contains(expected1), any(), eq(true), isNull(), any()); verify(http).request(anyString(), Mockito.contains(expected2), any(), eq(true), isNull(), any()); } }
package com.alexrnl.commons.mvc; import static org.junit.Assert.assertEquals; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Test suite for the * @author Alex */ public class MVCTest { /** The model for the tests*/ private ModelTest model; /** The view for the tests */ private ViewTest view; /** The controller for the tests */ private ControllerTest controller; /** * Set-up the MVC pattern. */ @Before public void setUp () { model = new ModelTest(); controller = new ControllerTest(); view = new ViewTest(controller); controller.addModel(model); controller.addView(view); model.initDefault(); } /** * Clean-up the controller. */ @After public void tearDown () { controller.removeModel(model); controller.removeView(view); } /** * Test the propagation of property through MVC, when changing the view. */ @Test public void changeFromViewTest () { assertEquals(8, view.getDisplayedValue().intValue()); assertEquals("Alex", view.getDisplayedName()); view.setName("Walt"); view.setValue(99); assertEquals(99, view.getDisplayedValue().intValue()); assertEquals("Walt", view.getDisplayedName()); } /** * Test the propagation of property which does not exist in the model. */ @Test public void changeUnexistingPropertyTest () { for (int i = 0; i < 2; ++i) { assertEquals(8, view.getDisplayedValue().intValue()); assertEquals("Alex", view.getDisplayedName()); view.setGhostProperty("LuD"); assertEquals(8, view.getDisplayedValue().intValue()); assertEquals("Alex", view.getDisplayedName()); Logger.getLogger(AbstractModel.class.getName()).setLevel(Level.FINE); Logger.getLogger(AbstractController.class.getName()).setLevel(Level.FINE); } } /** * Test that the controller can handle the addition of <code>null</code> views and model. */ @Test public void addNullModelAndView () { controller.addModel(null); controller.addView(null); } }
package com.github.arteam.jdbi3; import com.codahale.metrics.annotation.Timed; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.stringtemplate4.UseStringTemplateSqlLocator; import java.time.LocalDate; import java.util.Optional; @UseStringTemplateSqlLocator @Timed(name = "game-dao") public interface GameDao { @SqlQuery ImmutableList<Integer> findGameIds(); @SqlQuery ImmutableSet<String> findAllUniqueHomeTeams(); @SqlQuery Optional<Integer> findIdByTeamsAndDate(@Bind("home_team") String homeTeam, @Bind("visitor_team") String visitorTeam, @Bind("played_at") LocalDate date); @SqlQuery LocalDate getFirstPlayedSince(@Bind("up") LocalDate up); @SqlQuery @Timed(name = "last-played-date") Optional<LocalDate> getLastPlayedDateByTeams(@Bind("home_team") String homeTeam, @Bind("visitor_team") String visitorTeam); @SqlQuery Optional<String> findHomeTeamByGameId(@Bind("id") Optional<Integer> id); }
package com.lhkbob.entreri; import org.junit.Assert; import org.junit.Test; import com.lhkbob.entreri.component.IntComponent; public class IteratorTest { @Test public void testDisabledComponents() { EntitySystem system = new EntitySystem(); IntComponent cd = system.createDataInstance(TypeId.get(IntComponent.class)); Entity e1 = system.addEntity(); e1.add(TypeId.get(IntComponent.class)).setEnabled(true); Entity e2 = system.addEntity(); e2.add(TypeId.get(IntComponent.class)).setEnabled(false); ComponentIterator it = new ComponentIterator(system); it.addRequired(cd); it.reset(); int count = 0; while(it.next()) { count++; Assert.assertSame(e1, cd.getEntity()); } Assert.assertEquals(1, count); } @Test public void testIgnoreEnabledComponents() { EntitySystem system = new EntitySystem(); IntComponent cd = system.createDataInstance(TypeId.get(IntComponent.class)); Entity e1 = system.addEntity(); e1.add(TypeId.get(IntComponent.class)).setEnabled(true); Entity e2 = system.addEntity(); e2.add(TypeId.get(IntComponent.class)).setEnabled(false); ComponentIterator it = new ComponentIterator(system); it.addRequired(cd) .setIgnoreEnabled(true) .reset(); boolean hasE1 = false; boolean hasE2 = false; while(it.next()) { if (e1 == cd.getEntity()) { Assert.assertFalse(hasE1); hasE1 = true; } else if (e2 == cd.getEntity()) { Assert.assertFalse(hasE2); hasE2 = true; } else { Assert.fail(); } } Assert.assertTrue(hasE1); Assert.assertTrue(hasE2); } }
package hudson.plugins.jira; import com.atlassian.jira.rest.client.api.RestClientException; import com.atlassian.jira.rest.client.api.domain.Comment; import com.atlassian.jira.rest.client.api.domain.Issue; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import hudson.model.*; import hudson.plugins.jira.listissuesparameter.JiraIssueParameterValue; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.jvnet.hudson.test.Bug; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.rmi.RemoteException; import java.util.*; import java.util.regex.Pattern; import static org.mockito.Mockito.*; import static org.hamcrest.CoreMatchers.*; /** * Test case for the JIRA {@link Updater}. * * @author kutzi */ @SuppressWarnings("unchecked") public class UpdaterTest { private static class MockEntry extends Entry { private final String msg; public MockEntry(String msg) { this.msg = msg; } @Override public Collection<String> getAffectedPaths() { return null; } @Override public User getAuthor() { return null; } @Override public String getMsg() { return this.msg; } } /** * Tests that the JiraIssueParameters are identified as updateable JIRA * issues. */ @Test @Bug(12312) public void testFindIssuesWithJiraParameters() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); BuildListener listener = mock(BuildListener.class); JiraIssueParameterValue parameter = mock(JiraIssueParameterValue.class); JiraIssueParameterValue parameterTwo = mock(JiraIssueParameterValue.class); ParametersAction action = mock(ParametersAction.class); List<ParameterValue> parameters = new ArrayList<ParameterValue>(); when(changeLogSet.iterator()).thenReturn( Collections.EMPTY_LIST.iterator()); when(build.getChangeSet()).thenReturn(changeLogSet); when(build.getAction(ParametersAction.class)).thenReturn(action); when(action.getParameters()).thenReturn(parameters); when(parameter.getValue()).thenReturn("JIRA-123"); when(parameterTwo.getValue()).thenReturn("JIRA-321"); Set<String> ids = new HashSet<String>(); // Initial state contains zero parameters Updater.findIssues(build, ids, null, listener); Assert.assertTrue(ids.isEmpty()); ids = new HashSet<String>(); parameters.add(parameter); Updater.findIssues(build, ids, JiraSite.DEFAULT_ISSUE_PATTERN, listener); Assert.assertEquals(1, ids.size()); Assert.assertEquals("JIRA-123", ids.iterator().next()); ids = new TreeSet<String>(); parameters.add(parameterTwo); Updater.findIssues(build, ids, JiraSite.DEFAULT_ISSUE_PATTERN, listener); Assert.assertEquals(2, ids.size()); Set<String> expected = Sets.newTreeSet(Sets.newHashSet("JIRA-123", "JIRA-321")); Assert.assertEquals(expected, ids); } @Test @Bug(4132) public void testProjectNamesAllowed() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); BuildListener listener = mock(BuildListener.class); Set<? extends Entry> entries = Sets.newHashSet( new MockEntry("Fixed JI123-4711"), new MockEntry("Fixed foo_bar-4710"), new MockEntry("Fixed FoO_bAr-4711"), new MockEntry("Fixed someting.\nJFoO_bAr_MULTI-4718"), new MockEntry("TR-123: foo"), new MockEntry("[ABC-42] hallo"), new MockEntry("#123: this one must not match"), new MockEntry("ABC-: this one must also not match"), new MockEntry("ABC-: \n\nABC-127:\nthis one should match"), new MockEntry("ABC-: \n\nABC-128:\nthis one should match"), new MockEntry("ABC-: \n\nXYZ-10:\nXYZ-20 this one too"), new MockEntry("Fixed DOT-4."), new MockEntry("Fixed DOT-5. Did it right this time") ); when(build.getChangeSet()).thenReturn(changeLogSet); when(changeLogSet.iterator()).thenReturn(entries.iterator()); Set<String> expected = Sets.newHashSet( "JI123-4711", "FOO_BAR-4710", "FOO_BAR-4711", "JFOO_BAR_MULTI-4718", "TR-123", "ABC-42", "ABC-127", "ABC-128", "XYZ-10", "XYZ-20", "DOT-4", "DOT-5" ); Set<String> result = new HashSet<String>(); Updater.findIssues(build, result, JiraSite.DEFAULT_ISSUE_PATTERN, listener); Assert.assertEquals(expected.size(), result.size()); Assert.assertEquals(expected,result); } @Test public void testGetScmCommentsFromPreviousBuilds() throws Exception { final FreeStyleProject project = mock(FreeStyleProject.class); final FreeStyleBuild build1 = mock(FreeStyleBuild.class); final MockEntry entry1 = new MockEntry("FOOBAR-1: The first build"); { ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build1.getChangeSet()).thenReturn(changeLogSet); when(build1.getResult()).thenReturn(Result.FAILURE); doReturn(project).when(build1).getProject(); doReturn(new JiraCarryOverAction(Lists.newArrayList(new JiraIssue("FOOBAR-1", null)))) .when(build1).getAction(JiraCarryOverAction.class); final Set<? extends Entry> entries = Sets.newHashSet(entry1); when(changeLogSet.iterator()).thenAnswer(new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { return entries.iterator(); } }); } final FreeStyleBuild build2 = mock(FreeStyleBuild.class); final MockEntry entry2 = new MockEntry("FOOBAR-2: The next build"); { ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build2.getChangeSet()).thenReturn(changeLogSet); when(build2.getPreviousBuild()).thenReturn(build1); when(build2.getResult()).thenReturn(Result.SUCCESS); doReturn(project).when(build2).getProject(); final Set<? extends Entry> entries = Sets.newHashSet(entry2); when(changeLogSet.iterator()).thenAnswer(new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { return entries.iterator(); } }); } final List<Comment> comments = Lists.newArrayList(); final JiraSession session = mock(JiraSession.class); doAnswer(new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { Comment rc = Comment.createWithGroupLevel((String) invocation.getArguments()[1], (String) invocation.getArguments()[2]); comments.add(rc); return null; } }).when(session).addComment(anyString(), anyString(), anyString(), anyString()); final List<JiraIssue> ids = Lists.newArrayList(new JiraIssue("FOOBAR-1", null), new JiraIssue("FOOBAR-2", null)); Updater.submitComments(build2, System.out, "http://jenkins", ids, session, false, false, "", ""); Assert.assertEquals(2, comments.size()); Assert.assertThat(comments.get(0).getBody(), Matchers.containsString(entry1.getMsg())); Assert.assertThat(comments.get(1).getBody(), Matchers.containsString(entry2.getMsg())); } /** * Tests that the generated comment matches the expectations - * especially that the JIRA id is not stripped from the comment. */ @Test @Bug(4572) public void testComment() throws Exception { // mock JIRA session: JiraSession session = mock(JiraSession.class); when(session.existsIssue(Mockito.anyString())).thenReturn(Boolean.TRUE); final Issue mockIssue = Mockito.mock(Issue.class); when(session.getIssue(Mockito.anyString())).thenReturn(mockIssue); final List<String> comments = new ArrayList<String>(); Answer answer = new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { comments.add((String) invocation.getArguments()[1]); return null; } }; doAnswer(answer).when(session).addComment(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); // mock build: FreeStyleBuild build = mock(FreeStyleBuild.class); FreeStyleProject project = mock(FreeStyleProject.class); when(build.getProject()).thenReturn(project); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); when(build.getResult()).thenReturn(Result.SUCCESS); Set<? extends Entry> entries = Sets.newHashSet(new MockEntry("Fixed FOOBAR-4711")); when(changeLogSet.iterator()).thenReturn(entries.iterator()); // test: List<JiraIssue> ids = Lists.newArrayList(new JiraIssue("FOOBAR-4711", "Title")); Updater.submitComments(build, System.out, "http://jenkins", ids, session, false, false, "", ""); Assert.assertEquals(1, comments.size()); String comment = comments.get(0); Assert.assertTrue(comment.contains("FOOBAR-4711")); // must also work case-insensitively (JENKINS-4132) comments.clear(); entries = Sets.newHashSet(new MockEntry("Fixed Foobar-4711")); when(changeLogSet.iterator()).thenReturn(entries.iterator()); ids = Lists.newArrayList(new JiraIssue("FOOBAR-4711", "Title")); Updater.submitComments(build, System.out, "http://jenkins", ids, session, false, false, "", ""); Assert.assertEquals(1, comments.size()); comment = comments.get(0); Assert.assertTrue(comment.contains("Foobar-4711")); } /** * Tests that the default pattern doesn't match strings like * 'project-1.1'. * These patterns are used e.g. by the maven release plugin. */ @Test public void testDefaultPattertNotToMatchMavenRelease() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); // commit messages like the one from the Maven release plugin must not match Set<? extends Entry> entries = Sets.newHashSet(new MockEntry("prepare release project-4.7.1")); when(changeLogSet.iterator()).thenReturn(entries.iterator()); Set<String> ids = new HashSet<String>(); Updater.findIssues(build, ids, JiraSite.DEFAULT_ISSUE_PATTERN, null); Assert.assertEquals(0, ids.size()); } @Test @Bug(6043) public void testUserPatternNotMatch() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); Set<? extends Entry> entries = Sets.newHashSet(new MockEntry("Fixed FOO_BAR-4711")); when(changeLogSet.iterator()).thenReturn(entries.iterator()); Set<String> ids = new HashSet<String>(); Updater.findIssues(build, ids, Pattern.compile("[(w)]"), mock(BuildListener.class)); Assert.assertEquals(0, ids.size()); } @Test @Bug(6043) public void testUserPatternMatch() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); Set<? extends Entry> entries = Sets.newHashSet(new MockEntry("Fixed toto [FOOBAR-4711]"), new MockEntry("[TEST-9] with [dede]"), new MockEntry("toto [maven-release-plugin] prepare release foo-2.2.3")); when(changeLogSet.iterator()).thenReturn(entries.iterator()); Set<String> ids = new HashSet<String>(); Pattern pat = Pattern.compile("\\[(\\w+-\\d+)\\]"); Updater.findIssues(build, ids, pat, mock(BuildListener.class)); Assert.assertEquals(2, ids.size()); Assert.assertTrue(ids.contains("TEST-9")); Assert.assertTrue(ids.contains("FOOBAR-4711")); } @Test @Bug(6043) public void testUserPatternMatchTwoIssuesInOneComment() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); Set<? extends Entry> entries = Sets.newHashSet(new MockEntry("Fixed toto [FOOBAR-4711] [FOOBAR-21] "), new MockEntry("[TEST-9] with [dede]"), new MockEntry("toto [maven-release-plugin] prepare release foo-2.2.3")); when(changeLogSet.iterator()).thenReturn(entries.iterator()); Set<String> ids = new HashSet<String>(); Pattern pat = Pattern.compile("\\[(\\w+-\\d+)\\]"); Updater.findIssues(build, ids, pat, mock(BuildListener.class)); Assert.assertEquals(3, ids.size()); Assert.assertTrue(ids.contains("TEST-9")); Assert.assertTrue(ids.contains("FOOBAR-4711")); Assert.assertTrue(ids.contains("FOOBAR-21")); } /** * Checks if issues are correctly removed from the carry over list. * @throws RemoteException */ @Test @Bug(17156) public void testIssueIsRemovedFromCarryOverListAfterSubmission() throws RestClientException { // mock build: FreeStyleBuild build = mock(FreeStyleBuild.class); FreeStyleProject project = mock(FreeStyleProject.class); when(build.getProject()).thenReturn(project); ChangeLogSet changeLogSet = ChangeLogSet.createEmpty(build); when(build.getChangeSet()).thenReturn(changeLogSet); when(build.getResult()).thenReturn(Result.SUCCESS); final JiraIssue firstIssue = new JiraIssue("FOOBAR-1", "Title"); final JiraIssue secondIssue = new JiraIssue("ALIBA-1", "Title"); final JiraIssue thirdIssue = new JiraIssue("MOONA-1", "Title"); final JiraIssue deletedIssue = new JiraIssue("FOOBAR-2", "Title"); final JiraIssue forbiddenIssue = new JiraIssue("LASSO-17", "Title"); // assume that there is a following list of jira issues from scm commit messages out of hudson.plugins.jira.JiraCarryOverAction List<JiraIssue> issues = Lists.newArrayList(firstIssue, secondIssue, forbiddenIssue, thirdIssue); // mock JIRA session: JiraSession session = mock(JiraSession.class); when(session.existsIssue(Mockito.anyString())).thenReturn(Boolean.TRUE); // when(session.getIssue(Mockito.anyString())).thenReturn( new Issue()); // when(session.getGroup(Mockito.anyString())).thenReturn(new Group("Software Development", null)); final List<Comment> comments = new ArrayList<Comment>(); Answer answer = new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { Comment c = Comment.createWithGroupLevel((String) invocation.getArguments()[0], (String) invocation.getArguments()[1]); comments.add(c); return null; } }; doAnswer(answer).when(session).addComment(eq(firstIssue.id), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); doAnswer(answer).when(session).addComment(eq(secondIssue.id), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); doAnswer(answer).when(session).addComment(eq(thirdIssue.id), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); // issue for the caught exception doThrow(new RestClientException(new Throwable(), 404)).when(session).addComment(eq(deletedIssue.id), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); doThrow(new RestClientException(new Throwable(), 403)).when(session).addComment(eq(forbiddenIssue.id), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); final String groupVisibility = ""; final String roleVisibility = ""; Updater.submitComments( build, System.out, "http://jenkins", issues, session, false, false, groupVisibility, roleVisibility ); // expected issue list final List<JiraIssue> expectedIssuesToCarryOver = new ArrayList<JiraIssue>(); expectedIssuesToCarryOver.add(forbiddenIssue); Assert.assertThat(issues, is(expectedIssuesToCarryOver)); } }
package integration.blog; import integration.configuration.IntegrationTestsConfiguration; import org.hamcrest.MatcherAssert; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.bootstrap.context.initializer.ConfigFileApplicationContextInitializer; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.site.domain.blog.Post; import org.springframework.site.domain.blog.PostBuilder; import org.springframework.site.domain.blog.PostCategory; import org.springframework.site.domain.blog.PostRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = IntegrationTestsConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class) public class BlogIndexTests { @Autowired private WebApplicationContext wac; @Autowired private PostRepository postRepository; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); postRepository.deleteAll(); } @After public void tearDown() throws Exception { postRepository.deleteAll(); } @Test public void given1Post_blogIndexShowsPostSummary() throws Exception { Post post = createSinglePost(); MvcResult response = mockMvc.perform(get("/blog")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith("text/html")) .andReturn(); Document html = Jsoup.parse(response.getResponse().getContentAsString()); assertThat(html.select(".blog-preview--title a").first().text(), is(post.getTitle())); } private Post createSinglePost() { Post post = new PostBuilder().title("This week in Spring - June 3, 2013") .rawContent("Raw content") .renderedContent("Html content") .renderedSummary("Html summary") .build(); postRepository.save(post); return post; } @Test public void givenManyPosts_blogIndexShowsLatest10PostSummaries() throws Exception { createManyPostsInNovember(11); MvcResult response = mockMvc.perform(get("/blog")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith("text/html")) .andReturn(); Document html = Jsoup.parse(response.getResponse().getContentAsString()); assertThat(numberOfBlogPosts(html), is(10)); assertThat(html.select(".blog-preview--container .date").first().text(), is("November 11, 2012")); assertThat(html.select(".blog-preview--container .date").last().text(), is("November 2, 2012")); } private int numberOfBlogPosts(Document html) { return html.select(".blog-preview--title").size(); } private void createManyPostsInNovember(int numPostsToCreate) { Calendar calendar = Calendar.getInstance(); List<Post> posts = new ArrayList<Post>(); for (int postNumber = 1; postNumber <= numPostsToCreate; postNumber++) { calendar.set(2012, 10, postNumber); Post post = new PostBuilder().title("This week in Spring - November " + postNumber + ", 2012") .rawContent("Raw content") .renderedContent("Html content") .renderedSummary("Html summary") .dateCreated(calendar.getTime()) .publishAt(calendar.getTime()) .build(); posts.add(post); } postRepository.save(posts); } @Test public void given1PageOfResults_blogIndexDoesNotShowPaginationControl() throws Exception { createManyPostsInNovember(1); MvcResult response = this.mockMvc.perform(get("/blog")).andReturn(); Document html = Jsoup.parse(response.getResponse().getContentAsString()); assertThat(html.select("#pagination_control").first(), is(nullValue())); } @Test public void givenManyPosts_blogIndexShowsPaginationControl() throws Exception { createManyPostsInNovember(21); MvcResult response = this.mockMvc.perform(get("/blog?page=2")).andReturn(); Document html = Jsoup.parse(response.getResponse().getContentAsString()); Element previousLink = html.select("#pagination_control a.previous").first(); assertThat("No previous pagination link found", previousLink, is(notNullValue())); String previousHref = previousLink.attributes().get("href"); assertThat(previousHref, is("/blog?page=1")); Element nextLink = html.select("#pagination_control a.next").first(); assertThat("No next pagination link found", nextLink, is(notNullValue())); String nextHref = nextLink.attributes().get("href"); assertThat(nextHref, is("/blog?page=3")); } @Test public void viewBlogPostsForCategory() throws Exception { postRepository.save(PostBuilder.post() .title("DO NOT LOOK AT ME") .category(PostCategory.RELEASES).build()); postRepository.save(PostBuilder.post() .title("An Engineering Post") .category(PostCategory.ENGINEERING).build()); Page<Post> posts = postRepository.findByCategoryAndDraftFalse(PostCategory.ENGINEERING, new PageRequest(0, 10)); MatcherAssert.assertThat(posts.getSize(), greaterThanOrEqualTo(1)); this.mockMvc.perform(get("/blog/category/" + PostCategory.ENGINEERING.getUrlSlug())) .andExpect(content().contentTypeCompatibleWith("text/html")) .andExpect(content().string(containsString("An Engineering Post"))) .andExpect(content().string(not(containsString("DO NOT LOOK AT ME")))) .andExpect(content().string(containsString(PostCategory.ENGINEERING.toString()))); } @Test public void viewBroadcastBlogPosts() throws Exception { createManyPostsInNovember(5); postRepository.save(PostBuilder.post() .title("A broadcast post") .isBroadcast() .build()); postRepository.save(PostBuilder.post() .title("Another broadcast post") .isBroadcast() .build()); MvcResult response = this.mockMvc.perform(get("/blog/broadcasts")).andReturn(); Document html = Jsoup.parse(response.getResponse().getContentAsString()); assertThat(numberOfBlogPosts(html), is(2)); } }
package isomorphly; import isomorphly.annotations.Component; import isomorphly.annotations.Group; import java.lang.annotation.Annotation; import java.util.List; import test.isomorphly.dummy.annotations.Plugin; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for IsomorphlyEngine. */ public class IsomorphlyEngineTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ private IsomorphlyEngine engine; public IsomorphlyEngineTest( String testName ) { super( testName ); String packageNames[] = {"test.isomorphly.dummy.annotations", "test.isomorphly.dummy.implementation"}; engine = new IsomorphlyEngine(packageNames); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( IsomorphlyEngineTest.class ); } public void testIsomorphlyEngineInstance() { assertTrue( engine != null ); } public void testEngineInit() { engine.init(); assertTrue("engine not properly initialized.", engine.isInitialized()); } public void testGroupScan() { engine.init(); List<Class<?>> groups = engine.getIsomorphlyGroups(); assertNotNull("Groups should not null. Is engine's initialization ok?", groups); assertFalse("Groups should not be empty. Is engine's initialization ok?", groups.isEmpty()); for (Class<?> cls : groups) { assertTrue(cls.isAnnotation()); assertTrue(cls.isAnnotationPresent(Group.class)); } assertTrue(true); } public void testComponentsScan() { engine.init(); List<Class<?>> components = engine.getIsomorphlyComponents(); assertNotNull("Components should not null. Is engine's initialization ok?", components); assertTrue("Components should not be empty. Is engine's initialization ok?", components.size() > 0); for (Class<?> cls : components) { assertTrue(cls.isAnnotation()); assertTrue(cls.isAnnotationPresent(Component.class)); } assertTrue(true); } public void testPluginsScan() { engine.init(); List<Class<?>> annotatedClientGroups = engine.getIsomorphlyClientGroups(); assertFalse("AnnotatedClientGroups should not be empty. Is engine's initialization ok?", annotatedClientGroups.isEmpty()); for (Class<?> cls : annotatedClientGroups) { assertFalse("AnnotatedClient classes cannot be Interfaces", cls.isInterface()); assertFalse("AnnotatedClient classes cannot be Annotations", cls.isAnnotation()); boolean foundValidParentGroupAnnotation = false; for (Annotation a : cls.getAnnotations()) { foundValidParentGroupAnnotation |= a.annotationType().isAnnotationPresent(Group.class); } assertTrue("Unable to find a valid @Group Annotation in " + cls.getName(), foundValidParentGroupAnnotation); } assertTrue(engine != null); } }
package linenux.command; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.time.LocalDateTime; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import linenux.command.result.CommandResult; import linenux.model.Reminder; import linenux.model.Schedule; import linenux.model.Task; /** * JUnit test for list command. */ public class ListCommandTest { private Schedule schedule; private ListCommand listCommand; @Before public void setupListCommand() { this.schedule = new Schedule(); this.listCommand = new ListCommand(this.schedule); } /** * Test list all. */ @Test public void testRespondToListWithoutParams() { assertTrue(this.listCommand.respondTo("list")); } /** * Test search function in list. */ @Test public void testRespondToListWithKeywords() { assertTrue(this.listCommand.respondTo("list bla")); } /** * Test that list command is case insenstive. */ @Test public void testCaseInsensitiveRespondToList() { assertTrue(this.listCommand.respondTo("LiSt")); } /** * Test that list command does not respond to other commands. */ @Test public void testDoesNotRespondToOtherCommands() { assertFalse(this.listCommand.respondTo("whaddup")); } /** * Test that list without params should display all tasks and reminders */ @Test public void testDisplayTheEntireList() { this.schedule.addTask(new Task("First Task")); this.schedule.addTask(new Task("Second Task")); this.schedule.addTask(new Task("Deadline", null, LocalDateTime.of(2016, 1, 1, 17, 0))); this.schedule.addTask(new Task("Event", LocalDateTime.of(2016, 1, 1, 17, 0), LocalDateTime.of(2016, 1, 1, 18, 0))); Task taskWithReminder = new Task("Task with Reminder"); taskWithReminder = taskWithReminder.addReminder(new Reminder("Reminder", LocalDateTime.of(2016, 2, 1, 17, 0))); this.schedule.addTask(taskWithReminder); CommandResult result = this.listCommand.execute("list"); String expectedFeedback = "Reminders:\n" + "1. Reminder (On 2016-02-01 5:00PM)"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command displays multiple tasks correctly. */ @Test public void testDisplayTasksMatchingKeywords() { Task task1 = new Task("hello"); Task task2 = new Task("world"); Task task3 = new Task("hello world"); this.schedule.addTask(task1); this.schedule.addTask(task2); this.schedule.addTask(task3); this.listCommand.execute("list world"); assertTrue( this.schedule.getFilteredTasks().contains(task2) && this.schedule.getFilteredTasks().contains(task3)); } @Test public void testNoMatchingKeywords() { this.schedule.addTask(new Task("hi!")); CommandResult result = this.listCommand.execute("list hello"); String expectedFeedback = "There are no tasks and reminders found based on your given inputs!"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command displays multiple reminders correctly. */ @Test public void testDisplayRemindersMatchingKeywords() { Task hello = new Task("hello"); hello = hello.addReminder(new Reminder("world domination", LocalDateTime.of(2016, 2, 1, 17, 0))); hello = hello.addReminder(new Reminder("is my occupation", LocalDateTime.of(2016, 1, 1, 17, 0))); hello = hello.addReminder(new Reminder("hello world", LocalDateTime.of(2016, 3, 1, 17, 0))); this.schedule.addTask(hello); CommandResult result = this.listCommand.execute("list world"); ArrayList<Task> filteredTasks = this.schedule.getFilteredTasks(); assertTrue(!filteredTasks.contains(hello)); String expectedFeedback = "Reminders:\n1. world domination (On 2016-02-01 5:00PM)\n2. hello world (On 2016-03-01 5:00PM)"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command displays multiple reminders and tasks correctly. */ @Test public void testDisplayTaskAndRemindersMatchingKeywords() { Task hello = new Task("hello"); hello = hello.addReminder(new Reminder("world domination", LocalDateTime.of(2016, 2, 1, 17, 0))); hello = hello.addReminder(new Reminder("is my occupation", LocalDateTime.of(2016, 1, 1, 17, 0))); hello = hello.addReminder(new Reminder("hello world", LocalDateTime.of(2016, 3, 1, 17, 0))); hello = hello.addReminder(new Reminder("hello darkness", LocalDateTime.of(2016, 4, 1, 17, 0))); this.schedule.addTask(hello); Task helloWorld = new Task("Hello World"); helloWorld = helloWorld.addReminder(new Reminder("hello hello", LocalDateTime.of(2016, 1, 1, 17, 0))); this.schedule.addTask(helloWorld); CommandResult result = this.listCommand.execute("list hello"); String expectedFeedback = "Reminders:\n" + "1. hello hello (On 2016-01-01 5:00PM)\n" + "2. hello world (On 2016-03-01 5:00PM)\n" + "3. hello darkness (On 2016-04-01 5:00PM)"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command filters by start time */ @Test public void testFilterTaskAndRemindersByStartTime() { Task todo = new Task("todo"); todo = todo.addReminder(new Reminder("todo before", LocalDateTime.of(2015, 1, 1, 17, 0))); todo = todo.addReminder(new Reminder("todo after", LocalDateTime.of(2017, 1, 1, 17, 0))); todo = todo.addReminder(new Reminder("todo on", LocalDateTime.of(2016, 1, 1, 17, 0))); Task eventBefore = new Task("event before", LocalDateTime.of(2015, 1, 1, 17, 0), LocalDateTime.of(2015, 1, 1, 19, 0)); Task eventOn = new Task("event on", LocalDateTime.of(2015, 1, 1, 17, 0), LocalDateTime.of(2016, 1, 1, 17, 0)); Task eventAfter = new Task("event after", LocalDateTime.of(2015, 1, 1, 17, 0), LocalDateTime.of(2017, 1, 1, 17, 0)); Task deadlineBefore = new Task("deadline before", LocalDateTime.of(2015, 1, 1, 17, 0)); Task deadlineOn = new Task("deadline On", LocalDateTime.of(2016, 1, 1, 17, 0)); Task deadlineAfter = new Task("deadline before", LocalDateTime.of(2017, 1, 1, 17, 0)); this.schedule.addTask(todo); this.schedule.addTask(eventBefore); this.schedule.addTask(eventOn); this.schedule.addTask(eventAfter); this.schedule.addTask(deadlineBefore); this.schedule.addTask(deadlineOn); this.schedule.addTask(deadlineAfter); CommandResult result = this.listCommand.execute("list st/2016-01-01 5:00PM"); ArrayList<Task> filteredTasks = this.schedule.getFilteredTasks(); assertTrue(filteredTasks.contains(todo)); assertTrue(!filteredTasks.contains(eventBefore)); assertTrue(filteredTasks.contains(eventOn)); assertTrue(filteredTasks.contains(eventAfter)); assertTrue(!filteredTasks.contains(deadlineBefore)); assertTrue(filteredTasks.contains(deadlineOn)); assertTrue(filteredTasks.contains(deadlineAfter)); String expectedFeedback = "Reminders:\n" + "1. todo on (On 2016-01-01 5:00PM)\n" + "2. todo after (On 2017-01-01 5:00PM)"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command filters by end time */ @Test public void testFilterTaskAndRemindersByEndTime() { Task todo = new Task("todo"); todo = todo.addReminder(new Reminder("todo before", LocalDateTime.of(2015, 1, 1, 17, 0))); todo = todo.addReminder(new Reminder("todo after", LocalDateTime.of(2017, 1, 1, 17, 0))); todo = todo.addReminder(new Reminder("todo on", LocalDateTime.of(2016, 1, 1, 17, 0))); Task eventBefore = new Task("event before", LocalDateTime.of(2015, 1, 1, 17, 0), LocalDateTime.of(2015, 1, 1, 19, 0)); Task eventOn = new Task("event on", LocalDateTime.of(2015, 1, 1, 17, 0), LocalDateTime.of(2016, 1, 1, 17, 0)); Task eventEndTimeAfter = new Task("event after", LocalDateTime.of(2015, 1, 1, 19, 0), LocalDateTime.of(2017, 1, 1, 17, 0)); Task eventStartTimeAfter = new Task("event after", LocalDateTime.of(2017, 1, 1, 19, 0), LocalDateTime.of(2018, 1, 1, 17, 0)); Task deadlineBefore = new Task("deadline before", LocalDateTime.of(2015, 1, 1, 17, 0)); Task deadlineOn = new Task("deadline On", LocalDateTime.of(2016, 1, 1, 17, 0)); Task deadlineAfter = new Task("deadline after", LocalDateTime.of(2017, 1, 1, 17, 0)); this.schedule.addTask(todo); this.schedule.addTask(eventBefore); this.schedule.addTask(eventOn); this.schedule.addTask(eventEndTimeAfter); this.schedule.addTask(eventStartTimeAfter); this.schedule.addTask(deadlineBefore); this.schedule.addTask(deadlineOn); this.schedule.addTask(deadlineAfter); CommandResult result = this.listCommand.execute("list et/2016-01-01 5:00PM"); ArrayList<Task> filteredTasks = this.schedule.getFilteredTasks(); assertTrue(filteredTasks.contains(todo)); assertTrue(filteredTasks.contains(eventBefore)); assertTrue(filteredTasks.contains(eventOn)); assertTrue(filteredTasks.contains(eventEndTimeAfter)); assertTrue(!filteredTasks.contains(eventStartTimeAfter)); assertTrue(filteredTasks.contains(deadlineBefore)); assertTrue(filteredTasks.contains(deadlineOn)); assertTrue(!filteredTasks.contains(deadlineAfter)); String expectedFeedback = "Reminders:\n" + "1. todo before (On 2015-01-01 5:00PM)\n" + "2. todo on (On 2016-01-01 5:00PM)"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command filters by tags */ @Test public void testFilterTaskAndRemindersByTags() { ArrayList<String> tags1 = new ArrayList<>(); ArrayList<String> tags2 = new ArrayList<>(); ArrayList<String> tags3 = new ArrayList<>(); tags1.add("hello"); tags2.add("hello"); tags2.add("world"); tags3.add("wat"); Task todo1 = new Task("todo 1", tags1); Task todo2 = new Task("todo 2", tags2); Task todo3 = new Task("todo 3", tags3); this.schedule.addTask(todo1); this.schedule.addTask(todo2); this.schedule.addTask(todo3); this.listCommand.execute("list #/hello"); ArrayList<Task> filteredTasks = this.schedule.getFilteredTasks(); assertTrue(filteredTasks.contains(todo1)); assertTrue(filteredTasks.contains(todo2)); assertTrue(!filteredTasks.contains(todo3)); } /** * Test that list command filters by tags is case-insensitive */ @Test public void testFilterTaskAndRemindersByTagsCaseInsensitive() { ArrayList<String> tags1 = new ArrayList<>(); ArrayList<String> tags2 = new ArrayList<>(); ArrayList<String> tags3 = new ArrayList<>(); tags1.add("hello"); tags2.add("hello"); tags2.add("world"); tags3.add("wat"); Task todo1 = new Task("todo 1", tags1); Task todo2 = new Task("todo 2", tags2); Task todo3 = new Task("todo 3", tags3); this.schedule.addTask(todo1); this.schedule.addTask(todo2); this.schedule.addTask(todo3); this.listCommand.execute("list #/hElLo"); ArrayList<Task> filteredTasks = this.schedule.getFilteredTasks(); assertTrue(filteredTasks.contains(todo1)); assertTrue(filteredTasks.contains(todo2)); assertTrue(!filteredTasks.contains(todo3)); } /** * Test that list command field d/yes (view done only) */ @Test public void testFilterTaskAndRemindersByDoneOnly() { Task todo1 = new Task("todo 1"); Task todo2 = new Task("todo 2"); todo1 = todo1.markAsDone(); this.schedule.addTask(todo1); this.schedule.addTask(todo2); CommandResult result = this.listCommand.execute("list d/yes"); ArrayList<Task> filteredTasks = this.schedule.getFilteredTasks(); assertTrue(filteredTasks.contains(todo1)); assertTrue(!filteredTasks.contains(todo2)); String expectedFeedback = "1. todo 1"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command field d/all (view all including done) */ @Test public void testViewTaskAndRemindersIncludingDone() { Task todo1 = new Task("todo 1"); Task todo2 = new Task("todo 2"); todo1 = todo1.markAsDone(); this.schedule.addTask(todo1); this.schedule.addTask(todo2); CommandResult result = this.listCommand.execute("list d/all"); ArrayList<Task> filteredTasks = this.schedule.getFilteredTasks(); assertTrue(filteredTasks.contains(todo1)); assertTrue(filteredTasks.contains(todo2)); String expectedFeedback = "1. todo 1"; assertEquals(expectedFeedback, result.getFeedback()); } /** * Test that list command field d/ when invalid */ @Test public void testInvalidDoneField() { Task todo = new Task("todo"); this.schedule.addTask(todo); CommandResult result = this.listCommand.execute("list d/invalid"); String expectedFeedback = "Unable to parse \"invalid\".\n" + "Did you mean:\n" + "d/all - View all done and uncompleted tasks.\n" + "d/yes - Show only tasks that are marked done."; assertEquals(expectedFeedback, result.getFeedback()); } }
package org.mozilla.taskcluster; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.UUID; import java.util.logging.Logger; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import org.mozilla.taskcluster.client.APICallFailure; import org.mozilla.taskcluster.client.CallSummary; import org.mozilla.taskcluster.client.Certificate; import org.mozilla.taskcluster.client.Credentials; import org.mozilla.taskcluster.client.index.Index; import org.mozilla.taskcluster.client.queue.Queue; import org.mozilla.taskcluster.client.queue.TaskDefinitionRequest; import org.mozilla.taskcluster.client.queue.TaskStatusResponse; import com.google.gson.Gson; import net.iharder.Base64; public class APITest { private static Logger log = Logger.getGlobal(); /** * Generates a 22 character random slugId that is url-safe ([0-9a-zA-Z_\-]*) */ public static String slug() { UUID uuid = UUID.randomUUID(); long hi = uuid.getMostSignificantBits(); long lo = uuid.getLeastSignificantBits(); ByteBuffer raw = ByteBuffer.allocate(16); raw.putLong(hi); raw.putLong(lo); byte[] rawBytes = raw.array(); return Base64.encodeBytes(rawBytes).replace('+', '-').replace('/', '_').substring(0, 22); } /** * This is a silly test that looks for the latest mozilla-inbound linux64 debug * build and asserts that it must have a created time between a year ago and an * hour in the future. * * Could easily break at a point in the future, e.g. if this index route * changes, at which point we can change to something else. * * Note, no credentials are needed, so this can be run even on travis-ci.org, * for example. */ @Test public void findLatestLinux64DebugBuild() { Index index = new Index(); Queue queue = new Queue(); try { String taskId = index.findTask("gecko.v2.mozilla-inbound.latest.firefox.linux64-debug").responsePayload.taskId; Date created = queue.task(taskId).responsePayload.created; // calculate time an hour in the future to allow for clock drift Date now = new Date(); Calendar c = Calendar.getInstance(); c.setTime(now); c.add(Calendar.HOUR, 1); Date inAnHour = c.getTime(); c.setTime(now); c.add(Calendar.YEAR, -1); Date aYearAgo = c.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy 'at' HH:mm:ss Z"); System.out.println("=> Task " + taskId + " was created on " + sdf.format(created)); Assert.assertTrue(created.before(inAnHour)); Assert.assertTrue(created.after(aYearAgo)); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } /** * Tests whether it is possible to define a task against the production * Queue. */ @Test public void testDefineTask() { String clientId = System.getenv("TASKCLUSTER_CLIENT_ID"); String accessToken = System.getenv("TASKCLUSTER_ACCESS_TOKEN"); String certificate = System.getenv("TASKCLUSTER_CERTIFICATE"); Assume.assumeFalse(clientId == null || clientId == "" || accessToken == null || accessToken == ""); Queue queue = new Queue(new Credentials(clientId, accessToken, certificate)); String taskId = slug(); TaskDefinitionRequest td = new TaskDefinitionRequest(); td.created = new Date(); Calendar c = Calendar.getInstance(); c.setTime(td.created); c.add(Calendar.DATE, 1); td.deadline = c.getTime(); td.expires = td.deadline; Map<String, Object> index = new HashMap<String, Object>(); index.put("rank", 12345); Map<String, Object> extra = new HashMap<String, Object>(); extra.put("index", index); td.extra = extra; td.metadata = td.new MetaData(); td.metadata.description = "Stuff"; td.metadata.name = "[TC] Pete"; td.metadata.owner = "pmoore@mozilla.com"; td.metadata.source = "http://somewhere.com/"; Map<String, Object> features = new HashMap<String, Object>(); features.put("relengAPIProxy", true); Map<String, Object> payload = new HashMap<String, Object>(); payload.put("features", features); td.payload = payload; td.provisionerId = "win-provisioner"; td.retries = 5; td.routes = new String[] { "tc-treeherder.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163", "tc-treeherder-stage.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163" }; td.schedulerId = "junit-test-scheduler"; td.scopes = new String[] {}; Map<String, Object> tags = new HashMap<String, Object>(); tags.put("createdForUser", "cbook@mozilla.com"); td.tags = tags; td.priority = "high"; td.taskGroupId = "dtwuF2n9S-i83G37V9eBuQ"; td.workerType = "win2008-worker"; try { CallSummary<TaskDefinitionRequest, TaskStatusResponse> cs = queue.defineTask(taskId, td); Assert.assertEquals(cs.requestPayload.provisionerId, "win-provisioner"); Assert.assertEquals(cs.responsePayload.status.schedulerId, "junit-test-scheduler"); Assert.assertEquals(cs.responsePayload.status.retriesLeft, 5); Assert.assertEquals(cs.responsePayload.status.state, "unscheduled"); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } System.out.println("=> Task https://queue.taskcluster.net/v1/task/" + taskId + " created successfully"); } public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); static { sdf.setTimeZone(TimeZone.getTimeZone("UTC")); } @Test public void createTemporaryCredentials() { BufferedReader br = null; try { Gson gson = new Gson(); br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/testcases.json"))); TempCredsTestCase[] testCases = gson.fromJson(br, TempCredsTestCase[].class); for (TempCredsTestCase tc : testCases) { log.info("Testing " + tc.description); Date start = sdf.parse(tc.start); Date expiry = sdf.parse(tc.expiry); Credentials permCreds = new Credentials(tc.permCreds.clientId, tc.permCreds.accessToken); Credentials tempCreds = permCreds.createTemporaryCredentials(tc.tempCredsName, tc.tempCredsScopes, start, expiry); Certificate cert = tempCreds.getCertificate(); cert.seed = tc.seed; // need to generate access token using fixed seed tempCreds.accessToken = Credentials.generateTemporaryAccessToken(permCreds.accessToken, cert.seed); // need to recalculate signature, as seed was updated cert.generateSignature(permCreds.accessToken, tempCreds.clientId); // update credentials with updated certificate tempCreds.certificate = cert.toString(); Assert.assertEquals(tc.expectedTempCreds.clientId, tempCreds.clientId); Assert.assertEquals(tc.expectedTempCreds.accessToken, tempCreds.accessToken); Assert.assertEquals(tc.expectedTempCreds.certificate, tempCreds.certificate); } } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception thrown"); } finally { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } }
package seedu.address.testutil; import com.google.common.io.Files; import guitests.guihandles.PersonCardHandle; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import junit.framework.AssertionFailedError; import org.loadui.testfx.GuiTest; import org.testfx.api.FxToolkit; import seedu.address.TestApp; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.commons.util.FileUtil; import seedu.address.commons.util.XmlUtil; import seedu.address.model.AddressBook; import seedu.address.model.item.*; import seedu.address.model.tag.Tag; import seedu.address.model.tag.UniqueTagList; import seedu.address.storage.XmlSerializableAddressBook; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; /** * A utility class for test cases. */ public class TestUtil { public static String LS = System.lineSeparator(); public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) { try { executable.run(); } catch (Throwable actualException) { if (!actualException.getClass().isAssignableFrom(expected)) { String message = String.format("Expected thrown: %s, actual: %s", expected.getName(), actualException.getClass().getName()); throw new AssertionFailedError(message); } else return; } throw new AssertionFailedError( String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName())); } /** * Folder used for temp files created during testing. Ignored by Git. */ public static String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/"); public static final Item[] sampleItemData = getSampleItemData(); private static Item[] getSampleItemData() { try { return new Item[]{ new Item(new ItemType("event"), new Name("Game of Life"), new Date("07-07"), new Time("00:00"), new Date("08-07"), new Time("12:00"), new UniqueTagList()), new Item(new ItemType("deadline"), new Name("This is a deadline"), new Date(""), new Time(""), new Date("2017-05-05"), new Time("23:59"), new UniqueTagList()), new Item(new ItemType("task"), new Name("Win at Life"), new Date(""), new Time(""), new Date(""), new Time(""), new UniqueTagList()), new Item(new ItemType("event"), new Name("This is an event"), new Date("2018-05-05"), new Time("23:59"), new Date("2019-01-01"), new Time("02:30"), new UniqueTagList()), new Item(new ItemType("deadline"), new Name("Pay my bills"), new Date(""), new Time(""), new Date("2020-12-30"), new Time("04:49"), new UniqueTagList()), new Item(new ItemType("task"), new Name("This is a task"), new Date(""), new Time(""), new Date(""), new Time(""), new UniqueTagList()), new Item(new ItemType("event"), new Name("2103 exam"), new Date("2018-05-05"), new Time("21:59"), new Date("2022-01-01"), new Time("19:21"), new UniqueTagList()), new Item(new ItemType("deadline"), new Name("Submit report"), new Date(""), new Time(""), new Date("2023-03-03"), new Time("14:21"), new UniqueTagList()), new Item(new ItemType("task"), new Name("Buy a dozen cartons of milk"), new Date(""), new Time(""), new Date("2016-11-21"), new Time("13:10"), new UniqueTagList()) }; } catch (IllegalValueException e) { assert false; //not possible return null; } } public static final Tag[] sampleTagData = getSampleTagData(); private static Tag[] getSampleTagData() { try { return new Tag[]{ new Tag("relatives"), new Tag("friends") }; } catch (IllegalValueException e) { assert false; return null; //not possible } } public static List<Item> generateSampleItemData() { return Arrays.asList(sampleItemData); } /** * Appends the file name to the sandbox folder path. * Creates the sandbox folder if it doesn't exist. * @param fileName * @return */ public static String getFilePathInSandboxFolder(String fileName) { try { FileUtil.createDirs(new File(SANDBOX_FOLDER)); } catch (IOException e) { throw new RuntimeException(e); } return SANDBOX_FOLDER + fileName; } public static void createDataFileWithSampleData(String filePath) { createDataFileWithData(generateSampleStorageAddressBook(), filePath); } public static <T> void createDataFileWithData(T data, String filePath) { try { File saveFileForTesting = new File(filePath); FileUtil.createIfMissing(saveFileForTesting); XmlUtil.saveDataToFile(saveFileForTesting, data); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String... s) { createDataFileWithSampleData(TestApp.SAVE_LOCATION_FOR_TESTING); } public static AddressBook generateEmptyAddressBook() { return new AddressBook(new UniquePersonList(), new UniqueTagList()); } public static XmlSerializableAddressBook generateSampleStorageAddressBook() { return new XmlSerializableAddressBook(generateEmptyAddressBook()); } /** * Tweaks the {@code keyCodeCombination} to resolve the {@code KeyCode.SHORTCUT} to their * respective platform-specific keycodes */ public static KeyCode[] scrub(KeyCodeCombination keyCodeCombination) { List<KeyCode> keys = new ArrayList<>(); if (keyCodeCombination.getAlt() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.ALT); } if (keyCodeCombination.getShift() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.SHIFT); } if (keyCodeCombination.getMeta() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.META); } if (keyCodeCombination.getControl() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.CONTROL); } keys.add(keyCodeCombination.getCode()); return keys.toArray(new KeyCode[]{}); } public static boolean isHeadlessEnvironment() { String headlessProperty = System.getProperty("testfx.headless"); return headlessProperty != null && headlessProperty.equals("true"); } public static void captureScreenShot(String fileName) { File file = GuiTest.captureScreenshot(); try { Files.copy(file, new File(fileName + ".png")); } catch (IOException e) { e.printStackTrace(); } } public static String descOnFail(Object... comparedObjects) { return "Comparison failed \n" + Arrays.asList(comparedObjects).stream() .map(Object::toString) .collect(Collectors.joining("\n")); } public static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException{ field.setAccessible(true); // remove final modifier from field Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); // ~Modifier.FINAL is used to remove the final modifier from field so that its value is no longer // final and can be changed modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } public static void initRuntime() throws TimeoutException { FxToolkit.registerPrimaryStage(); FxToolkit.hideStage(); } public static void tearDownRuntime() throws Exception { FxToolkit.cleanupStages(); } /** * Gets private method of a class * Invoke the method using method.invoke(objectInstance, params...) * * Caveat: only find method declared in the current Class, not inherited from supertypes */ public static Method getPrivateMethod(Class objectClass, String methodName) throws NoSuchMethodException { Method method = objectClass.getDeclaredMethod(methodName); method.setAccessible(true); return method; } public static void renameFile(File file, String newFileName) { try { Files.copy(file, new File(newFileName)); } catch (IOException e1) { e1.printStackTrace(); } } /** * Gets mid point of a node relative to the screen. * @param node * @return */ public static Point2D getScreenMidPoint(Node node) { double x = getScreenPos(node).getMinX() + node.getLayoutBounds().getWidth() / 2; double y = getScreenPos(node).getMinY() + node.getLayoutBounds().getHeight() / 2; return new Point2D(x,y); } /** * Gets mid point of a node relative to its scene. * @param node * @return */ public static Point2D getSceneMidPoint(Node node) { double x = getScenePos(node).getMinX() + node.getLayoutBounds().getWidth() / 2; double y = getScenePos(node).getMinY() + node.getLayoutBounds().getHeight() / 2; return new Point2D(x,y); } /** * Gets the bound of the node relative to the parent scene. * @param node * @return */ public static Bounds getScenePos(Node node) { return node.localToScene(node.getBoundsInLocal()); } public static Bounds getScreenPos(Node node) { return node.localToScreen(node.getBoundsInLocal()); } public static double getSceneMaxX(Scene scene) { return scene.getX() + scene.getWidth(); } public static double getSceneMaxY(Scene scene) { return scene.getX() + scene.getHeight(); } public static Object getLastElement(List<?> list) { return list.get(list.size() - 1); } /** * Removes a subset from the list of persons. * @param items The list of persons * @param itemsToRemove The subset of persons. * @return The modified persons after removal of the subset from persons. */ public static TestItem[] removeItemsFromList(final TestItem[] items, TestItem... itemsToRemove) { List<TestItem> listOfItems = asList(items); listOfItems.removeAll(asList(itemsToRemove)); return listOfItems.toArray(new TestItem[listOfItems.size()]); } /** * Returns a copy of the list with the person at specified index removed. * @param list original list to copy from * @param targetIndexInOneIndexedFormat e.g. if the first element to be removed, 1 should be given as index. */ public static TestItem[] removeItemFromList(final TestItem[] list, int targetIndexInOneIndexedFormat) { return removeItemsFromList(list, list[targetIndexInOneIndexedFormat-1]); } /** * Replaces items[i] with an item. * @param items The array of items. * @param item The replacement item * @param index The index of the item to be replaced. * @return */ public static TestItem[] replaceItemFromList(TestItem[] items, TestItem item, int index) { items[index] = item; return items; } /** * Appends items to the array of items. * @param items A array of items. * @param itemsToAdd The items that are to be appended behind the original array. * @return The modified array of items. */ public static TestItem[] addItemsToList(final TestItem[] items, TestItem... itemsToAdd) { List<TestItem> listOfItems = asList(items); listOfItems.addAll(asList(itemsToAdd)); return listOfItems.toArray(new TestItem[listOfItems.size()]); } private static <T> List<T> asList(T[] objs) { List<T> list = new ArrayList<>(); for(T obj : objs) { list.add(obj); } return list; } public static boolean compareCardAndItem(PersonCardHandle card, ReadOnlyItem item) { return card.isSamePerson(item); } public static Tag[] getTagList(String tags) { if (tags.equals("")) { return new Tag[]{}; } final String[] split = tags.split(", "); final List<Tag> collect = Arrays.asList(split).stream().map(e -> { try { return new Tag(e.replaceFirst("Tag: ", "")); } catch (IllegalValueException e1) { //not possible assert false; return null; } }).collect(Collectors.toList()); return collect.toArray(new Tag[split.length]); } }
package com.facebook.presto.execution; import com.facebook.presto.OutputBuffers; import com.facebook.presto.ScheduledSplit; import com.facebook.presto.TaskSource; import com.facebook.presto.event.query.QueryMonitor; import com.facebook.presto.metadata.LocalStorageManager; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OperatorStats; import com.facebook.presto.operator.OutputProducingOperator; import com.facebook.presto.operator.Page; import com.facebook.presto.operator.PageIterator; import com.facebook.presto.operator.SourceHashProviderFactory; import com.facebook.presto.operator.SourceOperator; import com.facebook.presto.split.CollocatedSplit; import com.facebook.presto.split.DataStreamProvider; import com.facebook.presto.spi.Split; import com.facebook.presto.sql.analyzer.Session; import com.facebook.presto.sql.planner.LocalExecutionPlanner; import com.facebook.presto.sql.planner.LocalExecutionPlanner.LocalExecutionPlan; import com.facebook.presto.sql.planner.PlanFragment; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFutureTask; import com.google.common.util.concurrent.ListeningExecutorService; import io.airlift.node.NodeInfo; import io.airlift.units.DataSize; import io.airlift.units.Duration; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import java.lang.ref.WeakReference; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.BlockingDeque; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Math.max; public class SqlTaskExecution implements TaskExecution { private final TaskId taskId; private final TaskOutput taskOutput; private final DataStreamProvider dataStreamProvider; private final ExchangeOperatorFactory exchangeOperatorFactory; private final ListeningExecutorService shardExecutor; private final PlanFragment fragment; private final Metadata metadata; private final LocalStorageManager storageManager; private final DataSize maxOperatorMemoryUsage; private final Session session; private final QueryMonitor queryMonitor; private final NodeInfo nodeInfo; private final AtomicInteger pendingWorkerCount = new AtomicInteger(); @GuardedBy("this") private final SetMultimap<PlanNodeId, Split> unpartitionedSources = HashMultimap.create(); @GuardedBy("this") private final List<WeakReference<SplitWorker>> splitWorkers = new ArrayList<>(); @GuardedBy("this") private SourceHashProviderFactory sourceHashProviderFactory; @GuardedBy("this") private long maxAcknowledgedSplit = Long.MIN_VALUE; private final BlockingDeque<FutureTask<?>> unfinishedWorkerTasks = new LinkedBlockingDeque<>(); public static SqlTaskExecution createSqlTaskExecution(Session session, NodeInfo nodeInfo, TaskId taskId, URI location, PlanFragment fragment, int pageBufferMax, DataStreamProvider dataStreamProvider, ExchangeOperatorFactory exchangeOperatorFactory, Metadata metadata, LocalStorageManager storageManager, ExecutorService taskMasterExecutor, ListeningExecutorService shardExecutor, DataSize maxOperatorMemoryUsage, QueryMonitor queryMonitor) { SqlTaskExecution task = new SqlTaskExecution(session, nodeInfo, taskId, location, fragment, pageBufferMax, dataStreamProvider, exchangeOperatorFactory, metadata, storageManager, shardExecutor, maxOperatorMemoryUsage, queryMonitor); task.start(taskMasterExecutor); return task; } private SqlTaskExecution(Session session, NodeInfo nodeInfo, TaskId taskId, URI location, PlanFragment fragment, int pageBufferMax, DataStreamProvider dataStreamProvider, ExchangeOperatorFactory exchangeOperatorFactory, Metadata metadata, LocalStorageManager storageManager, ListeningExecutorService shardExecutor, DataSize maxOperatorMemoryUsage, QueryMonitor queryMonitor) { Preconditions.checkNotNull(session, "session is null"); Preconditions.checkNotNull(nodeInfo, "nodeInfo is null"); Preconditions.checkNotNull(taskId, "taskId is null"); Preconditions.checkNotNull(fragment, "fragment is null"); Preconditions.checkArgument(pageBufferMax > 0, "pageBufferMax must be at least 1"); Preconditions.checkNotNull(metadata, "metadata is null"); Preconditions.checkNotNull(storageManager, "storageManager is null"); Preconditions.checkNotNull(shardExecutor, "shardExecutor is null"); Preconditions.checkNotNull(maxOperatorMemoryUsage, "maxOperatorMemoryUsage is null"); Preconditions.checkNotNull(queryMonitor, "queryMonitor is null"); this.session = session; this.nodeInfo = nodeInfo; this.taskId = taskId; this.fragment = fragment; this.dataStreamProvider = dataStreamProvider; this.exchangeOperatorFactory = exchangeOperatorFactory; this.shardExecutor = shardExecutor; this.metadata = metadata; this.storageManager = storageManager; this.maxOperatorMemoryUsage = maxOperatorMemoryUsage; this.queryMonitor = queryMonitor; // create output buffers this.taskOutput = new TaskOutput(taskId, location, pageBufferMax); } // This code starts threads so it can not be in the constructor // TODO: merge the partitioned and unparitioned paths somehow private void start(ExecutorService taskMasterExecutor) { // if plan is unpartitioned, add a worker if (!fragment.isPartitioned()) { scheduleSplitWorker(null, null); } // NOTE: this must be started after the unpartitioned task or the task can be ended early taskMasterExecutor.submit(new TaskWorker(taskOutput, unfinishedWorkerTasks)); } @Override public TaskId getTaskId() { return taskId; } @Override public TaskInfo getTaskInfo(boolean full) { checkTaskCompletion(); return taskOutput.getTaskInfo(full); } @Override public synchronized void addSources(List<TaskSource> sources) { Preconditions.checkNotNull(sources, "sources is null"); long newMaxAcknowledgedSplit = maxAcknowledgedSplit; for (TaskSource source : sources) { PlanNodeId sourceId = source.getPlanNodeId(); for (ScheduledSplit scheduledSplit : source.getSplits()) { // only add a split if we have not already scheduled it if (scheduledSplit.getSequenceId() > maxAcknowledgedSplit) { addSplit(sourceId, scheduledSplit.getSplit()); newMaxAcknowledgedSplit = max(scheduledSplit.getSequenceId(), newMaxAcknowledgedSplit); } } if (source.isNoMoreSplits()) { noMoreSplits(sourceId); } } maxAcknowledgedSplit = newMaxAcknowledgedSplit; } @Override public synchronized void addResultQueue(OutputBuffers outputIds) { Preconditions.checkNotNull(outputIds, "outputIds is null"); for (String bufferId : outputIds.getBufferIds()) { taskOutput.addResultQueue(bufferId); } if (outputIds.isNoMoreBufferIds()) { taskOutput.noMoreResultQueues(); } } private synchronized void addSplit(PlanNodeId sourceId, Split split) { // is this a partitioned source if (fragment.isPartitioned() && fragment.getPartitionedSource().equals(sourceId)) { scheduleSplitWorker(sourceId, split); } else { // add this to all of the existing workers if (!unpartitionedSources.put(sourceId, split)) { return; } for (WeakReference<SplitWorker> workerReference : splitWorkers) { SplitWorker worker = workerReference.get(); // the worker can be GCed due to a failure or a limit if (worker != null) { worker.addSplit(sourceId, split); } } } } private synchronized void scheduleSplitWorker(@Nullable PlanNodeId partitionedSourceId, @Nullable Split partitionedSplit) { // create a new split worker SplitWorker worker = new SplitWorker(session, nodeInfo, taskOutput, fragment, getSourceHashProviderFactory(), metadata, maxOperatorMemoryUsage, storageManager, dataStreamProvider, exchangeOperatorFactory, queryMonitor); // TableScanOperator requires partitioned split to be added before task is started if (partitionedSourceId != null) { worker.addSplit(partitionedSourceId, partitionedSplit); } // add unpartitioned sources for (Entry<PlanNodeId, Split> entry : unpartitionedSources.entries()) { worker.addSplit(entry.getKey(), entry.getValue()); } // record new worker splitWorkers.add(new WeakReference<>(worker)); pendingWorkerCount.incrementAndGet(); taskOutput.getStats().addSplits(1); // execute worker final ListenableFutureTask<?> workerFutureTask = ListenableFutureTask.create(worker); unfinishedWorkerTasks.addFirst(workerFutureTask); shardExecutor.submit(workerFutureTask); // The callback must be added to the workerFutureTask and NOT the future returned // by the submit. This is because the future task catches the exception internally // to the executor only sees a successful return, and the errors will be ignored. Futures.addCallback(workerFutureTask, new FutureCallback<Object>() { @Override public void onSuccess(Object result) { pendingWorkerCount.decrementAndGet(); checkTaskCompletion(); // free the reference to the this task in the scheduled workers, so the memory can be released unfinishedWorkerTasks.removeFirstOccurrence(workerFutureTask); } @Override public void onFailure(Throwable t) { taskOutput.queryFailed(t); pendingWorkerCount.decrementAndGet(); // free the reference to the this task in the scheduled workers, so the memory can be released unfinishedWorkerTasks.removeFirstOccurrence(workerFutureTask); } }); } private synchronized void noMoreSplits(PlanNodeId sourceId) { // don't bother updating is this source has already been closed if (!taskOutput.noMoreSplits(sourceId)) { return; } if (sourceId.equals(fragment.getPartitionedSource())) { // all workers have been created // clear hash provider since it has a hard reference to every hash table sourceHashProviderFactory = null; } else { // add this to all of the existing workers for (WeakReference<SplitWorker> workerReference : splitWorkers) { SplitWorker worker = workerReference.get(); // the worker can be GCed due to a failure or a limit if (worker != null) { worker.noMoreSplits(sourceId); } } } } private synchronized void checkTaskCompletion() { // are there more partition splits expected? if (fragment.isPartitioned() && !taskOutput.getNoMoreSplits().contains(fragment.getPartitionedSource())) { return; } // do we still have running tasks? if (pendingWorkerCount.get() != 0) { return; } // Cool! All done! taskOutput.finish(); } private synchronized SourceHashProviderFactory getSourceHashProviderFactory() { if (sourceHashProviderFactory == null) { sourceHashProviderFactory = new SourceHashProviderFactory(maxOperatorMemoryUsage); } return sourceHashProviderFactory; } @Override public void cancel() { taskOutput.cancel(); } @Override public void fail(Throwable cause) { taskOutput.queryFailed(cause); } @Override public BufferResult<Page> getResults(String outputId, int maxPageCount, Duration maxWait) throws InterruptedException { return taskOutput.getResults(outputId, maxPageCount, maxWait); } @Override public void abortResults(String outputId) { taskOutput.abortResults(outputId); } @Override public void recordHeartBeat() { taskOutput.getStats().recordHeartBeat(); } @Override public String toString() { return Objects.toStringHelper(this) .add("taskId", taskId) .add("unpartitionedSources", unpartitionedSources) .add("taskOutput", taskOutput) .toString(); } private static class TaskWorker implements Callable<Void> { private final TaskOutput taskOutput; private final BlockingDeque<FutureTask<?>> scheduledWorkers; private TaskWorker(TaskOutput taskOutput, BlockingDeque<FutureTask<?>> scheduledWorkers) { this.taskOutput = taskOutput; this.scheduledWorkers = scheduledWorkers; } @Override public Void call() throws InterruptedException { while (!taskOutput.getState().isDone()) { FutureTask<?> futureTask = scheduledWorkers.pollFirst(1, TimeUnit.SECONDS); // if we got a task and the state is not done, run the task if (futureTask != null && taskOutput.getState().isDone()) { futureTask.run(); } } // assure all tasks are complete for (FutureTask<?> futureTask = scheduledWorkers.poll(); futureTask != null; futureTask = scheduledWorkers.poll()) { futureTask.cancel(true); } return null; } } private static class SplitWorker implements Callable<Void> { private final AtomicBoolean started = new AtomicBoolean(); private final TaskOutput taskOutput; private final PlanNodeId partitionedSource; private final Operator operator; private final OperatorStats operatorStats; private final QueryMonitor queryMonitor; private final Map<PlanNodeId, SourceOperator> sourceOperators; private final Map<PlanNodeId, OutputProducingOperator<?>> outputOperators; private SplitWorker(Session session, NodeInfo nodeInfo, TaskOutput taskOutput, PlanFragment fragment, SourceHashProviderFactory sourceHashProviderFactory, Metadata metadata, DataSize maxOperatorMemoryUsage, LocalStorageManager storageManager, DataStreamProvider dataStreamProvider, ExchangeOperatorFactory exchangeOperatorFactory, QueryMonitor queryMonitor) { this.taskOutput = taskOutput; partitionedSource = fragment.getPartitionedSource(); operatorStats = new OperatorStats(taskOutput); this.queryMonitor = queryMonitor; LocalExecutionPlanner planner = new LocalExecutionPlanner(session, nodeInfo, metadata, fragment.getSymbols(), operatorStats, sourceHashProviderFactory, maxOperatorMemoryUsage, dataStreamProvider, storageManager, exchangeOperatorFactory); LocalExecutionPlan localExecutionPlan = planner.plan(fragment.getRoot()); operator = localExecutionPlan.getRootOperator(); sourceOperators = localExecutionPlan.getSourceOperators(); outputOperators = localExecutionPlan.getOutputOperators(); } public void addSplit(PlanNodeId sourceId, Split split) { SourceOperator sourceOperator = sourceOperators.get(sourceId); Preconditions.checkArgument(sourceOperator != null, "Unknown plan source %s; known sources are %s", sourceId, sourceOperators.keySet()); if (split instanceof CollocatedSplit) { CollocatedSplit collocatedSplit = (CollocatedSplit) split; // unwind collocated splits for (Entry<PlanNodeId, Split> entry : collocatedSplit.getSplits().entrySet()) { addSplit(entry.getKey(), entry.getValue()); } } else { sourceOperator.addSplit(split); if (sourceId.equals(partitionedSource)) { operatorStats.addSplitInfo(split.getInfo()); } } } public void noMoreSplits(PlanNodeId sourceId) { SourceOperator sourceOperator = sourceOperators.get(sourceId); Preconditions.checkArgument(sourceOperator != null, "Unknown plan source %s; known sources are %s", sourceId, sourceOperators.keySet()); sourceOperator.noMoreSplits(); } @Override public Void call() throws InterruptedException { if (!started.compareAndSet(false, true)) { return null; } if (taskOutput.getState().isDone()) { return null; } operatorStats.start(); try (PageIterator pages = operator.iterator(operatorStats)) { while (pages.hasNext()) { Page page = pages.next(); taskOutput.getStats().addOutputDataSize(page.getDataSize()); taskOutput.getStats().addOutputPositions(page.getPositionCount()); if (!taskOutput.addPage(page)) { break; } } } finally { operatorStats.finish(); queryMonitor.splitCompletionEvent(taskOutput.getTaskInfo(false), operatorStats.snapshot()); for (Map.Entry<PlanNodeId, OutputProducingOperator<?>> entry : outputOperators.entrySet()) { taskOutput.addOutput(entry.getKey(), entry.getValue().getOutput()); } } return null; } } }
package uk.me.graphe.server.database; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import uk.me.graphe.server.database.dbitems.*; import uk.me.graphe.shared.Edge; import uk.me.graphe.shared.Vertex; import uk.me.graphe.shared.graphmanagers.OTGraphManager2d; import uk.me.graphe.shared.graphmanagers.OTGraphManager2dImpl; import uk.me.graphe.shared.graphmanagers.OTGraphManagerFactory; import uk.me.graphe.shared.jsonwrapper.JSONException; import uk.me.graphe.shared.jsonwrapper.JSONImplHolder; import uk.me.graphe.shared.jsonwrapper.JSONObject; import uk.me.graphe.shared.messages.Message; import uk.me.graphe.shared.messages.MessageFactory; import uk.me.graphe.shared.messages.operations.CompositeOperation; import uk.me.graphe.shared.messages.operations.GraphOperation; import com.google.code.morphia.Datastore; import com.google.code.morphia.Morphia; import com.google.code.morphia.query.Query; import com.google.code.morphia.query.UpdateOperations; import com.mongodb.DBCollection; import com.mongodb.Mongo; public class DatabaseImpl implements Database{ private Mongo mMongo; private Morphia mMorphia = new Morphia(); private Datastore mData; DBCollection mCollection; public DatabaseImpl () { try { mMongo = new Mongo(); } catch (UnknownHostException e) { return; } mData = mMorphia.createDatastore(mMongo, "graphs"); mCollection = mMongo.getDB("graphs").getCollection("OTGraphManager2dStore"); } @Override public void delete(int key) { mData.delete(mData.createQuery(OTGraphManager2dStore.class).filter("id =", key)); } @Override public void clean() { mCollection.drop(); } @Override public int size() { return (int) mCollection.getCount(); } @Override public OTGraphManager2d retrieve(int key) { // Extract OtGraphManagerStore from DB List<OTGraphManager2dStore> retrieves = mData.find(OTGraphManager2dStore.class, "id =", key).asList(); if (retrieves == null || retrieves.size() != 1) return null; OTGraphManager2dStore retrieve = retrieves.get(0); List<GraphOperation> operations = new ArrayList<GraphOperation>(); List<JSONObject> objects = new LinkedList<JSONObject>(); List<Message> messages = null; if (retrieve.getmOps() == null) return OTGraphManagerFactory.newInstance(key); for (String s : retrieve.getmOps()) { do { String toStrip = s.substring(s.indexOf('{'), s.indexOf('}')+1); String st = ""; for (int i=0; i < toStrip.length(); i++) if (toStrip.charAt(i) != '\\') st += toStrip.charAt(i); JSONObject item = parseItem(st); System.out.println("Parsing: " + st +" to " + item); objects.add(item); s = s.substring(s.indexOf('}') + 1); } while (s.indexOf('{') != -1); } try { messages = MessageFactory.makeOperationsFromJson(objects); } catch (JSONException e) { e.printStackTrace(); } OTGraphManager2d toReturn = OTGraphManagerFactory.newInstance(key); for (Message item : messages) { // Store all operations as local, map to server in restoreState() System.out.println("Applying operation:" + item.toJson() +" to graph"); toReturn.applyOperation((GraphOperation) item); } System.out.println("Returning graph: " + toReturn.getGraphId()); return toReturn; } private JSONObject parseItem (String json) { JSONObject object = null; try { object = JSONImplHolder.make(json) ; } catch (JSONException e) { // TODO Auto-generated catch block System.out.println("Error " + json); e.printStackTrace(); } return object; } @Override public int store(OTGraphManager2d manager) { OTGraphManager2dStore toStore = new OTGraphManager2dStore(manager); CompositeOperation history; // Check whether the graph exists in the database already List<OTGraphManager2dStore> retrieves = null; Query<OTGraphManager2dStore> exists = mData.find(OTGraphManager2dStore.class, "id =", manager.getGraphId()); retrieves = exists.asList(); if (retrieves == null || retrieves.isEmpty()) { history = manager.getCompleteHistory(); return newgraph(convertOperations(history), toStore); } else if (retrieves.size() > 1) throw new Error("Duplicate items"); else if (retrieves.size() == 1) { // Check state id of update is greater than value in database toStore = retrieves.get(0); if (manager.getStateId() <= toStore.getStateid()) return manager.getGraphId(); history = manager.getOperationDelta(toStore.getStateid()); return updategraph(convertOperations(history), manager.getGraphId(), manager.getStateId()); } else { history = manager.getCompleteHistory(); return newgraph(convertOperations(history), toStore); } } private int newgraph (List<String> operations, OTGraphManager2dStore toStore) { toStore.setmOps(operations); mData.save(toStore); return toStore.getId(); } private int updategraph (List<String> operations, int id, int newid) { Query<OTGraphManager2dStore> updateQuery = mData.createQuery(OTGraphManager2dStore.class).filter("id =", id); UpdateOperations<OTGraphManager2dStore> ops = mData.createUpdateOperations(OTGraphManager2dStore.class).add("mOps", operations, true).set("stateid", newid); mData.update(updateQuery, ops); return id; } private List<String> convertOperations(CompositeOperation history) { List<GraphOperation> operations = history.asIndividualOperations(); List<String> storedOperations = new ArrayList<String>(); for (GraphOperation op : operations) { storedOperations.add(op.toJson()); } return storedOperations; } }
package us.kbase.common.service; import us.kbase.auth.AuthException; import us.kbase.auth.AuthService; import us.kbase.auth.AuthToken; import us.kbase.auth.AuthUser; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.ini4j.Ini; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class JsonServerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String APP_JSON = "application/json"; private ObjectMapper mapper; private Map<String, Method> rpcCache; public static final int LOG_LEVEL_ERR = JsonServerSyslog.LOG_LEVEL_ERR; public static final int LOG_LEVEL_INFO = JsonServerSyslog.LOG_LEVEL_INFO; public static final int LOG_LEVEL_DEBUG = JsonServerSyslog.LOG_LEVEL_DEBUG; public static final int LOG_LEVEL_DEBUG2 = JsonServerSyslog.LOG_LEVEL_DEBUG + 1; public static final int LOG_LEVEL_DEBUG3 = JsonServerSyslog.LOG_LEVEL_DEBUG + 2; private JsonServerSyslog sysLogger; private JsonServerSyslog userLogger; final private static String KB_DEP = "KB_DEPLOYMENT_CONFIG"; final private static String KB_SERVNAME = "KB_SERVICE_NAME"; protected Map<String, String> config = new HashMap<String, String>(); private Server jettyServer = null; private Integer jettyPort = null; private boolean startupFailed = false; /** * Starts a test jetty server on an OS-determined port. Blocks until the * server is terminated. * @throws Exception if the server couldn't be started. */ public void startupServer() throws Exception { startupServer(0); } /** * Starts a test jetty server. Blocks until the * server is terminated. * @param port the port to which the server will connect. * @throws Exception if the server couldn't be started. */ public void startupServer(int port) throws Exception { jettyServer = new Server(port); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); jettyServer.setHandler(context); /** * Get the jetty test server port. Returns null if the server is not running or starting up. * @return the port */ public Integer getServerPort() { return jettyPort; } /** * Stops the test jetty server. * @throws Exception if there was an error stopping the server. */ public void stopServer() throws Exception { jettyServer.stop(); jettyServer = null; jettyPort = null; } public void startupFailed() { this.startupFailed = true; } public JsonServerServlet(String specServiceName) { this.mapper = new ObjectMapper().registerModule(new JacksonTupleModule()); this.rpcCache = new HashMap<String, Method>(); for (Method m : getClass().getMethods()) { if (m.isAnnotationPresent(JsonServerMethod.class)) { JsonServerMethod ann = m.getAnnotation(JsonServerMethod.class); rpcCache.put(ann.rpc(), m); } } String serviceName = System.getProperty(KB_SERVNAME) == null ? System.getenv(KB_SERVNAME) : System.getProperty(KB_SERVNAME); if (serviceName == null) { serviceName = specServiceName; if (serviceName.contains(":")) serviceName = serviceName.substring(0, serviceName.indexOf(':')).trim(); } String file = System.getProperty(KB_DEP) == null ? System.getenv(KB_DEP) : System.getProperty(KB_DEP); sysLogger = new JsonServerSyslog(serviceName, KB_DEP, LOG_LEVEL_INFO); userLogger = new JsonServerSyslog(sysLogger); //read the config file if (file == null) return; File deploy = new File(file); Ini ini = null; try { ini = new Ini(deploy); } catch (IOException ioe) { sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), "There was an IO Error reading the deploy file " + deploy + ". Traceback:\n" + ioe); return; } config = ini.get(serviceName); if (config == null) { config = new HashMap<String, String>(); sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), "The configuration file " + deploy + " has no section " + serviceName); } } /** * WARNING! Please use this method for testing purposes only. * @param output */ public void changeSyslogOutput(JsonServerSyslog.SyslogOutput output) { sysLogger.changeOutput(output); userLogger.changeOutput(output); } public void logErr(String message) { userLogger.logErr(message); } public void logErr(Throwable err) { userLogger.logErr(err); } public void logInfo(String message) { userLogger.logInfo(message); } public void logDebug(String message) { userLogger.logDebug(message); } public void logDebug(String message, int debugLevelFrom1to3) { userLogger.logDebug(message, debugLevelFrom1to3); } public int getLogLevel() { return userLogger.getLogLevel(); } public void setLogLevel(int level) { userLogger.setLogLevel(level); } public void clearLogLevel() { userLogger.clearLogLevel(); } public boolean isLogDebugEnabled() { return userLogger.getLogLevel() >= LOG_LEVEL_DEBUG; } @Override protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { setupResponseHeaders(request, response); response.setContentLength(0); response.getOutputStream().print(""); response.getOutputStream().flush(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset(); info.setIp(request.getRemoteAddr()); response.setContentType(APP_JSON); OutputStream output = response.getOutputStream(); JsonServerSyslog.getCurrentRpcInfo().reset(); if (startupFailed) { writeError(response, -32603, "The server did not start up properly. Please check the log files for the cause.", output); return; } writeError(response, -32300, "HTTP GET not allowed.", output); } private void setupResponseHeaders(HttpServletRequest request, HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin", "*"); String allowedHeaders = request.getHeader("HTTP_ACCESS_CONTROL_REQUEST_HEADERS"); response.setHeader("Access-Control-Allow-Headers", allowedHeaders == null ? "authorization" : allowedHeaders); response.setContentType(APP_JSON); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset(); info.setIp(request.getRemoteAddr()); setupResponseHeaders(request, response); OutputStream output = response.getOutputStream(); String rpcName = null; AuthToken userProfile = null; try { InputStream input = request.getInputStream(); JsonNode node; try { node = mapper.readTree(new UnclosableInputStream(input)); } catch (Exception ex) { writeError(response, -32700, "Parse error (" + ex.getMessage() + ")", output); return; } JsonNode idNode = node.get("id"); try { info.setId(idNode == null || node.isNull() ? null : idNode.asText()); } catch (Exception ex) {} JsonNode methodNode = node.get("method"); ArrayNode paramsNode = (ArrayNode)node.get("params"); node = null; rpcName = (methodNode!=null && !methodNode.isNull()) ? methodNode.asText() : null; if (rpcName.contains(".")) { int pos = rpcName.indexOf('.'); info.setModule(rpcName.substring(0, pos)); info.setMethod(rpcName.substring(pos + 1)); } else { info.setMethod(rpcName); } Method rpcMethod = rpcCache.get(rpcName); if (rpcMethod == null) { writeError(response, -32601, "Can not find method [" + rpcName + "] in server class " + getClass().getName(), output); return; } int rpcArgCount = rpcMethod.getGenericParameterTypes().length; Object[] methodValues = new Object[rpcArgCount]; if (rpcArgCount > 0 && rpcMethod.getParameterTypes()[rpcArgCount - 1].equals(AuthToken.class)) { String token = request.getHeader("Authorization"); if (token != null || !rpcMethod.getAnnotation(JsonServerMethod.class).authOptional()) { try { userProfile = validateToken(token); if (userProfile != null) info.setUser(userProfile.getClientId()); } catch (Throwable ex) { writeError(response, -32400, "Token validation failed: " + ex.getMessage(), output); return; } } rpcArgCount } if (startupFailed) { writeError(response, -32603, "The server did not start up properly. Please check the log files for the cause.", output); return; } if (paramsNode.size() != rpcArgCount) { writeError(response, -32602, "Wrong parameter count for method " + rpcName, output); return; } for (int typePos = 0; paramsNode.size() > 0; typePos++) { JsonNode jsonData = paramsNode.remove(0); Type paramType = rpcMethod.getGenericParameterTypes()[typePos]; PlainTypeRef paramJavaType = new PlainTypeRef(paramType); try { methodValues[typePos] = mapper.readValue(new JsonTreeTraversingParser(jsonData, mapper), paramJavaType); } catch (Exception ex) { writeError(response, -32602, "Wrong type of parameter " + typePos + " for method " + rpcName + " (" + ex.getMessage() + ")", output); return; } } paramsNode = null; if (userProfile != null && methodValues[methodValues.length - 1] == null) methodValues[methodValues.length - 1] = userProfile; Object result; try { sysLogger.log(LOG_LEVEL_INFO, getClass().getName(), "start method"); result = rpcMethod.invoke(this, methodValues); sysLogger.log(LOG_LEVEL_INFO, getClass().getName(), "end method"); } catch (Throwable ex) { if (ex instanceof InvocationTargetException && ex.getCause() != null) { ex = ex.getCause(); } writeError(response, -32500, ex, output); return; } boolean isTuple = rpcMethod.getAnnotation(JsonServerMethod.class).tuple(); if (!isTuple) { result = Arrays.asList(result); } ObjectNode ret = mapper.createObjectNode(); ret.put("version", "1.1"); ret.put("result", mapper.valueToTree(result)); mapper.writeValue(new UnclosableOutputStream(output), ret); output.flush(); } catch (Exception ex) { writeError(response, -32400, "Unexpected internal error (" + ex.getMessage() + ")", output); } } private static AuthToken validateToken(String token) throws Exception { if (token == null) throw new IllegalStateException("Token is not defined in http request header"); AuthToken ret = new AuthToken(token); if (!AuthService.validateToken(ret)) { throw new IllegalStateException("Token was not validated"); } return ret; } public static AuthUser getUserProfile(AuthToken token) throws KeyManagementException, UnsupportedEncodingException, NoSuchAlgorithmException, IOException, AuthException { return AuthService.getUserFromToken(token); } private void writeError(HttpServletResponse response, int code, String message, OutputStream output) { sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), message); writeError(response, code, message, null, output); } private void writeError(HttpServletResponse response, int code, Throwable ex, OutputStream output) { sysLogger.logErr(ex, getClass().getName()); StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); String errorMessage = ex.getLocalizedMessage(); if (errorMessage == null) errorMessage = ex.getMessage(); writeError(response, code, errorMessage, sw.toString(), output); } private void writeError(HttpServletResponse response, int code, String message, String data, OutputStream output) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ObjectNode ret = mapper.createObjectNode(); ObjectNode error = mapper.createObjectNode(); error.put("name", "JSONRPCError"); error.put("code", code); error.put("message", message); error.put("error", data); ret.put("version", "1.1"); ret.put("error", error); String id = JsonServerSyslog.getCurrentRpcInfo().getId(); if (id != null) ret.put("id", id); try { ByteArrayOutputStream bais = new ByteArrayOutputStream(); mapper.writeValue(bais, ret); bais.close(); //String logMessage = new String(bytes); //sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), logMessage); output.write(bais.toByteArray()); output.flush(); } catch (Exception e) { e.printStackTrace(); } } private static class PlainTypeRef extends TypeReference<Object> { Type type; PlainTypeRef(Type type) { this.type = type; } @Override public Type getType() { return type; } } private static class UnclosableInputStream extends InputStream { private InputStream inner; private boolean isClosed = false; public UnclosableInputStream(InputStream inner) { this.inner = inner; } @Override public int read() throws IOException { if (isClosed) return -1; return inner.read(); } @Override public int available() throws IOException { if (isClosed) return 0; return inner.available(); } @Override public void close() throws IOException { isClosed = true; } @Override public synchronized void mark(int readlimit) { inner.mark(readlimit); } @Override public boolean markSupported() { return inner.markSupported(); } @Override public int read(byte[] b) throws IOException { if (isClosed) return 0; return inner.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { if (isClosed) return 0; return inner.read(b, off, len); } @Override public synchronized void reset() throws IOException { if (isClosed) return; inner.reset(); } @Override public long skip(long n) throws IOException { if (isClosed) return 0; return inner.skip(n); } } private static class UnclosableOutputStream extends OutputStream { OutputStream inner; boolean isClosed = false; public UnclosableOutputStream(OutputStream inner) { this.inner = inner; } @Override public void write(int b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void close() throws IOException { isClosed = true; } @Override public void flush() throws IOException { inner.flush(); } @Override public void write(byte[] b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { if (isClosed) return; inner.write(b, off, len); } } }
package com.opengamma.core.id; import static org.testng.AssertJUnit.assertEquals; import org.testng.annotations.Test; import com.opengamma.id.ExternalId; import com.opengamma.util.test.TestGroup; /** * Test {@link ExternalSchemes}. */ @Test(groups = TestGroup.UNIT) public class ExternalSchemesTest { public void test_constants() { assertEquals("ISIN", ExternalSchemes.ISIN.getName()); assertEquals("CUSIP", ExternalSchemes.CUSIP.getName()); assertEquals("SEDOL1", ExternalSchemes.SEDOL1.getName()); assertEquals("BLOOMBERG_BUID", ExternalSchemes.BLOOMBERG_BUID.getName()); assertEquals("BLOOMBERG_TICKER", ExternalSchemes.BLOOMBERG_TICKER.getName()); assertEquals("BLOOMBERG_TCM", ExternalSchemes.BLOOMBERG_TCM.getName()); assertEquals("RIC", ExternalSchemes.RIC.getName()); assertEquals("MARKIT_RED_CODE", ExternalSchemes.MARKIT_RED_CODE.getName()); } public void test_identifiers() { assertEquals(ExternalId.of("ISIN", "A"), ExternalSchemes.isinSecurityId("A")); assertEquals(ExternalId.of("CUSIP", "A"), ExternalSchemes.cusipSecurityId("A")); assertEquals(ExternalId.of("SEDOL1", "A"), ExternalSchemes.sedol1SecurityId("A")); assertEquals(ExternalId.of("BLOOMBERG_BUID", "A"), ExternalSchemes.bloombergBuidSecurityId("A")); assertEquals(ExternalId.of("BLOOMBERG_TICKER", "A"), ExternalSchemes.bloombergTickerSecurityId("A")); assertEquals(ExternalId.of("BLOOMBERG_TCM", "T 4.75 15/08/43 Govt"), ExternalSchemes.bloombergTCMSecurityId("T", "4.75", "15/08/43", "Govt")); assertEquals(ExternalId.of("RIC", "A"), ExternalSchemes.ricSecurityId("A")); assertEquals(ExternalId.of("MARKIT_RED_CODE", "A"), ExternalSchemes.markItRedCode("A")); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_isin_null() { ExternalSchemes.isinSecurityId(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_cusip_null() { ExternalSchemes.cusipSecurityId(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_sedol1_null() { ExternalSchemes.sedol1SecurityId(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_bloombergBuid_null() { ExternalSchemes.bloombergBuidSecurityId(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_bloombergTicker_null() { ExternalSchemes.bloombergTickerSecurityId(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_bloombergTCM_null() { ExternalSchemes.bloombergTCMSecurityId(null, null, null, null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_ric_null() { ExternalSchemes.ricSecurityId(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_markitRedCode_null() { ExternalSchemes.markItRedCode(null); } }
package gov.nih.nci.cabig.caaers.web.security; import gov.nih.nci.cabig.caaers.AbstractTestCase; import gov.nih.nci.cabig.caaers.CaaersTestCase; import gov.nih.nci.security.acegi.csm.authorization.CSMAuthorizationCheck; import junit.framework.TestCase; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.providers.TestingAuthenticationToken; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.context.ApplicationContext; /** * @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a> * */ public class CSMTest extends CaaersTestCase { public CSMTest() { // TODO Auto-generated constructor stub } /** * @param arg0 */ public CSMTest(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public void testCSMLoad() { try { MyThread t = new MyThread(); t.start(); t.join(60 * 1000); assertTrue(t.getDone()); } catch (Exception ex) { ex.printStackTrace(); fail("Error encountered: " + ex.getMessage()); } } private void printStats(BasicDataSource bds) { System.out.println(" System.out.println("numActive: " + bds.getNumActive()); System.out.println("numIdle: " + bds.getNumIdle()); System.out.println(" } private class MyThread extends Thread { private boolean done = false; public boolean getDone() { return done; } public void run() { String userId = "study_cd1"; String objectId = "gov.nih.nci.cabig.caaers.domain.Study"; String privilege = "CREATE"; Authentication auth = new TestingAuthenticationToken(userId, "ignored", new GrantedAuthority[] { new GrantedAuthorityImpl("ignored") }); ApplicationContext ctx = getDeployedApplicationContext(); // BasicDataSource bds = (BasicDataSource)ctx.getBean("dataSource"); CSMAuthorizationCheck check = (CSMAuthorizationCheck) ctx .getBean("testCsmGroupAuthorizationCheck"); for (int i = 0; i < 50; i++) { // printStats(bds); check.checkAuthorizationForObjectId(auth, privilege, objectId); } done = true; } } }
package com.jetbrains.python.console; import com.intellij.codeInsight.hint.HintManager; import com.intellij.execution.console.LanguageConsoleImpl; import com.intellij.execution.console.LanguageConsoleViewImpl; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ConsoleExecuteActionHandler; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.source.codeStyle.HelperFactory; import com.intellij.psi.impl.source.codeStyle.IndentHelper; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.PythonLanguage; import com.jetbrains.python.console.pydev.ConsoleCommunication; import com.jetbrains.python.console.pydev.ConsoleCommunicationListener; import com.jetbrains.python.console.pydev.ICallback; import com.jetbrains.python.console.pydev.InterpreterResponse; import org.apache.commons.lang.StringUtils; import java.util.Scanner; /** * @author traff */ public class PydevConsoleExecuteActionHandler extends ConsoleExecuteActionHandler implements ConsoleCommunicationListener { private static final String DOUBLE_QUOTE_MULTILINE = "\"\"\"";
/** * Implements the Cold Fusion Function urlencodedformat */ package railo.runtime.functions.other; import java.io.UnsupportedEncodingException; import railo.commons.lang.StringUtil; import railo.commons.lang.URLEncoder; import railo.runtime.PageContext; import railo.runtime.exp.PageException; import railo.runtime.ext.function.Function; import railo.runtime.op.Caster; public final class URLEncodedFormat implements Function { public static String call(PageContext pc , String str) throws PageException { return call(pc,str, "UTF-8",true); } public static String call(PageContext pc , String str, String encoding) throws PageException { return call(pc,str, encoding,true); } public static String call(PageContext pc , String str, String encoding,boolean force) throws PageException { if(!force && !railo.commons.net.URLEncoder.needEncoding(str)) return str; try { String enc=java.net.URLEncoder.encode(str, encoding); return StringUtil.replace(enc, "+", "%20", false); //return enc; } catch (Throwable t) { try { return URLEncoder.encode(str, encoding); } catch (UnsupportedEncodingException e) { throw Caster.toPageException(e); } } } }
package com.apixandru.rummikub.server; import com.apixandru.rummikub.api.room.RummikubRoomListener; import com.apixandru.rummikub.model.Rummikub; import com.apixandru.rummikub.model.RummikubFactory; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import static com.apixandru.rummikub.server.RummikubException.Reason.NAME_TAKEN; import static com.apixandru.rummikub.server.RummikubException.Reason.NO_NAME; import static com.apixandru.rummikub.server.RummikubException.Reason.ONGOING_GAME; /** * @author Alexandru-Constantin Bledea * @since April 10, 2016 */ public class RummikubImpl implements RummikubRoomConfigurer { private final Map<String, StateChangeListener> players = new HashMap<>(); private final Map<String, RummikubRoomListener> waitingRoomListeners = new LinkedHashMap<>(); private Rummikub<Integer> rummikubGame; private boolean inProgress; private static boolean isEmpty(final String string) { return null == string || string.isEmpty(); } void validateCanJoin(final String playerName) { if (isEmpty(playerName)) { throw new RummikubException(NO_NAME); } if (players.containsKey(playerName)) { throw new RummikubException(NAME_TAKEN); } if (inProgress) { throw new RummikubException(ONGOING_GAME); } } void addPlayer(final String playerName, final StateChangeListener listener) { listener.enteredWaitingRoom(this); players.put(playerName, listener); } private void broadcastPlayerJoined(final String playerName) { waitingRoomListeners .values() .forEach(waitingRoomListener -> waitingRoomListener.playerJoined(playerName)); } private void broadcastPlayerLeft(final String playerName) { waitingRoomListeners .values() .forEach(waitingRoomListener -> waitingRoomListener.playerLeft(playerName)); } @Override public void startGame() { rummikubGame = RummikubFactory.newInstance(); players.values() .forEach(listener -> listener.enteredGame(rummikubGame)); inProgress = true; } @Override public void registerListener(String playerName, final RummikubRoomListener listener) { notifyOfPreviouslyJoinedPlayers(listener); waitingRoomListeners.put(playerName, listener); broadcastPlayerJoined(playerName); } private void notifyOfPreviouslyJoinedPlayers(RummikubRoomListener listener) { for (String previouslyJoinedPlayerName : waitingRoomListeners.keySet()) { listener.playerJoined(previouslyJoinedPlayerName); } } @Override public void unregisterListener(RummikubRoomListener listener) { Optional<String> optionalPlayerName = findPlayerName(listener); if (optionalPlayerName.isPresent()) { String playerName = optionalPlayerName.get(); waitingRoomListeners.remove(playerName); broadcastPlayerLeft(playerName); } } private Optional<String> findPlayerName(RummikubRoomListener listener) { return waitingRoomListeners.entrySet() .stream() .filter(entry -> entry.getValue() == listener) .map(Map.Entry::getKey) .findFirst(); } void unregister(final String playerName) { players.remove(playerName); // TODO synchronize deez! } }
package org.cyanogenmod.launcher.home.api.provider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.text.TextUtils; import android.util.Log; import org.cyanogenmod.launcher.home.api.cards.DataCardImage; import org.cyanogenmod.launcher.home.api.db.CmHomeDatabaseHelper; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.net.URI; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashSet; import java.util.Set; import java.util.UUID; import static org.cyanogenmod.launcher.home.api.db.CmHomeDatabaseHelper.DATA_CARD_IMAGE_TABLE_NAME; import static org.cyanogenmod.launcher.home.api.db.CmHomeDatabaseHelper.DATA_CARD_TABLE_NAME; public class CmHomeContentProvider extends ContentProvider { CmHomeDatabaseHelper mCmHomeDatabaseHelper; public final static String IMAGE_FILE_CACHE_DIR = "DataCardImageCache"; private static final String TAG = "CmHomeContentProvider"; private static final int DATA_CARD_LIST = 1; private static final int DATA_CARD_ITEM = 2; private static final int DATA_CARD_IMAGE_LIST = 3; private static final int DATA_CARD_IMAGE_ITEM = 4; private static final int IMAGE_FILE = 5; private static UriMatcher URI_MATCHER; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); setupUriMatcher(CmHomeContract.AUTHORITY); } private static void setupUriMatcher(String authority) { URI_MATCHER.addURI(CmHomeContract.AUTHORITY, CmHomeContract.DataCard.LIST_INSERT_UPDATE_URI_PATH, DATA_CARD_LIST); URI_MATCHER.addURI(CmHomeContract.AUTHORITY, CmHomeContract.DataCard.SINGLE_ROW_INSERT_UPDATE_URI_PATH, DATA_CARD_ITEM); URI_MATCHER.addURI(CmHomeContract.AUTHORITY, CmHomeContract.DataCardImage.LIST_INSERT_UPDATE_URI_PATH, DATA_CARD_IMAGE_LIST); URI_MATCHER.addURI(CmHomeContract.AUTHORITY, CmHomeContract.DataCardImage.SINGLE_ROW_INSERT_UPDATE_URI_PATH, DATA_CARD_IMAGE_ITEM); URI_MATCHER.addURI(CmHomeContract.AUTHORITY, /** * The authority of the ContentProvider must be unique across all apps that implement this * API protocol. To resolve this, dynamically set the authority to be unique for this package * name. */ private void setAuthority() { String providerAuthority = getContext().getPackageName() + ".cmhomeapi"; CmHomeContract.setAuthority(providerAuthority); setupUriMatcher(providerAuthority); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); SQLiteDatabase db = mCmHomeDatabaseHelper.getWritableDatabase(); int uriMatch = URI_MATCHER.match(uri); switch (uriMatch) { case DATA_CARD_LIST: queryBuilder.setTables(DATA_CARD_TABLE_NAME); if (TextUtils.isEmpty(sortOrder)) { sortOrder = CmHomeContract.DataCard.SORT_ORDER_DEFAULT; } break; case DATA_CARD_ITEM: queryBuilder.setTables(DATA_CARD_TABLE_NAME); queryBuilder.appendWhere(CmHomeContract.DataCard._ID + " = " + uri .getLastPathSegment()); break; case DATA_CARD_IMAGE_LIST: queryBuilder.setTables(DATA_CARD_IMAGE_TABLE_NAME); if (TextUtils.isEmpty(sortOrder)) { sortOrder = CmHomeContract.DataCardImage.SORT_ORDER_DEFAULT; } break; case DATA_CARD_IMAGE_ITEM: queryBuilder.setTables(DATA_CARD_IMAGE_TABLE_NAME); queryBuilder.appendWhere(CmHomeContract.DataCardImage._ID + " = " + uri .getLastPathSegment()); break; default: throw new IllegalArgumentException("Unsupported URI for insertion: " + uri); } Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts) throws FileNotFoundException { int uriMatch = URI_MATCHER.match(uri); if (uriMatch == IMAGE_FILE) { String filename = uri.getLastPathSegment(); File dir = new File(getContext().getFilesDir(), IMAGE_FILE_CACHE_DIR); ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(dir, filename), ParcelFileDescriptor.MODE_READ_ONLY); return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH); } throw new FileNotFoundException(); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = mCmHomeDatabaseHelper.getWritableDatabase(); int updateCount = 0; int uriMatch = URI_MATCHER.match(uri); switch (uriMatch) { case DATA_CARD_LIST: updateCount = db.update(DATA_CARD_TABLE_NAME, values, selection, selectionArgs); break; case DATA_CARD_ITEM: String idStr = uri.getLastPathSegment(); String where = CmHomeContract.DataCard._ID + " = " + idStr; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } updateCount = db.update(DATA_CARD_TABLE_NAME, values, where, selectionArgs); break; case DATA_CARD_IMAGE_LIST: updateCount = db.update(DATA_CARD_IMAGE_TABLE_NAME, values, selection, selectionArgs); break; case DATA_CARD_IMAGE_ITEM: idStr = uri.getLastPathSegment(); where = CmHomeContract.DataCardImage._ID + " = " + idStr; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } updateCount = db.update(DATA_CARD_IMAGE_TABLE_NAME, values, where, selectionArgs); break; default: throw new IllegalArgumentException("Unsupported URI for update: " + uri); } if (updateCount > 0) { getContext().getContentResolver().notifyChange(uri, null); } cleanupDataCardImageCache(); return updateCount; } @Override public Uri insert(Uri uri, ContentValues values) { int uriMatch = URI_MATCHER.match(uri); SQLiteDatabase db = mCmHomeDatabaseHelper.getWritableDatabase(); switch (uriMatch) { case DATA_CARD_LIST: long id = db.insert(DATA_CARD_TABLE_NAME, null, values); return getUriForId(id, uri); case DATA_CARD_ITEM: id = db.insertWithOnConflict(DATA_CARD_TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE); return getUriForId(id, uri); case DATA_CARD_IMAGE_LIST: id = db.insert(DATA_CARD_IMAGE_TABLE_NAME, null, values); return getUriForId(id, uri); case DATA_CARD_IMAGE_ITEM: id = db.insertWithOnConflict(DATA_CARD_IMAGE_TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE); return getUriForId(id, uri); default: throw new IllegalArgumentException("Unsupported URI for insertion: " + uri); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = mCmHomeDatabaseHelper.getWritableDatabase(); int deleteCount = 0; int uriMatch = URI_MATCHER.match(uri); String idStr = uri.getLastPathSegment(); switch (uriMatch) { case DATA_CARD_LIST: deleteCount = db.delete(DATA_CARD_TABLE_NAME, selection, selectionArgs); break; case DATA_CARD_ITEM: String where = CmHomeContract.DataCard._ID + " = " + idStr; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } deleteCount = db.delete(DATA_CARD_TABLE_NAME, where, selectionArgs); break; case DATA_CARD_IMAGE_LIST: deleteCount = db.delete(DATA_CARD_IMAGE_TABLE_NAME, selection, selectionArgs); break; case DATA_CARD_IMAGE_ITEM: where = CmHomeContract.DataCardImage._ID + " = " + idStr; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } deleteCount = db.delete(DATA_CARD_IMAGE_TABLE_NAME, where, selectionArgs); break; default: throw new IllegalArgumentException("Unsupported URI for update: " + uri); } if (deleteCount == 1) { if(uriMatch == DATA_CARD_ITEM) { // Notifies for a delete getUriForId(Long.parseLong(idStr), Uri.withAppendedPath(CmHomeContract.CONTENT_URI, CmHomeContract.DataCard.SINGLE_ROW_DELETE_URI_PATH)); } if(uriMatch == DATA_CARD_IMAGE_ITEM) { // Notifies for a delete getUriForId(Long.getLong(idStr), Uri.withAppendedPath(CmHomeContract.CONTENT_URI, CmHomeContract.DataCardImage.SINGLE_ROW_DELETE_URI_PATH)); } } else if (deleteCount > 1) { getContext().getContentResolver().notifyChange(uri, null); } cleanupDataCardImageCache(); return deleteCount; } private Uri getUriForId(long id, Uri uri) { if (id > 0) { Uri itemUri = ContentUris.withAppendedId(uri, id); // notify all listeners of changes: getContext().getContentResolver().notifyChange(itemUri, null); return itemUri; } throw new IllegalArgumentException("Problem while inserting into uri: " + uri); } @Override public String getType(Uri uri) { int uriMatch = URI_MATCHER.match(uri); switch (uriMatch) { case DATA_CARD_LIST: return CmHomeContract.DataCard.CONTENT_TYPE; case DATA_CARD_ITEM: return CmHomeContract.DataCard.CONTENT_ITEM_TYPE; case DATA_CARD_IMAGE_LIST: return CmHomeContract.DataCardImage.CONTENT_TYPE; case DATA_CARD_IMAGE_ITEM: return CmHomeContract.DataCardImage.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } /** * For all files in the DataCardImage cache directory, if * they are not represented in the database, delete them. */ private void cleanupDataCardImageCache() { Set<String> filenames = new HashSet<String>(); // Handle DataCardImage rows Cursor cursor = query(CmHomeContract.DataCardImage.CONTENT_URI, CmHomeContract.DataCardImage.PROJECTION_ALL, null, null, null); while(cursor.moveToNext()) { String uriString = cursor.getString(cursor.getColumnIndex(CmHomeContract .DataCardImage.IMAGE_URI_COL)); if (uriString != null) { String filename = Uri.parse(uriString).getLastPathSegment(); filenames.add(filename); } } // Handle DataCard image fields String[] dataCardProjection = {CmHomeContract.DataCard.AVATAR_IMAGE_URI_COL, CmHomeContract.DataCard.CONTENT_SOURCE_IMAGE_URI_COL}; cursor = query(CmHomeContract.DataCard.CONTENT_URI, dataCardProjection, null, null, null); while(cursor.moveToNext()) { String contentSourceUri = cursor.getString(cursor.getColumnIndex(CmHomeContract .DataCard.CONTENT_SOURCE_IMAGE_URI_COL)); String avatarUri = cursor.getString(cursor.getColumnIndex(CmHomeContract .DataCard.AVATAR_IMAGE_URI_COL)); if (contentSourceUri != null) { String filename = Uri.parse(contentSourceUri).getLastPathSegment(); filenames.add(filename); } if (avatarUri != null) { String filename = Uri.parse(avatarUri).getLastPathSegment(); filenames.add(filename); } } // Delete all files that do not exist in the database File internalStorageDir = getContext().getFilesDir(); File imageCacheDir = new File(internalStorageDir, IMAGE_FILE_CACHE_DIR); for (File file : imageCacheDir.listFiles()) { if (!filenames.contains(file.getName())) { file.delete(); } } } /** * Generates a String representing the MD5 hash of the input byte array. * @param bytes A byte array * @return A String representation of the MD5 hash of the input byte array */ private static String hashBytesMD5(byte[] bytes) { // Compute the hash try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(bytes, 0, bytes.length); String hash = new BigInteger(1, md.digest()).toString(16); return hash; } catch (NoSuchAlgorithmException e) { Log.w(TAG, "Unable to compute MD5 hash of byte array."); } // No hash computed return null; } /** * Check if a cached Bitmap file exists in {@link org.cyanogenmod.launcher.home.api.provider * .CmHomeContentProvider.IMAGE_FILE_CACHE_DIR} with the given filename. * @param filename The filename to check for * @param context The context with access to the directory that would contain this file. * @return True if the file exists. */ private static boolean bitmapCacheFileExists(String filename, Context context) { // Create a file in the cache subdirectory File imageDir = new File(context.getFilesDir(), IMAGE_FILE_CACHE_DIR); File imageFile = new File(imageDir, filename); return imageFile.exists(); } /** * Stores the given bitmap in internal storage in {@link org.cyanogenmod.launcher * .home.api.provider.CmHomeContentProvider.IMAGE_FILE_CACHE_DIR} using an MD5 sum of the * bitmap content as the filename, if the cache does not exist already. * @param bitmap The Bitmap to store in the cache * @param context A Context of the application that will share this image in this * ContentProvider. * @return A Uri pointing to the newly stored image file in the cache, or the existing image, * if one is found. */ public static Uri storeBitmapInCache(Bitmap bitmap, Context context) { FileOutputStream outputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; try { // Get the bytes containing the image data byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] bitmapBytes = byteArrayOutputStream.toByteArray(); String hash = hashBytesMD5(bitmapBytes); // Can't continue without a hash if (hash == null) return null; String filename = hash + ".png"; // If the cache already exists, just return the URI to the cache file if (bitmapCacheFileExists(filename, context)) { return Uri.withAppendedPath(CmHomeContract.ImageFile.CONTENT_URI, filename); } // Write the bytes to a file using the hash as the filename // Create a file in the cache subdirectory File imageDir = new File(context.getFilesDir(), IMAGE_FILE_CACHE_DIR); imageDir.mkdirs(); File imageFile = new File(imageDir, filename); outputStream = new FileOutputStream(imageFile); outputStream.write(bitmapBytes); Uri imageUri = Uri.withAppendedPath(CmHomeContract.ImageFile.CONTENT_URI, filename); // Set the image URI, which will actually be stored in the database. return imageUri; } catch (FileNotFoundException e) { Log.e(TAG, "Unable to save bitmap to temporary file. Could not open file."); } catch (IOException e) { Log.e(TAG, "Unable to save bitmap to temporary file, IOException occurred."); } finally { try { if (outputStream != null) { outputStream.close(); } if (byteArrayOutputStream != null) { byteArrayOutputStream.close(); } } catch (IOException e) { Log.e(TAG, "Unable to save bitmap to temporary file, IOException occurred."); } } // Failure, no URI available return null; } }
package io.spine.server.transport.memory; import io.spine.server.transport.ChannelId; import io.spine.server.transport.Subscriber; /** * An in-memory implementation of the {@link Subscriber}. * * <p>To use only in scope of the same JVM as {@linkplain InMemoryPublisher publishers}. */ class InMemorySubscriber extends Subscriber { InMemorySubscriber(ChannelId id) { super(id); } }
package org.spine3.server.entity; import com.google.common.base.Optional; import com.google.protobuf.Message; import org.spine3.base.Event; import org.spine3.base.EventContext; import org.spine3.base.Events; import org.spine3.server.BoundedContext; import org.spine3.server.entity.idfunc.IdSetEventFunction; import org.spine3.server.entity.idfunc.Producers; import javax.annotation.CheckReturnValue; import java.util.Set; /** * Abstract base for repositories that deliver events to entities they manage. * * @param <I> the type of IDs of entities * @param <E> the type of entities * @param <S> the type of entity state messages * @author Alexander Yevsyukov */ public abstract class EventDispatchingRepository<I, E extends AbstractVersionableEntity<I, S>, S extends Message> extends RecordBasedRepository<I, E, S> implements EntityEventDispatcher<I> { private final EntityFactory<I, E> entityFactory; private final IdSetFunctions<I> idSetFunctions; /** * Creates new repository instance. * * @param boundedContext the {@code BoundedContext} in which the repository works * @param defaultFunction the default function for getting an target entity IDs */ @SuppressWarnings("ThisEscapedInObjectConstruction") // OK as we only pass the reference. protected EventDispatchingRepository(BoundedContext boundedContext, IdSetEventFunction<I, Message> defaultFunction) { super(boundedContext); this.entityFactory = new DefaultEntityFactory<>(this); this.idSetFunctions = new IdSetFunctions<>(defaultFunction); } @Override protected EntityFactory<I, E> entityFactory() { return this.entityFactory; } /** * Adds {@code IdSetFunction} for the repository. * * <p>Typical usage for this method would be in a constructor of a {@code ProjectionRepository} * (derived from this class) to provide mapping between events to projection identifiers. * * <p>Such a mapping may be required when... * <ul> * <li>An event should be matched to more than one projection. * <li>The type of an event producer ID (stored in {@code EventContext}) * differs from {@code <I>}. * </ul> * * <p>If there is no function for the class of the passed event message, * the repository will use the event producer ID from an {@code EventContext} passed * with the event message. * * @param func the function instance * @param <M> the type of the event message handled by the function */ public <M extends Message> void addIdSetFunction(Class<M> eventClass, IdSetEventFunction<I, M> func) { idSetFunctions.put(eventClass, func); } /** * Removes {@code IdSetFunction} from the repository. * * @param eventClass the class of the event message * @param <M> the type of the event message handled by the function we want to remove */ public <M extends Message> void removeIdSetFunction(Class<M> eventClass) { idSetFunctions.remove(eventClass); } @Override public <M extends Message> Optional<IdSetEventFunction<I, M>> getIdSetFunction(Class<M> eventClass) { return idSetFunctions.get(eventClass); } @CheckReturnValue protected Set<I> findIds(Message event, EventContext context) { return idSetFunctions.findAndApply(event, context); } /** * Dispatches the passed event to entities. * * @param event the event to dispatch */ @Override public void dispatch(Event event) { final Message eventMessage = Events.getMessage(event); final EventContext context = event.getContext(); final Set<I> ids = findIds(eventMessage, context); for (I id : ids) { dispatchToEntity(id, eventMessage, context); } } /** * Dispatches the event to an entity with the passed ID. * * @param id the ID of the entity * @param eventMessage the event message * @param context the event context */ protected abstract void dispatchToEntity(I id, Message eventMessage, EventContext context); /** * Obtains default {@code IdSetFunction} that retrieves an event producer * from the event context. * * @param <I> the type of the event producer * @return {@code IdSetFunction} instance that returns a set with a single element */ protected static <I> IdSetEventFunction<I, Message> producerFromContext() { return Producers.producerFromContext(); } protected static <I> IdSetEventFunction<I, Message> producerFromFirstMessageField() { return Producers.producerFromFirstMessageField(); } }
package com.jcabi.github; import com.rexsl.test.request.FakeRequest; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; /** * Test case for {@link GhLimit}. * * @author Giang Le (giang@vn-smartsolutions.com) * @version $Id$ */ public final class GhLimitTest { /** * GhLimit can describe as a JSON object. * * @throws Exception if there is any problem */ @Test public void json() throws Exception { final Github github = Mockito.mock(Github.class); final GhLimit limit = new GhLimit(github, new FakeRequest().withBody(body()), "core"); MatcherAssert.assertThat( limit.json().toString(), Matchers.equalTo( "{\"limit\":5000,\"remaining\":4999,\"reset\":1372700873}" ) ); } /** * GhLimit can throw exception when resource is absent. * * @throws Exception if some problem inside */ @Test(expected = IllegalStateException.class) public void absent() throws Exception { final Github github = Mockito.mock(Github.class); final GhLimit limit = new GhLimit(github, new FakeRequest().withBody(body()), "absent"); MatcherAssert.assertThat( limit.json().toString(), Matchers.equalTo("{}") ); } /** * Example response from rate API. * @return Body string. */ private String body() { final StringBuilder builder = new StringBuilder(); builder.append("{\"resources\":{\"core\":{\"limit\":5000,"); builder.append("\"remaining\":4999,\"reset\":1372700873},"); builder.append("\"search\":{\"limit\":20,\"remaining\":18,"); builder.append("\"reset\":1372697452}},\"rate\":{\"limit\":5000,"); builder.append("\"remaining\":4999,\"reset\":1372700873}}"); return builder.toString(); } }
package com.opentok.test; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.opentok.Archive; import com.opentok.Archive.OutputMode; import com.opentok.ArchiveLayout; import com.opentok.ArchiveList; import com.opentok.ArchiveMode; import com.opentok.ArchiveProperties; import com.opentok.MediaMode; import com.opentok.OpenTok; import com.opentok.Role; import com.opentok.Session; import com.opentok.SessionProperties; import com.opentok.SignalProperties; import com.opentok.Stream; import com.opentok.StreamList; import com.opentok.TokenOptions; import com.opentok.exception.InvalidArgumentException; import com.opentok.exception.OpenTokException; import com.opentok.exception.RequestException; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class OpenTokTest { private final String SESSION_CREATE = "/session/create"; private int apiKey = 123456; private String archivePath = "/v2/project/" + apiKey + "/archive"; private String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; private String apiUrl = "http://localhost:8080"; private OpenTok sdk; @Rule public WireMockRule wireMockRule = new WireMockRule(8080); @Before public void setUp() throws OpenTokException { // read system properties for integration testing int anApiKey = 0; boolean useMockKey = false; String anApiKeyProp = System.getProperty("apiKey"); String anApiSecret = System.getProperty("apiSecret"); try { anApiKey = Integer.parseInt(anApiKeyProp); } catch (NumberFormatException e) { useMockKey = true; } if (!useMockKey && anApiSecret != null && !anApiSecret.isEmpty()) { // TODO: figure out when to turn mocking off based on this apiKey = anApiKey; apiSecret = anApiSecret; archivePath = "/v2/project/" + apiKey + "/archive"; } sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(apiUrl).build(); } @Test public void testSignalAllConnections() throws OpenTokException { String sessionId = "SESSIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); sdk.signal(sessionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testSignalWithEmptySessionID() throws OpenTokException { String sessionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); } } @Test public void testSignalWithEmoji() throws OpenTokException { String sessionId = "SESSIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; Boolean exceptionThrown = false; SignalProperties properties = new SignalProperties.Builder().type("test").data("\uD83D\uDE01").build(); try { sdk.signal(sessionId, properties); } catch (RequestException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } @Test public void testSignalSingleConnection() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); sdk.signal(sessionId, connectionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testSignalWithEmptyConnectionID() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithConnectionIDAndEmptySessionID() throws OpenTokException { String sessionId = ""; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithEmptySessionAndConnectionID() throws OpenTokException { String sessionId = ""; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testCreateDefaultSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(ArchiveMode.MANUAL, session.getProperties().archiveMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) .withRequestBody(matching(".*p2p.preference=enabled.*")) .withRequestBody(matching(".*archiveMode=manual.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateRoutedSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .mediaMode(MediaMode.ROUTED) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.ROUTED, session.getProperties().mediaMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // NOTE: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*p2p.preference=disabled.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateLocationHintSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .location(locationHint) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(locationHint, session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*location="+locationHint+".*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateAlwaysArchivedSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .archiveMode(ArchiveMode.ALWAYS) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(ArchiveMode.ALWAYS, session.getProperties().archiveMode()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*archiveMode=always.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test(expected = InvalidArgumentException.class) public void testCreateBadSession() throws OpenTokException { SessionProperties properties = new SessionProperties.Builder() .location("NOT A VALID IP") .build(); } // This is not part of the API because it would introduce a backwards incompatible change. // @Test(expected = InvalidArgumentException.class) // public void testCreateInvalidAlwaysArchivedAndRelayedSession() throws OpenTokException { // SessionProperties properties = new SessionProperties.Builder() // .mediaMode(MediaMode.RELAYED) // .archiveMode(ArchiveMode.ALWAYS) // .build(); // TODO: test session creation conditions that result in errors @Test public void testTokenDefault() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = opentok.generateToken(sessionId); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals(Integer.toString(apiKey), tokenData.get("partner_id")); assertNotNull(tokenData.get("create_time")); assertNotNull(tokenData.get("nonce")); } @Test public void testTokenLayoutClass() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = sdk.generateToken(sessionId, new TokenOptions.Builder() .initialLayoutClassList(Arrays.asList("full", "focus")) .build()); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals("full focus", tokenData.get("initial_layout_class_list")); } @Test public void testTokenRoles() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; Role role = Role.SUBSCRIBER; String defaultToken = opentok.generateToken(sessionId); String roleToken = sdk.generateToken(sessionId, new TokenOptions.Builder() .role(role) .build()); assertNotNull(defaultToken); assertNotNull(roleToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(roleToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals("publisher", defaultTokenData.get("role")); Map<String, String> roleTokenData = Helpers.decodeToken(roleToken); assertEquals(role.toString(), roleTokenData.get("role")); } @Test public void testTokenExpireTime() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); long now = System.currentTimeMillis() / 1000L; long inOneHour = now + (60 * 60); long inOneDay = now + (60 * 60 * 24); long inThirtyDays = now + (60 * 60 * 24 * 30); ArrayList<Exception> exceptions = new ArrayList<Exception>(); String defaultToken = opentok.generateToken(sessionId); String oneHourToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inOneHour) .build()); try { String earlyExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(now - 10) .build()); } catch (Exception exception) { exceptions.add(exception); } try { String lateExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inThirtyDays + (60 * 60 * 24) /* 31 days */) .build()); } catch (Exception exception) { exceptions.add(exception); } assertNotNull(defaultToken); assertNotNull(oneHourToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(oneHourToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals(Long.toString(inOneDay), defaultTokenData.get("expire_time")); Map<String, String> oneHourTokenData = Helpers.decodeToken(oneHourToken); assertEquals(Long.toString(inOneHour), oneHourTokenData.get("expire_time")); assertEquals(2, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } @Test public void testTokenConnectionData() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); // purposely contains some exotic characters String actualData = "{\"name\":\"%foo ç &\"}"; Exception tooLongException = null; String defaultToken = opentok.generateToken(sessionId); String dataBearingToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(actualData) .build()); try { String dataTooLongToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(StringUtils.repeat("x", 1001)) .build()); } catch (InvalidArgumentException e) { tooLongException = e; } assertNotNull(defaultToken); assertNotNull(dataBearingToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(dataBearingToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertNull(defaultTokenData.get("connection_data")); Map<String, String> dataBearingTokenData = Helpers.decodeToken(dataBearingToken); assertEquals(actualData, dataBearingTokenData.get("connection_data")); assertEquals(InvalidArgumentException.class, tooLongException.getClass()); } @Test public void testTokenBadSessionId() throws OpenTokException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); ArrayList<Exception> exceptions = new ArrayList<Exception>(); try { String nullSessionToken = opentok.generateToken(null); } catch (Exception e) { exceptions.add(e); } try { String emptySessionToken = opentok.generateToken(""); } catch (Exception e) { exceptions.add(e); } try { String invalidSessionToken = opentok.generateToken("NOT A VALID SESSION ID"); } catch (Exception e) { exceptions.add(e); } assertEquals(3, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } @Test public void testGetArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F" + archiveId + "%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Si" + "gnature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(apiKey, archive.getPartnerId()); assertEquals(archiveId, archive.getId()); assertEquals(1395187836000L, archive.getCreatedAt()); assertEquals(62, archive.getDuration()); assertEquals("", archive.getName()); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(8347554, archive.getSize()); assertEquals(Archive.Status.AVAILABLE, archive.getStatus()); assertEquals("http://tokbox.com.archive2.s3.amazonaws.com/123456%2F"+archiveId +"%2Farchive.mp4?Expires=13951" + "94362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", archive.getUrl()); verify(getRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test get archive failure scenarios @Test public void testListArchives() throws OpenTokException { stubFor(get(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionIdOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1&sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId, 1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionId() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithEmptySessionID() throws OpenTokException { int exceptionCount = 0; int testCount = 2; try { ArchiveList archives = sdk.listArchives(""); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(null); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testListArchivesWithWrongOffsetCountValues() throws OpenTokException { int exceptionCount = 0; int testCount = 4; try { ArchiveList archives = sdk.listArchives(-2,0); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(0,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,12); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testStartArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().name(null).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartArchiveWithName() throws OpenTokException { String sessionId = "SESSIONID"; String name = "archive_name"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"archive_name\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.startArchive(sessionId, name); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertEquals(name, archive.getName()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartVoiceOnlyArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"hasVideo\" : false,\n" + " \"hasAudio\" : true\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().hasVideo(false).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchiveWithLayout() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .layout(new ArchiveLayout(ArchiveLayout.Type.CUSTOM, "stream { position: absolute; }")) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartIndividualArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"individual\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().outputMode(OutputMode.INDIVIDUAL).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.INDIVIDUAL, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } // TODO: test start archive with name // TODO: test start archive failure scenarios @Test public void testStopArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(post(urlEqualTo(archivePath + "/" + archiveId + "/stop")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 0,\n" + " \"id\" : \"ARCHIVEID\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"stopped\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.stopArchive(archiveId); assertNotNull(archive); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(archiveId, archive.getId()); verify(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))))); Helpers.verifyUserAgent(); } // TODO: test stop archive failure scenarios @Test public void testDeleteArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(delete(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.deleteArchive(archiveId); verify(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test delete archive failure scenarios // NOTE: this test is pretty sloppy @Test public void testGetExpiredArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.EXPIRED, archive.getStatus()); } // NOTE: this test is pretty sloppy @Test public void testGetPausedArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"paused\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.PAUSED, archive.getStatus()); } @Test public void testGetArchiveWithUnknownProperties() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null,\n" + " \"thisisnotaproperty\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); } @Test public void testGetStreamWithId() throws OpenTokException { String sessionID = "SESSIONID"; String streamID = "STREAMID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream/" + streamID; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"id\" : \"" + streamID + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }"))); Stream stream = sdk.getStream(sessionID, streamID); assertNotNull(stream); assertEquals(streamID, stream.getId()); assertEquals("", stream.getName()); assertEquals("camera", stream.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListStreams() throws OpenTokException { String sessionID = "SESSIONID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 2,\n" + " \"items\" : [ {\n" + " \"id\" : \"" + 1234 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }, {\n" + " \"id\" : \"" + 5678 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"screen\",\n" + " \"layoutClassList\" : [] \n" + " } ]\n" + " }"))); StreamList streams = sdk.listStreams(sessionID); assertNotNull(streams); assertEquals(2,streams.getTotalCount()); Stream stream1 = streams.get(0); Stream stream2 = streams.get(1); assertEquals("1234", stream1.getId()); assertEquals("", stream1.getName()); assertEquals("camera", stream1.getVideoType()); assertEquals("5678", stream2.getId()); assertEquals("", stream2.getName()); assertEquals("screen", stream2.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testforceDisconnect() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId ; stubFor(delete(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.forceDisconnect(sessionId,connectionId); verify(deleteRequestedFor(urlMatching(path))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testCreateSessionWithProxy() throws OpenTokException, UnknownHostException { WireMockConfiguration proxyConfig = WireMockConfiguration.wireMockConfig(); proxyConfig.dynamicPort(); WireMockServer proxyingService = new WireMockServer(proxyConfig); proxyingService.start(); WireMock proxyingServiceAdmin = new WireMock(proxyingService.port()); String targetServiceBaseUrl = "http://localhost:" + wireMockRule.port(); proxyingServiceAdmin.register(any(urlMatching(".*")).atPriority(10) .willReturn(aResponse() .proxiedFrom(targetServiceBaseUrl))); String sessionId = "SESSIONID"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getLocalHost(), proxyingService.port())); sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(targetServiceBaseUrl).proxy(proxy).build(); stubFor(post(urlEqualTo("/session/create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); verify(postRequestedFor(urlMatching(SESSION_CREATE))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } }
package org.jgroups.tests; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.*; import org.jgroups.blocks.RpcDispatcher; import org.jgroups.mux.MuxChannel; import org.jgroups.stack.GossipRouter; import org.jgroups.util.Util; import java.io.InputStream; import java.io.OutputStream; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.*; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * * @author Bela Ban * @author Vladimir Blagojevic * @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a> * @version $Revision$ */ public class ChannelTestBase extends TestCase { protected final static Random RANDOM = new Random(); private static final int LETTER_A = 64; protected final static String DEFAULT_MUX_FACTORY_COUNT = "4"; protected static String CHANNEL_CONFIG = "udp.xml"; protected static String MUX_CHANNEL_CONFIG = "stacks.xml"; protected static String MUX_CHANNEL_CONFIG_STACK_NAME ="udp"; protected int active_threads = 0; protected JChannelFactory muxFactory[] = null; protected String thread_dump = null; protected int currentChannelGeneratedName = LETTER_A; private static final int ROUTER_PORT = 12001; private static final String BIND_ADDR = "127.0.0.1"; GossipRouter router = null; protected final Log log = LogFactory.getLog(this.getClass()); public ChannelTestBase() { super(); } public ChannelTestBase(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); MUX_CHANNEL_CONFIG = System.getProperty("mux.conf", MUX_CHANNEL_CONFIG); MUX_CHANNEL_CONFIG_STACK_NAME = System.getProperty("mux.conf.stack", MUX_CHANNEL_CONFIG_STACK_NAME); CHANNEL_CONFIG = System.getProperty("channel.conf", CHANNEL_CONFIG); currentChannelGeneratedName = LETTER_A; if (isTunnelUsed()){ router = new GossipRouter(ROUTER_PORT, BIND_ADDR); router.start(); } if (isMuxChannelUsed()) { muxFactory = new JChannelFactory[getMuxFactoryCount()]; for (int i = 0; i < muxFactory.length; i++) { muxFactory[i] = new JChannelFactory(); muxFactory[i].setMultiplexerConfig(MUX_CHANNEL_CONFIG); } } if (shouldCompareThreadCount()) { active_threads = Thread.activeCount(); thread_dump = "active threads before (" + active_threads + "):\n" + Util.activeThreads(); } } protected static boolean isTunnelUsed() { //TODO add maybe a bit more foolproof check later return CHANNEL_CONFIG.contains("tunnel"); } protected void tearDown() throws Exception { super.tearDown(); if (isMuxChannelUsed()) { for (int i = 0; i < muxFactory.length; i++) { muxFactory[i].destroy(); } } if(router != null){ router.stop(); //TODO ensure proper thread/socket cleanup when stopping GossipRouter Util.sleep(100); } if (shouldCompareThreadCount()) { // at the moment Thread.activeCount() is called // it might count in threads that are just being // excluded from active count. // Therefore we include a slight delay of 20 msec Util.sleep(20); int current_active_threads = Thread.activeCount(); String msg = ""; if (active_threads != current_active_threads) { System.out.println(thread_dump); System.out.println("active threads after (" + current_active_threads + "):\n" + Util.activeThreads()); msg = "active threads:\n" + Util.dumpThreads(); } assertEquals(msg, active_threads, current_active_threads); } } /** * Returns an array of mux application/service names with a guarantee that: * <p> * - there are no application/service name collissions on top of one channel * (i.e cannot have two application/service(s) with the same name on top of one channel) * <p> * - each generated application/service name is guaranteed to have a corresponding * pair application/service with the same name on another channel * * @param muxApplicationstPerChannelCount * @return */ protected String [] createMuxApplicationNames(int muxApplicationstPerChannelCount) { return createMuxApplicationNames(muxApplicationstPerChannelCount,getMuxFactoryCount()); } /** * Returns an array of mux application/service names with a guarantee that: * <p> * - there are no application/service name collissions on top of one channel * (i.e cannot have two application/service(s) with the same name on top of one channel) * <p> * - each generated application/service name is guaranteed to have a corresponding * pair application/service with the same name on another channel * * @param muxApplicationstPerChannelCount * @param muxFactoryCount how many mux factories should be used (has to be less than getMuxFactoryCount()) * @return array of mux application id's represented as String objects */ protected String [] createMuxApplicationNames(int muxApplicationstPerChannelCount, int muxFactoryCount) { if(muxFactoryCount>getMuxFactoryCount()) { throw new IllegalArgumentException("Parameter muxFactoryCount hs to be less than or equal to getMuxFactoryCount()"); } int startLetter = LETTER_A; String names [] = null; int totalMuxAppCount = muxFactoryCount * muxApplicationstPerChannelCount; names = new String[totalMuxAppCount]; boolean pickNextLetter = false; for (int i = 0; i < totalMuxAppCount; i++) { pickNextLetter =(i % muxFactoryCount == 0); if(pickNextLetter) { startLetter++; } names[i] = Character.toString((char)startLetter); } return names; } /** * Returns channel name as String next in alphabetic sequence since getNextChannelName() * has been called last. Sequence is restarted to letter "A" after each setUp call. * * @return */ protected String getNextChannelName() { return Character.toString((char)++currentChannelGeneratedName); } protected String [] createApplicationNames(int applicationCount) { String names [] = new String[applicationCount]; for(int i = 0;i<applicationCount;i++) { names [i] = getNextChannelName(); } return names; } protected JChannel createChannel(Object id) throws Exception { JChannel c = null; if (isMuxChannelUsed()) { for (int i = 0; i < muxFactory.length; i++) { if (!muxFactory[i].hasMuxChannel(MUX_CHANNEL_CONFIG_STACK_NAME, id.toString())) { c = new DefaultMuxChannelTestFactory(muxFactory[i]).createChannel(id); return c; } } throw new Exception("Cannot create mux channel with id " + id + " since all currently used channels have already registered service with that id"); } else { c = new DefaultChannelTestFactory().createChannel(id); } return c; } protected JChannel createChannel() throws Exception { return createChannel("A"); } /** * Default channel factory used in junit tests */ protected class DefaultChannelTestFactory implements ChannelTestFactory { public JChannel createChannel(Object id) throws Exception { return createChannel(CHANNEL_CONFIG, useBlocking()); } protected JChannel createChannel(String configFile, boolean useBlocking) throws Exception { HashMap channelOptions = new HashMap(); channelOptions.put(new Integer(Channel.BLOCK), Boolean.valueOf(useBlocking)); return createChannel(configFile, channelOptions); } protected JChannel createChannel(String configFile, Map channelOptions) throws Exception { JChannel ch = null; log.info("Using configuration file " + configFile); ch = new JChannel(configFile); for (Iterator iter = channelOptions.keySet().iterator(); iter.hasNext();) { Integer key = (Integer) iter.next(); Object value = channelOptions.get(key); ch.setOpt(key.intValue(), value); } return ch; } } /** * Default channel factory used in junit tests * */ public class DefaultMuxChannelTestFactory implements ChannelTestFactory { JChannelFactory f = null; public DefaultMuxChannelTestFactory(JChannelFactory f) { this.f = f; } public JChannel createChannel(Object id) throws Exception { JChannel c =(JChannel)f.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, id.toString()); if(useBlocking()) { c.setOpt(Channel.BLOCK, Boolean.TRUE); } Address address = c.getLocalAddress(); String append = "[" + id + "]" + " using " + MUX_CHANNEL_CONFIG + ",stack " + MUX_CHANNEL_CONFIG_STACK_NAME; if (address == null) { log.info("Created unconnected mux channel " + append); } else { log.info("Created mux channel "+ address + append); } return c; } } public class NextAvailableMuxChannelTestFactory implements ChannelTestFactory { public Channel createChannel(Object id) throws Exception { return ChannelTestBase.this.createChannel(id); } } /** * Decouples channel creation for junit tests * */ protected interface ChannelTestFactory { public Channel createChannel(Object id) throws Exception; } /** * Base class for all aplications using channel * * */ protected abstract class ChannelApplication implements Runnable, MemberRetrievable { protected Channel channel; protected Thread thread; protected Throwable exception; protected String name; public ChannelApplication(String name,JChannelFactory f) throws Exception { if(f==null) { createChannel(name, new DefaultChannelTestFactory()); } else { createChannel(name, new DefaultMuxChannelTestFactory(f)); } } /** * Creates a unconnected channel and assigns a name to it. * * @param name name of this channel * @param factory factory to create Channel * @throws ChannelException */ public ChannelApplication(String name, ChannelTestFactory factory) throws Exception { createChannel(name, factory); } private void createChannel(String name, ChannelTestFactory factory) throws Exception { this.name = name; channel = factory.createChannel(name); } /** * Method allowing implementation of specific test application level logic * @throws Exception */ protected abstract void useChannel() throws Exception; public void run() { try { useChannel(); } catch (Exception e) { log.error(name + ": " + e.getLocalizedMessage(), e); exception = e; // Save it for the test to check } } public List getMembers() { List result = null; View v = channel.getView(); if (v != null) { result = v.getMembers(); } return result; } public boolean isUsingMuxChannel() { return channel instanceof MuxChannel; } public Address getLocalAddress() { return channel.getLocalAddress(); } public void start() { thread = new Thread(this, getName()); thread.start(); Address a = getLocalAddress(); boolean connected =a != null; if (connected) { log.info("Thread for channel " + a + "[" + getName() + "] started"); } else { log.info("Thread for channel [" + getName() + "] started"); } } public void setChannel(Channel ch) { this.channel = ch; } public Channel getChannel() { return channel; } public String getName() { return name; } public void cleanup() { if (thread != null && thread.isAlive()) { thread.interrupt(); } Address a = getLocalAddress(); boolean connected =a != null; if (connected) { log.info("Closing channel " + a + "[" + getName() + "]"); } else { log.info("Closing channel [" + getName() + "]"); } channel.close(); } } protected abstract class PushChannelApplication extends ChannelApplication implements ExtendedReceiver { RpcDispatcher dispatcher; public PushChannelApplication(String name) throws Exception { this(name, new DefaultChannelTestFactory(), false); } public PushChannelApplication(String name, JChannelFactory f) throws Exception { this(name, new DefaultMuxChannelTestFactory(f), false); } public PushChannelApplication(String name, boolean useDispatcher) throws Exception { this(name, new DefaultChannelTestFactory(), useDispatcher); } public PushChannelApplication(String name, ChannelTestFactory factory, boolean useDispatcher) throws Exception { super(name, factory); if (useDispatcher) { dispatcher = new RpcDispatcher(channel, this, this, this); } else { channel.setReceiver(this); } } public RpcDispatcher getDispatcher() { return dispatcher; } public boolean hasDispatcher() { return dispatcher != null; } public void block() { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] in blocking"); } public byte[] getState() { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] "); return null; } public void getState(OutputStream ostream) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "]"); } public byte[] getState(String state_id) { log.debug("Channel " + getLocalAddress() + "[" + getName() + " state id =" + state_id); return null; } public void getState(String state_id, OutputStream ostream) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] state id =" + state_id); } public void receive(Message msg) { } public void setState(byte[] state) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] "); } public void setState(InputStream istream) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "]"); } public void setState(String state_id, byte[] state) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] state id =" + state_id + ", state size is " + state.length); } public void setState(String state_id, InputStream istream) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] state id " + state_id); } public void suspect(Address suspected_mbr) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] suspecting " + suspected_mbr); } public void unblock() { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] unblocking"); } public void viewAccepted(View new_view) { log.debug("Channel " + getLocalAddress() + "[" + getName() + "] accepted view " + new_view); } } /** * Channel with semaphore allows application to go through fine-grained synchronous step control. * <p> * PushChannelApplicationWithSemaphore application will not proceed to useChannel() * until it acquires permit from semphore. After useChannel() completes the acquired * permit will be released. Test driver should control how semaphore tickets are given * and acquired. * */ protected abstract class PushChannelApplicationWithSemaphore extends PushChannelApplication { protected Semaphore semaphore; public PushChannelApplicationWithSemaphore(String name, ChannelTestFactory factory, Semaphore semaphore, boolean useDispatcher) throws Exception { super(name, factory, useDispatcher); this.semaphore = semaphore; } protected PushChannelApplicationWithSemaphore(String name, Semaphore semaphore) throws Exception { this(name, new DefaultChannelTestFactory(), semaphore, false); } protected PushChannelApplicationWithSemaphore(String name, JChannelFactory f,Semaphore semaphore) throws Exception { this(name, new DefaultMuxChannelTestFactory(f), semaphore, false); } protected PushChannelApplicationWithSemaphore(String name, Semaphore semaphore, boolean useDispatcher) throws Exception { this(name, new DefaultChannelTestFactory(), semaphore, useDispatcher); } public void run() { boolean acquired = false; try { acquired = semaphore.tryAcquire(60000L, TimeUnit.MILLISECONDS); if (!acquired) { throw new Exception(name + " cannot acquire semaphore"); } useChannel(); } catch (Exception e) { log.error(name + ": " + e.getLocalizedMessage(), e); // Save it for the test to check exception = e; } finally { if (acquired) { semaphore.release(); } } } } protected interface MemberRetrievable { public List getMembers(); public Address getLocalAddress(); } /** * Returns true if JVM has been started with mux.on system property * set to true, false otherwise. * * @return */ protected boolean isMuxChannelUsed() { return Boolean.valueOf(System.getProperty("mux.on", "false")).booleanValue(); } /** * Returns true if JVM has been started with threadcount system property * set to true, false otherwise. * * @return */ protected boolean shouldCompareThreadCount() { return Boolean.valueOf(System.getProperty("threadcount", "false")).booleanValue(); } /** * Returns value of mux.factorycount system property has been set, otherwise returns * DEFAULT_MUX_FACTORY_COUNT. * * @return */ protected int getMuxFactoryCount() { return Integer.parseInt(System.getProperty("mux.factorycount", DEFAULT_MUX_FACTORY_COUNT)); } /** * Returns true if JVM has been started with useBlocking system property * set to true, false otherwise. * * @return */ protected boolean useBlocking() { return Boolean.valueOf(System.getProperty("useBlocking", "false")).booleanValue(); } /** * Checks each channel in the parameter array to see if it has the * exact same view as other channels in an array. */ public static boolean areViewsComplete(MemberRetrievable[] channels,int memberCount) { for (int i = 0; i < memberCount; i++) { if (!isViewComplete(channels[i], memberCount)) { return false; } } return true; } /** * Loops, continually calling {@link #areViewsComplete(org.jgroups.tests.ChannelTestBase.MemberRetrievable[], int)} * until it either returns true or <code>timeout</code> ms have elapsed. * * @param channels channels which must all have consistent views * @param timeout max number of ms to loop * @throws RuntimeException if <code>timeout</code> ms have elapse without * all channels having the same number of members. */ public static void blockUntilViewsReceived(MemberRetrievable[] channels,long timeout) { blockUntilViewsReceived(channels,channels.length,timeout); } public static void blockUntilViewsReceived(Collection channels,long timeout) { blockUntilViewsReceived(channels,channels.size(),timeout); } /** * Loops, continually calling {@link #areViewsComplete(org.jgroups.tests.ChannelTestBase.MemberRetrievable[], int)} * until it either returns true or <code>timeout</code> ms have elapsed. * * @param channels channels which must all have consistent views * @param timeout max number of ms to loop * @throws RuntimeException if <code>timeout</code> ms have elapse without * all channels having the same number of members. */ public static void blockUntilViewsReceived(MemberRetrievable[] channels, int count, long timeout) { long failTime = System.currentTimeMillis() + timeout; while (System.currentTimeMillis() < failTime) { sleepThread(100); if (areViewsComplete(channels,count)) { return; } } throw new RuntimeException("timed out before caches had complete views"); } public static void blockUntilViewsReceived(Collection channels, int count, long timeout) { long failTime = System.currentTimeMillis() + timeout; while (System.currentTimeMillis() < failTime) { sleepThread(100); if (areViewsComplete((MemberRetrievable[])channels.toArray(new MemberRetrievable[channels.size()]),count)) { return; } } throw new RuntimeException("timed out before caches had complete views"); } public static boolean isViewComplete(MemberRetrievable channel, int memberCount) { List members = channel.getMembers(); if (members == null || memberCount > members.size()) { return false; } else if (memberCount < members.size()) { // This is an exceptional condition StringBuilder sb=new StringBuilder("Channel at address "); sb.append(channel.getLocalAddress()); sb.append(" had "); sb.append(members.size()); sb.append(" members; expecting "); sb.append(memberCount); sb.append(". Members were ("); for (int j = 0; j < members.size(); j++) { if (j > 0) { sb.append(", "); } sb.append(members.get(j)); } sb.append(')'); throw new IllegalStateException(sb.toString()); } return true; } public static void takeAllPermits(Semaphore semaphore, int count) { for (int i = 0; i < count; i++) { try { semaphore.acquire(); } catch (InterruptedException e) { //not interested e.printStackTrace(); } } } public static void acquireSemaphore(Semaphore semaphore, long timeout, int count) throws Exception { for (int i = 0; i < count; i++) { boolean acquired = false; try { acquired = semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { //not interested but print it e.printStackTrace(); } if (!acquired) throw new Exception("Failed to acquire semaphore"); } } public static void sleepRandom(int maxTime) { sleepThread(RANDOM.nextInt(maxTime)); } /** * Puts the current thread to sleep for the desired number of ms, suppressing * any exceptions. * * @param sleeptime number of ms to sleep */ public static void sleepThread(long sleeptime) { try { Thread.sleep(sleeptime); } catch (InterruptedException ie) { } } }
package com.redhat.victims; public class Resources { public static final String JAR_FILE = "testdata/junit-4.11/junit-4.11.jar"; public static final String JAR_SHA1 = JAR_FILE + ".sha1"; public static final String JAR_JSON = JAR_FILE + ".json"; public static final String POM_FILE = "testdata/junit-4.11/junit-4.11.pom"; public static final String POM_SHA1 = POM_FILE + ".sha1"; public static final String POM_JSON = POM_FILE + ".json"; public static final String RECORD_CLIENT_JAR = "testdata/records/victims-client.jar.json"; public static final String TEST_RESPONSE = "testdata/service/test.response"; public static final String TEST_SHA512 = "testdata/service/test.sha512"; public static final String TEST_CVE = "testdata/service/test.cve"; }
package gov.adlnet.xapi; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.UUID; import org.junit.Test; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import gov.adlnet.xapi.client.ActivityClient; import gov.adlnet.xapi.client.StatementClient; import gov.adlnet.xapi.model.Activity; import gov.adlnet.xapi.model.ActivityProfile; import gov.adlnet.xapi.model.ActivityState; import gov.adlnet.xapi.model.Agent; import gov.adlnet.xapi.model.Statement; import gov.adlnet.xapi.model.Verb; import gov.adlnet.xapi.util.Base64; import junit.framework.TestCase; public class ActivityTest extends TestCase { private String PUT_PROFILE_ID; private String POST_PROFILE_ID; private String PUT_STATE_ID; private String POST_STATE_ID; private String ACTIVITY_ID; private static final String LRS_URI = "https://lrs.adlnet.gov/xAPI"; private static final String USERNAME = "jXAPI"; private static final String PASSWORD = "password"; private static final String MBOX = "mailto:test@example.com"; private static final UUID REGISTRATION = UUID.randomUUID(); public void setUp() throws IOException { PUT_PROFILE_ID = UUID.randomUUID().toString(); POST_PROFILE_ID = UUID.randomUUID().toString(); PUT_STATE_ID = UUID.randomUUID().toString(); POST_STATE_ID = UUID.randomUUID().toString(); ACTIVITY_ID = "http://example.com/" + UUID.randomUUID().toString(); Agent a = new Agent(); a.setMbox(MBOX); ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); JsonObject puobj = new JsonObject(); puobj.addProperty("putproftest", "putproftest"); ActivityProfile puap = new ActivityProfile(ACTIVITY_ID, PUT_PROFILE_ID); puap.setProfile(puobj); HashMap<String, String> putEtag = new HashMap<String, String>(); putEtag.put("If-None-Match", "*"); assertTrue(_client.putActivityProfile(puap, putEtag)); JsonObject pobj = new JsonObject(); pobj.addProperty("postproftest", "postproftest"); ActivityProfile pap = new ActivityProfile(ACTIVITY_ID, POST_PROFILE_ID); pap.setProfile(pobj); HashMap<String, String> postEtag = new HashMap<String, String>(); postEtag.put("If-Match", "*"); assertTrue(_client.postActivityProfile(pap, postEtag)); JsonObject pusobj = new JsonObject(); pusobj.addProperty("putstatetest", "putstatetest"); ActivityState pus = new ActivityState(ACTIVITY_ID, PUT_STATE_ID, a); pus.setRegistration(REGISTRATION); pus.setState(pusobj); assertTrue(_client.putActivityState(pus)); JsonObject posbj = new JsonObject(); posbj.addProperty("poststatetest", "poststatetest"); ActivityState pos = new ActivityState(ACTIVITY_ID, POST_STATE_ID, a); pos.setState(posbj); assertTrue(_client.postActivityState(pos)); } public void tearDown() throws IOException { ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); assertTrue(_client.deleteActivityProfile(new ActivityProfile(ACTIVITY_ID, PUT_PROFILE_ID), "*")); assertTrue(_client.deleteActivityProfile(new ActivityProfile(ACTIVITY_ID, POST_PROFILE_ID), "*")); assertTrue(_client.deleteActivityState(new ActivityState(ACTIVITY_ID, PUT_STATE_ID, a))); assertTrue(_client.deleteActivityStates(ACTIVITY_ID, a, null)); } @Test public void testActivityClientUrlStringString() throws IOException { URL lrs_url = new URL(LRS_URI); StatementClient sc = new StatementClient(lrs_url, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(ACTIVITY_ID); Statement st = new Statement(a, v, act); sc.postStatement(st); // Happy path ActivityClient ac = new ActivityClient(lrs_url, USERNAME, PASSWORD); Activity returnAct = ac.getActivity(ACTIVITY_ID); assertNotNull(returnAct); assertEquals(returnAct.getId(), ACTIVITY_ID); // Incorrect password ac = new ActivityClient(lrs_url, USERNAME, "passw0rd"); try { returnAct = ac.getActivity(ACTIVITY_ID); } catch (Exception e) { assertTrue(true); } } @Test public void testActivityClientStringStringString() throws IOException { StatementClient sc = new StatementClient(LRS_URI, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(ACTIVITY_ID); Statement st = new Statement(a, v, act); sc.postStatement(st); // Happy path ActivityClient ac = new ActivityClient(LRS_URI, USERNAME, PASSWORD); Activity returnAct = ac.getActivity(ACTIVITY_ID); assertNotNull(returnAct); assertEquals(returnAct.getId(), ACTIVITY_ID); // Incorrect password ac = new ActivityClient(LRS_URI, USERNAME, "passw0rd"); try { returnAct = ac.getActivity(ACTIVITY_ID); } catch (Exception e) { assertTrue(true); } // Non URL parameter try { ac = new ActivityClient("fail", USERNAME, PASSWORD); } catch (Exception e) { assertTrue(true); } } @Test public void testActivityClientUrlString() throws IOException { URL lrs_url = new URL(LRS_URI); String encodedCreds = Base64.encodeToString((USERNAME + ":" + PASSWORD).getBytes(), Base64.NO_WRAP); StatementClient sc = new StatementClient(lrs_url, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(ACTIVITY_ID); Statement st = new Statement(a, v, act); sc.postStatement(st); // Happy path ActivityClient ac = new ActivityClient(lrs_url, encodedCreds); Activity returnAct = ac.getActivity(ACTIVITY_ID); assertNotNull(returnAct); assertEquals(returnAct.getId(), ACTIVITY_ID); // Incorrect password encodedCreds = Base64.encodeToString((USERNAME + ":" + "passw0rd").getBytes(), Base64.NO_WRAP); ac = new ActivityClient(lrs_url, encodedCreds); try { returnAct = ac.getActivity(ACTIVITY_ID); } catch (Exception e) { assertTrue(true); } } @Test public void testActivityClientStringString() throws IOException { String encodedCreds = Base64.encodeToString((USERNAME + ":" + PASSWORD).getBytes(), Base64.NO_WRAP); StatementClient sc = new StatementClient(LRS_URI, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(ACTIVITY_ID); Statement st = new Statement(a, v, act); sc.postStatement(st); // Happy path ActivityClient ac = new ActivityClient(LRS_URI, encodedCreds); Activity returnAct = ac.getActivity(ACTIVITY_ID); assertNotNull(returnAct); assertEquals(returnAct.getId(), ACTIVITY_ID); // Incorrect password encodedCreds = Base64.encodeToString((USERNAME + ":" + "passw0rd").getBytes(), Base64.NO_WRAP); ac = new ActivityClient(LRS_URI, encodedCreds); try { returnAct = ac.getActivity(ACTIVITY_ID); } catch (Exception e) { assertTrue(true); } encodedCreds = Base64.encodeToString((USERNAME + ":" + PASSWORD).getBytes(), Base64.NO_WRAP); // Non URL parameter try { ac = new ActivityClient("fail", encodedCreds); } catch (Exception e) { assertTrue(true); } } public void testGetActivity() throws IOException { StatementClient sc = new StatementClient(LRS_URI, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); Verb v = new Verb("http://example.com/tested"); Activity act = new Activity(ACTIVITY_ID); Statement st = new Statement(a, v, act); sc.postStatement(st); ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); Activity returnAct = _client.getActivity(ACTIVITY_ID); assertNotNull(returnAct); assertEquals(returnAct.getId(), ACTIVITY_ID); } public void testGetActivityProfile() throws IOException { ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); JsonElement putProfile = _client.getActivityProfile(new ActivityProfile(ACTIVITY_ID, PUT_PROFILE_ID)); assertNotNull(putProfile); assertTrue(putProfile.isJsonObject()); JsonObject obj = (JsonObject) putProfile; assertEquals(obj.getAsJsonPrimitive("putproftest").getAsString(), "putproftest"); ActivityProfile ap = new ActivityProfile(); ap.setActivityId(ACTIVITY_ID); ap.setProfileId(POST_PROFILE_ID); JsonElement postProfile = _client.getActivityProfile(ap); assertNotNull(postProfile); assertTrue(postProfile.isJsonObject()); JsonObject pobj = (JsonObject) postProfile; assertEquals(pobj.getAsJsonPrimitive("postproftest").getAsString(), "postproftest"); } public void testPutProfileIfNoneMatch() throws IOException { } public void testPostProfileIfNoneMatch() throws IOException { } public void testPutProfileBadEtag() throws IOException { } public void testPostProfileBadEtag() throws IOException { } public void testGetActivityProfiles() throws IOException { ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); JsonArray a = _client.getActivityProfiles(ACTIVITY_ID, null); assertNotNull(a); assertTrue(a.size() >= 2); } public void testGetActivityProfilesWithSince() throws IOException { ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); JsonArray a = _client.getActivityProfiles(ACTIVITY_ID, "2014-05-02T17:28:47.00Z"); assertNotNull(a); assertTrue(a.size() >= 2); } public void testGetActivityState() throws IOException { ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); JsonElement putState = _client.getActivityState(new ActivityState(ACTIVITY_ID, PUT_STATE_ID, a)); assertNotNull(putState); assertTrue(putState.isJsonObject()); JsonObject obj = (JsonObject) putState; assertEquals(obj.getAsJsonPrimitive("putstatetest").getAsString(), "putstatetest"); ActivityState pas = new ActivityState(); pas.setActivityId(ACTIVITY_ID); pas.setStateId(POST_STATE_ID); pas.setAgent(a); JsonElement postState = _client.getActivityState(pas); assertNotNull(postState); assertTrue(postState.isJsonObject()); JsonObject pobj = (JsonObject) postState; assertEquals(pobj.getAsJsonPrimitive("poststatetest").getAsString(), "poststatetest"); } public void testGetActivityStateWithRegistration() throws IOException { ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); ActivityState as = new ActivityState(ACTIVITY_ID, PUT_STATE_ID, a); as.setRegistration(REGISTRATION); JsonElement putState = _client.getActivityState(new ActivityState(ACTIVITY_ID, PUT_STATE_ID, a)); assertNotNull(putState); assertTrue(putState.isJsonObject()); JsonObject obj = (JsonObject) putState; assertEquals(obj.getAsJsonPrimitive("putstatetest").getAsString(), "putstatetest"); } public void testGetActivityStates() throws IOException { ActivityClient _client = new ActivityClient(LRS_URI, USERNAME, PASSWORD); Agent a = new Agent(); a.setMbox(MBOX); JsonArray arr = _client.getActivityStates(ACTIVITY_ID, a, null, null); assertNotNull(arr); assertEquals(2, arr.size()); } }
package guitests; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import seedu.taskboss.commons.core.Messages; import seedu.taskboss.logic.commands.AddCommand; import seedu.taskboss.logic.commands.MarkDoneCommand; import seedu.taskboss.model.task.Recurrence.Frequency; import seedu.taskboss.testutil.TaskBuilder; import seedu.taskboss.testutil.TestTask; //@@author A0144904H public class MarkDoneCommandTest extends TaskBossGuiTest { // The list of tasks in the task list panel is expected to match this list. // This list is updated with every successful call to assertEditSuccess(). TestTask[] expectedTasksList = td.getTypicalTasks(); /* * EP: valid task index, * should add category "Done" to the task's current category list. * - test for long and short command formats * - test multiple and single mark done */ //long command format //single mark done @Test public void markDone_validIndex_longCommandFormat_success() throws Exception { int taskBossIndex = 1; TestTask markedDoneTask = new TaskBuilder().withName("Clean house").withPriorityLevel("Yes") .withStartDateTime("Feb 19, 2017 11pm") .withEndDateTime("Feb 28, 2017 5pm") .withInformation("wall street").withRecurrence(Frequency.NONE) .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); assertMarkDoneSuccess(false, taskBossIndex, taskBossIndex, markedDoneTask, expectedTasksList); } //multiple mark done @Test public void multiple_markDone_validIndexes_longCommandFormat_success() throws Exception { commandBox.runCommand("mark 4 5"); expectedTasksList[4] = new TaskBuilder().withName("Birthday party") .withInformation("311, Clementi Ave 2, #02-25") .withPriorityLevel("No") .withRecurrence(Frequency.NONE) .withStartDateTime("Feb 23, 2017 10pm") .withEndDateTime("Jun 28, 2017 5pm") .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS, "Friends", "Owesmoney").build(); expectedTasksList[3] = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes") .withStartDateTime("Feb 20, 2017 11.30pm") .withEndDateTime("Apr 28, 2017 3pm") .withRecurrence(Frequency.NONE) .withInformation("10th street") .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); TestTask[] markedDone = new TestTask[] {expectedTasksList[4], expectedTasksList[3]}; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS, getDesiredFormat(markedDone))); } //short command format //single mark done @Test public void markTaskDone_validIndex_shortCommandFormat_success() throws Exception { int taskBossIndex = 1; TestTask markedDoneTask = new TaskBuilder().withName("Clean house").withPriorityLevel("Yes") .withStartDateTime("Feb 19, 2017 11pm") .withEndDateTime("Feb 28, 2017 5pm") .withInformation("wall street").withRecurrence(Frequency.NONE) .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); assertMarkDoneSuccess(true, taskBossIndex, taskBossIndex, markedDoneTask, expectedTasksList); } //multiple mark done @Test public void multiple_markDone_validIndexes_shortCommandFormat_success() throws Exception { commandBox.runCommand("m 4 5"); expectedTasksList[4] = new TaskBuilder().withName("Birthday party") .withInformation("311, Clementi Ave 2, #02-25") .withPriorityLevel("No") .withRecurrence(Frequency.NONE) .withStartDateTime("Feb 23, 2017 10pm") .withEndDateTime("Jun 28, 2017 5pm") .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS, "Friends", "Owesmoney").build(); expectedTasksList[3] = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes") .withStartDateTime("Feb 20, 2017 11.30pm") .withEndDateTime("Apr 28, 2017 3pm") .withRecurrence(Frequency.NONE) .withInformation("10th street") .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); TestTask[] markedDone = new TestTask[] {expectedTasksList[4], expectedTasksList[3]}; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS, getDesiredFormat(markedDone))); } /* * EP: missing task index, * should show error message: invalid command format * and display a message demonstrating the correct way to write the command */ @Test public void markDone_missingTaskIndex_failure() { //long command format commandBox.runCommand("mark "); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); //short command format commandBox.runCommand("m "); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); } /* * EP: invalid task index, * should show error message: invalid index * - test short and long command format * - test multiple and single mark done */ //single mark done @Test public void markDone_invalidTaskIndex_failure() { //long command format commandBox.runCommand("mark 9"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); commandBox.runCommand("mark -1"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); // non-numeric inputs commandBox.runCommand("mark ^"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); commandBox.runCommand("mark b"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); //short command format commandBox.runCommand("m 10"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); commandBox.runCommand("m 0"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); // non-numeric inputs commandBox.runCommand("m ^"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); commandBox.runCommand("m b"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); } //multiple mark done @Test public void multiple_markDone_InvalidIndexes_failure() { //long command format commandBox.runCommand("mark 1 2 100"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); commandBox.runCommand("mark 0 2 3"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); //user inputs non-numeric index values commandBox.runCommand("mark a 2 3"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); commandBox.runCommand("mark ; 2 3"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); //short command format commandBox.runCommand("m 1 2 100"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); commandBox.runCommand("m 0 2 3"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); //user inputs non-numeric index values commandBox.runCommand("m a 2 3"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); commandBox.runCommand("m ; 2 3"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE)); } /* * EP: marking a marked task, * should show error message: cannot mark marked tasks * - test short and long command format * - test multiple and single mark done */ //long command format //single mark done @Test public void markDone_taskMarkedDone_longCommandFormat_failure() { commandBox.runCommand("mark 1"); commandBox.runCommand("mark 1"); assertResultMessage(MarkDoneCommand.ERROR_MARKED_TASK); } //multiple mark done @Test public void multiple_markDone_taskMarkedDone_longCommandFormat_failure() { commandBox.runCommand("mark 1 4"); commandBox.runCommand("mark 2 4"); assertResultMessage(MarkDoneCommand.ERROR_MARKED_TASK); } //short command format //single mark done @Test public void markDone_taskMarkedDone_shortCommandFormat_failure() { commandBox.runCommand("m 1"); commandBox.runCommand("m 1"); assertResultMessage(MarkDoneCommand.ERROR_MARKED_TASK); } //multiple mark done @Test public void multiple_markDone_taskMarkedDone_shortCommandFormat_failure() { commandBox.runCommand("m 1 5"); commandBox.runCommand("m 2 5"); assertResultMessage(MarkDoneCommand.ERROR_MARKED_TASK); } /* * EP: marking multiple tasks with spaces between indexes, * should add category "Done" to all the tasks's current category lists. */ @Test public void multiple_SpacesInBetween_markTaskDone_success() throws Exception { commandBox.runCommand("mark 5 4 "); expectedTasksList[4] = new TaskBuilder().withName("Birthday party") .withInformation("311, Clementi Ave 2, #02-25") .withPriorityLevel("No") .withRecurrence(Frequency.NONE) .withStartDateTime("Feb 23, 2017 10pm") .withEndDateTime("Jun 28, 2017 5pm") .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS, "Friends", "Owesmoney").build(); expectedTasksList[3] = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes") .withStartDateTime("Feb 20, 2017 11.30pm") .withEndDateTime("Apr 28, 2017 3pm") .withRecurrence(Frequency.NONE) .withInformation("10th street") .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); TestTask[] markedDone = new TestTask[] {expectedTasksList[4], expectedTasksList[3]}; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS, getDesiredFormat(markedDone))); } /* * EP: marking after finding a task, * should add category "Done" to the task's current category list. */ @Test public void markDone_findThenMarkDone_success() throws Exception { commandBox.runCommand("find Clean house"); int filteredTaskListIndex = 1; int taskBossIndex = 1; TestTask taskToMarkDone = expectedTasksList[taskBossIndex - 1]; TestTask markedDoneTask = new TaskBuilder(taskToMarkDone).withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); TestTask[] expectedList = { markedDoneTask }; assertMarkDoneSuccess(false, filteredTaskListIndex, taskBossIndex, markedDoneTask, expectedList); } /* * EP: marking non-recurring task, * should add category "Done" to the task's current category list. */ @Test public void markDone_nonRecurring_success() throws Exception { int taskBossIndex = 1; TestTask markedDoneTask = new TaskBuilder().withName("Clean house").withPriorityLevel("Yes") .withStartDateTime("Feb 19, 2017 11pm") .withEndDateTime("Feb 28, 2017 5pm") .withInformation("wall street").withRecurrence(Frequency.NONE) .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); assertMarkDoneSuccess(false, taskBossIndex, taskBossIndex, markedDoneTask, expectedTasksList); } /* * EP: marking recurring task, * should update task's dates based on recurrence type. */ @Test public void markDone_recurring_success() throws Exception { int taskBossIndex = 2; TestTask markedDoneTask = new TaskBuilder().withName("Ensure code quality").withPriorityLevel("No") .withStartDateTime("Mar 22, 2017 5pm") .withEndDateTime("Mar 28, 2017 5pm") .withRecurrence(Frequency.MONTHLY) .withInformation("michegan ave") .withCategories(AddCommand.BUILT_IN_ALL_TASKS).build(); assertMarkDoneSuccess(false, taskBossIndex, taskBossIndex, markedDoneTask, expectedTasksList); } /* * EP: marking recurring and non-recurring tasks at the same time, * should update the recurring task's dates based on recurrence type. * should add category "Done" to the non-recurring task's current category list. */ @Test public void markDone_mixTypes_success() throws Exception { commandBox.runCommand("mark 2 4"); // recurring expectedTasksList[1] = new TaskBuilder().withName("Ensure code quality").withPriorityLevel("No") .withStartDateTime("Mar 22, 2017 5pm") .withEndDateTime("Mar 28, 2017 5pm") .withRecurrence(Frequency.MONTHLY) .withInformation("michegan ave") .withCategories(AddCommand.BUILT_IN_ALL_TASKS).build(); //non recurring expectedTasksList[3] = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes") .withStartDateTime("Feb 20, 2017 11.30pm") .withEndDateTime("Apr 28, 2017 3pm") .withRecurrence(Frequency.NONE) .withInformation("10th street") .withCategories(AddCommand.BUILT_IN_DONE, AddCommand.BUILT_IN_ALL_TASKS).build(); TestTask[] markedDone = new TestTask[] {expectedTasksList[3], expectedTasksList[1]}; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS, getDesiredFormat(markedDone))); } private void assertMarkDoneSuccess(boolean isShort, int filteredTaskListIndex, int taskBossIndex, TestTask markedDoneTask, TestTask[] expectedTasks) { if (isShort) { commandBox.runCommand("m " + filteredTaskListIndex); } else { commandBox.runCommand("mark " + filteredTaskListIndex); } // confirm the list now contains all previous tasks plus the task with updated details expectedTasksList[taskBossIndex - 1] = markedDoneTask; assertTrue(taskListPanel.isListMatching(expectedTasks)); assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS, "1. " + markedDoneTask)); } //@@author A0143157J /** * Returns a formatted {@code Array} tasksToMarkDone, * so that each TestTask in the Array is numbered */ private String getDesiredFormat(TestTask[] markedDoneTask) { int indexOne = 1; String numberingDot = ". "; int i = indexOne; StringBuilder builder = new StringBuilder(); for (TestTask task : markedDoneTask) { builder.append(i + numberingDot).append(task.toString()); i++; } return builder.toString(); } }
package net.afnf.blog; import java.sql.Connection; import javax.sql.DataSource; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml", "file:src/main/webapp/WEB-INF/applicationContext-db.xml", "file:src/main/webapp/WEB-INF/applicationContext-security.xml", "classpath:/applicationContext-testdb.xml" }) public abstract class SpringTestBase { @Autowired private ApplicationContext ctx; @Autowired protected DataSource dataSource; protected void executeSql(String path) { Resource resource = new ClassPathResource(path, getClass()); ResourceDatabasePopulator rdp = new ResourceDatabasePopulator(); rdp.addScript(resource); rdp.setSqlScriptEncoding("UTF-8"); rdp.setIgnoreFailedDrops(true); rdp.setContinueOnError(false); JdbcTemplate template = new JdbcTemplate(dataSource); try (Connection conn = DataSourceUtils.getConnection(template.getDataSource());) { rdp.populate(conn); } catch (Exception e) { throw new IllegalStateException("executeSql failed, path=" + path, e); } } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.Filter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.PatternFilter; import org.jdesktop.swingx.decorator.ShuttleSorter; import org.jdesktop.swingx.decorator.Sorter; /** * @author Jeanette Winzenburg */ public class JXTableIssues extends InteractiveTestCase { public JXTableIssues() { super("JXTableIssues"); // TODO Auto-generated constructor stub } public void testClearSelectionAndFilter() { JXTable table = new JXTable(createModel(0, 20)); int modelRow = table.getRowCount() - 1; // set a selection near the end - will be invalid after filtering table.setRowSelectionInterval(modelRow, modelRow); table.clearSelection(); table.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("9", 0, 0) })); int viewRow = table.convertRowIndexToView(modelRow); assertTrue("view index visible", viewRow >= 0); table.setRowSelectionInterval(viewRow, viewRow); } /** * Issue #167-swingx: table looses individual row height * on update. * * This happens if the indy row is filtered and the selection is empty - * updateSelectionAndRowHeight case analysis is incomplete. * */ public void testKeepRowHeightOnUpdateAndEmptySelection() { JXTable table = new JXTable(10, 3); table.setRowHeightEnabled(true); // sanity assert assertTrue("row height enabled", table.isRowHeightEnabled()); table.setRowHeight(0, 25); // sanity assert assertEquals(25, table.getRowHeight(0)); // setting an arbitrary value table.setValueAt("dummy", 1, 0); assertEquals(25, table.getRowHeight(0)); // filter to leave only the row with the value set table.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("d", 0, 0)})); assertEquals(1, table.getRowCount()); // setting an arbitrary value in the visible rows table.setValueAt("otherdummy", 0, 1); // reset filter to show all table.setFilters(null); assertEquals(25, table.getRowHeight(0)); } /** * Issue #223 - part d) * * test if selection is cleared after receiving a dataChanged. * Need to specify behaviour: lead/anchor of selectionModel are * not changed in clearSelection(). So modelSelection has old * lead which is mapped as a selection in the view (may be out-of * range). Hmmm... * */ public void testSelectionAfterDataChanged() { DefaultTableModel ascendingModel = createAscendingModel(0, 20, 5, false); JXTable table = new JXTable(ascendingModel); int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); // sanity assertEquals("last row must be selected", selectedRow, table.getSelectedRow()); ascendingModel.fireTableDataChanged(); assertEquals("selection must be cleared", -1, table.getSelectedRow()); } /** * Issue #223 - part d) * * test if selection is cleared after receiving a dataChanged. * */ public void testCoreTableSelectionAfterDataChanged() { DefaultTableModel ascendingModel = createAscendingModel(0, 20, 5, false); JTable table = new JTable(ascendingModel); int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); // sanity assertEquals("last row must be selected", selectedRow, table.getSelectedRow()); ascendingModel.fireTableDataChanged(); assertEquals("selection must be cleared", -1, table.getSelectedRow()); } /** * Issue #119: Exception if sorter on last column and setting * model with fewer columns. * * JW: related to #53-swingx - sorter not removed on column removed. * * PatternFilter does not throw - checks with modelToView if the * column is visible and returns false match if not. Hmm... * * */ public void testFilterInChainOnModelChange() { JXTable table = new JXTable(createAscendingModel(0, 10, 5, true)); int columnCount = table.getColumnCount(); assertEquals(5, columnCount); Filter filter = new PatternFilter(".*", 0, columnCount - 1); FilterPipeline pipeline = new FilterPipeline(new Filter[] {filter}); table.setFilters(pipeline); assertEquals(10, pipeline.getOutputSize()); table.setModel(new DefaultTableModel(10, columnCount - 1)); } /** * Issue #119: Exception if sorter on last column and setting * model with fewer columns. * * * JW: related to #53-swingx - sorter not removed on column removed. * * Similar if sorter in filter pipeline -- absolutely need mutable * pipeline!! * Filed the latter part as Issue #55-swingx * */ public void testSorterInChainOnModelChange() { JXTable table = new JXTable(new DefaultTableModel(10, 5)); int columnCount = table.getColumnCount(); Sorter sorter = new ShuttleSorter(columnCount - 1, false); FilterPipeline pipeline = new FilterPipeline(new Filter[] {sorter}); table.setFilters(pipeline); table.setModel(new DefaultTableModel(10, columnCount - 1)); } public void testComponentAdapterCoordinates() { JXTable table = new JXTable(createModel(0, 10)); Object originalFirstRowValue = table.getValueAt(0,0); Object originalLastRowValue = table.getValueAt(table.getRowCount() - 1, 0); assertEquals("view row coordinate equals model row coordinate", table.getModel().getValueAt(0, 0), originalFirstRowValue); // sort first column - actually does not change anything order table.setSorter(0); // sanity asssert assertEquals("view order must be unchanged ", table.getValueAt(0, 0), originalFirstRowValue); // invert sort table.setSorter(0); // sanity assert assertEquals("view order must be reversed changed ", table.getValueAt(0, 0), originalLastRowValue); ComponentAdapter adapter = table.getComponentAdapter(); assertEquals("adapter filteredValue expects view coordinates", table.getValueAt(0, 0), adapter.getFilteredValueAt(0, 0)); // adapter coordinates are view coordinates adapter.row = 0; adapter.column = 0; assertEquals("adapter filteredValue expects view coordinates", table.getValueAt(0, 0), adapter.getValue()); } //-------------------- adapted jesse wilson: #223 /** * Enhancement: modifying (= filtering by resetting the content) should keep * selection * */ public void testModifyTableContentAndSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" }); Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" }); assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterModify); } /** * Enhancement: modifying (= filtering by resetting the content) should keep * selection */ public void testModifyXTableContentAndSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" }); Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" }); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterModify); } /** * Issue #223: deleting row above selection does not * update the view selection correctly. * * fixed - PENDING: move to normal test (need to move special models as well) * */ public void testDeleteRowAboveSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.removeRow(0); assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); } /** * test: deleting row below selection - should not change */ public void testDeleteRowBelowSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1); assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); } /** * test: deleting last row in selection - should remove last item from selection. */ public void testDeleteLastRowInSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(7, 8); compare.xTable.getSelectionModel().setSelectionInterval(7, 8); Object[] selectedObjects = new Object[] { "H", "I" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1); Object[] selectedObjectsAfterDelete = new Object[] { "H" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterDelete); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterDelete); } private void assertSelection(TableModel tableModel, ListSelectionModel selectionModel, Object[] expected) { List selected = new ArrayList(); for(int r = 0; r < tableModel.getRowCount(); r++) { if(selectionModel.isSelectedIndex(r)) selected.add(tableModel.getValueAt(r, 0)); } List expectedList = Arrays.asList(expected); assertEquals("selected Objects must be as expected", expectedList, selected); } public void interactiveDeleteRowAboveSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); JComponent box = createContent(compare, createRowDeleteAction(0, compare.tableModel)); JFrame frame = wrapInFrame(box, "delete above selection"); frame.setVisible(true); } public void interactiveDeleteRowBelowSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(6, 7); compare.xTable.getSelectionModel().setSelectionInterval(6, 7); JComponent box = createContent(compare, createRowDeleteAction(-1, compare.tableModel)); JFrame frame = wrapInFrame(box, "delete below selection"); frame.setVisible(true); } public void interactiveDataChanged() { final DefaultTableModel model = createAscendingModel(0, 10, 5, false); JXTable xtable = new JXTable(model); xtable.setRowSelectionInterval(0, 0); JTable table = new JTable(model); table.setRowSelectionInterval(0, 0); AbstractAction action = new AbstractAction("fire dataChanged") { public void actionPerformed(ActionEvent e) { model.fireTableDataChanged(); } }; JXFrame frame = wrapWithScrollingInFrame(xtable, table, "selection after data changed"); addAction(frame, action); frame.setVisible(true); } private JComponent createContent(CompareTableBehaviour compare, Action action) { JComponent box = new JPanel(new BorderLayout()); box.add(new JScrollPane(compare.table), BorderLayout.WEST); box.add(new JScrollPane(compare.xTable), BorderLayout.EAST); box.add(new JButton(action), BorderLayout.SOUTH); return box; } private Action createRowDeleteAction(final int row, final ReallySimpleTableModel simpleTableModel) { Action delete = new AbstractAction("DeleteRow " + ((row < 0) ? "last" : "" + row)) { public void actionPerformed(ActionEvent e) { int rowToDelete = row; if (row < 0) { rowToDelete = simpleTableModel.getRowCount() - 1; } if ((rowToDelete < 0) || (rowToDelete >= simpleTableModel.getRowCount())) { return; } simpleTableModel.removeRow(rowToDelete); if (simpleTableModel.getRowCount() == 0) { setEnabled(false); } } }; return delete; } public static class CompareTableBehaviour { public ReallySimpleTableModel tableModel; public JTable table; public JXTable xTable; public CompareTableBehaviour(Object[] model) { tableModel = new ReallySimpleTableModel(); tableModel.setContents(model); table = new JTable(tableModel); xTable = new JXTable(tableModel); table.getColumnModel().getColumn(0).setHeaderValue("JTable"); xTable.getColumnModel().getColumn(0).setHeaderValue("JXTable"); } }; /** * A one column table model where all the data is in an Object[] array. */ static class ReallySimpleTableModel extends AbstractTableModel { private List contents = new ArrayList(); public void setContents(List contents) { this.contents.clear(); this.contents.addAll(contents); fireTableDataChanged(); } public void setContents(Object[] contents) { setContents(Arrays.asList(contents)); } public void removeRow(int row) { contents.remove(row); fireTableRowsDeleted(row, row); } public int getRowCount() { return contents.size(); } public int getColumnCount() { return 1; } public Object getValueAt(int row, int column) { if(column != 0) throw new IllegalArgumentException(); return contents.get(row); } } /** * returns a tableModel with count rows filled with * ascending integers in first column * starting from startRow. * @param startRow the value of the first row * @param rowCount the number of rows * @return */ private DefaultTableModel createAscendingModel(int startRow, final int rowCount, final int columnCount, boolean fillLast) { DefaultTableModel model = new DefaultTableModel(rowCount, columnCount) { public Class getColumnClass(int column) { Object value = rowCount > 0 ? getValueAt(0, column) : null; return value != null ? value.getClass() : super.getColumnClass(column); } }; int filledColumn = fillLast ? columnCount - 1 : 0; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, filledColumn); } return model; } private DefaultTableModel createModel(int startRow, int count) { DefaultTableModel model = new DefaultTableModel(count, 5); for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, 0); } return model; } /** * JW: Still needed? moved to main testCase? * */ public void testNewRendererInstance() { JXTable table = new JXTable(); TableCellRenderer newRenderer = table.getNewDefaultRenderer(Boolean.class); TableCellRenderer sharedRenderer = table.getDefaultRenderer(Boolean.class); assertNotNull(newRenderer); assertNotSame("new renderer must be different from shared", sharedRenderer, newRenderer); assertNotSame("new renderer must be different from object renderer", table.getDefaultRenderer(Object.class), newRenderer); } /** * Issue #??: JXTable pattern search differs from * PatternHighlighter/Filter. * * Fixing the issue (respect the pattern as is by calling * pattern.matcher().matches instead of the find()) must * make sure that the search methods taking the string * include wildcards. * * Note: this method passes as long as the issue is not * fixed! */ public void testWildCardInSearchByString() { JXTable table = new JXTable(createModel(0, 11)); int row = 1; String lastName = table.getValueAt(row, 0).toString(); int found = table.getSearchable().search(lastName, -1); assertEquals("found must be equal to row", row, found); found = table.getSearchable().search(lastName, found); assertEquals("search must succeed", 10, found); } public static void main(String args[]) { JXTableIssues test = new JXTableIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Siz.*"); // test.runInteractiveTests("interactive.*Render.*"); // test.runInteractiveTests("interactive.*Toggle.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } }
package tk.wurst_client.features.mods; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.math.BlockPos; import tk.wurst_client.events.LeftClickEvent; import tk.wurst_client.events.listeners.LeftClickListener; import tk.wurst_client.events.listeners.RenderListener; import tk.wurst_client.events.listeners.UpdateListener; import tk.wurst_client.features.Feature; import tk.wurst_client.features.special_features.YesCheatSpf.BypassLevel; import tk.wurst_client.settings.ModeSetting; import tk.wurst_client.settings.SliderSetting; import tk.wurst_client.settings.SliderSetting.ValueDisplay; import tk.wurst_client.utils.BlockUtils; import tk.wurst_client.utils.BlockUtils.BlockValidator; import tk.wurst_client.utils.RenderUtils; @Mod.Info( description = "Destroys blocks around you.\n" + "Use .nuker mode <mode> to change the mode.", name = "Nuker", help = "Mods/Nuker") @Mod.Bypasses public class NukerMod extends Mod implements LeftClickListener, UpdateListener, RenderListener { public int id = 0; private BlockPos currentBlock; private BlockValidator validator; public final SliderSetting range = new SliderSetting("Range", 6, 1, 6, 0.05, ValueDisplay.DECIMAL); public final ModeSetting mode = new ModeSetting("Mode", new String[]{"Normal", "ID", "Flat", "Smash"}, 0) { @Override public void update() { switch(getSelected()) { default: case 0: // normal mode validator = (pos) -> true; break; case 1: // id mode validator = (pos) -> id == BlockUtils.getId(pos); break; case 2: // flat mode validator = (pos) -> pos.getY() >= mc.player.posY; break; case 3: // smash mode validator = (pos) -> BlockUtils.getHardness(pos) >= 1; break; } } }; @Override public void initSettings() { settings.add(range); settings.add(mode); } @Override public String getRenderName() { switch(mode.getSelected()) { case 0: return "Nuker"; case 1: return "IDNuker [" + id + "]"; default: return mode.getSelectedMode() + "Nuker"; } } @Override public Feature[] getSeeAlso() { return new Feature[]{wurst.mods.nukerLegitMod, wurst.mods.speedNukerMod, wurst.mods.tunnellerMod, wurst.mods.fastBreakMod, wurst.mods.autoMineMod, wurst.mods.overlayMod}; } @Override public void onEnable() { // disable other nukers if(wurst.mods.nukerLegitMod.isEnabled()) wurst.mods.nukerLegitMod.setEnabled(false); if(wurst.mods.speedNukerMod.isEnabled()) wurst.mods.speedNukerMod.setEnabled(false); if(wurst.mods.tunnellerMod.isEnabled()) wurst.mods.tunnellerMod.setEnabled(false); // add listeners wurst.events.add(LeftClickListener.class, this); wurst.events.add(UpdateListener.class, this); wurst.events.add(RenderListener.class, this); } @Override public void onDisable() { // remove listeners wurst.events.remove(LeftClickListener.class, this); wurst.events.remove(UpdateListener.class, this); wurst.events.remove(RenderListener.class, this); // resets mc.playerController.resetBlockRemoving(); currentBlock = null; id = 0; } @Override public void onLeftClick(LeftClickEvent event) { // check hitResult if(mc.objectMouseOver == null || mc.objectMouseOver.getBlockPos() == null) return; // check mode if(mode.getSelected() != 1) return; // check material if(BlockUtils .getMaterial(mc.objectMouseOver.getBlockPos()) == Material.AIR) return; // set id id = Block.getIdFromBlock( BlockUtils.getBlock(mc.objectMouseOver.getBlockPos())); } @Override public void onUpdate() { // abort if using IDNuker without an ID being set if(mode.getSelected() == 1 && id == 0) return; boolean legit = wurst.special.yesCheatSpf.getBypassLevel() .ordinal() > BypassLevel.MINEPLEX.ordinal(); // find closest valid block currentBlock = BlockUtils.findClosestValidBlock(range.getValue(), !legit, validator); // check if any block was found if(currentBlock == null) { mc.playerController.resetBlockRemoving(); return; } // nuke all if(mc.player.capabilities.isCreativeMode && !legit) { mc.playerController.resetBlockRemoving(); // break blocks BlockUtils.forEachValidBlock(range.getValue(), validator, (pos) -> BlockUtils.breakBlockPacketSpam(pos)); return; } boolean successful; // break block if(legit) successful = BlockUtils.breakBlockLegit(currentBlock); else successful = BlockUtils.breakBlockSimple(currentBlock); // reset if failed if(!successful) { mc.playerController.resetBlockRemoving(); currentBlock = null; } } @Override public void onRender() { if(currentBlock == null) return; // check if block can be destroyed instantly if(mc.player.capabilities.isCreativeMode || BlockUtils.getHardness(currentBlock) >= 1) RenderUtils.nukerBox(currentBlock, 1); else RenderUtils.nukerBox(currentBlock, mc.playerController.curBlockDamageMP); } @Override public void onYesCheatUpdate(BypassLevel bypassLevel) { switch(bypassLevel) { default: case OFF: case MINEPLEX: range.unlock(); break; case ANTICHEAT: case OLDER_NCP: case LATEST_NCP: case GHOST_MODE: range.lockToMax(4.25); break; } } }
package be.fedict.dcat.tools; import be.fedict.dcat.helpers.Storage; import com.google.common.collect.ListMultimap; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Pattern; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.DCAT; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.rio.RDFParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Generate ARFF for machine learning tools. * * @author Bart.Hanssens */ public class ARFF { private final static Logger logger = LoggerFactory.getLogger(ARFF.class); private final static String PROP_PREFIX = "be.fedict.dcat.tools.arff"; private final static Properties prop = new Properties(); private final static Pattern WHITES = Pattern.compile("\\s+"); private final static Pattern NO_ALPHA = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS); private static Storage store = null; /** * Exit cleanly. * * @param code return code */ private static void exit(int code) { if (store != null) { try { store.shutdown(); } catch (RepositoryException ex) { logger.error("Error shutting down repository", ex); } } logger.info("-- STOP --"); System.exit(code); } /** * Read RDF file. */ private static void readRDF() { String file = prop.getProperty(PROP_PREFIX + ".store", ""); store = new Storage(new File(file)); try { store.startup(); } catch (RepositoryException ex) { logger.error("Error starting repository", ex); exit(-3); } String rdfin = prop.getProperty(PROP_PREFIX + ".rdfin", ""); try { store.read(new BufferedReader(new FileReader(rdfin))); } catch (IOException ex ) { logger.error("Could not read from rdf file {}", rdfin, ex); exit(-4); } catch (RepositoryException|RDFParseException ex) { logger.error("Repository error", ex); exit(-4); } } /** * Sanitize strings * * @param str input string * @return lowercase string without punctuation */ private static String sanitize(String str) { if (str == null || str.isEmpty()){ return ""; } String s = WHITES.matcher(str).replaceAll(" "); s = NO_ALPHA.matcher(s).replaceAll(" "); return s.toLowerCase(); } /** * Sanitize list of strings * * @param strs array of input string * @return lowercase string without punctuation */ private static String sanitize(List<String> strs) { if (strs == null || strs.isEmpty()){ return ""; } String s = ""; for (String str: strs) { String tmp = WHITES.matcher(str).replaceAll(" "); s += NO_ALPHA.matcher(tmp).replaceAll(" "); } return s.toLowerCase(); } /** * Turn a list of themes into boolean strings * * @param dataset list of dataset themes * @param all list of all possible themes * @return comma-separated string of booleans */ private static String[] bitThemes(List<String> dataset, String[] all) { dataset.removeIf(str -> !str.startsWith("http://publications.europa.eu")); dataset.replaceAll(str -> str.substring(str.lastIndexOf("/") + 1, str.lastIndexOf("/") + 5)); String[] bools = new String[all.length]; int i = 0; for (String theme: all) { bools[i++] = dataset.contains(theme) ? "1" : "0"; } return bools; } /** * Not categorized * * @param themes list of themes * @return all themes set to 0 */ private static String noThemes(String[] themes) { StringBuilder w = new StringBuilder(); for (int i = 0; i < themes.length -1; i++) { w.append("0,"); } w.append('0'); return w.toString(); } /** * Generate ARFF header data * * @param langs languages * @param themes DCAT themes * @return String * @throws IOException */ private static String arffHeader(String[] langs, String[] themes) throws IOException { StringBuilder w = new StringBuilder(); w.append("@relation 'DCAT datasets:") .append(" -C -").append(String.valueOf(themes.length)).append("'") .append(System.lineSeparator()).append(System.lineSeparator()); w.append("@attribute id string").append(System.lineSeparator()); for (String lang: langs) { w.append("@attribute title").append(lang).append(" string").append(System.lineSeparator()); w.append("@attribute desc").append(lang).append(" string").append(System.lineSeparator()); w.append("@attribute keywords").append(lang).append(" string").append(System.lineSeparator()); } for (String theme: themes) { w.append("@attribute ").append(theme).append(" {0,1}").append(System.lineSeparator()); } w.append(System.lineSeparator()); w.append("@data").append(System.lineSeparator()); w.append(System.lineSeparator()); return w.toString(); } /** * Write data line to ARFF file * * @param langs languages * @param themes DCAT themes * @param uri IRI of the dataset * @throws IOException */ private static String arffLine(String[] langs, String[] themes, IRI uri) throws IOException { StringBuilder w = new StringBuilder(); Map<IRI, ListMultimap<String, String>> fields = store.queryProperties(uri); w.append(uri.stringValue()).append(','); for (String lang : langs) { String title = sanitize(Storage.getOne(fields, DCTERMS.TITLE, lang)); String desc = sanitize(Storage.getOne(fields, DCTERMS.DESCRIPTION, lang)); String kw = sanitize(Storage.getMany(fields, DCAT.KEYWORD, lang)); w.append('\'').append(title).append('\'').append(',') .append('\'').append(desc).append('\'').append(',') .append('\'').append(kw).append('\'').append(','); } String[] themebits = bitThemes(Storage.getMany(fields, DCAT.THEME, ""), themes); int i = 1; for (String themebit: themebits) { w.append(themebit); if (i++ < themebits.length) { w.append(','); } } w.append(System.lineSeparator()); return w.toString(); } /** * Write ARFF file for Meka/Weka */ private static void writeARFF() { String fDone = prop.getProperty(PROP_PREFIX + ".done", ""); if (fDone.isEmpty()) { logger.error("No output ARFF file defined for classified datasets"); exit(-5); } String fTodo = prop.getProperty(PROP_PREFIX + ".todo", ""); if (fTodo.isEmpty()) { logger.error("No output ARFF file defined for unclassified datasets"); exit(-5); } String[] langs = prop.getProperty(PROP_PREFIX + ".languages", "").split(","); if (langs.length == 0 || langs[0].isEmpty()) { logger.error("No languages defined"); exit(-6); } String[] themes = prop.getProperty(PROP_PREFIX + ".themes", "").split(","); if (themes.length == 0 || themes[0].isEmpty()) { logger.error("No themes defined"); exit(-7); } try ( BufferedWriter wDone = Files.newBufferedWriter(Paths.get(fDone)); BufferedWriter wTodo = Files.newBufferedWriter(Paths.get(fTodo))) { wDone.append(arffHeader(langs, themes)); wTodo.append(arffHeader(langs, themes)); String none = noThemes(themes) + System.lineSeparator(); List<IRI> uris = store.query(DCAT.DATASET); for(IRI uri: uris) { String line = arffLine(langs, themes, uri); if (line.endsWith(none)) { wTodo.append(line); } else { wDone.append(line); } } wDone.close(); wTodo.close(); } catch (IOException ex) { logger.error("Error writing to arff", ex); exit(-8); } } /** * ARFF program * * @param args */ public static void main(String[] args) { logger.info("-- START --"); if (args.length == 0) { logger.error("No config file"); exit(-1); } File config = new File(args[0]); try { prop.load(new FileInputStream(config)); } catch (IOException ex) { logger.error("I/O Exception while reading {}", config, ex); exit(-2); } readRDF(); writeARFF(); } }
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.component; import java.io.File; import java.util.ArrayList; import java.util.List; public class Component { enum Shell { CMD, SH } private static final Shell mShell; static { String osName = System.getProperty("os.name"); if (osName != null && osName.startsWith("Windows")) { mShell = Shell.CMD; } else { mShell = Shell.SH; } } static private IOs mOs; static private File mPath = null; public static void setOs(IOs os) { mOs = os; } public static void setPath(File path) { mPath = path; } public static void setUpEnvironment(ProcessBuilder pb) { mOs.setUpEnvironment(pb, mPath); } public static ArrayList<String> getOpenCommand() { return getCommandByName("flint-open"); } private static ArrayList<String> getCommandLineString(CommandLine commandLine) { ArrayList<String> list = new ArrayList<>(); if (mShell == Shell.CMD) { list.add("cmd"); list.add("/c"); } else { list.add("/bin/sh"); list.add("-c"); } String s = null; for (Command command : commandLine.getCommands()) { String cs = mOs.getCommandString(command, mPath); if (s == null) { s = cs; } else { s += " | " + cs; } } list.add(s); return list; } public static List<String> getFlintExecCommand() { return getCommandByName("flint-exec"); } public static List<String> getFlintRunCommand() { return getCommandByName("flint-run"); } public static List<String> getFlintPauseCommand(int pid) { return getCommandByName("flint-pause " + pid); } public static List<String> getFlintResumeCommand(int pid) { return getCommandByName("flint-resume " + pid); } public static List<String> getIsd2csvCommand(File inputFile, File outputFile) { Command command = new Command("isd2csv"); command.addArgument(inputFile); command.setOutputFile(outputFile); return getCommandLineString(new CommandLine(command)); } public static List<String> getIsd2csvCommand(File inputFile, File outputFile, int port) { Command command = new Command("isd2csv"); command.addOption("progress", port); command.addArgument(inputFile); command.setOutputFile(outputFile); return getCommandLineString(new CommandLine(command)); } public static ArrayList<String> getCommandByName(String name) { ArrayList<String> list = new ArrayList<>(); if (mShell == Shell.CMD) { list.add("cmd"); list.add("/c"); } else { list.add("/bin/sh"); list.add("-c"); } list.add(name); return list; } }
// FakeReader.java package loci.formats.in; import java.io.IOException; import java.util.Random; import loci.common.DataTools; import loci.common.Location; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; public class FakeReader extends FormatReader { // -- Constants -- public static final int BOX_SIZE = 10; public static final int DEFAULT_SIZE_X = 512; public static final int DEFAULT_SIZE_Y = 512; public static final int DEFAULT_SIZE_Z = 1; public static final int DEFAULT_SIZE_C = 1; public static final int DEFAULT_SIZE_T = 1; public static final int DEFAULT_PIXEL_TYPE = FormatTools.UINT8; public static final int DEFAULT_RGB_CHANNEL_COUNT = 1; public static final String DEFAULT_DIMENSION_ORDER = "XYZCT"; private static final String TOKEN_SEPARATOR = "&"; private static final long SEED = 0xcafebabe; // -- Fields -- /** Scale factor for gradient, if any. */ private double scaleFactor = 1; /** 8-bit lookup table, if indexed color, one per channel. */ private byte[][][] lut8 = null; /** 16-bit lookup table, if indexed color, one per channel. */ private short[][][] lut16 = null; /** For indexed color, mapping from indices to values and vice versa. */ private int[][] indexToValue = null, valueToIndex = null; /** Channel of last opened image plane. */ private int ac = -1; // -- Constructor -- /** Constructs a new fake reader. */ public FakeReader() { super("Simulated data", "fake"); } // -- IFormatReader API methods -- /* @see IFormatReader#get8BitLookupTable() */ @Override public byte[][] get8BitLookupTable() throws FormatException, IOException { return ac < 0 || lut8 == null ? null : lut8[ac]; } /* @see IFormatReader#get16BitLookupTable() */ @Override public short[][] get16BitLookupTable() throws FormatException, IOException { return ac < 0 || lut16 == null ? null : lut16[ac]; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ @Override public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); final int series = getSeries(); final int pixelType = getPixelType(); final int bpp = FormatTools.getBytesPerPixel(pixelType); final boolean signed = FormatTools.isSigned(pixelType); final boolean floating = FormatTools.isFloatingPoint(pixelType); final int rgb = getRGBChannelCount(); final boolean indexed = isIndexed(); final boolean little = isLittleEndian(); final boolean interleaved = isInterleaved(); final int[] zct = getZCTCoords(no); final int zIndex = zct[0], cIndex = zct[1], tIndex = zct[2]; ac = cIndex; // integer types start gradient at the smallest value long min = signed ? (long) -Math.pow(2, 8 * bpp - 1) : 0; if (floating) min = 0; // floating point types always start at 0 for (int cOffset=0; cOffset<rgb; cOffset++) { int channel = rgb * cIndex + cOffset; for (int row=0; row<h; row++) { int yy = y + row; for (int col=0; col<w; col++) { int xx = x + col; long pixel = min + xx; // encode various information into the image plane boolean specialPixel = false; if (yy < BOX_SIZE) { int grid = xx / BOX_SIZE; specialPixel = true; switch (grid) { case 0: pixel = series; break; case 1: pixel = no; break; case 2: pixel = zIndex; break; case 3: pixel = channel; break; case 4: pixel = tIndex; break; default: // just a normal pixel in the gradient specialPixel = false; } } // if indexed color with non-null LUT, convert value to index if (indexed) { if (lut8 != null) pixel = valueToIndex[ac][(int) (pixel % 256)]; if (lut16 != null) pixel = valueToIndex[ac][(int) (pixel % 65536)]; } // scale pixel value by the scale factor // if floating point, convert value to raw IEEE floating point bits switch (pixelType) { case FormatTools.FLOAT: float floatPixel; if (specialPixel) floatPixel = pixel; else floatPixel = (float) (scaleFactor * pixel); pixel = Float.floatToIntBits(floatPixel); break; case FormatTools.DOUBLE: double doublePixel; if (specialPixel) doublePixel = pixel; else doublePixel = scaleFactor * pixel; pixel = Double.doubleToLongBits(doublePixel); break; default: if (!specialPixel) pixel = (long) (scaleFactor * pixel); } // unpack pixel into byte buffer int index; if (interleaved) index = w * rgb * row + rgb * col + cOffset; // CXY else index = h * w * cOffset + w * row + col; // XYC index *= bpp; DataTools.unpackBytes(pixel, buf, index, bpp, little); } } } return buf; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ @Override protected void initFile(String id) throws FormatException, IOException { super.initFile(id); String path = id; if (new Location(id).exists()) { path = new Location(id).getAbsoluteFile().getName(); } String noExt = path.substring(0, path.lastIndexOf(".")); String[] tokens = noExt.split(TOKEN_SEPARATOR); String name = null; int sizeX = DEFAULT_SIZE_X; int sizeY = DEFAULT_SIZE_Y; int sizeZ = DEFAULT_SIZE_Z; int sizeC = DEFAULT_SIZE_C; int sizeT = DEFAULT_SIZE_T; int thumbSizeX = 0; // default int thumbSizeY = 0; // default int pixelType = DEFAULT_PIXEL_TYPE; int bitsPerPixel = 0; // default int rgb = DEFAULT_RGB_CHANNEL_COUNT; String dimOrder = DEFAULT_DIMENSION_ORDER; boolean orderCertain = true; boolean little = true; boolean interleaved = false; boolean indexed = false; boolean falseColor = false; boolean metadataComplete = true; boolean thumbnail = false; int seriesCount = 1; int lutLength = 3; // parse tokens from filename for (String token : tokens) { if (name == null) { // first token is the image name name = token; continue; } int equals = token.indexOf("="); if (equals < 0) { LOGGER.warn("ignoring token: {}", token); continue; } String key = token.substring(0, equals); String value = token.substring(equals + 1); boolean boolValue = value.equals("true"); double doubleValue = Double.NaN; try { doubleValue = Double.parseDouble(value); } catch (NumberFormatException exc) { } int intValue = Double.isNaN(doubleValue) ? -1 : (int) doubleValue; if (key.equals("sizeX")) sizeX = intValue; else if (key.equals("sizeY")) sizeY = intValue; else if (key.equals("sizeZ")) sizeZ = intValue; else if (key.equals("sizeC")) sizeC = intValue; else if (key.equals("sizeT")) sizeT = intValue; else if (key.equals("thumbSizeX")) thumbSizeX = intValue; else if (key.equals("thumbSizeY")) thumbSizeY = intValue; else if (key.equals("pixelType")) { pixelType = FormatTools.pixelTypeFromString(value); } else if (key.equals("bitsPerPixel")) bitsPerPixel = intValue; else if (key.equals("rgb")) rgb = intValue; else if (key.equals("dimOrder")) dimOrder = value.toUpperCase(); else if (key.equals("orderCertain")) orderCertain = boolValue; else if (key.equals("little")) little = boolValue; else if (key.equals("interleaved")) interleaved = boolValue; else if (key.equals("indexed")) indexed = boolValue; else if (key.equals("falseColor")) falseColor = boolValue; else if (key.equals("metadataComplete")) metadataComplete = boolValue; else if (key.equals("thumbnail")) thumbnail = boolValue; else if (key.equals("series")) seriesCount = intValue; else if (key.equals("lutLength")) lutLength = intValue; else if (key.equals("scaleFactor")) scaleFactor = doubleValue; } // do some sanity checks if (sizeX < 1) throw new FormatException("Invalid sizeX: " + sizeX); if (sizeY < 1) throw new FormatException("Invalid sizeY: " + sizeY); if (sizeZ < 1) throw new FormatException("Invalid sizeZ: " + sizeZ); if (sizeC < 1) throw new FormatException("Invalid sizeC: " + sizeC); if (sizeT < 1) throw new FormatException("Invalid sizeT: " + sizeT); if (thumbSizeX < 0) { throw new FormatException("Invalid thumbSizeX: " + thumbSizeX); } if (thumbSizeY < 0) { throw new FormatException("Invalid thumbSizeY: " + thumbSizeY); } if (rgb < 1 || rgb > sizeC || sizeC % rgb != 0) { throw new FormatException("Invalid sizeC/rgb combination: " + sizeC + "/" + rgb); } getDimensionOrder(dimOrder); if (falseColor && !indexed) { throw new FormatException("False color images must be indexed"); } if (seriesCount < 1) { throw new FormatException("Invalid seriesCount: " + seriesCount); } if (lutLength < 1) { throw new FormatException("Invalid lutLength: " + lutLength); } // populate core metadata int effSizeC = sizeC / rgb; core = new CoreMetadata[seriesCount]; for (int s=0; s<seriesCount; s++) { core[s] = new CoreMetadata(); core[s].sizeX = sizeX; core[s].sizeY = sizeY; core[s].sizeZ = sizeZ; core[s].sizeC = sizeC; core[s].sizeT = sizeT; core[s].thumbSizeX = thumbSizeX; core[s].thumbSizeY = thumbSizeY; core[s].pixelType = pixelType; core[s].bitsPerPixel = bitsPerPixel; core[s].imageCount = sizeZ * effSizeC * sizeT; core[s].rgb = rgb > 1; core[s].dimensionOrder = dimOrder; core[s].orderCertain = orderCertain; core[s].littleEndian = little; core[s].interleaved = interleaved; core[s].indexed = indexed; core[s].falseColor = falseColor; core[s].metadataComplete = metadataComplete; core[s].thumbnail = thumbnail; } // populate OME metadata MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); for (int s=0; s<seriesCount; s++) { String imageName = s > 0 ? name + " " + (s + 1) : name; store.setImageName(imageName, s); MetadataTools.setDefaultCreationDate(store, id, s); } // for indexed color images, create lookup tables if (indexed) { if (pixelType == FormatTools.UINT8) { // create 8-bit LUTs final int num = 256; createIndexMap(num); lut8 = new byte[sizeC][lutLength][num]; // linear ramp for (int c=0; c<sizeC; c++) { for (int i=0; i<lutLength; i++) { for (int index=0; index<num; index++) { lut8[c][i][index] = (byte) indexToValue[c][index]; } } } } else if (pixelType == FormatTools.UINT16) { // create 16-bit LUTs final int num = 65536; createIndexMap(num); lut16 = new short[sizeC][lutLength][num]; // linear ramp for (int c=0; c<sizeC; c++) { for (int i=0; i<lutLength; i++) { for (int index=0; index<num; index++) { lut16[c][i][index] = (short) indexToValue[c][index]; } } } } // NB: Other pixel types will have null LUTs. } } // -- Helper methods -- /** Creates a mapping between indices and color values. */ private void createIndexMap(int num) { int sizeC = core[0].sizeC; // create random mapping from indices to values indexToValue = new int[sizeC][num]; for (int c=0; c<sizeC; c++) { for (int index=0; index<num; index++) indexToValue[c][index] = index; shuffle(c, indexToValue[c]); } // create inverse mapping: values to indices valueToIndex = new int[sizeC][num]; for (int c=0; c<sizeC; c++) { for (int index=0; index<num; index++) { int value = indexToValue[c][index]; valueToIndex[c][value] = index; } } } /** Fisher-Yates shuffle with constant seeds to ensure reproducibility. */ private static void shuffle(int c, int[] array) { Random r = new Random(SEED + c); for (int i = array.length; i > 1; i int j = r.nextInt(i); int tmp = array[j]; array[j] = array[i - 1]; array[i - 1] = tmp; } } }
// Colorizer.java package loci.plugins.in; import ij.CompositeImage; import ij.ImagePlus; import ij.measure.Calibration; import ij.process.ColorProcessor; import ij.process.ImageProcessor; import ij.process.LUT; import java.awt.Color; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.io.IOException; import java.util.Arrays; import java.util.List; import loci.formats.ChannelFiller; import loci.formats.DimensionSwapper; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.ImageReader; import loci.formats.MinMaxCalculator; import loci.plugins.BF; import loci.plugins.util.ImageProcessorReader; public class Colorizer { // -- Fields -- private ImportProcess process; // -- Constructor -- public Colorizer(ImportProcess process) { this.process = process; } // -- Colorizer methods -- public List<ImagePlus> applyColors(List<ImagePlus> imps) { final ImporterOptions options = process.getOptions(); final ImageProcessorReader reader = process.getReader(); final DimensionSwapper dimSwapper = process.getDimensionSwapper(); final ChannelFiller channelFiller = process.getChannelFiller(); final ImageReader imageReader = process.getImageReader(); for (int i=0; i<imps.size(); i++) { ImagePlus imp = imps.get(i); final int series = (Integer) imp.getProperty(ImagePlusReader.PROP_SERIES); reader.setSeries(series); // get LUT for each channel final String stackOrder = dimSwapper.getDimensionOrder(); final int zSize = imp.getNSlices(); final int cSize = imp.getNChannels(); final int tSize = imp.getNFrames(); final int stackSize = imp.getStackSize(); final LUT[] channelLUTs = new LUT[cSize]; boolean hasChannelLUT = false; for (int c=0; c<cSize; c++) { final int index = FormatTools.getIndex(stackOrder, zSize, cSize, tSize, stackSize, 0, c, 0); channelLUTs[c] = (LUT) imp.getProperty(ImagePlusReader.PROP_LUT + index); if (channelLUTs[c] != null) hasChannelLUT = true; } // compute color mode and LUTs to use int mode = -1; LUT[] luts; if (options.isColorModeDefault()) { // NB: Default color mode behavior depends on the situation. final boolean isRGB = reader.isRGB() || imageReader.isRGB(); if (isRGB || channelFiller.isFilled()) { // NB: The original data had more than one channel per plane // (e.g., RGB image planes), so we use the composite display mode. mode = CompositeImage.COMPOSITE; luts = makeLUTs(channelLUTs, true); // preserve original LUTs } else if (hasChannelLUT) { // NB: The original data had only one channel per plane, // but had at least one lookup table defined. We use the color // display mode, with missing LUTs as grayscale. mode = CompositeImage.COLOR; luts = makeLUTs(channelLUTs, false); // preserve original LUTs } else { // NB: The original data had only one channel per plane, // and had no lookup tables defined, so we use the grayscale mode. mode = CompositeImage.GRAYSCALE; luts = null; } } else if (options.isColorModeComposite()) { mode = CompositeImage.COMPOSITE; luts = makeLUTs(channelLUTs, true); // preserve existing channel LUTs } else if (options.isColorModeColorized()) { mode = CompositeImage.COLOR; luts = makeLUTs(channelLUTs, true); // preserve existing channel LUTs } else if (options.isColorModeGrayscale()) { mode = CompositeImage.GRAYSCALE; luts = null; // use default (grayscale) channel LUTs } else if (options.isColorModeCustom()) { mode = CompositeImage.COLOR; luts = makeLUTs(series); // override any existing channel LUTs } else { throw new IllegalStateException("Invalid color mode: " + options.getColorMode()); } // apply color mode and LUTs final boolean doComposite = !options.isViewStandard() && mode != -1 && cSize > 1 && cSize <= 7; if (doComposite) { CompositeImage compImage = new CompositeImage(imp, mode); if (luts != null) compImage.setLuts(luts); imps.set(i, compImage); imp = compImage; } else { // NB: Cannot use CompositeImage for some reason. if (luts != null && luts.length > 0 && luts[0] != null) { imp.getProcessor().setColorModel(luts[0]); } if (mode != -1 && cSize > 7) { // NB: Cannot use CompositeImage with more than seven channels. BF.warn(options.isQuiet(), "Data has too many channels for " + options.getColorMode() + " color mode"); } } applyDisplayRanges(imp, series); } return imps; } // -- Helper methods -- private void applyDisplayRanges(ImagePlus imp, int series) { final ImporterOptions options = process.getOptions(); final ImageProcessorReader reader = process.getReader(); final int pixelType = reader.getPixelType(); final boolean autoscale = options.isAutoscale() || FormatTools.isFloatingPoint(pixelType); // always autoscale float data final int cSize = imp.getNChannels(); final double[] cMin = new double[cSize]; final double[] cMax = new double[cSize]; Arrays.fill(cMin, Double.NaN); Arrays.fill(cMax, Double.NaN); if (autoscale) { // extract display ranges for autoscaling final MinMaxCalculator minMaxCalc = process.getMinMaxCalculator(); final int cBegin = process.getCBegin(series); final int cStep = process.getCStep(series); for (int c=0; c<cSize; c++) { final int cIndex = cBegin + c * cStep; Double cMinVal = null, cMaxVal = null; try { cMinVal = minMaxCalc.getChannelGlobalMinimum(cIndex); cMaxVal = minMaxCalc.getChannelGlobalMaximum(cIndex); } catch (FormatException exc) { } catch (IOException exc) { } if (cMinVal != null) cMin[c] = cMinVal; if (cMaxVal != null) cMax[c] = cMaxVal; } } // fill in default display ranges as appropriate final int bitDepth = reader.getBitsPerPixel(); // NB: ImageJ does not directly support signed data (it is merely // unsigned data shifted downward by half via a "calibration"), // so the following min and max values also work for signed. final double min = 0; final double max = Math.pow(2, bitDepth) - 1; for (int c=0; c<cSize; c++) { if (Double.isNaN(cMin[c])) cMin[c] = min; if (Double.isNaN(cMax[c])) cMax[c] = max; } // apply display ranges if (imp instanceof CompositeImage) { // apply channel display ranges final CompositeImage compImage = (CompositeImage) imp; for (int c=0; c<cSize; c++) { LUT lut = compImage.getChannelLut(c + 1); // NB: Uncalibrate min/max values before assigning to LUT min/max. double minOffset = 0; final Calibration cal = imp.getCalibration(); if (cal.getFunction() == Calibration.STRAIGHT_LINE) { // adjust minimum offset for signed data double[] coeffs = cal.getCoefficients(); if (coeffs.length > 0) minOffset = coeffs[0]; } lut.min = cMin[c] - minOffset; lut.max = cMax[c] - minOffset; } } else { // compute global display range from channel display ranges double globalMin = Double.POSITIVE_INFINITY; double globalMax = Double.NEGATIVE_INFINITY; for (int c=0; c<cSize; c++) { if (cMin[c] < globalMin) globalMin = cMin[c]; if (cMax[c] > globalMax) globalMax = cMax[c]; } // apply global display range ImageProcessor proc = imp.getProcessor(); if (proc instanceof ColorProcessor) { // NB: Should never occur. ;-) final ColorProcessor colorProc = (ColorProcessor) proc; colorProc.setMinAndMax(min, max, 3); } else proc.setMinAndMax(min, max); } } private LUT[] makeLUTs(ColorModel[] cm, boolean colorize) { final ImporterOptions options = process.getOptions(); final LUT[] luts = new LUT[cm.length]; for (int c=0; c<luts.length; c++) { if (cm[c] instanceof LUT) luts[c] = (LUT) cm[c]; else if (cm[c] instanceof IndexColorModel) { luts[c] = new LUT((IndexColorModel) cm[c], 0, 255); } else { Color color = colorize ? options.getDefaultCustomColor(c) : Color.white; luts[c] = makeLUT(color); } } return luts; } private LUT[] makeLUTs(int series) { final ImageProcessorReader reader = process.getReader(); reader.setSeries(series); LUT[] luts = new LUT[reader.getSizeC()]; for (int c=0; c<luts.length; c++) luts[c] = makeLUT(series, c); return luts; } private LUT makeLUT(int series, int channel) { final ImporterOptions options = process.getOptions(); Color color = options.getCustomColor(series, channel); if (color == null) color = options.getDefaultCustomColor(channel); return makeLUT(color); } private LUT makeLUT(Color color) { final int red = color.getRed(); final int green = color.getGreen(); final int blue = color.getBlue(); final int lutLength = 256; final int lutDivisor = lutLength - 1; byte[] r = new byte[lutLength]; byte[] g = new byte[lutLength]; byte[] b = new byte[lutLength]; for (int i=0; i<lutLength; i++) { r[i] = (byte) (i * red / lutDivisor); g[i] = (byte) (i * green / lutDivisor); b[i] = (byte) (i * blue / lutDivisor); } LUT lut = new LUT(r, g, b); return lut; } }
package dk.netarkivet.archive.tools; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import dk.netarkivet.common.distribute.JMSConnectionFactory; import dk.netarkivet.common.distribute.arcrepository.ARCLookup; import dk.netarkivet.common.distribute.arcrepository.ArcRepositoryClientFactory; import dk.netarkivet.common.distribute.arcrepository.ResultStream; import dk.netarkivet.common.distribute.arcrepository.ViewerArcRepositoryClient; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.exceptions.NetarkivetException; import dk.netarkivet.common.tools.SimpleCmdlineTool; import dk.netarkivet.common.tools.ToolRunnerBase; /** * A command-line tool to get ARC records from the bitarchive. Requires an * Lucene index file * * Usage: java dk.netarkivet.archive.tools.GetRecord indexfile uri > * myrecord.arcrec */ public class GetRecord extends ToolRunnerBase { /** * Main method. Reads a record from the bitarchive and copies it to stdout. * Setup, teardown and run is delegated to the GetRecordTool class. * Management of this, exception handling etc. is delegated to * ToolRunnerBase class. * * @param argv Takes two command line paramers: - indexdir (the Lucene index * directory) - uri (the URI to get the record from) */ public static void main(String[] argv) { GetRecord instance = new GetRecord(); instance.runTheTool(argv); } /** * Method for creating the simple command line tool. * * @return The commandline tool for GetRecord. */ protected SimpleCmdlineTool makeMyTool() { return new GetRecordTool(); } /** * Command line tool for running this tool. */ private static class GetRecordTool implements SimpleCmdlineTool { /** * This instance is declared outside of run method to ensure reliable * teardown in case of exceptions during execution. */ private ViewerArcRepositoryClient arcrep; /** * Accept only exactly 2 parameters. * * @param args the arguments * @return true, if length of args list is 2; returns false otherwise */ public boolean checkArgs(String... args) { return args.length == 2; } /** * Create the ArcRepositoryClient instance here for reliable execution * of close method in teardown. * * @param args the arguments (not used) */ public void setUp(String... args) { arcrep = ArcRepositoryClientFactory.getViewerInstance(); ArgumentNotValid.checkNotNull(arcrep, "arcrep"); } /** * Ensure reliable execution of the ArcRepositoryClient.close() method. * Remember to check if arcrep was actually created. Also reliably * clean up JMSConnection. */ public void tearDown() { if (arcrep != null) { arcrep.close(); } JMSConnectionFactory.getInstance().cleanup(); } /** * Perform the actual work. Procure the necessary information to run * the ARCArchiveAccess from command line parameters and system * settings, and perform the write. Creating and closing the * ArcRepositoryClient (arcrep) is done in setup and teardown methods. * * @param args the arguments */ public void run(String... args) { try { String indexPath = args[0]; String uri = args[1]; ARCLookup lookup = new ARCLookup(arcrep); lookup.setIndex(new File(indexPath)); ResultStream rs = lookup.lookup(new URI(uri)); if (rs == null) { throw new IOFailure( "Resource missing in index or repository for '" + uri + "' in '" + indexPath + "'"); } processRecord(rs.getInputStream()); } catch (NetarkivetException e) { throw new IOFailure( "NetarkivetException while performing " + "ARCArchiveAccess.lookup", e); } catch (URISyntaxException e) { throw new IOFailure("URI has illegal syntax", e); } } /** * Copy a record from content to System.out. * * @param content The InputStream containing the record to copy to * System.out. */ private static void processRecord(InputStream content) { try { BufferedReader br = new BufferedReader( new InputStreamReader(content)); try { int i; while ((i = br.read()) != -1) { System.out.append((char) i); } } finally { br.close(); } } catch (IOException e) { throw new IOFailure( "Internal error: Could not read InputStream from " + "repository", e); } } /** * Return the list of parameters accepted by the GetRecordTool class. * * @return the list parameters accepted. */ public String listParameters() { return "indexfile uri"; } } }
package org.jfree.data.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; /** * A {@link PieDataset} that reads data from a database via JDBC. * <P> * A query should be supplied that returns data in two columns, the first * containing VARCHAR data, and the second containing numerical data. The * data is cached in-memory and can be refreshed at any time. */ public class JDBCPieDataset extends DefaultPieDataset { /** The database connection. */ private transient Connection connection; /** * Creates a new JDBCPieDataset and establishes a new database connection. * * @param url the URL of the database connection. * @param driverName the database driver class name. * @param user the database user. * @param password the database users password. * * @throws ClassNotFoundException if the driver cannot be found. * @throws SQLException if there is a problem obtaining a database * connection. */ public JDBCPieDataset(String url, String driverName, String user, String password) throws SQLException, ClassNotFoundException { Class.forName(driverName); this.connection = DriverManager.getConnection(url, user, password); } /** * Creates a new JDBCPieDataset using a pre-existing database connection. * <P> * The dataset is initially empty, since no query has been supplied yet. * * @param con the database connection. */ public JDBCPieDataset(Connection con) { if (con == null) { throw new NullPointerException("A connection must be supplied."); } this.connection = con; } /** * Creates a new JDBCPieDataset using a pre-existing database connection. * <P> * The dataset is initialised with the supplied query. * * @param con the database connection. * @param query the database connection. * * @throws SQLException if there is a problem executing the query. */ public JDBCPieDataset(Connection con, String query) throws SQLException { this(con); executeQuery(query); } /** * ExecuteQuery will attempt execute the query passed to it against the * existing database connection. If no connection exists then no action * is taken. * The results from the query are extracted and cached locally, thus * applying an upper limit on how many rows can be retrieved successfully. * * @param query the query to be executed. * * @throws SQLException if there is a problem executing the query. */ public void executeQuery(String query) throws SQLException { executeQuery(this.connection, query); } /** * ExecuteQuery will attempt execute the query passed to it against the * existing database connection. If no connection exists then no action * is taken. * The results from the query are extracted and cached locally, thus * applying an upper limit on how many rows can be retrieved successfully. * * @param query the query to be executed * @param con the connection the query is to be executed against * * @throws SQLException if there is a problem executing the query. */ public void executeQuery(Connection con, String query) throws SQLException { Statement statement = null; ResultSet resultSet = null; try { statement = con.createStatement(); resultSet = statement.executeQuery(query); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); if (columnCount != 2) { throw new SQLException( "Invalid sql generated. PieDataSet requires 2 columns only" ); } int columnType = metaData.getColumnType(2); double value = Double.NaN; while (resultSet.next()) { Comparable key = resultSet.getString(1); switch (columnType) { case Types.NUMERIC: case Types.REAL: case Types.INTEGER: case Types.DOUBLE: case Types.FLOAT: case Types.DECIMAL: case Types.BIGINT: value = resultSet.getDouble(2); setValue(key, value); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: Timestamp date = resultSet.getTimestamp(2); value = date.getTime(); setValue(key, value); break; default: System.err.println( "JDBCPieDataset - unknown data type" ); break; } } fireDatasetChanged(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (Exception e) { System.err.println("JDBCPieDataset: swallowing exception."); } } if (statement != null) { try { statement.close(); } catch (Exception e) { System.err.println("JDBCPieDataset: swallowing exception."); } } } } /** * Close the database connection */ public void close() { try { this.connection.close(); } catch (Exception e) { System.err.println("JdbcXYDataset: swallowing exception."); } } }
package app.android.gambit.remote; import com.google.api.client.util.Key; public class CellEntry { @Key("gs:cell") private Cell cell; @Key private String id; @Key private String content; public Cell getCell() { return cell; } public String getId() { return id; } public String getContent() { return content; } public boolean isEmpty() { return cell.isEmpty() && id.isEmpty() && content.isEmpty(); } public CellEntry(WorksheetEntry worksheet, Cell cell) { this(); this.cell = cell; id = worksheet.getCellEditUrl(cell.getRow(), cell.getColumn()).toString(); } public CellEntry() { cell = new Cell(); // empty cell id = new String(); content = new String(); } }