lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
lgpl-2.1
b9e6d90120d6eb11798f55ab059facf069868a46
0
i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,xwiki-contrib/currikiorg
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.curriki.xwiki.plugin.asset; import com.xpn.xwiki.api.Property; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseStringProperty; import java.io.InputStream; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.lang.reflect.Constructor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.curriki.xwiki.plugin.asset.composite.RootCollectionCompositeAsset; import org.curriki.xwiki.plugin.asset.composite.FolderCompositeAsset; import org.curriki.xwiki.plugin.asset.composite.CollectionCompositeAsset; import org.curriki.xwiki.plugin.asset.attachment.AttachmentAsset; import org.curriki.xwiki.plugin.asset.attachment.ImageAsset; import org.curriki.xwiki.plugin.asset.attachment.ArchiveAsset; import org.curriki.xwiki.plugin.asset.attachment.AudioAsset; import org.curriki.xwiki.plugin.asset.attachment.AnimationAsset; import org.curriki.xwiki.plugin.asset.text.TextAsset; import org.curriki.xwiki.plugin.asset.external.ExternalAsset; import org.curriki.xwiki.plugin.asset.external.VIDITalkAsset; import org.curriki.xwiki.plugin.asset.other.InvalidAsset; import org.curriki.xwiki.plugin.asset.other.ProtectedAsset; public class Asset extends CurrikiDocument { private static final Log LOG = LogFactory.getLog(Asset.class); public Asset(XWikiDocument doc, XWikiContext context) { super(doc, context); } public static Asset createTempAsset(String parentAsset, XWikiContext context) throws XWikiException { if (Constants.GUEST_USER.equals(context.getUser())) { throw new AssetException(AssetException.ERROR_ASSET_FORBIDDEN, "XWikiGuest cannot create assets."); } String pageName = context.getWiki().getUniquePageName(Constants.ASSET_TEMPORARY_SPACE, context); XWikiDocument newDoc = context.getWiki().getDocument(Constants.ASSET_TEMPORARY_SPACE, pageName, context); Asset assetDoc = new Asset(newDoc, context); assetDoc.init(parentAsset); assetDoc.saveDocument(context.getMessageTool().get("curriki.comment.createnewsourceasset")); return assetDoc; } protected void init(String parentAsset) throws XWikiException { assertCanEdit(); doc.setCreator(context.getUser()); inheritMetadata(parentAsset); doc.setCustomClass(getClass().getName()); setDefaultContent(); String rights = doc.getObject(Constants.ASSET_CLASS).getStringValue(Constants.ASSET_CLASS_RIGHT); applyRightsPolicy(rights); } protected void setDefaultContent() throws XWikiException { assertCanEdit(); doc.setContent("#includeForm(\"XWiki.AssetTemplate\")"); } protected void initSubType() throws XWikiException { assertCanEdit(); // Empty for Superclass } public void addAttachment(InputStream iStream, String name) throws XWikiException, IOException { assertCanEdit(); XWikiAttachment att = addAttachment(name, iStream); doc.saveAttachmentContent(att, context); } public String getDisplayTitle() { String className = getActiveClass(); use(Constants.ASSET_CLASS); String title = (String) getValue(Constants.ASSET_CLASS_TITLE); if (className != null) { use(className); } return (title == null || title.length() == 0) ? Constants.ASSET_DISPLAYTITLE_UNTITLED : title; } public String getDescription() { String className = getActiveClass(); use(Constants.ASSET_CLASS); String description = (String) getValue(Constants.ASSET_CLASS_DESCRIPTION); if (className != null) { use(className); } return (description == null || description.length() == 0) ? "" : description; } public void changeOwnership(String newUser) { if (hasProgrammingRights()) { XWikiDocument assetDoc = getDoc(); assetDoc.setCreator(newUser); } } /** * Set the rights objects based on the current right setting * * @throws XWikiException */ public void applyRightsPolicy() throws XWikiException { applyRightsPolicy(null); } /** * Set the rights object based on the right in param or the current right setting if null * * @param right * @throws XWikiException */ public void applyRightsPolicy(String right) throws XWikiException { XWikiDocument assetDoc = getDoc(); assetDoc.removeObjects("XWiki.XWikiRights"); BaseObject assetObj = assetDoc.getObject(Constants.ASSET_CLASS); String rights; if (right == null) { // Use existing rights value rights = assetObj.getStringValue(Constants.ASSET_CLASS_RIGHT); } else { rights = right; assetObj.setStringValue(Constants.ASSET_CLASS_RIGHT, right); } // Make sure rights value is valid, default to PUBLIC if not if (rights == null || !(rights.equals(Constants.ASSET_CLASS_RIGHT_PUBLIC) || rights.equals(Constants.ASSET_CLASS_RIGHT_MEMBERS) || rights.equals(Constants.ASSET_CLASS_RIGHT_PRIVATE))) { rights = Constants.ASSET_CLASS_RIGHT_PUBLIC; assetObj.setStringValue(Constants.ASSET_CLASS_RIGHT, rights); } // Rights BaseObject rightObj; // If collection is user String usergroupfield = "users"; String usergroupvalue = ("".equals(assetDoc.getCreator())) ? context.getUser() : assetDoc.getCreator(); // If collection is group if (assetDoc.getSpace().startsWith(Constants.GROUP_COLLECTION_SPACE_PREFIX)) { usergroupfield = "groups"; usergroupvalue = assetDoc.getSpace().substring(5) + ".MemberGroup"; } // Always let the admin group have edit access rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue("groups", "XWiki.XWikiAdminGroup"); rightObj.setStringValue("levels", "edit"); rightObj.setIntValue("allow", 1); // Always let the creator/group edit rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue(usergroupfield, usergroupvalue); rightObj.setStringValue("levels", "edit"); rightObj.setIntValue("allow", 1); if (rights.equals(Constants.ASSET_CLASS_RIGHT_PUBLIC)) { // Viewable by all and any member can edit rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue("groups", "XWiki.XWikiAllGroup"); rightObj.setStringValue("levels", "edit"); rightObj.setIntValue("allow", 1); } else if (rights.equals(Constants.ASSET_CLASS_RIGHT_MEMBERS)) { // Viewable by all, only user/group can edit } else { // rights == private, so only allow creator/group to view and edit rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue(usergroupfield, usergroupvalue); rightObj.setStringValue("levels", "view"); rightObj.setIntValue("allow", 1); } } public Class<? extends Asset> determineAssetSubtype() { if (hasAccessLevel("view")) { if (isFolder()){ if (isRootCollection()){ // Note that the Root Collection doesn't have an Asset Class // so it has to come before checking if no ASSET_CLASS return RootCollectionCompositeAsset.class; } else if (isCollection()){ return CollectionCompositeAsset.class; } else { return FolderCompositeAsset.class; } } // If category is empty then must be an attachment BaseObject obj = doc.getObject(Constants.ASSET_CLASS); if (obj == null) { return InvalidAsset.class; } // Check specific objects to find displayer if (getObject(Constants.TEXT_ASSET_CLASS) != null){ return TextAsset.class; // 3 sub-types HTMLText, WikiText, CBOEText } if (getObject(Constants.EXTERNAL_ASSET_CLASS) != null){ return ExternalAsset.class; // Link } if (getObject(Constants.MIMETYPE_PICTURE_CLASS) != null){ return ImageAsset.class; } if (getObject(Constants.VIDITALK_CLASS) != null){ // category == AUDIO at the moment return VIDITalkAsset.class; } if (getObject(Constants.MIMETYPE_ARCHIVE_CLASS) != null){ return ArchiveAsset.class; } // Check category String category = obj.getStringValue(Constants.EXTERNAL_ASSET_LINK); if (category.equals(Constants.CATEGORY_IMAGE)) { return ImageAsset.class; } else if (category.equals(Constants.CATEGORY_AUDIO)) { return AudioAsset.class; } else if (category.equals(Constants.CATEGORY_ANIMATION)) { return AnimationAsset.class; } else if (category.equals(Constants.CATEGORY_TEXT)) { return TextAsset.class; // ?? But no text class exists } else if (category.equals(Constants.CATEGORY_COLLECTION)) { return FolderCompositeAsset.class; // ?? But no collection class exists } else if (category.equals(Constants.CATEGORY_LINK)) { return ExternalAsset.class; // ?? But no external asset class exists } else if (category.equals(Constants.CATEGORY_ARCHIVE)) { return ArchiveAsset.class; // ?? But no mimetype archive class exists } // Last is just an attachment item if (doc.getAttachmentList().size() > 0) { return AttachmentAsset.class; } // Otherwise is non-specific yet return Asset.class; } else { return ProtectedAsset.class; } } public boolean isFolder() { if (doc.getObjectNumbers(Constants.COMPOSITE_ASSET_CLASS) == 0){ return false; } else { // Work around a bug XWIKI-1624 // TODO: Remove the work-around once XWIKI-1624 is fixed List subAssets = doc.getObjects(Constants.COMPOSITE_ASSET_CLASS); Iterator i = subAssets.iterator(); int count = 0; while (i.hasNext() && count == 0){ if (i.next() != null){ count++; } } if (count == 0){ return false; } } return true; } public boolean isCollection() { if (isFolder()) { com.xpn.xwiki.api.Object obj = getObject(Constants.COMPOSITE_ASSET_CLASS); if (getValue(Constants.COMPOSITE_ASSET_CLASS_TYPE, obj).equals(Constants.COMPOSITE_ASSET_CLASS_TYPE_COLLECTION)) { return true; } } return false; } public boolean isRootCollection() { if (isFolder()) { com.xpn.xwiki.api.Object obj = getObject(Constants.COMPOSITE_ASSET_CLASS); if (getValue(Constants.COMPOSITE_ASSET_CLASS_TYPE, obj).equals(Constants.COMPOSITE_ASSET_CLASS_TYPE_ROOT_COLLECTION)) { return true; } } return false; } public List<Property> getMetadata() { List<Property> md = new ArrayList<Property>(); com.xpn.xwiki.api.Object assetObj = getObject(Constants.ASSET_CLASS); for (Object prop : assetObj.getPropertyNames()) { LOG.debug("Adding "+prop+" to metadata list"); md.add(assetObj.getProperty((String) prop)); } com.xpn.xwiki.api.Object licenseObj = getObject(Constants.ASSET_LICENCE_CLASS); for (Object prop : licenseObj.getPropertyNames()) { LOG.debug("Adding "+prop+" to metadata list"); md.add(licenseObj.getProperty((String) prop)); } // Add assetType to metadata Class assetType = determineAssetSubtype(); String fullAssetType = assetType.getCanonicalName(); BaseStringProperty baseProp = new BaseStringProperty(); baseProp.setName("assetType"); baseProp.setValue(fullAssetType); Property prop = new Property(baseProp, context); md.add(prop); // And add shortAssetType to metadata String shortAssetType = assetType.getSimpleName(); if (!shortAssetType.equals("Asset")) { shortAssetType = shortAssetType.replaceAll("Asset$", ""); } baseProp = new BaseStringProperty(); baseProp.setName("shortAssetType"); baseProp.setValue(shortAssetType); prop = new Property(baseProp, context); md.add(prop); return md; } public <A extends Asset> A as(Class<? extends Asset> wantedClass) throws XWikiException { return (A) as(wantedClass, false); } public <A extends Asset> A subclassAs(Class<? extends Asset> wantedClass) throws XWikiException { return (A) this.as(wantedClass, true); } public <A extends Asset> A as(Class<? extends Asset> wantedClass, boolean moreSpecific) throws XWikiException { // If this is already a subtype of the wanted class then just return this if (wantedClass != null && wantedClass.isAssignableFrom(this.getClass())) { return (A) this; } Class returnClass; // Make sure the determined type is a subclass of the wanted type Class<? extends Asset> assetType = determineAssetSubtype(); if (!moreSpecific) { if (wantedClass == null) { // Return as whatever subtype it is returnClass = assetType; } else if (wantedClass.isAssignableFrom(assetType)) { // Return as the desired type returnClass = wantedClass; } else { throw new AssetException(AssetException.ERROR_ASSET_INCOMPATIBLE, "Document of type "+assetType+" cannot become "+wantedClass); } } else { // Subclass an Asset if (assetType.equals(wantedClass)) { // Already is that type, so don't initialize moreSpecific = false; returnClass = wantedClass; } else if (assetType.equals(Asset.class) && assetType.isAssignableFrom(wantedClass)) { // Turn into a specified subtype of Asset (initializing the subtype) returnClass = wantedClass; } else { throw new AssetException(AssetException.ERROR_ASSET_INCOMPATIBLE, "Document of type "+assetType+" cannot become "+wantedClass); } } Class[] parameterTypes = new Class[2]; parameterTypes[0] = XWikiDocument.class; parameterTypes[1] = XWikiContext.class; Object[] initargs = new Object[2]; initargs[0] = doc; initargs[1] = context; A subtyped; try { Constructor<A> constructor = returnClass.getConstructor(parameterTypes); subtyped = constructor.newInstance(initargs); if (moreSpecific) { subtyped.initSubType(); } } catch (Exception e) { throw new AssetException(AssetException.ERROR_ASSET_INCOMPATIBLE, "Document of type "+assetType+" cannot become "+wantedClass, e); } return subtyped; } public void inheritMetadata() throws XWikiException { inheritMetadata(null); } public void inheritMetadata(String parentAsset) throws XWikiException { assertCanEdit(); BaseObject assetObj = doc.getObject(Constants.ASSET_CLASS); if (assetObj == null) { assetObj = doc.newObject(Constants.ASSET_CLASS, context); } XWikiDocument parentDoc = null; if (parentAsset != null) { parentDoc = context.getWiki().getDocument(parentAsset, context); if (parentDoc.isNew()) { throw new AssetException(AssetException.MODULE_PLUGIN_ASSET, AssetException.ERROR_ASSET_NOT_FOUND, "Parent asset not found"); } } // the Root collection does not have an asset class so we can't inherit from it if (parentDoc != null && parentDoc.getObject(Constants.ASSET_CLASS) != null) { BaseObject parentAssetObj = (BaseObject) parentDoc.getObject(Constants.ASSET_CLASS).clone(); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_EDUCATIONAL_LEVEL); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_FRAMEWORK_ITEMS); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_RIGHT); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_KEYWORDS); } // make sure default rights value is not empty (default to public) String rights = assetObj.getStringValue(Constants.ASSET_CLASS_RIGHT); if ((rights==null)||(rights.equals(""))) { assetObj.setStringValue(Constants.ASSET_CLASS_RIGHT, Constants.ASSET_CLASS_RIGHT_PUBLIC); } BaseObject newLicenceObj = doc.getObject(Constants.ASSET_LICENCE_CLASS); if (newLicenceObj == null) { newLicenceObj = doc.newObject(Constants.ASSET_LICENCE_CLASS, context); } // the Root collection does not have an asset Licence class if (parentDoc != null && parentDoc.getObject(Constants.ASSET_LICENCE_CLASS) != null) { BaseObject parentLicenceObjAsset = parentDoc.getObject(Constants.ASSET_LICENCE_CLASS); copyProperty(parentLicenceObjAsset, newLicenceObj, Constants.ASSET_LICENCE_ITEM_LICENCE_TYPE); } else { newLicenceObj.setStringValue(Constants.ASSET_LICENCE_ITEM_LICENCE_TYPE, Constants.ASSET_LICENCE_ITEM_LICENCE_TYPE_DEFAULT); } // Rights holder should be by default the pretty name of the user newLicenceObj.setStringValue(Constants.ASSET_LICENCE_ITEM_RIGHTS_HOLDER, context.getWiki().getLocalUserName(context.getUser(), null, false, context)); } public FolderCompositeAsset makeFolder(String page) throws XWikiException { assertCanEdit(); FolderCompositeAsset asset = subclassAs(FolderCompositeAsset.class); asset.addSubasset(page); saveDocument(context.getMessageTool().get("curriki.comment.createfoldersourceasset")); return asset; } public ExternalAsset makeExternal(String link) throws XWikiException { assertCanEdit(); ExternalAsset asset = subclassAs(ExternalAsset.class); asset.addLink(link); saveDocument(context.getMessageTool().get("curriki.comment.createlinksourceasset")); return asset; } public VIDITalkAsset makeVIDITalk(String videoId) throws XWikiException { assertCanEdit(); VIDITalkAsset asset = subclassAs(VIDITalkAsset.class); asset.addVideoId(videoId); saveDocument(context.getMessageTool().get("curriki.comment.createviditalksourceasset")); return asset; } public TextAsset makeTextAsset(Long type, String content) throws XWikiException { assertCanEdit(); TextAsset asset = subclassAs(TextAsset.class); asset.addText(type, content); saveDocument(context.getMessageTool().get("curriki.comment.createtextsourceasset")); return asset; } public Boolean isPublished() { return !getSpace().equals("AssetTemp"); } public Asset publish(String space) throws XWikiException { assertCanEdit(); if (!space.startsWith(Constants.COLLECTION_PREFIX)) { throw new AssetException("You cannot publish to the space "+space); } if (!validate()) { throw new AssetException("Validation failed."); } // Let's choose a nice name for the page String prettyName = context.getWiki().clearName(doc.getStringValue(Constants.ASSET_CLASS_TITLE), true, true, context); doc.rename(space + "." + context.getWiki().getUniquePageName(space, prettyName.trim(), context), new ArrayList(), context); applyRightsPolicy(); List<String> params = new ArrayList<String>(); params.add(doc.getStringValue(Constants.ASSET_CLASS_CATEGORY)); save(context.getMessageTool().get("curriki.comment.finishcreatingsubasset", params)); return this; } public boolean validate() throws XWikiException { // Has the asset been subtyped ? if (determineAssetSubtype().equals(Asset.class)) { throw new AssetException("This asset is not complete."); } // Other validation // Super's validate return super.validate(); } }
plugins/asset/src/main/java/org/curriki/xwiki/plugin/asset/Asset.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.curriki.xwiki.plugin.asset; import com.xpn.xwiki.api.Property; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseStringProperty; import java.io.InputStream; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.lang.reflect.Constructor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.curriki.xwiki.plugin.asset.composite.RootCollectionCompositeAsset; import org.curriki.xwiki.plugin.asset.composite.FolderCompositeAsset; import org.curriki.xwiki.plugin.asset.composite.CollectionCompositeAsset; import org.curriki.xwiki.plugin.asset.attachment.AttachmentAsset; import org.curriki.xwiki.plugin.asset.attachment.ImageAsset; import org.curriki.xwiki.plugin.asset.attachment.ArchiveAsset; import org.curriki.xwiki.plugin.asset.attachment.AudioAsset; import org.curriki.xwiki.plugin.asset.attachment.AnimationAsset; import org.curriki.xwiki.plugin.asset.text.TextAsset; import org.curriki.xwiki.plugin.asset.external.ExternalAsset; import org.curriki.xwiki.plugin.asset.external.VIDITalkAsset; import org.curriki.xwiki.plugin.asset.other.InvalidAsset; import org.curriki.xwiki.plugin.asset.other.ProtectedAsset; public class Asset extends CurrikiDocument { private static final Log LOG = LogFactory.getLog(Asset.class); public Asset(XWikiDocument doc, XWikiContext context) { super(doc, context); } public static Asset createTempAsset(String parentAsset, XWikiContext context) throws XWikiException { if (Constants.GUEST_USER.equals(context.getUser())) { throw new AssetException(AssetException.ERROR_ASSET_FORBIDDEN, "XWikiGuest cannot create assets."); } String pageName = context.getWiki().getUniquePageName(Constants.ASSET_TEMPORARY_SPACE, context); XWikiDocument newDoc = context.getWiki().getDocument(Constants.ASSET_TEMPORARY_SPACE, pageName, context); Asset assetDoc = new Asset(newDoc, context); assetDoc.init(parentAsset); assetDoc.saveDocument(context.getMessageTool().get("curriki.comment.createnewsourceasset")); return assetDoc; } protected void init(String parentAsset) throws XWikiException { assertCanEdit(); doc.setCreator(context.getUser()); inheritMetadata(parentAsset); doc.setCustomClass(getClass().getName()); setDefaultContent(); String rights = doc.getObject(Constants.ASSET_CLASS).getStringValue(Constants.ASSET_CLASS_RIGHT); applyRightsPolicy(rights); } protected void setDefaultContent() throws XWikiException { assertCanEdit(); doc.setContent("#includeForm(\"XWiki.AssetTemplate\")"); } protected void initSubType() throws XWikiException { assertCanEdit(); // Empty for Superclass } public void addAttachment(InputStream iStream, String name) throws XWikiException, IOException { assertCanEdit(); XWikiAttachment att = addAttachment(name, iStream); doc.saveAttachmentContent(att, context); } public String getDisplayTitle() { String className = getActiveClass(); use(Constants.ASSET_CLASS); String title = (String) getValue(Constants.ASSET_CLASS_TITLE); if (className != null) { use(className); } return (title == null || title.length() == 0) ? Constants.ASSET_DISPLAYTITLE_UNTITLED : title; } public String getDescription() { String className = getActiveClass(); use(Constants.ASSET_CLASS); String description = (String) getValue(Constants.ASSET_CLASS_DESCRIPTION); if (className != null) { use(className); } return (description == null || description.length() == 0) ? "" : description; } public void changeOwnership(String newUser) { if (hasProgrammingRights()) { XWikiDocument assetDoc = getDoc(); assetDoc.setCreator(newUser); } } /** * Set the rights objects based on the current right setting * * @throws XWikiException */ public void applyRightsPolicy() throws XWikiException { applyRightsPolicy(null); } /** * Set the rights object based on the right in param or the current right setting if null * * @param right * @throws XWikiException */ public void applyRightsPolicy(String right) throws XWikiException { XWikiDocument assetDoc = getDoc(); assetDoc.removeObjects("XWiki.XWikiRights"); BaseObject assetObj = assetDoc.getObject(Constants.ASSET_CLASS); String rights; if (right == null) { // Use existing rights value rights = assetObj.getStringValue(Constants.ASSET_CLASS_RIGHT); } else { rights = right; assetObj.setStringValue(Constants.ASSET_CLASS_RIGHT, right); } // Make sure rights value is valid, default to PUBLIC if not if (rights == null || !(rights.equals(Constants.ASSET_CLASS_RIGHT_PUBLIC) || rights.equals(Constants.ASSET_CLASS_RIGHT_MEMBERS) || rights.equals(Constants.ASSET_CLASS_RIGHT_PRIVATE))) { rights = Constants.ASSET_CLASS_RIGHT_PUBLIC; assetObj.setStringValue(Constants.ASSET_CLASS_RIGHT, rights); } // Rights BaseObject rightObj; // If collection is user String usergroupfield = "users"; String usergroupvalue = ("".equals(assetDoc.getCreator())) ? context.getUser() : assetDoc.getCreator(); // If collection is group if (assetDoc.getSpace().startsWith(Constants.GROUP_COLLECTION_SPACE_PREFIX)) { usergroupfield = "groups"; usergroupvalue = assetDoc.getSpace().substring(5) + ".MemberGroup"; } // Always let the admin group have edit access rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue("groups", "XWiki.XWikiAdminGroup"); rightObj.setStringValue("levels", "edit"); rightObj.setIntValue("allow", 1); // Always let the creator/group edit rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue(usergroupfield, usergroupvalue); rightObj.setStringValue("levels", "edit"); rightObj.setIntValue("allow", 1); if (rights.equals(Constants.ASSET_CLASS_RIGHT_PUBLIC)) { // Viewable by all and any member can edit rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue("groups", "XWiki.XWikiAllGroup"); rightObj.setStringValue("levels", "edit"); rightObj.setIntValue("allow", 1); } else if (rights.equals(Constants.ASSET_CLASS_RIGHT_MEMBERS)) { // Viewable by all, only user/group can edit } else { // rights == private, so only allow creator/group to view and edit rightObj = assetDoc.newObject("XWiki.XWikiRights", context); rightObj.setStringValue(usergroupfield, usergroupvalue); rightObj.setStringValue("levels", "view"); rightObj.setIntValue("allow", 1); } } public Class<? extends Asset> determineAssetSubtype() { if (hasAccessLevel("view")) { if (isFolder()){ if (isRootCollection()){ // Note that the Root Collection doesn't have an Asset Class // so it has to come before checking if no ASSET_CLASS return RootCollectionCompositeAsset.class; } else if (isCollection()){ return CollectionCompositeAsset.class; } else { return FolderCompositeAsset.class; } } // If category is empty then must be an attachment BaseObject obj = doc.getObject(Constants.ASSET_CLASS); if (obj == null) { return InvalidAsset.class; } // Check specific objects to find displayer if (getObject(Constants.TEXT_ASSET_CLASS) != null){ return TextAsset.class; // 3 sub-types HTMLText, WikiText, CBOEText } if (getObject(Constants.EXTERNAL_ASSET_CLASS) != null){ return ExternalAsset.class; // Link } if (getObject(Constants.MIMETYPE_PICTURE_CLASS) != null){ return ImageAsset.class; } if (getObject(Constants.VIDITALK_CLASS) != null){ // category == AUDIO at the moment return VIDITalkAsset.class; } if (getObject(Constants.MIMETYPE_ARCHIVE_CLASS) != null){ return ArchiveAsset.class; } // Check category String category = obj.getStringValue(Constants.EXTERNAL_ASSET_LINK); if (category.equals(Constants.CATEGORY_IMAGE)) { return ImageAsset.class; } else if (category.equals(Constants.CATEGORY_AUDIO)) { return AudioAsset.class; } else if (category.equals(Constants.CATEGORY_ANIMATION)) { return AnimationAsset.class; } else if (category.equals(Constants.CATEGORY_TEXT)) { return TextAsset.class; // ?? But no text class exists } else if (category.equals(Constants.CATEGORY_COLLECTION)) { return FolderCompositeAsset.class; // ?? But no collection class exists } else if (category.equals(Constants.CATEGORY_LINK)) { return ExternalAsset.class; // ?? But no external asset class exists } else if (category.equals(Constants.CATEGORY_ARCHIVE)) { return ArchiveAsset.class; // ?? But no mimetype archive class exists } // Last is just an attachment item if (doc.getAttachmentList().size() > 0) { return AttachmentAsset.class; } // Otherwise is non-specific yet return Asset.class; } else { return ProtectedAsset.class; } } public boolean isFolder() { if (doc.getObjectNumbers(Constants.COMPOSITE_ASSET_CLASS) == 0){ return false; } else { // Work around a bug XWIKI-1624 // TODO: Remove the work-around once XWIKI-1624 is fixed List subAssets = doc.getObjects(Constants.COMPOSITE_ASSET_CLASS); Iterator i = subAssets.iterator(); int count = 0; while (i.hasNext() && count == 0){ if (i.next() != null){ count++; } } if (count == 0){ return false; } } return true; } public boolean isCollection() { if (isFolder()) { com.xpn.xwiki.api.Object obj = getObject(Constants.COMPOSITE_ASSET_CLASS); if (getValue(Constants.COMPOSITE_ASSET_CLASS_TYPE, obj).equals(Constants.COMPOSITE_ASSET_CLASS_TYPE_COLLECTION)) { return true; } } return false; } public boolean isRootCollection() { if (isFolder()) { com.xpn.xwiki.api.Object obj = getObject(Constants.COMPOSITE_ASSET_CLASS); if (getValue(Constants.COMPOSITE_ASSET_CLASS_TYPE, obj).equals(Constants.COMPOSITE_ASSET_CLASS_TYPE_ROOT_COLLECTION)) { return true; } } return false; } public List<Property> getMetadata() { List<Property> md = new ArrayList<Property>(); com.xpn.xwiki.api.Object assetObj = getObject(Constants.ASSET_CLASS); for (Object prop : assetObj.getPropertyNames()) { LOG.debug("Adding "+prop+" to metadata list"); md.add(assetObj.getProperty((String) prop)); } com.xpn.xwiki.api.Object licenseObj = getObject(Constants.ASSET_LICENCE_CLASS); for (Object prop : licenseObj.getPropertyNames()) { LOG.debug("Adding "+prop+" to metadata list"); md.add(licenseObj.getProperty((String) prop)); } // Add assetType to metadata Class assetType = determineAssetSubtype(); String fullAssetType = assetType.getCanonicalName(); BaseStringProperty baseProp = new BaseStringProperty(); baseProp.setName("assetType"); baseProp.setValue(fullAssetType); Property prop = new Property(baseProp, context); md.add(prop); // And add shortAssetType to metadata String shortAssetType = assetType.getSimpleName(); if (!shortAssetType.equals("Asset")) { shortAssetType = shortAssetType.replaceAll("Asset$", ""); } baseProp = new BaseStringProperty(); baseProp.setName("shortAssetType"); baseProp.setValue(shortAssetType); prop = new Property(baseProp, context); md.add(prop); return md; } public <A extends Asset> A as(Class<? extends Asset> wantedClass) throws XWikiException { return (A) as(wantedClass, false); } public <A extends Asset> A subclassAs(Class<? extends Asset> wantedClass) throws XWikiException { return (A) this.as(wantedClass, true); } public <A extends Asset> A as(Class<? extends Asset> wantedClass, boolean moreSpecific) throws XWikiException { // If this is already a subtype of the wanted class then just return this if (wantedClass != null && wantedClass.isAssignableFrom(this.getClass())) { return (A) this; } Class returnClass; // Make sure the determined type is a subclass of the wanted type Class<? extends Asset> assetType = determineAssetSubtype(); if (!moreSpecific) { if (wantedClass == null) { // Return as whatever subtype it is returnClass = assetType; } else if (wantedClass.isAssignableFrom(assetType)) { // Return as the desired type returnClass = wantedClass; } else { throw new AssetException(AssetException.ERROR_ASSET_INCOMPATIBLE, "Document of type "+assetType+" cannot become "+wantedClass); } } else { // Subclass an Asset if (assetType.equals(wantedClass)) { // Already is that type, so don't initialize moreSpecific = false; returnClass = wantedClass; } else if (assetType.equals(Asset.class) && assetType.isAssignableFrom(wantedClass)) { // Turn into a specified subtype of Asset (initializing the subtype) returnClass = wantedClass; } else { throw new AssetException(AssetException.ERROR_ASSET_INCOMPATIBLE, "Document of type "+assetType+" cannot become "+wantedClass); } } Class[] parameterTypes = new Class[2]; parameterTypes[0] = XWikiDocument.class; parameterTypes[1] = XWikiContext.class; Object[] initargs = new Object[2]; initargs[0] = doc; initargs[1] = context; A subtyped; try { Constructor<A> constructor = returnClass.getConstructor(parameterTypes); subtyped = constructor.newInstance(initargs); if (moreSpecific) { subtyped.initSubType(); } } catch (Exception e) { throw new AssetException(AssetException.ERROR_ASSET_INCOMPATIBLE, "Document of type "+assetType+" cannot become "+wantedClass, e); } return subtyped; } protected void inheritMetadata(String parentAsset) throws XWikiException { assertCanEdit(); BaseObject assetObj = doc.newObject(Constants.ASSET_CLASS, context); XWikiDocument parentDoc = null; if (parentAsset != null){ parentDoc = context.getWiki().getDocument(parentAsset, context); if (parentDoc.isNew()) { throw new AssetException(AssetException.MODULE_PLUGIN_ASSET, AssetException.ERROR_ASSET_NOT_FOUND, "Parent asset not found"); } } // the Root collection does not have an asset class so we can't inherit from it if (parentDoc != null && parentDoc.getObject(Constants.ASSET_CLASS) != null) { BaseObject parentAssetObj = (BaseObject) parentDoc.getObject(Constants.ASSET_CLASS).clone(); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_EDUCATIONAL_LEVEL); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_FRAMEWORK_ITEMS); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_RIGHT); copyProperty(parentAssetObj, assetObj, Constants.ASSET_CLASS_KEYWORDS); } // make sure default rights value is not empty String rights = assetObj.getStringValue(Constants.ASSET_CLASS_RIGHT); if ((rights==null)||(rights.equals(""))) { assetObj.setStringValue(Constants.ASSET_CLASS_RIGHT, Constants.ASSET_CLASS_RIGHT_PUBLIC); } BaseObject newLicenceObj = doc.newObject(Constants.ASSET_LICENCE_CLASS, context); // the Root collection does not have an asset Licence class if (parentDoc != null && parentDoc.getObject(Constants.ASSET_LICENCE_CLASS) != null) { BaseObject parentLicenceObjAsset = parentDoc.getObject(Constants.ASSET_LICENCE_CLASS); copyProperty(parentLicenceObjAsset, newLicenceObj, Constants.ASSET_LICENCE_ITEM_LICENCE_TYPE); } else { newLicenceObj.setStringValue(Constants.ASSET_LICENCE_ITEM_LICENCE_TYPE, Constants.ASSET_LICENCE_ITEM_LICENCE_TYPE_DEFAULT); } // Rights holder should be by default the pretty name of the user newLicenceObj.setStringValue(Constants.ASSET_LICENCE_ITEM_RIGHTS_HOLDER, context.getWiki().getLocalUserName(context.getUser(), null, false, context)); } public FolderCompositeAsset makeFolder(String page) throws XWikiException { assertCanEdit(); FolderCompositeAsset asset = subclassAs(FolderCompositeAsset.class); asset.addSubasset(page); saveDocument(context.getMessageTool().get("curriki.comment.createfoldersourceasset")); return asset; } public ExternalAsset makeExternal(String link) throws XWikiException { assertCanEdit(); ExternalAsset asset = subclassAs(ExternalAsset.class); asset.addLink(link); saveDocument(context.getMessageTool().get("curriki.comment.createlinksourceasset")); return asset; } public VIDITalkAsset makeVIDITalk(String videoId) throws XWikiException { assertCanEdit(); VIDITalkAsset asset = subclassAs(VIDITalkAsset.class); asset.addVideoId(videoId); saveDocument(context.getMessageTool().get("curriki.comment.createviditalksourceasset")); return asset; } public TextAsset makeTextAsset(Long type, String content) throws XWikiException { assertCanEdit(); TextAsset asset = subclassAs(TextAsset.class); asset.addText(type, content); saveDocument(context.getMessageTool().get("curriki.comment.createtextsourceasset")); return asset; } public Boolean isPublished() { return !getSpace().equals("AssetTemp"); } public Asset publish(String space) throws XWikiException { assertCanEdit(); if (!space.startsWith(Constants.COLLECTION_PREFIX)) { throw new AssetException("You cannot publish to the space "+space); } if (!validate()) { throw new AssetException("Validation failed."); } // Let's choose a nice name for the page String prettyName = context.getWiki().clearName(doc.getStringValue(Constants.ASSET_CLASS_TITLE), true, true, context); doc.rename(space + "." + context.getWiki().getUniquePageName(space, prettyName.trim(), context), new ArrayList(), context); applyRightsPolicy(); List<String> params = new ArrayList<String>(); params.add(doc.getStringValue(Constants.ASSET_CLASS_CATEGORY)); save(context.getMessageTool().get("curriki.comment.finishcreatingsubasset", params)); return this; } public boolean validate() throws XWikiException { // Has the asset been subtyped ? if (determineAssetSubtype().equals(Asset.class)) { throw new AssetException("This asset is not complete."); } // Other validation // Super's validate return super.validate(); } }
- CURRIKI-1964 - An Asset can now have inherited metadata applied after it is created. svn@9909
plugins/asset/src/main/java/org/curriki/xwiki/plugin/asset/Asset.java
- CURRIKI-1964 - An Asset can now have inherited metadata applied after it is created.
Java
lgpl-2.1
b564117b5597afb99e5474acfdb3ee7b0220deb4
0
cwarden/kettle,cwarden/kettle,cwarden/kettle,juanmjacobs/kettle,juanmjacobs/kettle,juanmjacobs/kettle
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.TimeZone; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.laf.BasePropertyHandler; /** * This class is used to define a number of default values for various settings throughout Kettle. * It also contains a number of static final methods to make your life easier. * * @author Matt * @since 07-05-2003 * */ public class Const { private static Class<?> PKG = Const.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ /** * Version number */ public static final String VERSION = "3.3.0-M1"; /** * Sleep time waiting when buffer is empty */ public static final int TIMEOUT_GET_MILLIS = 50; /** * Sleep time waiting when buffer is full */ public static final int TIMEOUT_PUT_MILLIS = 50; // luxury problem! /** * print update every ... lines */ public static final int ROWS_UPDATE = 50000; /** * Size of rowset: bigger = faster for large amounts of data */ public static final int ROWS_IN_ROWSET = 10000; /** * Fetch size in rows when querying a database */ public static final int FETCH_SIZE = 5000; /** * Sort size: how many rows do we sort in memory at once? */ public static final int SORT_SIZE = 5000; /** * What's the file systems file separator on this operating system? */ public static final String FILE_SEPARATOR = System.getProperty("file.separator"); /** * What's the path separator on this operating system? */ public static final String PATH_SEPARATOR = System.getProperty("path.separator"); /** * CR: operating systems specific Carriage Return */ public static final String CR = System.getProperty("line.separator"); /** * DOSCR: MS-DOS specific Carriage Return */ public static final String DOSCR = "\n\r"; /** * An empty ("") String. */ public static final String EMPTY_STRING = ""; /** * The Java runtime version */ public static final String JAVA_VERSION = System.getProperty("java.vm.version"); /** * Path to the users home directory (keep this entry above references to getKettleDirectory()) */ public static final String USER_HOME_DIRECTORY = NVL(System.getProperty("KETTLE_HOME"), System.getProperty("user.home")); /* * The images directory * public static final String IMAGE_DIRECTORY = "/ui/images/"; */ /** * Public directory containing external steps plugins */ public static final String PLUGIN_STEPS_DIRECTORY_PUBLIC = "plugins" + FILE_SEPARATOR + "steps"; /** * Private directory containing external steps plugins */ public static final String PLUGIN_STEPS_DIRECTORY_PRIVATE = getKettleDirectory() + FILE_SEPARATOR + "plugins" + FILE_SEPARATOR + "steps"; /** * Public directory containing external job entries plugins */ public static final String PLUGIN_JOBENTRIES_DIRECTORY_PUBLIC = "plugins" + FILE_SEPARATOR + "jobentries"; /** * Private directory containing external job entries plugins */ public static final String PLUGIN_JOBENTRIES_DIRECTORY_PRIVATE = getKettleDirectory() + FILE_SEPARATOR + "plugins" + FILE_SEPARATOR + "jobentries"; /** * Default minimum date range... */ public static final Date MIN_DATE = new Date(-2208992400000L); // 1900/01/01 00:00:00.000 /** * Default maximum date range... */ public static final Date MAX_DATE = new Date(7258114799468L); // 2199/12/31 23:59:59.999 /** * The default minimum year in a dimension date range */ public static final int MIN_YEAR = 1900; /** * The default maximum year in a dimension date range */ public static final int MAX_YEAR = 2199; /** * Specifies the number of pixels to the right we have to go in dialog boxes. */ public static final int RIGHT = 400; /** * Specifies the length (width) of fields in a number of pixels in dialog boxes. */ public static final int LENGTH = 350; /** * The margin between the different dialog components & widgets */ public static final int MARGIN = 4; /** * The default percentage of the width of screen where we consider the middle of a dialog. */ public static final int MIDDLE_PCT = 35; /** * The default width of an arrow in the Graphical Views */ public static final int ARROW_WIDTH = 1; /** * The horizontal and vertical margin of a dialog box. */ public static final int FORM_MARGIN = 5; /** * The default shadow size on the graphical view. */ public static final int SHADOW_SIZE = 4; /** * The size of relationship symbols */ public static final int SYMBOLSIZE = 10; /** * Max nr. of files to remember */ public static final int MAX_FILE_HIST = 9; /** * The default locale for the kettle environment (system defined) */ public static final Locale DEFAULT_LOCALE = Locale.getDefault(); // new Locale("nl", "BE"); /** * The default decimal separator . or , */ public static final char DEFAULT_DECIMAL_SEPARATOR = (new DecimalFormatSymbols(DEFAULT_LOCALE)).getDecimalSeparator(); /** * The default grouping separator , or . */ public static final char DEFAULT_GROUPING_SEPARATOR = (new DecimalFormatSymbols(DEFAULT_LOCALE)).getGroupingSeparator(); /** * The default currency symbol */ public static final String DEFAULT_CURRENCY_SYMBOL = (new DecimalFormatSymbols(DEFAULT_LOCALE)).getCurrencySymbol(); /** * The default number format */ public static final String DEFAULT_NUMBER_FORMAT = ((DecimalFormat) (NumberFormat.getInstance())).toPattern(); /** * Default string representing Null String values (empty) */ public static final String NULL_STRING = ""; /** * Default string representing Null Number values (empty) */ public static final String NULL_NUMBER = ""; /** * Default string representing Null Date values (empty) */ public static final String NULL_DATE = ""; /** * Default string representing Null BigNumber values (empty) */ public static final String NULL_BIGNUMBER = ""; /** * Default string representing Null Boolean values (empty) */ public static final String NULL_BOOLEAN = ""; /** * Default string representing Null Integer values (empty) */ public static final String NULL_INTEGER = ""; /** * Default string representing Null Binary values (empty) */ public static final String NULL_BINARY = ""; /** * Default string representing Null Undefined values (empty) */ public static final String NULL_NONE = ""; /** * The base name of the Chef logfile */ public static final String CHEF_LOG_FILE = "chef"; /** * The base name of the Spoon logfile */ public static final String SPOON_LOG_FILE = "spoon"; /** * The base name of the Menu logfile */ public static final String MENU_LOG_FILE = "menu"; /** * A number of tips that are shown when the application first starts. */ private static String tips[]; /** * An array of date conversion formats */ private static String dateFormats[]; /** * An array of number conversion formats */ private static String numberFormats[]; /** * Generalized date/time format: * Wherever dates are used, date and time values are organized from the most to the least significant. * see also method StringUtil.getFormattedDateTime() */ public static final String GENERALIZED_DATE_TIME_FORMAT = "yyyyddMM_hhmmss"; public static final String GENERALIZED_DATE_TIME_FORMAT_MILLIS = "yyyyddMM_hhmmssSSS"; /** * Default we store our information in Unicode UTF-8 character set. */ public static final String XML_ENCODING = "UTF-8"; /** The possible extensions a transformation XML file can have. */ public static final String STRING_TRANS_AND_JOB_FILTER_EXT[] = new String[] { "*.ktr;*.kjb;*.xml", "*.ktr;*.xml", "*.kjb;*.xml", "*.xml", "*.*" }; /** The discriptions of the possible extensions a transformation XML file can have. */ private static String STRING_TRANS_AND_JOB_FILTER_NAMES[]; /** The extension of a Kettle transformation XML file */ public static final String STRING_TRANS_DEFAULT_EXT = "ktr"; /** The possible extensions a transformation XML file can have. */ public static final String STRING_TRANS_FILTER_EXT[] = new String[] { "*.ktr;*.xml", "*.xml", "*.*" }; /** The discriptions of the possible extensions a transformation XML file can have. */ private static String STRING_TRANS_FILTER_NAMES[]; /** The extension of a Kettle job XML file */ public static final String STRING_JOB_DEFAULT_EXT = "kjb"; /** The possible extensions a job XML file can have. */ public static final String STRING_JOB_FILTER_EXT[] = new String[] { "*.kjb;*.xml", "*.xml", "*.*" }; /** The discriptions of the possible extensions a job XML file can have. */ private static String STRING_JOB_FILTER_NAMES[]; /** Name of the kettle parameters file */ public static final String KETTLE_PROPERTIES = "kettle.properties"; /** The prefix that all internal kettle variables should have */ public static final String INTERNAL_VARIABLE_PREFIX = "Internal"; /** The version number as an internal variable */ public static final String INTERNAL_VARIABLE_KETTLE_VERSION = INTERNAL_VARIABLE_PREFIX+".Kettle.Version"; /** The build version as an internal variable */ public static final String INTERNAL_VARIABLE_KETTLE_BUILD_VERSION = INTERNAL_VARIABLE_PREFIX+".Kettle.Build.Version"; /** The build date as an internal variable */ public static final String INTERNAL_VARIABLE_KETTLE_BUILD_DATE = INTERNAL_VARIABLE_PREFIX+".Kettle.Build.Date"; /** The job filename directory */ public static final String INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Job.Filename.Directory"; /** The job filename name */ public static final String INTERNAL_VARIABLE_JOB_FILENAME_NAME = INTERNAL_VARIABLE_PREFIX+".Job.Filename.Name"; /** The job name */ public static final String INTERNAL_VARIABLE_JOB_NAME = INTERNAL_VARIABLE_PREFIX+".Job.Name"; /** The job directory */ public static final String INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Transformation.Repository.Directory"; /** * All the internal job variables */ public static final String[] INTERNAL_TRANS_VARIABLES = new String[] { Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, Const.INTERNAL_VARIABLE_TRANSFORMATION_NAME, Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY, }; /** * All the internal job variables */ public static final String[] INTERNAL_JOB_VARIABLES = new String[] { Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY, Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME, Const.INTERNAL_VARIABLE_JOB_NAME, Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY, }; /** The transformation filename directory */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Transformation.Filename.Directory"; /** The transformation filename name */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME = INTERNAL_VARIABLE_PREFIX+".Transformation.Filename.Name"; /** The transformation name */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_NAME = INTERNAL_VARIABLE_PREFIX+".Transformation.Name"; /** The transformation directory */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Transformation.Repository.Directory"; /** The step partition ID */ public static final String INTERNAL_VARIABLE_STEP_PARTITION_ID = INTERNAL_VARIABLE_PREFIX+".Step.Partition.ID"; /** The step partition number */ public static final String INTERNAL_VARIABLE_STEP_PARTITION_NR = INTERNAL_VARIABLE_PREFIX+".Step.Partition.Number"; /** The slave transformation number */ public static final String INTERNAL_VARIABLE_SLAVE_SERVER_NUMBER = INTERNAL_VARIABLE_PREFIX+".Slave.Transformation.Number"; /** The slave transformation name */ public static final String INTERNAL_VARIABLE_SLAVE_SERVER_NAME = INTERNAL_VARIABLE_PREFIX+".Slave.Server.Name"; /** The size of the cluster : number of slaves */ public static final String INTERNAL_VARIABLE_CLUSTER_SIZE = INTERNAL_VARIABLE_PREFIX+".Cluster.Size"; /** The slave transformation number */ public static final String INTERNAL_VARIABLE_STEP_UNIQUE_NUMBER = INTERNAL_VARIABLE_PREFIX+".Step.Unique.Number"; /** Is this transformation running clustered, on the master? */ public static final String INTERNAL_VARIABLE_CLUSTER_MASTER = INTERNAL_VARIABLE_PREFIX+".Cluster.Master"; /** The size of the cluster : number of slaves */ public static final String INTERNAL_VARIABLE_STEP_UNIQUE_COUNT = INTERNAL_VARIABLE_PREFIX+".Step.Unique.Count"; /** The step name */ public static final String INTERNAL_VARIABLE_STEP_NAME = INTERNAL_VARIABLE_PREFIX+".Step.Name"; /** The step copy nr */ public static final String INTERNAL_VARIABLE_STEP_COPYNR = INTERNAL_VARIABLE_PREFIX+".Step.CopyNr"; /** The default maximum for the nr of lines in the GUI logs */ public static final int MAX_NR_LOG_LINES = 5000; /** The default maximum for the nr of lines in the history views */ public static final int MAX_NR_HISTORY_LINES = 50; /** UI-agnostic flag for warnings */ public static final int WARNING = 1; /** UI-agnostic flag for warnings */ public static final int ERROR = 2; /** UI-agnostic flag for warnings */ public static final int INFO = 3; /** * The margin between the text of a note and its border. */ public static final int NOTE_MARGIN = 5; /** * The default undo level for Kettle */ public static final int MAX_UNDO = 100; /** * You can set this environment variable to make Kettle scan additional packages for annotated plugins. * The packages are comma (,) delimited and the base specification is in the kettle-config.xml file */ public static final String KETTLE_PLUGIN_PACKAGES = "KETTLE_PLUGIN_PACKAGES"; /** * If you set this environment variable you can limit the log size of all transformations and jobs * that don't have the "log size limit" property set in their respective properties. */ public static final String KETTLE_LOG_SIZE_LIMIT = "KETTLE_LOG_SIZE_LIMIT"; private static String[] emptyPaddedSpacesStrings; /** * rounds double f to any number of places after decimal point * Does arithmetic using BigDecimal class to avoid integer overflow while rounding * TODO: make the rounding itself optional in the Props for performance reasons. * * @param f The value to round * @param places The number of decimal places * @return The rounded floating point value */ public static final double round(double f, int places) { java.math.BigDecimal bdtemp = java.math.BigDecimal.valueOf(f); bdtemp = bdtemp.setScale(places, java.math.BigDecimal.ROUND_HALF_EVEN); return bdtemp.doubleValue(); } /* OLD code: caused a lot of problems with very small and very large numbers. * It's a miracle it worked at all. * Go ahead, have a laugh... public static final float round(double f, int places) { float temp = (float) (f * (Math.pow(10, places))); temp = (Math.round(temp)); temp = temp / (int) (Math.pow(10, places)); return temp; } */ /** * Convert a String into an integer. If the conversion fails, assign a default value. * @param str The String to convert to an integer * @param def The default value * @return The converted value or the default. */ public static final int toInt(String str, int def) { int retval; try { retval = Integer.parseInt(str); } catch (Exception e) { retval = def; } return retval; } /** * Convert a String into a long integer. If the conversion fails, assign a default value. * @param str The String to convert to a long integer * @param def The default value * @return The converted value or the default. */ public static final long toLong(String str, long def) { long retval; try { retval = Long.parseLong(str); } catch (Exception e) { retval = def; } return retval; } /** * Convert a String into a double. If the conversion fails, assign a default value. * @param str The String to convert to a double * @param def The default value * @return The converted value or the default. */ public static final double toDouble(String str, double def) { double retval; try { retval = Double.parseDouble(str); } catch (Exception e) { retval = def; } return retval; } /** * Convert a String into a date. * The date format is <code>yyyy/MM/dd HH:mm:ss.SSS</code>. * If the conversion fails, assign a default value. * @param str The String to convert into a Date * @param def The default value * @return The converted value or the default. */ public static final Date toDate(String str, Date def) { SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US); try { return df.parse(str); } catch (ParseException e) { return def; } } /** * Determines whether or not a character is considered a space. * A character is considered a space in Kettle if it is a space, a tab, a newline or a cariage return. * @param c The character to verify if it is a space. * @return true if the character is a space. false otherwise. */ public static final boolean isSpace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } /** * Left trim: remove spaces to the left of a String. * @param str The String to left trim * @return The left trimmed String */ public static String ltrim(String source) { if (source==null) return null; int from = 0; while (from < source.length() && isSpace(source.charAt(from))) from++; return source.substring(from); } /** * Right trim: remove spaces to the right of a string * @param str The string to right trim * @return The trimmed string. */ public static String rtrim(String source) { if (source==null) return null; int max = source.length(); while (max > 0 && isSpace(source.charAt(max - 1))) max--; return source.substring(0, max); } /** * Trims a string: removes the leading and trailing spaces of a String. * @param str The string to trim * @return The trimmed string. */ public static final String trim(String str) { if (str==null) return null; int max = str.length() - 1; int min = 0; while (min <= max && isSpace(str.charAt(min))) min++; while (max >= 0 && isSpace(str.charAt(max))) max--; if (max < min) return ""; return str.substring(min, max + 1); } /** * Right pad a string: adds spaces to a string until a certain length. * If the length is smaller then the limit specified, the String is truncated. * @param ret The string to pad * @param limit The desired length of the padded string. * @return The padded String. */ public static final String rightPad(String ret, int limit) { if (ret == null) return rightPad(new StringBuffer(), limit); else return rightPad(new StringBuffer(ret), limit); } /** * Right pad a StringBuffer: adds spaces to a string until a certain length. * If the length is smaller then the limit specified, the String is truncated. * @param ret The StringBuffer to pad * @param limit The desired length of the padded string. * @return The padded String. */ public static final String rightPad(StringBuffer ret, int limit) { int len = ret.length(); int l; if (len > limit) { ret.setLength(limit); } else { for (l = len; l < limit; l++) ret.append(' '); } return ret.toString(); } /** * Replace values in a String with another. * @param string The original String. * @param repl The text to replace * @param with The new text bit * @return The resulting string with the text pieces replaced. */ public static final String replace(String string, String repl, String with) { StringBuffer str = new StringBuffer(string); for (int i = str.length() - 1; i >= 0; i--) { if (str.substring(i).startsWith(repl)) { str.delete(i, i + repl.length()); str.insert(i, with); } } return str.toString(); } /** * Alternate faster version of string replace using a stringbuffer as input. * * @param str The string where we want to replace in * @param code The code to search for * @param repl The replacement string for code */ public static void repl(StringBuffer str, String code, String repl) { int clength = code.length(); int i = str.length() - clength; while (i >= 0) { String look = str.substring(i, i + clength); if (look.equalsIgnoreCase(code)) // Look for a match! { str.replace(i, i + clength, repl); } i--; } } /** * Count the number of spaces to the left of a text. (leading) * @param field The text to examine * @return The number of leading spaces found. */ public static final int nrSpacesBefore(String field) { int nr = 0; int len = field.length(); while (nr < len && field.charAt(nr) == ' ') { nr++; } return nr; } /** * Count the number of spaces to the right of a text. (trailing) * @param field The text to examine * @return The number of trailing spaces found. */ public static final int nrSpacesAfter(String field) { int nr = 0; int len = field.length(); while (nr < len && field.charAt(field.length() - 1 - nr) == ' ') { nr++; } return nr; } /** * Checks whether or not a String consists only of spaces. * @param str The string to check * @return true if the string has nothing but spaces. */ public static final boolean onlySpaces(String str) { for (int i = 0; i < str.length(); i++) if (!isSpace(str.charAt(i))) return false; return true; } /** * determine the OS name * @return The name of the OS */ public static final String getOS() { return System.getProperty("os.name"); } /** * @return True if the OS is a Windows derivate. */ public static final boolean isWindows() { return getOS().startsWith("Windows"); } /** * @return True if the OS is a Linux derivate. */ public static final boolean isLinux() { return getOS().startsWith("Linux"); } /** * @return True if the OS is an OSX derivate. */ public static final boolean isOSX() { return getOS().toUpperCase().contains("OS X"); } /** * Determine the hostname of the machine Kettle is running on * @return The hostname */ public static final String getHostname() { String lastHostname = "localhost"; try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface nwi = en.nextElement(); Enumeration<InetAddress> ip = nwi.getInetAddresses(); while (ip.hasMoreElements()) { InetAddress in = (InetAddress) ip.nextElement(); lastHostname=in.getHostName(); //System.out.println(" ip address bound : "+in.getHostAddress()); //System.out.println(" hostname : "+in.getHostName()); //System.out.println(" Cann.hostname : "+in.getCanonicalHostName()); //System.out.println(" ip string : "+in.toString()); if (!lastHostname.equalsIgnoreCase("localhost") && !(lastHostname.indexOf(':')>=0) ) { return lastHostname; } } } } catch (SocketException e) { } return lastHostname; } /** * Determins the IP address of the machine Kettle is running on. * @return The IP address */ public static final String getIPAddress() throws Exception { Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); while (enumInterfaces.hasMoreElements()) { NetworkInterface nwi = (NetworkInterface) enumInterfaces.nextElement(); Enumeration<InetAddress> ip = nwi.getInetAddresses(); while (ip.hasMoreElements()) { InetAddress in = (InetAddress) ip.nextElement(); if (!in.isLoopbackAddress() && in.toString().indexOf(":") < 0) { return in.getHostAddress(); } } } return "127.0.0.1"; } /** * Get the primary IP address tied to a network interface (excluding loop-back etc) * @param networkInterfaceName the name of the network interface to interrogate * @return null if the network interface or address wasn't found. * * @throws SocketException in case of a security or network error */ public static final String getIPAddress(String networkInterfaceName) throws SocketException { NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName); Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress inetAddress = (InetAddress) ipAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) { String hostname = inetAddress.getHostAddress(); return hostname; } } return null; } /** * Tries to determine the MAC address of the machine Kettle is running on. * @return The MAC address. */ public static final String getMACAddress() throws Exception { String ip = getIPAddress(); String mac = "none"; String os = getOS(); String s = ""; //System.out.println("os = "+os+", ip="+ip); if (os.equalsIgnoreCase("Windows NT") || os.equalsIgnoreCase("Windows 2000") || os.equalsIgnoreCase("Windows XP") || os.equalsIgnoreCase("Windows 95") || os.equalsIgnoreCase("Windows 98") || os.equalsIgnoreCase("Windows Me") || os.startsWith("Windows")) { try { // System.out.println("EXEC> nbtstat -a "+ip); Process p = Runtime.getRuntime().exec("nbtstat -a " + ip); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { // System.out.println("NBTSTAT> "+s); if (s.indexOf("MAC") >= 0) { int idx = s.indexOf('='); mac = s.substring(idx + 2); } } } stdInput.close(); } catch (Exception e) { } } else if (os.equalsIgnoreCase("Linux")) { try { Process p = Runtime.getRuntime().exec("/sbin/ifconfig -a"); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { int idx = s.indexOf("HWaddr"); if (idx >= 0) { mac = s.substring(idx + 7); } } } stdInput.close(); } catch (Exception e) { } } else if (os.equalsIgnoreCase("Solaris")) { try { Process p = Runtime.getRuntime().exec("/usr/sbin/ifconfig -a"); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { int idx = s.indexOf("ether"); if (idx >= 0) { mac = s.substring(idx + 6); } } } stdInput.close(); } catch (Exception e) { } } else if (os.equalsIgnoreCase("HP-UX")) { try { Process p = Runtime.getRuntime().exec("/usr/sbin/lanscan -a"); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { if (s.indexOf("MAC") >= 0) { int idx = s.indexOf("0x"); mac = s.substring(idx + 2); } } } stdInput.close(); } catch (Exception e) { } } return Const.trim(mac); } private static final boolean procDone(Process p) { try { p.exitValue(); return true; } catch (IllegalThreadStateException e) { return false; } } /** * Determines the Kettle directory in the user's home directory. * @return The Kettle directory. */ public static final String getKettleDirectory() { return USER_HOME_DIRECTORY + FILE_SEPARATOR + BasePropertyHandler.getProperty("userBaseDir", ".kettle"); } /** * Determines the location of the shared objects file * @return the name of the shared objects file */ public static final String getSharedObjectsFile() { return getKettleDirectory() + FILE_SEPARATOR + "shared.xml"; } /** * Returns the path to the Kettle local (current directory) repositories XML file. * @return The local repositories file. */ public static final String getKettleLocalRepositoriesFile() { return "repositories.xml"; } /** * Returns the full path to the Kettle repositories XML file. * @return The Kettle repositories file. */ public static final String getKettleUserRepositoriesFile() { return getKettleDirectory() + FILE_SEPARATOR + getKettleLocalRepositoriesFile(); } /** * Returns the path to the Kettle local (current directory) Carte password file:<p> * ./pwd/kettle.pwd<br> * * @return The local Carte password file. */ public static final String getKettleLocalCartePasswordFile() { return "pwd/kettle.pwd"; } /** * Returns the path to the Kettle Carte password file in the home directory:<p> * $KETTLE_HOME/.kettle/kettle.pwd<br> * * @return The Carte password file in the home directory. */ public static final String getKettleCartePasswordFile() { return getKettleDirectory() + FILE_SEPARATOR + "kettle.pwd"; } /** * Retrieves the content of an environment variable * * @param variable The name of the environment variable * @param deflt The default value in case no value was found * @return The value of the environment variable or the value of deflt in case no variable was defined. */ public static String getEnvironmentVariable(String variable, String deflt) { return System.getProperty(variable, deflt); } /** * Replaces environment variables in a string. * For example if you set KETTLE_HOME as an environment variable, you can * use %%KETTLE_HOME%% in dialogs etc. to refer to this value. * This procedures looks for %%...%% pairs and replaces them including the * name of the environment variable with the actual value. * In case the variable was not set, nothing is replaced! * * @param string The source string where text is going to be replaced. * * @return The expanded string. * @deprecated use StringUtil.environmentSubstitute(): handles both Windows and unix conventions */ public static final String replEnv(String string) { if (string == null) return null; StringBuffer str = new StringBuffer(string); int idx = str.indexOf("%%"); while (idx >= 0) { //OK, so we found a marker, look for the next one... int to = str.indexOf("%%", idx + 2); if (to >= 0) { // OK, we found the other marker also... String marker = str.substring(idx, to + 2); String var = str.substring(idx + 2, to); if (var != null && var.length() > 0) { // Get the environment variable String newval = getEnvironmentVariable(var, null); if (newval != null) { // Replace the whole bunch str.replace(idx, to + 2, newval); //System.out.println("Replaced ["+marker+"] with ["+newval+"]"); // The last position has changed... to += newval.length() - marker.length(); } } } else // We found the start, but NOT the ending %% without closing %% { to = idx; } // Look for the next variable to replace... idx = str.indexOf("%%", to + 1); } return str.toString(); } /** * Replaces environment variables in an array of strings.<p> * See also: replEnv(String string) * @param string The array of strings that wants its variables to be replaced. * @return the array with the environment variables replaced. * @deprecated please use StringUtil.environmentSubstitute now. */ public static final String[] replEnv(String string[]) { String retval[] = new String[string.length]; for (int i = 0; i < string.length; i++) { retval[i] = Const.replEnv(string[i]); } return retval; } /** * Implements Oracle style NVL function * @param source The source argument * @param def The default value in case source is null or the length of the string is 0 * @return source if source is not null, otherwise return def */ public static final String NVL(String source, String def) { if (source == null || source.length() == 0) return def; return source; } /** * Search for a string in an array of strings and return the index. * @param lookup The string to search for * @param array The array of strings to look in * @return The index of a search string in an array of strings. -1 if not found. */ public static final int indexOfString(String lookup, String array[]) { if (array == null) return -1; if (lookup == null) return -1; for (int i = 0; i < array.length; i++) { if (lookup.equalsIgnoreCase(array[i])) return i; } return -1; } /** * Search for strings in an array of strings and return the indexes. * @param lookup The strings to search for * @param array The array of strings to look in * @return The indexes of strings in an array of strings. -1 if not found. */ public static final int[] indexsOfStrings(String lookup[], String array[]) { int[] indexes = new int[lookup.length]; for (int i=0;i<indexes.length;i++) indexes[i] = indexOfString(lookup[i], array); return indexes; } /** * Search for strings in an array of strings and return the indexes. * If a string is not found, the index is not returned. * * @param lookup The strings to search for * @param array The array of strings to look in * @return The indexes of strings in an array of strings. Only existing indexes are returned (no -1) */ public static final int[] indexsOfFoundStrings(String lookup[], String array[]) { List<Integer> indexesList = new ArrayList<Integer>(); for (int i=0;i<lookup.length;i++) { int idx = indexOfString(lookup[i], array); if (idx>=0) indexesList.add(Integer.valueOf(idx)); } int[] indexes = new int[indexesList.size()]; for (int i=0;i<indexesList.size();i++) indexes[i] = (indexesList.get(i)).intValue(); return indexes; } /** * Search for a string in a list of strings and return the index. * @param lookup The string to search for * @param list The ArrayList of strings to look in * @return The index of a search string in an array of strings. -1 if not found. */ public static final int indexOfString(String lookup, List<String> list) { if (list == null) return -1; for (int i = 0; i < list.size(); i++) { String compare = list.get(i); if (lookup.equalsIgnoreCase(compare)) return i; } return -1; } /** * Sort the strings of an array in alphabetical order. * @param input The array of strings to sort. * @return The sorted array of strings. */ public static final String[] sortStrings(String input[]) { Arrays.sort(input); return input; } /** * Convert strings separated by a string into an array of strings.<p> * <code> Example: a;b;c;d ==> new String[] { a, b, c, d } * </code> * * <p><b>NOTE: this differs from String.split() in a way that the built-in method uses regular expressions and this one does not.</b> * * @param string The string to split * @param separator The separator used. * @return the string split into an array of strings */ public static final String[] splitString(String string, String separator) { /* * 0123456 * Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<String>(); if (string == null || string.length() == 0) { return new String[] {}; } int sepLen = separator.length(); int from = 0; int end = string.length() - sepLen + 1; for (int i = from; i < end; i += sepLen) { if (string.substring(i, i + sepLen).equalsIgnoreCase(separator)) { // OK, we found a separator, the string to add to the list // is [from, i[ list.add(NVL(string.substring(from, i), "")); from = i + sepLen; } } // Wait, if the string didn't end with a separator, we still have information at the end of the string... // In our example that would be "d"... if (from + sepLen <= string.length()) { list.add(NVL(string.substring(from, string.length()), "")); } return list.toArray(new String[list.size()]); } /** * Convert strings separated by a character into an array of strings.<p> * <code> Example: a;b;c;d == new String[] { a, b, c, d } * </code> * * @param string The string to split * @param separator The separator used. * @return the string split into an array of strings */ public static final String[] splitString(String string, char separator) { /* * 0123456 * Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<String>(); if (string == null || string.length() == 0) { return new String[] {}; } int from = 0; int end = string.length(); for (int i = from; i < end; i += 1) { if (string.charAt(i) == separator) { // OK, we found a separator, the string to add to the list // is [from, i[ list.add(NVL(string.substring(from, i), "")); from = i + 1; } } // Wait, if the string didn't end with a separator, we still have information at the end of the string... // In our example that would be "d"... if (from + 1 <= string.length()) { list.add(NVL(string.substring(from, string.length()), "")); } return list.toArray(new String[list.size()]); } /** * Convert strings separated by a string into an array of strings.<p> * <code> * Example /a/b/c --> new String[] { a, b, c } * </code> * * @param path The string to split * @param separator The separator used. * @return the string split into an array of strings */ public static final String[] splitPath(String path, String separator) { /* * 012345 * Example /a/b/c --> new String[] { a, b, c } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); if (path == null || path.length() == 0 || path.equals(separator)) { return new String[] {}; } int sepLen = separator.length(); int nr_separators = 1; int from = path.startsWith(separator) ? sepLen : 0; for (int i = from; i < path.length(); i += sepLen) { if (path.substring(i, i + sepLen).equalsIgnoreCase(separator)) { nr_separators++; } } String spath[] = new String[nr_separators]; int nr = 0; for (int i = from; i < path.length(); i += sepLen) { if (path.substring(i, i + sepLen).equalsIgnoreCase(separator)) { spath[nr] = path.substring(from, i); // System.out.println(nr+" --> ["+spath[nr]+"], (from,to)=("+from+", "+i+")"); nr++; from = i + sepLen; } } if (nr < spath.length) { spath[nr] = path.substring(from); // System.out.println(nr+" --> ["+spath[nr]+"], (from,to)=("+from+", "+path.length()+")"); } // // a --> { a } // if (spath.length == 0 && path.length() > 0) { spath = new String[] { path }; } return spath; } /** * @return An array of all default conversion formats, to be used in dialogs etc. */ public static String[] getConversionFormats() { String dats[] = Const.getDateFormats(); String nums[] = Const.getNumberFormats(); int totsize = dats.length + nums.length; String formats[] = new String[totsize]; for (int x = 0; x < dats.length; x++) formats[x] = dats[x]; for (int x = 0; x < nums.length; x++) formats[dats.length + x] = nums[x]; return formats; } /** * Sorts the array of Strings, determines the uniquely occurring strings. * @param strings the array that you want to do a distinct on * @return a sorted array of uniquely occurring strings */ public static final String[] getDistinctStrings(String[] strings) { if (strings == null) return null; if (strings.length == 0) return new String[] {}; String[] sorted = sortStrings(strings); List<String> result = new ArrayList<String>(); String previous = ""; for (int i = 0; i < sorted.length; i++) { if (!sorted[i].equalsIgnoreCase(previous)) { result.add(sorted[i]); } previous = sorted[i]; } return result.toArray(new String[result.size()]); } /** * Returns a string of the stack trace of the specified exception */ public static final String getStackTracker(Throwable e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); String string = stringWriter.getBuffer().toString(); try { stringWriter.close(); } catch(IOException ioe) {} // is this really required? return string; } /** * Check if the string supplied is empty. A String is empty when it is null or when the length is 0 * @param string The string to check * @return true if the string supplied is empty */ public static final boolean isEmpty(String string) { return string==null || string.length()==0; } /** * Check if the stringBuffer supplied is empty. A StringBuffer is empty when it is null or when the length is 0 * @param string The stringBuffer to check * @return true if the stringBuffer supplied is empty */ public static final boolean isEmpty(StringBuffer string) { return string==null || string.length()==0; } /** * Check if the string array supplied is empty. A String array is empty when it is null or when the number of elements is 0 * @param string The string array to check * @return true if the string array supplied is empty */ public static final boolean isEmpty(String[] strings) { return strings==null || strings.length==0; } /** * Check if the array supplied is empty. An array is empty when it is null or when the length is 0 * @param array The array to check * @return true if the array supplied is empty */ public static final boolean isEmpty(Object[] array) { return array==null || array.length==0; } /** * @return a new ClassLoader */ public static final ClassLoader createNewClassLoader() throws KettleException { try { // Nothing really in URL, everything is in scope. URL urls[] = new URL[] { }; URLClassLoader ucl = new URLClassLoader(urls); return ucl; } catch (Exception e) { throw new KettleException("Unexpected error during classloader creation", e); } } /** * Utility class for use in JavaScript to create a new byte array. * This is surprisingly difficult to do in JavaScript. * * @return a new java byte array */ public static final byte[] createByteArray(int size) { return new byte[size]; } /** * Sets the first character of each word in upper-case. * @param string The strings to convert to initcap * @return the input string but with the first character of each word converted to upper-case. */ public static final String initCap(String string) { StringBuffer change=new StringBuffer(string); boolean new_word; int i; char lower, upper, ch; new_word=true; for (i=0 ; i<string.length() ; i++) { lower=change.substring(i,i+1).toLowerCase().charAt(0); // Lowercase is default. upper=change.substring(i,i+1).toUpperCase().charAt(0); // Uppercase for new words. ch=upper; if (new_word) { change.setCharAt(i, upper); } else { change.setCharAt(i, lower); } new_word = false; // Cast to (int) is required for extended characters (SB) if ( !Character.isLetterOrDigit((int)ch) && ch!='_' ) new_word = true; } return change.toString(); } /** * Create a valid filename using a name * We remove all special characters, spaces, etc. * @param name The name to use as a base for the filename * @return a valid filename */ public static final String createFilename(String name) { StringBuffer filename = new StringBuffer(); for (int i=0;i<name.length();i++) { char c = name.charAt(i); if ( Character.isUnicodeIdentifierPart(c) ) { filename.append(c); } else if (Character.isWhitespace(c)) { filename.append('_'); } } return filename.toString().toLowerCase(); } public static final String createFilename(String directory, String name, String extension) { if (directory.endsWith(Const.FILE_SEPARATOR)) { return directory+createFilename(name)+extension; } else { return directory+Const.FILE_SEPARATOR+createFilename(name)+extension; } } public static final String createName(String filename) { if (Const.isEmpty(filename)) return filename; String pureFilename = filenameOnly(filename); if (pureFilename.endsWith(".ktr") || pureFilename.endsWith(".kjb") || pureFilename.endsWith(".xml")) { pureFilename = pureFilename.substring(0, pureFilename.length()-4); } StringBuffer sb = new StringBuffer(); for (int i=0; i < pureFilename.length(); i++) { char c = pureFilename.charAt(i); if ( Character.isUnicodeIdentifierPart(c) ) { sb.append(c); } else if (Character.isWhitespace(c)) { sb.append(' '); } else if (c=='-') { sb.append(c); } } return sb.toString(); } /** * <p> * Returns the pure filename of a filename with full path. E.g. if passed parameter is * <code>/opt/tomcat/logs/catalina.out</code> this method returns <code>catalina.out</code>. * The method works with the Environment variable <i>System.getProperty("file.separator")</i>, * so on linux/Unix it will check for the last occurrence of a frontslash, on windows for * the last occurrence of a backslash. * </p> * * <p> * To make this OS independent, the method could check for the last occurrence of a * frontslash and backslash and use the higher value of both. Should work, since these * characters aren't allowed in filenames on neither OS types (or said differently: * Neither linux nor windows can carry frontslashes OR backslashes in filenames). * Just a suggestion of an improvement ... * </p> * * @param sFullPath * @return */ public static String filenameOnly(String sFullPath) { if (Const.isEmpty(sFullPath)) return sFullPath; int idx = sFullPath.lastIndexOf(FILE_SEPARATOR); if (idx != -1) { return sFullPath.substring(idx + 1); } else { idx = sFullPath.lastIndexOf('/'); // URL, VFS if (idx != -1) { return sFullPath.substring(idx + 1); } else { return sFullPath; } } } /** * Returning the internationalized tips of the days. They get created once on first * request. * * @return */ public static String[] getTips() { if (tips == null) { int tipsOfDayCount = toInt(BaseMessages.getString(PKG, "Const.TipOfDay.Count"), 0); tips = new String[tipsOfDayCount]; for (int i = 1; i <= tipsOfDayCount; i++) tips[i - 1] = BaseMessages.getString(PKG, "Const.TipOfDay" + Integer.toString(i)); } return tips; } /** * Returning the localized date conversion formats. They get created once on first request. * * @return */ public static String[] getDateFormats() { if (dateFormats == null) { int dateFormatsCount = toInt(BaseMessages.getString(PKG, "Const.DateFormat.Count"), 0); dateFormats = new String[dateFormatsCount]; for (int i = 1; i <= dateFormatsCount; i++) dateFormats[i - 1] = BaseMessages.getString(PKG, "Const.DateFormat" + Integer.toString(i)); } return dateFormats; } /** * Returning the localized number conversion formats. They get created once on first request. * * @return */ public static String[] getNumberFormats() { if (numberFormats == null) { int numberFormatsCount = toInt(BaseMessages.getString(PKG, "Const.NumberFormat.Count"), 0); numberFormats = new String[numberFormatsCount + 1]; numberFormats[0] = DEFAULT_NUMBER_FORMAT; for (int i = 1; i <= numberFormatsCount; i++) numberFormats[i] = BaseMessages.getString(PKG, "Const.NumberFormat" + Integer.toString(i)); } return numberFormats; } public static String[] getTransformationAndJobFilterNames() { if (STRING_TRANS_AND_JOB_FILTER_NAMES == null) { STRING_TRANS_AND_JOB_FILTER_NAMES = new String[] { BaseMessages.getString(PKG, "Const.FileFilter.TransformationJob"), BaseMessages.getString(PKG, "Const.FileFilter.Transformations"), BaseMessages.getString(PKG, "Const.FileFilter.Jobs"), BaseMessages.getString(PKG, "Const.FileFilter.XML"), BaseMessages.getString(PKG, "Const.FileFilter.All") }; } return STRING_TRANS_AND_JOB_FILTER_NAMES; } public static String[] getTransformationFilterNames() { if (STRING_TRANS_FILTER_NAMES == null) { STRING_TRANS_FILTER_NAMES = new String[] { BaseMessages.getString(PKG, "Const.FileFilter.Transformations"), BaseMessages.getString(PKG, "Const.FileFilter.XML"), BaseMessages.getString(PKG, "Const.FileFilter.All") }; } return STRING_TRANS_FILTER_NAMES; } public static String[] getJobFilterNames() { if (STRING_JOB_FILTER_NAMES == null) { STRING_JOB_FILTER_NAMES = new String[] { BaseMessages.getString(PKG, "Const.FileFilter.Jobs"), BaseMessages.getString(PKG, "Const.FileFilter.XML"), BaseMessages.getString(PKG, "Const.FileFilter.All") }; } return STRING_JOB_FILTER_NAMES; } /** * Return the current time as nano-seconds. * * @return time as nano-seconds. */ public static long nanoTime() { return new Date().getTime()*1000; } /** * Return the input string trimmed as specified. * * @param string String to be trimmed * @param trimType Type of trimming * * @return Trimmed string. */ public static String trimToType(String string,int trimType) { switch(trimType) { case ValueMetaInterface.TRIM_TYPE_BOTH: return trim(string); case ValueMetaInterface.TRIM_TYPE_LEFT: return ltrim(string); case ValueMetaInterface.TRIM_TYPE_RIGHT: return rtrim(string); case ValueMetaInterface.TRIM_TYPE_NONE: default: return string; } } /** * implemented to help prevent errors in matching up pluggable LAF directories and paths/files * eliminating malformed URLs - duplicate file separators or missing file separators. * * @param dir * @param file * @return concatenated string representing a file url */ public static String safeAppendDirectory(String dir, String file) { boolean dirHasSeparator = ((dir.lastIndexOf(FILE_SEPARATOR)) == dir.length()); boolean fileHasSeparator = (file.indexOf(FILE_SEPARATOR) != 0); if ((dirHasSeparator && !fileHasSeparator) || (!dirHasSeparator && fileHasSeparator)) return dir + file; if (dirHasSeparator && fileHasSeparator) return dir + file.substring(1); return dir + FILE_SEPARATOR + file; } /** * Create an array of Strings consisting of spaces. The index of a String in * the array determines the number of spaces in that string. * * @return array of 'space' Strings. */ public static String[] getEmptyPaddedStrings() { if (emptyPaddedSpacesStrings==null) { emptyPaddedSpacesStrings = new String[250]; for (int i=0;i<emptyPaddedSpacesStrings.length;i++) { emptyPaddedSpacesStrings[i] = rightPad("", i); } } return emptyPaddedSpacesStrings; } /** * Return the percentage of free memory for this JVM. * * @return Percentage of free memory. */ public static final int getPercentageFreeMemory() { Runtime runtime = Runtime.getRuntime(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); long totalFreeMemory = (freeMemory + (maxMemory - allocatedMemory)); int percentage = (int)Math.round(100*(double)totalFreeMemory / (double)maxMemory); return percentage; } /** * Return non digits only. * * @return non digits in a string. */ public static String removeDigits(String input) { if(Const.isEmpty(input)) return null; StringBuffer digitsOnly = new StringBuffer (); char c; for (int i = 0; i < input.length (); i++) { c = input.charAt (i); if (!Character.isDigit (c)) { digitsOnly.append (c); } } return digitsOnly.toString (); } /** * Return digits only. * * @return digits in a string. */ public static String getDigitsOnly(String input) { if(Const.isEmpty(input)) return null; StringBuffer digitsOnly = new StringBuffer (); char c; for (int i = 0; i < input.length (); i++) { c = input.charAt (i); if (Character.isDigit (c)) { digitsOnly.append (c); } } return digitsOnly.toString (); } /** * Remove time from a date. * * @return a date without hour. */ public static Date removeTimeFromDate(Date input) { if(input==null) return null; // Get an instance of the Calendar. Calendar calendar = Calendar.getInstance(); // Make sure the calendar will not perform automatic correction. calendar.setLenient(false); // Set the time of the calendar to the given date. calendar.setTime(input); // Remove the hours, minutes, seconds and milliseconds. calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); // Return the date again. return calendar.getTime(); } /** * Mask XML content. * i.e. replace characters with &values; * @param content content * @return masked content */ public static String maskXML (String content) { if (isEmpty(content)) return content; StringBuffer out = new StringBuffer(); char[] chars = content.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; switch (c) { case '<': out.append("&lt;"); break; case '>': out.append("&gt;"); break; case '&': out.append("&amp;"); break; case '"': out.append("&quot;"); break; case '\'': out.append("&apos;"); break; default: out.append(c); break; } } return out.toString(); } /** * Remove CR / LF from String * @param in input * @return cleaned string */ public static String removeCRLF (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\n' || c == '\r') ; else out.append(c); } return out.toString(); } /** * Remove CR / LF from String * @param in input * @return cleaned string */ public static String removeCR (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\n') ; else out.append(c); } return out.toString(); } // removeCR /** * Remove CR / LF from String * @param in input * @return cleaned string */ public static String removeLF (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\r') ; else out.append(c); } return out.toString(); } // removeCRLF /** * Remove Horizontan Tab from String * @param in input * @return cleaned string */ public static String removeTAB (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\t') ; else out.append(c); } return out.toString(); } /** * Add time to an input date * @param input the date * @param time the time to add (in string) * @param DateFormat the time format * @return date = input + time */ public static Date addTimeToDate(Date input, String time,String DateFormat) throws Exception { if(isEmpty(time)) return input; if(input==null) return null; String dateformatString=NVL(DateFormat,"HH:mm:ss"); int t = decodeTime(time,dateformatString); Date d = new Date(input.getTime()+t); return d; } // Decodes a time value in specified date format and returns it as milliseconds since midnight. public static int decodeTime (String s,String DateFormat) throws Exception { SimpleDateFormat f = new SimpleDateFormat(DateFormat); TimeZone utcTimeZone = TimeZone.getTimeZone("UTC"); f.setTimeZone (utcTimeZone); f.setLenient (false); ParsePosition p = new ParsePosition(0); Date d = f.parse(s,p); if (d == null) throw new Exception("Invalid time value " + DateFormat +": \"" + s + "\"."); return (int)d.getTime(); } /** * Get the number of occurances of searchFor in string. * @param string String to be searched * @param searchFor to be counted string * @return number of occurances */ public static int getOccurenceString (String string, String searchFor) { if (string == null || string.length() == 0) return 0; int counter=0; int len = searchFor.length(); int result = 0; if (len > 0) { int start = string.indexOf(searchFor); while (start != -1) { result++; start = string.indexOf(searchFor, start+len); } } return counter; } }
src-core/org/pentaho/di/core/Const.java
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.TimeZone; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.laf.BasePropertyHandler; import org.pentaho.di.trans.steps.csvinput.CsvInputMeta; /** * This class is used to define a number of default values for various settings throughout Kettle. * It also contains a number of static final methods to make your life easier. * * @author Matt * @since 07-05-2003 * */ public class Const { private static Class<?> PKG = Const.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ /** * Version number */ public static final String VERSION = "3.3.0-M1"; /** * Sleep time waiting when buffer is empty */ public static final int TIMEOUT_GET_MILLIS = 50; /** * Sleep time waiting when buffer is full */ public static final int TIMEOUT_PUT_MILLIS = 50; // luxury problem! /** * print update every ... lines */ public static final int ROWS_UPDATE = 50000; /** * Size of rowset: bigger = faster for large amounts of data */ public static final int ROWS_IN_ROWSET = 10000; /** * Fetch size in rows when querying a database */ public static final int FETCH_SIZE = 5000; /** * Sort size: how many rows do we sort in memory at once? */ public static final int SORT_SIZE = 5000; /** * What's the file systems file separator on this operating system? */ public static final String FILE_SEPARATOR = System.getProperty("file.separator"); /** * What's the path separator on this operating system? */ public static final String PATH_SEPARATOR = System.getProperty("path.separator"); /** * CR: operating systems specific Carriage Return */ public static final String CR = System.getProperty("line.separator"); /** * DOSCR: MS-DOS specific Carriage Return */ public static final String DOSCR = "\n\r"; /** * An empty ("") String. */ public static final String EMPTY_STRING = ""; /** * The Java runtime version */ public static final String JAVA_VERSION = System.getProperty("java.vm.version"); /** * Path to the users home directory (keep this entry above references to getKettleDirectory()) */ public static final String USER_HOME_DIRECTORY = NVL(System.getProperty("KETTLE_HOME"), System.getProperty("user.home")); /* * The images directory * public static final String IMAGE_DIRECTORY = "/ui/images/"; */ /** * Public directory containing external steps plugins */ public static final String PLUGIN_STEPS_DIRECTORY_PUBLIC = "plugins" + FILE_SEPARATOR + "steps"; /** * Private directory containing external steps plugins */ public static final String PLUGIN_STEPS_DIRECTORY_PRIVATE = getKettleDirectory() + FILE_SEPARATOR + "plugins" + FILE_SEPARATOR + "steps"; /** * Public directory containing external job entries plugins */ public static final String PLUGIN_JOBENTRIES_DIRECTORY_PUBLIC = "plugins" + FILE_SEPARATOR + "jobentries"; /** * Private directory containing external job entries plugins */ public static final String PLUGIN_JOBENTRIES_DIRECTORY_PRIVATE = getKettleDirectory() + FILE_SEPARATOR + "plugins" + FILE_SEPARATOR + "jobentries"; /** * Default minimum date range... */ public static final Date MIN_DATE = new Date(-2208992400000L); // 1900/01/01 00:00:00.000 /** * Default maximum date range... */ public static final Date MAX_DATE = new Date(7258114799468L); // 2199/12/31 23:59:59.999 /** * The default minimum year in a dimension date range */ public static final int MIN_YEAR = 1900; /** * The default maximum year in a dimension date range */ public static final int MAX_YEAR = 2199; /** * Specifies the number of pixels to the right we have to go in dialog boxes. */ public static final int RIGHT = 400; /** * Specifies the length (width) of fields in a number of pixels in dialog boxes. */ public static final int LENGTH = 350; /** * The margin between the different dialog components & widgets */ public static final int MARGIN = 4; /** * The default percentage of the width of screen where we consider the middle of a dialog. */ public static final int MIDDLE_PCT = 35; /** * The default width of an arrow in the Graphical Views */ public static final int ARROW_WIDTH = 1; /** * The horizontal and vertical margin of a dialog box. */ public static final int FORM_MARGIN = 5; /** * The default shadow size on the graphical view. */ public static final int SHADOW_SIZE = 4; /** * The size of relationship symbols */ public static final int SYMBOLSIZE = 10; /** * Max nr. of files to remember */ public static final int MAX_FILE_HIST = 9; /** * The default locale for the kettle environment (system defined) */ public static final Locale DEFAULT_LOCALE = Locale.getDefault(); // new Locale("nl", "BE"); /** * The default decimal separator . or , */ public static final char DEFAULT_DECIMAL_SEPARATOR = (new DecimalFormatSymbols(DEFAULT_LOCALE)).getDecimalSeparator(); /** * The default grouping separator , or . */ public static final char DEFAULT_GROUPING_SEPARATOR = (new DecimalFormatSymbols(DEFAULT_LOCALE)).getGroupingSeparator(); /** * The default currency symbol */ public static final String DEFAULT_CURRENCY_SYMBOL = (new DecimalFormatSymbols(DEFAULT_LOCALE)).getCurrencySymbol(); /** * The default number format */ public static final String DEFAULT_NUMBER_FORMAT = ((DecimalFormat) (NumberFormat.getInstance())).toPattern(); /** * Default string representing Null String values (empty) */ public static final String NULL_STRING = ""; /** * Default string representing Null Number values (empty) */ public static final String NULL_NUMBER = ""; /** * Default string representing Null Date values (empty) */ public static final String NULL_DATE = ""; /** * Default string representing Null BigNumber values (empty) */ public static final String NULL_BIGNUMBER = ""; /** * Default string representing Null Boolean values (empty) */ public static final String NULL_BOOLEAN = ""; /** * Default string representing Null Integer values (empty) */ public static final String NULL_INTEGER = ""; /** * Default string representing Null Binary values (empty) */ public static final String NULL_BINARY = ""; /** * Default string representing Null Undefined values (empty) */ public static final String NULL_NONE = ""; /** * The base name of the Chef logfile */ public static final String CHEF_LOG_FILE = "chef"; /** * The base name of the Spoon logfile */ public static final String SPOON_LOG_FILE = "spoon"; /** * The base name of the Menu logfile */ public static final String MENU_LOG_FILE = "menu"; /** * A number of tips that are shown when the application first starts. */ private static String tips[]; /** * An array of date conversion formats */ private static String dateFormats[]; /** * An array of number conversion formats */ private static String numberFormats[]; /** * Generalized date/time format: * Wherever dates are used, date and time values are organized from the most to the least significant. * see also method StringUtil.getFormattedDateTime() */ public static final String GENERALIZED_DATE_TIME_FORMAT = "yyyyddMM_hhmmss"; public static final String GENERALIZED_DATE_TIME_FORMAT_MILLIS = "yyyyddMM_hhmmssSSS"; /** * Default we store our information in Unicode UTF-8 character set. */ public static final String XML_ENCODING = "UTF-8"; /** The possible extensions a transformation XML file can have. */ public static final String STRING_TRANS_AND_JOB_FILTER_EXT[] = new String[] { "*.ktr;*.kjb;*.xml", "*.ktr;*.xml", "*.kjb;*.xml", "*.xml", "*.*" }; /** The discriptions of the possible extensions a transformation XML file can have. */ private static String STRING_TRANS_AND_JOB_FILTER_NAMES[]; /** The extension of a Kettle transformation XML file */ public static final String STRING_TRANS_DEFAULT_EXT = "ktr"; /** The possible extensions a transformation XML file can have. */ public static final String STRING_TRANS_FILTER_EXT[] = new String[] { "*.ktr;*.xml", "*.xml", "*.*" }; /** The discriptions of the possible extensions a transformation XML file can have. */ private static String STRING_TRANS_FILTER_NAMES[]; /** The extension of a Kettle job XML file */ public static final String STRING_JOB_DEFAULT_EXT = "kjb"; /** The possible extensions a job XML file can have. */ public static final String STRING_JOB_FILTER_EXT[] = new String[] { "*.kjb;*.xml", "*.xml", "*.*" }; /** The discriptions of the possible extensions a job XML file can have. */ private static String STRING_JOB_FILTER_NAMES[]; /** Name of the kettle parameters file */ public static final String KETTLE_PROPERTIES = "kettle.properties"; /** The prefix that all internal kettle variables should have */ public static final String INTERNAL_VARIABLE_PREFIX = "Internal"; /** The version number as an internal variable */ public static final String INTERNAL_VARIABLE_KETTLE_VERSION = INTERNAL_VARIABLE_PREFIX+".Kettle.Version"; /** The build version as an internal variable */ public static final String INTERNAL_VARIABLE_KETTLE_BUILD_VERSION = INTERNAL_VARIABLE_PREFIX+".Kettle.Build.Version"; /** The build date as an internal variable */ public static final String INTERNAL_VARIABLE_KETTLE_BUILD_DATE = INTERNAL_VARIABLE_PREFIX+".Kettle.Build.Date"; /** The job filename directory */ public static final String INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Job.Filename.Directory"; /** The job filename name */ public static final String INTERNAL_VARIABLE_JOB_FILENAME_NAME = INTERNAL_VARIABLE_PREFIX+".Job.Filename.Name"; /** The job name */ public static final String INTERNAL_VARIABLE_JOB_NAME = INTERNAL_VARIABLE_PREFIX+".Job.Name"; /** The job directory */ public static final String INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Transformation.Repository.Directory"; /** * All the internal job variables */ public static final String[] INTERNAL_TRANS_VARIABLES = new String[] { Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, Const.INTERNAL_VARIABLE_TRANSFORMATION_NAME, Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY, }; /** * All the internal job variables */ public static final String[] INTERNAL_JOB_VARIABLES = new String[] { Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY, Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME, Const.INTERNAL_VARIABLE_JOB_NAME, Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY, }; /** The transformation filename directory */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Transformation.Filename.Directory"; /** The transformation filename name */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME = INTERNAL_VARIABLE_PREFIX+".Transformation.Filename.Name"; /** The transformation name */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_NAME = INTERNAL_VARIABLE_PREFIX+".Transformation.Name"; /** The transformation directory */ public static final String INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY = INTERNAL_VARIABLE_PREFIX+".Transformation.Repository.Directory"; /** The step partition ID */ public static final String INTERNAL_VARIABLE_STEP_PARTITION_ID = INTERNAL_VARIABLE_PREFIX+".Step.Partition.ID"; /** The step partition number */ public static final String INTERNAL_VARIABLE_STEP_PARTITION_NR = INTERNAL_VARIABLE_PREFIX+".Step.Partition.Number"; /** The slave transformation number */ public static final String INTERNAL_VARIABLE_SLAVE_SERVER_NUMBER = INTERNAL_VARIABLE_PREFIX+".Slave.Transformation.Number"; /** The slave transformation name */ public static final String INTERNAL_VARIABLE_SLAVE_SERVER_NAME = INTERNAL_VARIABLE_PREFIX+".Slave.Server.Name"; /** The size of the cluster : number of slaves */ public static final String INTERNAL_VARIABLE_CLUSTER_SIZE = INTERNAL_VARIABLE_PREFIX+".Cluster.Size"; /** The slave transformation number */ public static final String INTERNAL_VARIABLE_STEP_UNIQUE_NUMBER = INTERNAL_VARIABLE_PREFIX+".Step.Unique.Number"; /** Is this transformation running clustered, on the master? */ public static final String INTERNAL_VARIABLE_CLUSTER_MASTER = INTERNAL_VARIABLE_PREFIX+".Cluster.Master"; /** The size of the cluster : number of slaves */ public static final String INTERNAL_VARIABLE_STEP_UNIQUE_COUNT = INTERNAL_VARIABLE_PREFIX+".Step.Unique.Count"; /** The step name */ public static final String INTERNAL_VARIABLE_STEP_NAME = INTERNAL_VARIABLE_PREFIX+".Step.Name"; /** The step copy nr */ public static final String INTERNAL_VARIABLE_STEP_COPYNR = INTERNAL_VARIABLE_PREFIX+".Step.CopyNr"; /** The default maximum for the nr of lines in the GUI logs */ public static final int MAX_NR_LOG_LINES = 5000; /** The default maximum for the nr of lines in the history views */ public static final int MAX_NR_HISTORY_LINES = 50; /** UI-agnostic flag for warnings */ public static final int WARNING = 1; /** UI-agnostic flag for warnings */ public static final int ERROR = 2; /** UI-agnostic flag for warnings */ public static final int INFO = 3; /** * The margin between the text of a note and its border. */ public static final int NOTE_MARGIN = 5; /** * The default undo level for Kettle */ public static final int MAX_UNDO = 100; /** * You can set this environment variable to make Kettle scan additional packages for annotated plugins. * The packages are comma (,) delimited and the base specification is in the kettle-config.xml file */ public static final String KETTLE_PLUGIN_PACKAGES = "KETTLE_PLUGIN_PACKAGES"; /** * If you set this environment variable you can limit the log size of all transformations and jobs * that don't have the "log size limit" property set in their respective properties. */ public static final String KETTLE_LOG_SIZE_LIMIT = "KETTLE_LOG_SIZE_LIMIT"; private static String[] emptyPaddedSpacesStrings; /** * rounds double f to any number of places after decimal point * Does arithmetic using BigDecimal class to avoid integer overflow while rounding * TODO: make the rounding itself optional in the Props for performance reasons. * * @param f The value to round * @param places The number of decimal places * @return The rounded floating point value */ public static final double round(double f, int places) { java.math.BigDecimal bdtemp = java.math.BigDecimal.valueOf(f); bdtemp = bdtemp.setScale(places, java.math.BigDecimal.ROUND_HALF_EVEN); return bdtemp.doubleValue(); } /* OLD code: caused a lot of problems with very small and very large numbers. * It's a miracle it worked at all. * Go ahead, have a laugh... public static final float round(double f, int places) { float temp = (float) (f * (Math.pow(10, places))); temp = (Math.round(temp)); temp = temp / (int) (Math.pow(10, places)); return temp; } */ /** * Convert a String into an integer. If the conversion fails, assign a default value. * @param str The String to convert to an integer * @param def The default value * @return The converted value or the default. */ public static final int toInt(String str, int def) { int retval; try { retval = Integer.parseInt(str); } catch (Exception e) { retval = def; } return retval; } /** * Convert a String into a long integer. If the conversion fails, assign a default value. * @param str The String to convert to a long integer * @param def The default value * @return The converted value or the default. */ public static final long toLong(String str, long def) { long retval; try { retval = Long.parseLong(str); } catch (Exception e) { retval = def; } return retval; } /** * Convert a String into a double. If the conversion fails, assign a default value. * @param str The String to convert to a double * @param def The default value * @return The converted value or the default. */ public static final double toDouble(String str, double def) { double retval; try { retval = Double.parseDouble(str); } catch (Exception e) { retval = def; } return retval; } /** * Convert a String into a date. * The date format is <code>yyyy/MM/dd HH:mm:ss.SSS</code>. * If the conversion fails, assign a default value. * @param str The String to convert into a Date * @param def The default value * @return The converted value or the default. */ public static final Date toDate(String str, Date def) { SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US); try { return df.parse(str); } catch (ParseException e) { return def; } } /** * Determines whether or not a character is considered a space. * A character is considered a space in Kettle if it is a space, a tab, a newline or a cariage return. * @param c The character to verify if it is a space. * @return true if the character is a space. false otherwise. */ public static final boolean isSpace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } /** * Left trim: remove spaces to the left of a String. * @param str The String to left trim * @return The left trimmed String */ public static String ltrim(String source) { if (source==null) return null; int from = 0; while (from < source.length() && isSpace(source.charAt(from))) from++; return source.substring(from); } /** * Right trim: remove spaces to the right of a string * @param str The string to right trim * @return The trimmed string. */ public static String rtrim(String source) { if (source==null) return null; int max = source.length(); while (max > 0 && isSpace(source.charAt(max - 1))) max--; return source.substring(0, max); } /** * Trims a string: removes the leading and trailing spaces of a String. * @param str The string to trim * @return The trimmed string. */ public static final String trim(String str) { if (str==null) return null; int max = str.length() - 1; int min = 0; while (min <= max && isSpace(str.charAt(min))) min++; while (max >= 0 && isSpace(str.charAt(max))) max--; if (max < min) return ""; return str.substring(min, max + 1); } /** * Right pad a string: adds spaces to a string until a certain length. * If the length is smaller then the limit specified, the String is truncated. * @param ret The string to pad * @param limit The desired length of the padded string. * @return The padded String. */ public static final String rightPad(String ret, int limit) { if (ret == null) return rightPad(new StringBuffer(), limit); else return rightPad(new StringBuffer(ret), limit); } /** * Right pad a StringBuffer: adds spaces to a string until a certain length. * If the length is smaller then the limit specified, the String is truncated. * @param ret The StringBuffer to pad * @param limit The desired length of the padded string. * @return The padded String. */ public static final String rightPad(StringBuffer ret, int limit) { int len = ret.length(); int l; if (len > limit) { ret.setLength(limit); } else { for (l = len; l < limit; l++) ret.append(' '); } return ret.toString(); } /** * Replace values in a String with another. * @param string The original String. * @param repl The text to replace * @param with The new text bit * @return The resulting string with the text pieces replaced. */ public static final String replace(String string, String repl, String with) { StringBuffer str = new StringBuffer(string); for (int i = str.length() - 1; i >= 0; i--) { if (str.substring(i).startsWith(repl)) { str.delete(i, i + repl.length()); str.insert(i, with); } } return str.toString(); } /** * Alternate faster version of string replace using a stringbuffer as input. * * @param str The string where we want to replace in * @param code The code to search for * @param repl The replacement string for code */ public static void repl(StringBuffer str, String code, String repl) { int clength = code.length(); int i = str.length() - clength; while (i >= 0) { String look = str.substring(i, i + clength); if (look.equalsIgnoreCase(code)) // Look for a match! { str.replace(i, i + clength, repl); } i--; } } /** * Count the number of spaces to the left of a text. (leading) * @param field The text to examine * @return The number of leading spaces found. */ public static final int nrSpacesBefore(String field) { int nr = 0; int len = field.length(); while (nr < len && field.charAt(nr) == ' ') { nr++; } return nr; } /** * Count the number of spaces to the right of a text. (trailing) * @param field The text to examine * @return The number of trailing spaces found. */ public static final int nrSpacesAfter(String field) { int nr = 0; int len = field.length(); while (nr < len && field.charAt(field.length() - 1 - nr) == ' ') { nr++; } return nr; } /** * Checks whether or not a String consists only of spaces. * @param str The string to check * @return true if the string has nothing but spaces. */ public static final boolean onlySpaces(String str) { for (int i = 0; i < str.length(); i++) if (!isSpace(str.charAt(i))) return false; return true; } /** * determine the OS name * @return The name of the OS */ public static final String getOS() { return System.getProperty("os.name"); } /** * @return True if the OS is a Windows derivate. */ public static final boolean isWindows() { return getOS().startsWith("Windows"); } /** * @return True if the OS is a Linux derivate. */ public static final boolean isLinux() { return getOS().startsWith("Linux"); } /** * @return True if the OS is an OSX derivate. */ public static final boolean isOSX() { return getOS().toUpperCase().contains("OS X"); } /** * Determine the hostname of the machine Kettle is running on * @return The hostname */ public static final String getHostname() { String lastHostname = "localhost"; try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface nwi = en.nextElement(); Enumeration<InetAddress> ip = nwi.getInetAddresses(); while (ip.hasMoreElements()) { InetAddress in = (InetAddress) ip.nextElement(); lastHostname=in.getHostName(); //System.out.println(" ip address bound : "+in.getHostAddress()); //System.out.println(" hostname : "+in.getHostName()); //System.out.println(" Cann.hostname : "+in.getCanonicalHostName()); //System.out.println(" ip string : "+in.toString()); if (!lastHostname.equalsIgnoreCase("localhost") && !(lastHostname.indexOf(':')>=0) ) { return lastHostname; } } } } catch (SocketException e) { } return lastHostname; } /** * Determins the IP address of the machine Kettle is running on. * @return The IP address */ public static final String getIPAddress() throws Exception { Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); while (enumInterfaces.hasMoreElements()) { NetworkInterface nwi = (NetworkInterface) enumInterfaces.nextElement(); Enumeration<InetAddress> ip = nwi.getInetAddresses(); while (ip.hasMoreElements()) { InetAddress in = (InetAddress) ip.nextElement(); if (!in.isLoopbackAddress() && in.toString().indexOf(":") < 0) { return in.getHostAddress(); } } } return "127.0.0.1"; } /** * Get the primary IP address tied to a network interface (excluding loop-back etc) * @param networkInterfaceName the name of the network interface to interrogate * @return null if the network interface or address wasn't found. * * @throws SocketException in case of a security or network error */ public static final String getIPAddress(String networkInterfaceName) throws SocketException { NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName); Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress inetAddress = (InetAddress) ipAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) { String hostname = inetAddress.getHostAddress(); return hostname; } } return null; } /** * Tries to determine the MAC address of the machine Kettle is running on. * @return The MAC address. */ public static final String getMACAddress() throws Exception { String ip = getIPAddress(); String mac = "none"; String os = getOS(); String s = ""; //System.out.println("os = "+os+", ip="+ip); if (os.equalsIgnoreCase("Windows NT") || os.equalsIgnoreCase("Windows 2000") || os.equalsIgnoreCase("Windows XP") || os.equalsIgnoreCase("Windows 95") || os.equalsIgnoreCase("Windows 98") || os.equalsIgnoreCase("Windows Me") || os.startsWith("Windows")) { try { // System.out.println("EXEC> nbtstat -a "+ip); Process p = Runtime.getRuntime().exec("nbtstat -a " + ip); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { // System.out.println("NBTSTAT> "+s); if (s.indexOf("MAC") >= 0) { int idx = s.indexOf('='); mac = s.substring(idx + 2); } } } stdInput.close(); } catch (Exception e) { } } else if (os.equalsIgnoreCase("Linux")) { try { Process p = Runtime.getRuntime().exec("/sbin/ifconfig -a"); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { int idx = s.indexOf("HWaddr"); if (idx >= 0) { mac = s.substring(idx + 7); } } } stdInput.close(); } catch (Exception e) { } } else if (os.equalsIgnoreCase("Solaris")) { try { Process p = Runtime.getRuntime().exec("/usr/sbin/ifconfig -a"); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { int idx = s.indexOf("ether"); if (idx >= 0) { mac = s.substring(idx + 6); } } } stdInput.close(); } catch (Exception e) { } } else if (os.equalsIgnoreCase("HP-UX")) { try { Process p = Runtime.getRuntime().exec("/usr/sbin/lanscan -a"); // read the standard output of the command BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!procDone(p)) { while ((s = stdInput.readLine()) != null) { if (s.indexOf("MAC") >= 0) { int idx = s.indexOf("0x"); mac = s.substring(idx + 2); } } } stdInput.close(); } catch (Exception e) { } } return Const.trim(mac); } private static final boolean procDone(Process p) { try { p.exitValue(); return true; } catch (IllegalThreadStateException e) { return false; } } /** * Determines the Kettle directory in the user's home directory. * @return The Kettle directory. */ public static final String getKettleDirectory() { return USER_HOME_DIRECTORY + FILE_SEPARATOR + BasePropertyHandler.getProperty("userBaseDir", ".kettle"); } /** * Determines the location of the shared objects file * @return the name of the shared objects file */ public static final String getSharedObjectsFile() { return getKettleDirectory() + FILE_SEPARATOR + "shared.xml"; } /** * Returns the path to the Kettle local (current directory) repositories XML file. * @return The local repositories file. */ public static final String getKettleLocalRepositoriesFile() { return "repositories.xml"; } /** * Returns the full path to the Kettle repositories XML file. * @return The Kettle repositories file. */ public static final String getKettleUserRepositoriesFile() { return getKettleDirectory() + FILE_SEPARATOR + getKettleLocalRepositoriesFile(); } /** * Returns the path to the Kettle local (current directory) Carte password file:<p> * ./pwd/kettle.pwd<br> * * @return The local Carte password file. */ public static final String getKettleLocalCartePasswordFile() { return "pwd/kettle.pwd"; } /** * Returns the path to the Kettle Carte password file in the home directory:<p> * $KETTLE_HOME/.kettle/kettle.pwd<br> * * @return The Carte password file in the home directory. */ public static final String getKettleCartePasswordFile() { return getKettleDirectory() + FILE_SEPARATOR + "kettle.pwd"; } /** * Retrieves the content of an environment variable * * @param variable The name of the environment variable * @param deflt The default value in case no value was found * @return The value of the environment variable or the value of deflt in case no variable was defined. */ public static String getEnvironmentVariable(String variable, String deflt) { return System.getProperty(variable, deflt); } /** * Replaces environment variables in a string. * For example if you set KETTLE_HOME as an environment variable, you can * use %%KETTLE_HOME%% in dialogs etc. to refer to this value. * This procedures looks for %%...%% pairs and replaces them including the * name of the environment variable with the actual value. * In case the variable was not set, nothing is replaced! * * @param string The source string where text is going to be replaced. * * @return The expanded string. * @deprecated use StringUtil.environmentSubstitute(): handles both Windows and unix conventions */ public static final String replEnv(String string) { if (string == null) return null; StringBuffer str = new StringBuffer(string); int idx = str.indexOf("%%"); while (idx >= 0) { //OK, so we found a marker, look for the next one... int to = str.indexOf("%%", idx + 2); if (to >= 0) { // OK, we found the other marker also... String marker = str.substring(idx, to + 2); String var = str.substring(idx + 2, to); if (var != null && var.length() > 0) { // Get the environment variable String newval = getEnvironmentVariable(var, null); if (newval != null) { // Replace the whole bunch str.replace(idx, to + 2, newval); //System.out.println("Replaced ["+marker+"] with ["+newval+"]"); // The last position has changed... to += newval.length() - marker.length(); } } } else // We found the start, but NOT the ending %% without closing %% { to = idx; } // Look for the next variable to replace... idx = str.indexOf("%%", to + 1); } return str.toString(); } /** * Replaces environment variables in an array of strings.<p> * See also: replEnv(String string) * @param string The array of strings that wants its variables to be replaced. * @return the array with the environment variables replaced. * @deprecated please use StringUtil.environmentSubstitute now. */ public static final String[] replEnv(String string[]) { String retval[] = new String[string.length]; for (int i = 0; i < string.length; i++) { retval[i] = Const.replEnv(string[i]); } return retval; } /** * Implements Oracle style NVL function * @param source The source argument * @param def The default value in case source is null or the length of the string is 0 * @return source if source is not null, otherwise return def */ public static final String NVL(String source, String def) { if (source == null || source.length() == 0) return def; return source; } /** * Search for a string in an array of strings and return the index. * @param lookup The string to search for * @param array The array of strings to look in * @return The index of a search string in an array of strings. -1 if not found. */ public static final int indexOfString(String lookup, String array[]) { if (array == null) return -1; if (lookup == null) return -1; for (int i = 0; i < array.length; i++) { if (lookup.equalsIgnoreCase(array[i])) return i; } return -1; } /** * Search for strings in an array of strings and return the indexes. * @param lookup The strings to search for * @param array The array of strings to look in * @return The indexes of strings in an array of strings. -1 if not found. */ public static final int[] indexsOfStrings(String lookup[], String array[]) { int[] indexes = new int[lookup.length]; for (int i=0;i<indexes.length;i++) indexes[i] = indexOfString(lookup[i], array); return indexes; } /** * Search for strings in an array of strings and return the indexes. * If a string is not found, the index is not returned. * * @param lookup The strings to search for * @param array The array of strings to look in * @return The indexes of strings in an array of strings. Only existing indexes are returned (no -1) */ public static final int[] indexsOfFoundStrings(String lookup[], String array[]) { List<Integer> indexesList = new ArrayList<Integer>(); for (int i=0;i<lookup.length;i++) { int idx = indexOfString(lookup[i], array); if (idx>=0) indexesList.add(Integer.valueOf(idx)); } int[] indexes = new int[indexesList.size()]; for (int i=0;i<indexesList.size();i++) indexes[i] = (indexesList.get(i)).intValue(); return indexes; } /** * Search for a string in a list of strings and return the index. * @param lookup The string to search for * @param list The ArrayList of strings to look in * @return The index of a search string in an array of strings. -1 if not found. */ public static final int indexOfString(String lookup, List<String> list) { if (list == null) return -1; for (int i = 0; i < list.size(); i++) { String compare = list.get(i); if (lookup.equalsIgnoreCase(compare)) return i; } return -1; } /** * Sort the strings of an array in alphabetical order. * @param input The array of strings to sort. * @return The sorted array of strings. */ public static final String[] sortStrings(String input[]) { Arrays.sort(input); return input; } /** * Convert strings separated by a string into an array of strings.<p> * <code> Example: a;b;c;d ==> new String[] { a, b, c, d } * </code> * * <p><b>NOTE: this differs from String.split() in a way that the built-in method uses regular expressions and this one does not.</b> * * @param string The string to split * @param separator The separator used. * @return the string split into an array of strings */ public static final String[] splitString(String string, String separator) { /* * 0123456 * Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<String>(); if (string == null || string.length() == 0) { return new String[] {}; } int sepLen = separator.length(); int from = 0; int end = string.length() - sepLen + 1; for (int i = from; i < end; i += sepLen) { if (string.substring(i, i + sepLen).equalsIgnoreCase(separator)) { // OK, we found a separator, the string to add to the list // is [from, i[ list.add(NVL(string.substring(from, i), "")); from = i + sepLen; } } // Wait, if the string didn't end with a separator, we still have information at the end of the string... // In our example that would be "d"... if (from + sepLen <= string.length()) { list.add(NVL(string.substring(from, string.length()), "")); } return list.toArray(new String[list.size()]); } /** * Convert strings separated by a character into an array of strings.<p> * <code> Example: a;b;c;d == new String[] { a, b, c, d } * </code> * * @param string The string to split * @param separator The separator used. * @return the string split into an array of strings */ public static final String[] splitString(String string, char separator) { /* * 0123456 * Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<String>(); if (string == null || string.length() == 0) { return new String[] {}; } int from = 0; int end = string.length(); for (int i = from; i < end; i += 1) { if (string.charAt(i) == separator) { // OK, we found a separator, the string to add to the list // is [from, i[ list.add(NVL(string.substring(from, i), "")); from = i + 1; } } // Wait, if the string didn't end with a separator, we still have information at the end of the string... // In our example that would be "d"... if (from + 1 <= string.length()) { list.add(NVL(string.substring(from, string.length()), "")); } return list.toArray(new String[list.size()]); } /** * Convert strings separated by a string into an array of strings.<p> * <code> * Example /a/b/c --> new String[] { a, b, c } * </code> * * @param path The string to split * @param separator The separator used. * @return the string split into an array of strings */ public static final String[] splitPath(String path, String separator) { /* * 012345 * Example /a/b/c --> new String[] { a, b, c } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); if (path == null || path.length() == 0 || path.equals(separator)) { return new String[] {}; } int sepLen = separator.length(); int nr_separators = 1; int from = path.startsWith(separator) ? sepLen : 0; for (int i = from; i < path.length(); i += sepLen) { if (path.substring(i, i + sepLen).equalsIgnoreCase(separator)) { nr_separators++; } } String spath[] = new String[nr_separators]; int nr = 0; for (int i = from; i < path.length(); i += sepLen) { if (path.substring(i, i + sepLen).equalsIgnoreCase(separator)) { spath[nr] = path.substring(from, i); // System.out.println(nr+" --> ["+spath[nr]+"], (from,to)=("+from+", "+i+")"); nr++; from = i + sepLen; } } if (nr < spath.length) { spath[nr] = path.substring(from); // System.out.println(nr+" --> ["+spath[nr]+"], (from,to)=("+from+", "+path.length()+")"); } // // a --> { a } // if (spath.length == 0 && path.length() > 0) { spath = new String[] { path }; } return spath; } /** * @return An array of all default conversion formats, to be used in dialogs etc. */ public static String[] getConversionFormats() { String dats[] = Const.getDateFormats(); String nums[] = Const.getNumberFormats(); int totsize = dats.length + nums.length; String formats[] = new String[totsize]; for (int x = 0; x < dats.length; x++) formats[x] = dats[x]; for (int x = 0; x < nums.length; x++) formats[dats.length + x] = nums[x]; return formats; } /** * Sorts the array of Strings, determines the uniquely occurring strings. * @param strings the array that you want to do a distinct on * @return a sorted array of uniquely occurring strings */ public static final String[] getDistinctStrings(String[] strings) { if (strings == null) return null; if (strings.length == 0) return new String[] {}; String[] sorted = sortStrings(strings); List<String> result = new ArrayList<String>(); String previous = ""; for (int i = 0; i < sorted.length; i++) { if (!sorted[i].equalsIgnoreCase(previous)) { result.add(sorted[i]); } previous = sorted[i]; } return result.toArray(new String[result.size()]); } /** * Returns a string of the stack trace of the specified exception */ public static final String getStackTracker(Throwable e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); String string = stringWriter.getBuffer().toString(); try { stringWriter.close(); } catch(IOException ioe) {} // is this really required? return string; } /** * Check if the string supplied is empty. A String is empty when it is null or when the length is 0 * @param string The string to check * @return true if the string supplied is empty */ public static final boolean isEmpty(String string) { return string==null || string.length()==0; } /** * Check if the stringBuffer supplied is empty. A StringBuffer is empty when it is null or when the length is 0 * @param string The stringBuffer to check * @return true if the stringBuffer supplied is empty */ public static final boolean isEmpty(StringBuffer string) { return string==null || string.length()==0; } /** * Check if the string array supplied is empty. A String array is empty when it is null or when the number of elements is 0 * @param string The string array to check * @return true if the string array supplied is empty */ public static final boolean isEmpty(String[] strings) { return strings==null || strings.length==0; } /** * Check if the array supplied is empty. An array is empty when it is null or when the length is 0 * @param array The array to check * @return true if the array supplied is empty */ public static final boolean isEmpty(Object[] array) { return array==null || array.length==0; } /** * @return a new ClassLoader */ public static final ClassLoader createNewClassLoader() throws KettleException { try { // Nothing really in URL, everything is in scope. URL urls[] = new URL[] { }; URLClassLoader ucl = new URLClassLoader(urls); return ucl; } catch (Exception e) { throw new KettleException("Unexpected error during classloader creation", e); } } /** * Utility class for use in JavaScript to create a new byte array. * This is surprisingly difficult to do in JavaScript. * * @return a new java byte array */ public static final byte[] createByteArray(int size) { return new byte[size]; } /** * Sets the first character of each word in upper-case. * @param string The strings to convert to initcap * @return the input string but with the first character of each word converted to upper-case. */ public static final String initCap(String string) { StringBuffer change=new StringBuffer(string); boolean new_word; int i; char lower, upper, ch; new_word=true; for (i=0 ; i<string.length() ; i++) { lower=change.substring(i,i+1).toLowerCase().charAt(0); // Lowercase is default. upper=change.substring(i,i+1).toUpperCase().charAt(0); // Uppercase for new words. ch=upper; if (new_word) { change.setCharAt(i, upper); } else { change.setCharAt(i, lower); } new_word = false; // Cast to (int) is required for extended characters (SB) if ( !Character.isLetterOrDigit((int)ch) && ch!='_' ) new_word = true; } return change.toString(); } /** * Create a valid filename using a name * We remove all special characters, spaces, etc. * @param name The name to use as a base for the filename * @return a valid filename */ public static final String createFilename(String name) { StringBuffer filename = new StringBuffer(); for (int i=0;i<name.length();i++) { char c = name.charAt(i); if ( Character.isUnicodeIdentifierPart(c) ) { filename.append(c); } else if (Character.isWhitespace(c)) { filename.append('_'); } } return filename.toString().toLowerCase(); } public static final String createFilename(String directory, String name, String extension) { if (directory.endsWith(Const.FILE_SEPARATOR)) { return directory+createFilename(name)+extension; } else { return directory+Const.FILE_SEPARATOR+createFilename(name)+extension; } } public static final String createName(String filename) { if (Const.isEmpty(filename)) return filename; String pureFilename = filenameOnly(filename); if (pureFilename.endsWith(".ktr") || pureFilename.endsWith(".kjb") || pureFilename.endsWith(".xml")) { pureFilename = pureFilename.substring(0, pureFilename.length()-4); } StringBuffer sb = new StringBuffer(); for (int i=0; i < pureFilename.length(); i++) { char c = pureFilename.charAt(i); if ( Character.isUnicodeIdentifierPart(c) ) { sb.append(c); } else if (Character.isWhitespace(c)) { sb.append(' '); } else if (c=='-') { sb.append(c); } } return sb.toString(); } /** * <p> * Returns the pure filename of a filename with full path. E.g. if passed parameter is * <code>/opt/tomcat/logs/catalina.out</code> this method returns <code>catalina.out</code>. * The method works with the Environment variable <i>System.getProperty("file.separator")</i>, * so on linux/Unix it will check for the last occurrence of a frontslash, on windows for * the last occurrence of a backslash. * </p> * * <p> * To make this OS independent, the method could check for the last occurrence of a * frontslash and backslash and use the higher value of both. Should work, since these * characters aren't allowed in filenames on neither OS types (or said differently: * Neither linux nor windows can carry frontslashes OR backslashes in filenames). * Just a suggestion of an improvement ... * </p> * * @param sFullPath * @return */ public static String filenameOnly(String sFullPath) { if (Const.isEmpty(sFullPath)) return sFullPath; int idx = sFullPath.lastIndexOf(FILE_SEPARATOR); if (idx != -1) { return sFullPath.substring(idx + 1); } else { idx = sFullPath.lastIndexOf('/'); // URL, VFS if (idx != -1) { return sFullPath.substring(idx + 1); } else { return sFullPath; } } } /** * Returning the internationalized tips of the days. They get created once on first * request. * * @return */ public static String[] getTips() { if (tips == null) { int tipsOfDayCount = toInt(BaseMessages.getString(PKG, "Const.TipOfDay.Count"), 0); tips = new String[tipsOfDayCount]; for (int i = 1; i <= tipsOfDayCount; i++) tips[i - 1] = BaseMessages.getString(PKG, "Const.TipOfDay" + Integer.toString(i)); } return tips; } /** * Returning the localized date conversion formats. They get created once on first request. * * @return */ public static String[] getDateFormats() { if (dateFormats == null) { int dateFormatsCount = toInt(BaseMessages.getString(PKG, "Const.DateFormat.Count"), 0); dateFormats = new String[dateFormatsCount]; for (int i = 1; i <= dateFormatsCount; i++) dateFormats[i - 1] = BaseMessages.getString(PKG, "Const.DateFormat" + Integer.toString(i)); } return dateFormats; } /** * Returning the localized number conversion formats. They get created once on first request. * * @return */ public static String[] getNumberFormats() { if (numberFormats == null) { int numberFormatsCount = toInt(BaseMessages.getString(PKG, "Const.NumberFormat.Count"), 0); numberFormats = new String[numberFormatsCount + 1]; numberFormats[0] = DEFAULT_NUMBER_FORMAT; for (int i = 1; i <= numberFormatsCount; i++) numberFormats[i] = BaseMessages.getString(PKG, "Const.NumberFormat" + Integer.toString(i)); } return numberFormats; } public static String[] getTransformationAndJobFilterNames() { if (STRING_TRANS_AND_JOB_FILTER_NAMES == null) { STRING_TRANS_AND_JOB_FILTER_NAMES = new String[] { BaseMessages.getString(PKG, "Const.FileFilter.TransformationJob"), BaseMessages.getString(PKG, "Const.FileFilter.Transformations"), BaseMessages.getString(PKG, "Const.FileFilter.Jobs"), BaseMessages.getString(PKG, "Const.FileFilter.XML"), BaseMessages.getString(PKG, "Const.FileFilter.All") }; } return STRING_TRANS_AND_JOB_FILTER_NAMES; } public static String[] getTransformationFilterNames() { if (STRING_TRANS_FILTER_NAMES == null) { STRING_TRANS_FILTER_NAMES = new String[] { BaseMessages.getString(PKG, "Const.FileFilter.Transformations"), BaseMessages.getString(PKG, "Const.FileFilter.XML"), BaseMessages.getString(PKG, "Const.FileFilter.All") }; } return STRING_TRANS_FILTER_NAMES; } public static String[] getJobFilterNames() { if (STRING_JOB_FILTER_NAMES == null) { STRING_JOB_FILTER_NAMES = new String[] { BaseMessages.getString(PKG, "Const.FileFilter.Jobs"), BaseMessages.getString(PKG, "Const.FileFilter.XML"), BaseMessages.getString(PKG, "Const.FileFilter.All") }; } return STRING_JOB_FILTER_NAMES; } /** * Return the current time as nano-seconds. * * @return time as nano-seconds. */ public static long nanoTime() { return new Date().getTime()*1000; } /** * Return the input string trimmed as specified. * * @param string String to be trimmed * @param trimType Type of trimming * * @return Trimmed string. */ public static String trimToType(String string,int trimType) { switch(trimType) { case ValueMetaInterface.TRIM_TYPE_BOTH: return trim(string); case ValueMetaInterface.TRIM_TYPE_LEFT: return ltrim(string); case ValueMetaInterface.TRIM_TYPE_RIGHT: return rtrim(string); case ValueMetaInterface.TRIM_TYPE_NONE: default: return string; } } /** * implemented to help prevent errors in matching up pluggable LAF directories and paths/files * eliminating malformed URLs - duplicate file separators or missing file separators. * * @param dir * @param file * @return concatenated string representing a file url */ public static String safeAppendDirectory(String dir, String file) { boolean dirHasSeparator = ((dir.lastIndexOf(FILE_SEPARATOR)) == dir.length()); boolean fileHasSeparator = (file.indexOf(FILE_SEPARATOR) != 0); if ((dirHasSeparator && !fileHasSeparator) || (!dirHasSeparator && fileHasSeparator)) return dir + file; if (dirHasSeparator && fileHasSeparator) return dir + file.substring(1); return dir + FILE_SEPARATOR + file; } /** * Create an array of Strings consisting of spaces. The index of a String in * the array determines the number of spaces in that string. * * @return array of 'space' Strings. */ public static String[] getEmptyPaddedStrings() { if (emptyPaddedSpacesStrings==null) { emptyPaddedSpacesStrings = new String[250]; for (int i=0;i<emptyPaddedSpacesStrings.length;i++) { emptyPaddedSpacesStrings[i] = rightPad("", i); } } return emptyPaddedSpacesStrings; } /** * Return the percentage of free memory for this JVM. * * @return Percentage of free memory. */ public static final int getPercentageFreeMemory() { Runtime runtime = Runtime.getRuntime(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); long totalFreeMemory = (freeMemory + (maxMemory - allocatedMemory)); int percentage = (int)Math.round(100*(double)totalFreeMemory / (double)maxMemory); return percentage; } /** * Return non digits only. * * @return non digits in a string. */ public static String removeDigits(String input) { if(Const.isEmpty(input)) return null; StringBuffer digitsOnly = new StringBuffer (); char c; for (int i = 0; i < input.length (); i++) { c = input.charAt (i); if (!Character.isDigit (c)) { digitsOnly.append (c); } } return digitsOnly.toString (); } /** * Return digits only. * * @return digits in a string. */ public static String getDigitsOnly(String input) { if(Const.isEmpty(input)) return null; StringBuffer digitsOnly = new StringBuffer (); char c; for (int i = 0; i < input.length (); i++) { c = input.charAt (i); if (Character.isDigit (c)) { digitsOnly.append (c); } } return digitsOnly.toString (); } /** * Remove time from a date. * * @return a date without hour. */ public static Date removeTimeFromDate(Date input) { if(input==null) return null; // Get an instance of the Calendar. Calendar calendar = Calendar.getInstance(); // Make sure the calendar will not perform automatic correction. calendar.setLenient(false); // Set the time of the calendar to the given date. calendar.setTime(input); // Remove the hours, minutes, seconds and milliseconds. calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); // Return the date again. return calendar.getTime(); } /** * Mask XML content. * i.e. replace characters with &values; * @param content content * @return masked content */ public static String maskXML (String content) { if (isEmpty(content)) return content; StringBuffer out = new StringBuffer(); char[] chars = content.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; switch (c) { case '<': out.append("&lt;"); break; case '>': out.append("&gt;"); break; case '&': out.append("&amp;"); break; case '"': out.append("&quot;"); break; case '\'': out.append("&apos;"); break; default: out.append(c); break; } } return out.toString(); } /** * Remove CR / LF from String * @param in input * @return cleaned string */ public static String removeCRLF (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\n' || c == '\r') ; else out.append(c); } return out.toString(); } /** * Remove CR / LF from String * @param in input * @return cleaned string */ public static String removeCR (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\n') ; else out.append(c); } return out.toString(); } // removeCR /** * Remove CR / LF from String * @param in input * @return cleaned string */ public static String removeLF (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\r') ; else out.append(c); } return out.toString(); } // removeCRLF /** * Remove Horizontan Tab from String * @param in input * @return cleaned string */ public static String removeTAB (String in) { char[] inArray = in.toCharArray(); StringBuffer out = new StringBuffer (inArray.length); for (int i = 0; i < inArray.length; i++) { char c = inArray[i]; if (c == '\t') ; else out.append(c); } return out.toString(); } /** * Add time to an input date * @param input the date * @param time the time to add (in string) * @param DateFormat the time format * @return date = input + time */ public static Date addTimeToDate(Date input, String time,String DateFormat) throws Exception { if(isEmpty(time)) return input; if(input==null) return null; String dateformatString=NVL(DateFormat,"HH:mm:ss"); int t = decodeTime(time,dateformatString); Date d = new Date(input.getTime()+t); return d; } // Decodes a time value in specified date format and returns it as milliseconds since midnight. public static int decodeTime (String s,String DateFormat) throws Exception { SimpleDateFormat f = new SimpleDateFormat(DateFormat); TimeZone utcTimeZone = TimeZone.getTimeZone("UTC"); f.setTimeZone (utcTimeZone); f.setLenient (false); ParsePosition p = new ParsePosition(0); Date d = f.parse(s,p); if (d == null) throw new Exception("Invalid time value " + DateFormat +": \"" + s + "\"."); return (int)d.getTime(); } /** * Get the number of occurances of searchFor in string. * @param string String to be searched * @param searchFor to be counted string * @return number of occurances */ public static int getOccurenceString (String string, String searchFor) { if (string == null || string.length() == 0) return 0; int counter=0; int len = searchFor.length(); int result = 0; if (len > 0) { int start = string.indexOf(searchFor); while (start != -1) { result++; start = string.indexOf(searchFor, start+len); } } return counter; } /** * Determines the package name of a class, specifically for i18n purposes. * This method is scanned for by Translator2 : DO NOT RENAME OR REFACTOR. * * @param class1 * @return */ public static String getPackageName(Class<CsvInputMeta> clazz) { return clazz.getPackage().getName(); } }
PDI-2135 : Get rid of Messages classes (compile fix) git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@10589 5fb7f6ec-07c1-534a-b4ca-9155e429e800
src-core/org/pentaho/di/core/Const.java
PDI-2135 : Get rid of Messages classes (compile fix)
Java
apache-2.0
29c0caecda656c3943ac2ebd520126a2cde38c22
0
nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yawni.wn; import org.yawni.util.Utils; import static org.yawni.util.Utils.*; import static org.fest.assertions.Assertions.assertThat; import java.util.*; import org.junit.BeforeClass; import org.junit.Test; import org.yawni.util.Joiner; public class DictionaryDatabaseTest { private static DictionaryDatabase dictionary; @BeforeClass public static void init() { dictionary = FileBackedDictionary.getInstance(); } /** * test POS.ALL support * + List<String> lookupBaseForms(POS pos, String someString) * - List<Synset> lookupSynsets(POS pos, String someString) * - Iterator<Relation> relations(POS pos) * - Iterator<Relation> relations(POS pos, RelationType relationType) * - Iterator<Word> words(POS pos) * - Iterator<Synset> synsets(POS pos) * - Iterator<WordSense> wordSenses(POS pos) */ //@Ignore @Test public void test() { final List<String> tanks = dictionary.lookupBaseForms("tank", POS.ALL); System.err.println("tanks: "+tanks); final List<String> geese = dictionary.lookupBaseForms("geese", POS.ALL); System.err.println("geese: "+geese); } /** * Expects exception because POS.ALL does not make sense for method * lookupWord(POS, lemma) which returns at most 1 result. * TODO subclass IllegalArgumentException (a RuntimeException) * indicating this. */ @Test(expected=IllegalArgumentException.class) public void test_lookupWord() { dictionary.lookupWord("tank", POS.ALL); } /** * Look for warning issues with lookupSynsets() */ @Test public void lookupSynsetsTest() { //String str = "allow for"; //String str = "allowing for"; String str = "allows for"; POS pos = POS.VERB; List<Synset> syns = dictionary.lookupSynsets(str, pos); if (syns.isEmpty()) { System.err.println("XXX PROBLEM: "+str+" no syns found (loopback failure)"); } //System.err.println(str+": "+Arrays.toString(syns)); syns = dictionary.lookupSynsets("compromise", POS.ALL); assertThat(isUnique(syns)).isTrue(); assertThat(syns.size()).isEqualTo(5); } @Test public void coordinateTerms() { final Word synonyms = dictionary.lookupWord("synonyms", POS.NOUN); assertThat(synonyms).isNull(); final Word synonym = dictionary.lookupWord("synonym", POS.NOUN); final List<WordSense> senses = synonym.getWordSenses(); assertThat(senses).hasSize(1); final WordSense sense = senses.get(0); final List<RelationTarget> parents = sense.getRelationTargets(RelationType.HYPERNYM); assertThat(parents).hasSize(1); // though most Synsets have a single parent, not all do final RelationTarget parent = parents.get(0); //final Synset parentSyn = parent.getSynset(); final List<RelationTarget> coordinateTerms = parent.getRelationTargets(RelationType.HYPONYM); // TODO // this is a confusing example :) // "antonym", "hyponym", "hypernym" will all be among the coordinate terms of "synonym" // comprehensive loops version // for Word from string // for WordSense / Synset : word // for parent : wordSense.getRelationTargets(RelationType.HYPERNYM) // coordinateTerms/neighbors = parent.getRelationTargets(RelationType.HYPONYM) // // TODO: // represent each coordinateTerms as a RelationType; represent each coordinateTerm as a Relation // * multiParent sources add ambiguity, but maybe this doesn't matter ? define as "have <em>a</em> common parent } @Test public void synsetsCommands() { System.err.println("synsetsCommands"); String query; Iterable<Synset> result; int offset; boolean caughtExpectedException; query = "?POS=ALL"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // basic 8-digit offset query // NOTE: leading zero integer literal is octal! (base 8), e.g., 04073208 != 4073208 // in fact, 04073208 is not a valid octal number because 8 is not a valid octimal (?) digit assertThat(010).isEqualTo(8); offset = 4073208; //query = "?POS=n&offset=04073208"; query = String.format("?POS=n&offset=%08d", offset); // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); assertThat(first(result).getOffset()).isEqualTo(offset); // simple hapens-to-be-less-than-8-digit offset query with (mandatory) POS query = "?POS=n&offset=" + offset; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); assertThat(first(result).getOffset()).isEqualTo(offset); // simple hapens-to-be-less-than-8-digit offset query, forgot POS query = "?offset=" + offset; // System.err.println("query: "+query); caughtExpectedException = false; try { result = dictionary.synsets(query); } catch (IllegalArgumentException e) { caughtExpectedException = true; } assertThat(caughtExpectedException).isTrue(); // command repetition not supported query = "?POS=n&offset=04073208&offset=05847753"; // System.err.println("query: "+query); caughtExpectedException = false; try { result = dictionary.synsets(query); } catch (IllegalArgumentException e) { caughtExpectedException = true; } assertThat(caughtExpectedException).isTrue(); // command repetition not supported query = "?POS=n&POS=v"; // System.err.println("query: "+query); caughtExpectedException = false; try { result = dictionary.synsets(query); } catch (IllegalArgumentException e) { caughtExpectedException = true; } assertThat(caughtExpectedException).isTrue(); // basic ordinal POS query query = "?POS=1"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // 9-digit POS + offset query query = "?offset=104073208"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // invalid (random) synset offsets cause various exceptions in Synset parsing ctor query = "?offset=100001000"; // System.err.println("query: "+query); caughtExpectedException = false; try { result = dictionary.synsets(query); } catch (IllegalArgumentException e) { caughtExpectedException = true; } assertThat(caughtExpectedException).isTrue(); // lexname query query = "?lexname=verb.contact"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // lexname query query = "?lexname=contact"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // lexname query final String query1 = "?lexname=verb.contact"; final String query2 = "?lexname=contact"; // System.err.println("query1: "+query1); // System.err.println("query2: "+query2); final Iterable<Synset> result1 = dictionary.synsets(query1); final Iterable<Synset> result2 = dictionary.synsets(query2); assertThat(isEmpty(result1)).isFalse(); assertThat(isEmpty(result2)).isFalse(); assertThat(Utils.equals(result1, result2)).isTrue(); // word query query = "?word=yawn"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(size(result)).isEqualTo(3); // word query query = "?word=yawn&pos=NOUN"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(size(result)).isEqualTo(1); // word query with stemming query = "?word=wounds"; // System.err.println("query: "+query); result = dictionary.synsets(query); // System.err.println("query: "+query+" \n "+Joiner.on("\n ").join(result)); assertThat(size(result)).isEqualTo(6); } @Test public void wordSensesCommands() { System.err.println("wordSensesCommands"); String query; Iterable<WordSense> result; boolean caughtExpectedException; query = "?POS=ALL"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); query = "?POS=1"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); // adjposition query query = "?adj_position=PREDICATIVE"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); // adjposition query query = "?adj_position=predicative"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); // word query query = "?word=yawn"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(size(result)).isEqualTo(3); // word query with POS query = "?word=yawn&pos=NOUN"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(size(result)).isEqualTo(1); // word query with stemming query = "?word=wounds"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); // System.err.println("query: "+query+" \n "+Joiner.on("\n ").join(result)); assertThat(size(result)).isEqualTo(6); } private static <T> boolean isUnique(final Collection<T> items) { return items.size() == new HashSet<T>(items).size(); } }
core/src/test/java/org/yawni/wn/DictionaryDatabaseTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yawni.wn; import org.yawni.util.Utils; import static org.yawni.util.Utils.*; import static org.fest.assertions.Assertions.assertThat; import java.util.*; import org.junit.BeforeClass; import org.junit.Test; public class DictionaryDatabaseTest { private static DictionaryDatabase dictionary; @BeforeClass public static void init() { dictionary = FileBackedDictionary.getInstance(); } /** * test POS.ALL support * + List<String> lookupBaseForms(POS pos, String someString) * - List<Synset> lookupSynsets(POS pos, String someString) * - Iterator<Relation> relations(POS pos) * - Iterator<Relation> relations(POS pos, RelationType relationType) * - Iterator<Word> words(POS pos) * - Iterator<Synset> synsets(POS pos) * - Iterator<WordSense> wordSenses(POS pos) */ //@Ignore @Test public void test() { final List<String> tanks = dictionary.lookupBaseForms("tank", POS.ALL); System.err.println("tanks: "+tanks); final List<String> geese = dictionary.lookupBaseForms("geese", POS.ALL); System.err.println("geese: "+geese); } /** * Expects exception because POS.ALL does not make sense for method * lookupWord(POS, lemma) which returns at most 1 result. * TODO subclass IllegalArgumentException (a RuntimeException) * indicating this. */ @Test(expected=IllegalArgumentException.class) public void test_lookupWord() { dictionary.lookupWord("tank", POS.ALL); } /** * Look for warning issues with lookupSynsets() */ @Test public void lookupSynsetsTest() { //String str = "allow for"; //String str = "allowing for"; String str = "allows for"; POS pos = POS.VERB; List<Synset> syns = dictionary.lookupSynsets(str, pos); if (syns.isEmpty()) { System.err.println("XXX PROBLEM: "+str+" no syns found (loopback failure)"); } //System.err.println(str+": "+Arrays.toString(syns)); syns = dictionary.lookupSynsets("compromise", POS.ALL); assertThat(isUnique(syns)).isTrue(); assertThat(syns.size()).isEqualTo(5); } @Test public void coordinateTerms() { final Word synonyms = dictionary.lookupWord("synonyms", POS.NOUN); assertThat(synonyms).isNull(); final Word synonym = dictionary.lookupWord("synonym", POS.NOUN); final List<WordSense> senses = synonym.getWordSenses(); assertThat(senses).hasSize(1); final WordSense sense = senses.get(0); final List<RelationTarget> parents = sense.getRelationTargets(RelationType.HYPERNYM); assertThat(parents).hasSize(1); // though most Synsets have a single parent, not all do final RelationTarget parent = parents.get(0); //final Synset parentSyn = parent.getSynset(); final List<RelationTarget> coordinateTerms = parent.getRelationTargets(RelationType.HYPONYM); // TODO // this is a confusing example :) // "antonym", "hyponym", "hypernym" will all be among the coordinate terms of "synonym" // comprehensive loops version // for Word from string // for WordSense / Synset : word // for parent : wordSense.getRelationTargets(RelationType.HYPERNYM) // coordinateTerms/neighbors = parent.getRelationTargets(RelationType.HYPONYM) // // TODO: // represent each coordinateTerms as a RelationType; represent each coordinateTerm as a Relation // * multiParent sources add ambiguity, but maybe this doesn't matter ? define as "have <em>a</em> common parent } @Test public void synsetsCommands() { System.err.println("synsetsCommands"); String query; Iterable<Synset> result; int offset; boolean caughtExpectedException; query = "?POS=ALL"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // basic 8-digit offset query // NOTE: leading zero integer literal is octal! (base 8), e.g., 04073208 != 4073208 // in fact, 04073208 is not a valid octal number because 8 is not a valid octimal (?) digit assertThat(010).isEqualTo(8); offset = 4073208; //query = "?POS=n&offset=04073208"; query = String.format("?POS=n&offset=%08d", offset); // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); assertThat(first(result).getOffset()).isEqualTo(offset); // simple hapens-to-be-less-than-8-digit offset query with (mandatory) POS query = "?POS=n&offset=" + offset; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); assertThat(first(result).getOffset()).isEqualTo(offset); // simple hapens-to-be-less-than-8-digit offset query, forgot POS query = "?offset=" + offset; // System.err.println("query: "+query); caughtExpectedException = false; try { result = dictionary.synsets(query); } catch (IllegalArgumentException e) { caughtExpectedException = true; } assertThat(caughtExpectedException).isTrue(); // command repetition not supported query = "?POS=n&offset=04073208&offset=05847753"; // System.err.println("query: "+query); caughtExpectedException = false; try { result = dictionary.synsets(query); } catch (IllegalArgumentException e) { caughtExpectedException = true; } assertThat(caughtExpectedException).isTrue(); // basic ordinal POS query query = "?POS=1"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // 9-digit POS + offset query query = "?offset=104073208"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // invalid (random) synset offsets cause various exceptions in Synset parsing ctor query = "?offset=100001000"; // System.err.println("query: "+query); caughtExpectedException = false; try { result = dictionary.synsets(query); } catch (IllegalArgumentException e) { caughtExpectedException = true; } assertThat(caughtExpectedException).isTrue(); // lexname query query = "?lexname=verb.contact"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // lexname query query = "?lexname=contact"; // System.err.println("query: "+query); result = dictionary.synsets(query); assertThat(isEmpty(result)).isFalse(); // lexname query final String query1 = "?lexname=verb.contact"; final String query2 = "?lexname=contact"; // System.err.println("query1: "+query1); // System.err.println("query2: "+query2); final Iterable<Synset> result1 = dictionary.synsets(query1); final Iterable<Synset> result2 = dictionary.synsets(query2); assertThat(isEmpty(result1)).isFalse(); assertThat(isEmpty(result2)).isFalse(); assertThat(Utils.equals(result1, result2)).isTrue(); } @Test public void wordSensesCommands() { System.err.println("wordSensesCommands"); String query; Iterable<WordSense> result; boolean caughtExpectedException; query = "?POS=ALL"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); query = "?POS=1"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); // adjposition query query = "?adj_position=PREDICATIVE"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); // adjposition query query = "?adj_position=predicative"; // System.err.println("query: "+query); result = dictionary.wordSenses(query); assertThat(isEmpty(result)).isFalse(); } private static <T> boolean isUnique(final Collection<T> items) { return items.size() == new HashSet<T>(items).size(); } }
more tests
core/src/test/java/org/yawni/wn/DictionaryDatabaseTest.java
more tests
Java
apache-2.0
f894f04f11562927c4d75e3df22d67e4d83a10a5
0
aduprat/james,aduprat/james,aduprat/james,rouazana/james,aduprat/james,chibenwa/james,chibenwa/james,rouazana/james,chibenwa/james,chibenwa/james,rouazana/james,rouazana/james
/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE file. */ package org.apache.james.transport; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Vector; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.Logger; import org.apache.avalon.phoenix.BlockContext; /** * * $Id: Loader.java,v 1.4 2003/01/15 12:49:34 danny Exp $ */ public class Loader implements Contextualizable { protected ClassLoader mailetClassLoader = null; protected String baseDirectory = null; protected Logger logger; protected final String MAILET_PACKAGE = "mailetpackage"; protected final String MATCHER_PACKAGE = "matcherpackage"; /** * The list of packages that may contain Mailets or matchers */ protected Vector packages; /** * @see org.apache.avalon.framework.context.Contextualizable#contextualize(Context) */ public void contextualize(final Context context) throws ContextException { try { baseDirectory = ((BlockContext) context).getBaseDirectory().getCanonicalPath(); } catch (IOException e) { logger.error("cant get base directory for mailet loader"); throw new ContextException("cant contextualise mailet loader " + e.getMessage(), e); } } /** * Method setLogger. * @param logger */ public void setLogger(Logger logger) { this.logger = logger; } protected void getPackages(Configuration conf, String packageType) throws ConfigurationException { packages = new Vector(); packages.addElement(""); final Configuration[] pkgConfs = conf.getChildren(packageType); for (int i = 0; i < pkgConfs.length; i++) { Configuration c = pkgConfs[i]; String packageName = c.getValue(); if (!packageName.endsWith(".")) { packageName += "."; } packages.addElement(packageName); } } /** * Method getMailetClassLoader. */ protected void configureMailetClassLoader() { File base = new File(baseDirectory + "/SAR-INF/lib"); String[] flist = base.list(); Vector jarlist = new Vector(); URL[] classPath = null; try { jarlist.add(new URL("file://" + baseDirectory + "/SAR-INF/classes/")); } catch (MalformedURLException e) { logger.error( "cant add " + "file://" + baseDirectory + "/SAR-INF/classes/ to mailet classloader"); } if (flist != null) { for (int i = 0; i < flist.length; i++) { try { if (flist[i].indexOf("jar") == flist[i].length() - 3) { jarlist.add(new URL("file://" + baseDirectory +"/SAR-INF/lib/"+ flist[i])); logger.debug("added file://" + baseDirectory +"/SAR-INF/lib/" + flist[i] + " to mailet Classloader"); } } catch (MalformedURLException e) { logger.error("cant add file://" + baseDirectory +"/SAR-INF/lib/"+ flist[i] + " to mailet classloader"); } } } classPath = (URL[]) jarlist.toArray(new URL[jarlist.size()]); mailetClassLoader = new URLClassLoader(classPath, this.getClass().getClassLoader()); } }
src/java/org/apache/james/transport/Loader.java
/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE file. */ package org.apache.james.transport; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Vector; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.Logger; import org.apache.avalon.phoenix.BlockContext; /** * * $Id: Loader.java,v 1.3 2003/01/14 13:41:55 serge Exp $ */ public class Loader implements Contextualizable { protected ClassLoader mailetClassLoader = null; protected String baseDirectory = null; protected Logger logger; protected final String MAILET_PACKAGE = "mailetpackage"; protected final String MATCHER_PACKAGE = "matcherpackage"; /** * The list of packages that may contain Mailets or matchers */ protected Vector packages; /** * @see org.apache.avalon.framework.context.Contextualizable#contextualize(Context) */ public void contextualize(final Context context) throws ContextException { try { baseDirectory = ((BlockContext) context).getBaseDirectory().getCanonicalPath(); } catch (IOException e) { logger.error("cant get base directory for mailet loader"); throw new ContextException("cant contextualise mailet loader " + e.getMessage(), e); } } /** * Method setLogger. * @param logger */ public void setLogger(Logger logger) { this.logger = logger; } protected void getPackages(Configuration conf, String packageType) throws ConfigurationException { packages = new Vector(); packages.addElement(""); final Configuration[] pkgConfs = conf.getChildren(packageType); for (int i = 0; i < pkgConfs.length; i++) { Configuration c = pkgConfs[i]; String packageName = c.getValue(); if (!packageName.endsWith(".")) { packageName += "."; } packages.addElement(packageName); } } /** * Method getMailetClassLoader. */ protected void configureMailetClassLoader() { File base = new File(baseDirectory + "/SAR-INF/lib"); String[] flist = base.list(); Vector jarlist = new Vector(); URL[] classPath = null; try { jarlist.add(new URL("file://" + baseDirectory + "/SAR-INF/lib/classes/")); } catch (MalformedURLException e) { logger.error( "cant add " + "file://" + baseDirectory + "/SAR-INF/classes/ to mailet classloader"); } if (flist != null) { for (int i = 0; i < flist.length; i++) { try { if (flist[i].indexOf("jar") == flist[i].length() - 3) { jarlist.add(new URL("file://" + flist[i])); logger.debug("added " + flist[i] + " to mailet Classloader"); } } catch (MalformedURLException e) { logger.error("cant add " + "file://" + flist[i] + " to mailet classloader"); } } } classPath = (URL[]) jarlist.toArray(new URL[jarlist.size()]); mailetClassLoader = new URLClassLoader(classPath, this.getClass().getClassLoader()); } }
Added path to jar URL's being added to classloader. Can't believe that I missed this last time. Removed /lib/ from classes directory path. git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@108348 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/james/transport/Loader.java
Added path to jar URL's being added to classloader. Can't believe that I missed this last time. Removed /lib/ from classes directory path.
Java
apache-2.0
c28ded60a05f8b7f634f7b6c09d580d54963053a
0
ONLYOFFICE/document-server-integration,ONLYOFFICE/document-server-integration,ONLYOFFICE/document-server-integration,ONLYOFFICE/document-server-integration,ONLYOFFICE/document-server-integration,ONLYOFFICE/document-server-integration,ONLYOFFICE/document-server-integration,ONLYOFFICE/document-server-integration
/** * * (c) Copyright Ascensio System SIA 2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.onlyoffice.integration.controllers; import com.onlyoffice.integration.controllers.objects.ConverterBody; import com.onlyoffice.integration.entities.User; import com.onlyoffice.integration.entities.enums.DocumentType; import com.onlyoffice.integration.services.UserServices; import com.onlyoffice.integration.util.documentManagers.DocumentManagerExts; import com.onlyoffice.integration.util.documentManagers.DocumentTokenManager; import com.onlyoffice.integration.util.fileUtilities.FileUtility; import com.onlyoffice.integration.util.objects.ActionObject; import com.onlyoffice.integration.util.objects.TrackManagerRequestBody; import com.onlyoffice.integration.util.serviceConverter.ServiceConverter; import com.onlyoffice.integration.util.TrackManager; import com.onlyoffice.integration.util.documentManagers.DocumentManager; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.primeframework.jwt.Verifier; import org.primeframework.jwt.domain.JWT; import org.primeframework.jwt.hmac.HMACVerifier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @Controller public class FileController { @Autowired private FileUtility fileUtility; @Autowired private DocumentManager documentManager; @Autowired private DocumentTokenManager documentTokenManager; @Autowired private DocumentManagerExts documentManagerExts; @Autowired private TrackManager trackManager; @Autowired private UserServices userService; @Autowired private ServiceConverter serviceConverter; @Value("${files.docservice.header}") private String documentJwtHeader; @Value("${files.docservice.secret}") private String tokenSecret; private String createUserMetadata(String uid, String fullFileName) throws IOException { Optional<User> optionalUser = userService.findUserById(Integer.parseInt(uid)); String fileName = fileUtility.getFileNameWithoutExtension(fullFileName); String documentType = fileUtility.getDocumentType(fullFileName).toString().toLowerCase(); if(optionalUser.isPresent()){ User user = optionalUser.get(); documentManager.createMeta(fileName, String.valueOf(user.getId()), user.getName(), null); } return "{ \"filename\": \"" + fullFileName + "\", \"documentType\": \"" + documentType + "\" }"; } private ResponseEntity<Resource> downloadFile(String fileName){ String fileLocation = documentManager.forceSavePath(fileName, null, false); if (fileLocation.equals("")){ fileLocation = documentManager.storagePath(fileName, null); } Resource resource = documentManager.loadFileAsResource(fileLocation); String contentType = null; if(contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file, @CookieValue("uid") String uid){ try { String fullFileName = file.getOriginalFilename(); String fileExtension = fileUtility.getFileExtension(fullFileName); long fileSize = file.getSize(); byte[] bytes = file.getBytes(); String directory = documentManager.filesRootPath(null); if(documentManager.getMaxFileSize() < fileSize || fileSize <= 0){ return "{ \"error\": \"File size is incorrect\"}"; } if(!documentManagerExts.getFileExts().contains(fileExtension)){ return "{ \"error\": \"File type is not supported\"}"; } Path path = fileUtility.generateFilepath(directory, fullFileName); String fileName = fileUtility.getFileNameWithoutExtension(path.getFileName().toString()); Files.write(path, bytes); return createUserMetadata(uid, fileName+fileExtension); } catch (Exception e) { e.printStackTrace(); } return "{ \"error\": \"Something went wrong when uploading the file.\"}"; } @PostMapping(path = "${url.converter}") @ResponseBody public String convert(@RequestBody ConverterBody body, @CookieValue("uid") String uid){ String fileName = body.getFileName(); String fileUri = documentManager.getFileUri(fileName, true); String filePass = body.getFilePass() != null ? body.getFilePass() : null; String fileExt = fileUtility.getFileExtension(fileName); DocumentType type = fileUtility.getDocumentType(fileName); String internalFileExt = fileUtility.getInternalExtension(type); try{ if(documentManagerExts.getConvertExts().contains(fileExt)){ String key = serviceConverter.generateRevisionId(fileUri); String newFileUri = serviceConverter .getConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true); if(newFileUri.isEmpty()){ return "{ \"step\" : \"0\", \"filename\" : \"" + fileName + "\"}"; } String correctedName = documentManager .getCorrectName(fileUtility.getFileNameWithoutExtension(fileName)+internalFileExt, null); URL url = new URL(newFileUri); java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); InputStream stream = connection.getInputStream(); if (stream == null) { throw new Exception("Stream is null"); } File convertedFile = new File(documentManager.storagePath(correctedName, null)); try (FileOutputStream out = new FileOutputStream(convertedFile)) { int read; final byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); } connection.disconnect(); fileName = correctedName; } return createUserMetadata(uid, fileName+fileExt); }catch (Exception e) { e.printStackTrace(); } return "{ \"error\": \"" + "The file can't be converted.\"}"; } @PostMapping("/delete") @ResponseBody public String delete(@RequestBody ConverterBody body){ try { String fullFileName = fileUtility.getFileName(body.getFileName()); String fileName = fileUtility.getFileNameWithoutExtension(body.getFileName()); String fileLocation = documentManager.storagePath(fullFileName, null); String historyLocation = documentManager.historyDir(documentManager .storagePath(fileName, null)); String convertedHistoryLocation = documentManager.historyDir(documentManager .storagePath(fullFileName, null)); documentManager.deleteFilesRecursively(Paths.get(fileLocation.replace("%20"," "))); documentManager.deleteFilesRecursively(Paths.get(historyLocation.replace("%20"," "))); documentManager.deleteFilesRecursively(Paths.get(convertedHistoryLocation.replace("%20"," "))); return "{ \"success\": true }"; } catch (Exception e) { return "{ \"error\": \"" + e.getMessage() + "\"}"; } } @GetMapping("/download") public ResponseEntity<Resource> download(@RequestParam("fileName") String fileName, HttpServletRequest request){ try{ if(documentTokenManager.tokenEnabled()){ String header = request.getHeader(documentJwtHeader == null || documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader); if(header != null && !header.isEmpty()){ String token = header.startsWith("Bearer ") ? header.substring(7) : header; try { Verifier verifier = HMACVerifier.newVerifier(tokenSecret); JWT.getDecoder().decode(token, verifier); } catch (Exception e) { return null; } } } return downloadFile(fileName); } catch(Exception e){ return null; } } @GetMapping("/create") public String create(@RequestParam("fileExt") String fileExt, @RequestParam(value = "sample", required = false) Optional<Boolean> isSample, @CookieValue(value = "uid", required = false) String uid, Model model){ Boolean sampleData=(isSample.isPresent() && !isSample.isEmpty()) && isSample.get(); if(fileExt!=null){ try{ Optional<User> user = userService.findUserById(Integer.parseInt(uid)); String uname = user.get().getName(); String fileName = documentManager.createDemo(fileExt, sampleData, uid, uname); return "redirect:editor?fileName=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8); }catch (Exception ex){ // return "Error: "+ex.getMessage(); model.addAttribute("error",ex.getMessage()); return "error.html"; } } return "redirect:/"; } @GetMapping("/assets") public ResponseEntity<Resource> assets(@RequestParam("name") String name) { String fileName = "assets/sample/" + fileUtility.getFileName(name); return downloadFile(fileName); } @GetMapping("/csv") public ResponseEntity<Resource> csv() { String fileName = "assets/sample/csv.csv"; return downloadFile(fileName); } @GetMapping("/files") @ResponseBody public ArrayList<Map<String, Object>> files(@RequestParam(value = "fileId", required = false) String fileId){ ArrayList<Map<String, Object>> files = null; if(fileId == null){ files = documentManager.getFilesInfo(); } else { files = documentManager.getFilesInfo(fileId); } return files; } @PostMapping("/track") @ResponseBody public String track(@RequestParam("fileName") String fileName, @RequestParam("userAddress") String userAddress, @RequestBody TrackManagerRequestBody body){ try { JSONObject bodyCheck = trackManager.readBody(body); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } int status = body.getStatus(); int saved = 0; if (status == 1) { //Editing List<ActionObject> actions = body.getActions(); List<String> users = body.getUsers(); ActionObject action = actions.get(0); if (actions != null && action.getType().equals("0")) { //finished edit String user = action.getUserid(); if (users.indexOf(user) == -1) { String key = body.getKey(); try { trackManager.commandRequest("forcesave", key); } catch (Exception e) { e.printStackTrace(); } } } } fileName = fileUtility.getFileName(fileName); if (status == 2 || status == 3) { //MustSave, Corrupted try { trackManager.processSave(body, fileName, userAddress); } catch (Exception ex) { ex.printStackTrace(); saved = 1; } } if (status == 6 || status == 7) { //MustForceSave, CorruptedForceSave try { trackManager.processForceSave(body, fileName, userAddress); } catch (Exception ex) { ex.printStackTrace(); saved = 1; } } return"{\"error\":" + saved + "}"; } }
web/documentserver-example/java-spring/src/main/java/com/onlyoffice/integration/controllers/FileController.java
/** * * (c) Copyright Ascensio System SIA 2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.onlyoffice.integration.controllers; import com.onlyoffice.integration.controllers.objects.ConverterBody; import com.onlyoffice.integration.entities.User; import com.onlyoffice.integration.entities.enums.DocumentType; import com.onlyoffice.integration.services.UserServices; import com.onlyoffice.integration.util.documentManagers.DocumentManagerExts; import com.onlyoffice.integration.util.documentManagers.DocumentTokenManager; import com.onlyoffice.integration.util.fileUtilities.FileUtility; import com.onlyoffice.integration.util.objects.ActionObject; import com.onlyoffice.integration.util.objects.TrackManagerRequestBody; import com.onlyoffice.integration.util.serviceConverter.ServiceConverter; import com.onlyoffice.integration.util.TrackManager; import com.onlyoffice.integration.util.documentManagers.DocumentManager; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.primeframework.jwt.Verifier; import org.primeframework.jwt.domain.JWT; import org.primeframework.jwt.hmac.HMACVerifier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @Controller public class FileController { @Autowired private FileUtility fileUtility; @Autowired private DocumentManager documentManager; @Autowired private DocumentTokenManager documentTokenManager; @Autowired private DocumentManagerExts documentManagerExts; @Autowired private TrackManager trackManager; @Autowired private UserServices userService; @Autowired private ServiceConverter serviceConverter; @Value("${files.docservice.header}") private String documentJwtHeader; @Value("${files.docservice.secret}") private String tokenSecret; private String createUserMetadata(String uid, String fullFileName) throws IOException { Optional<User> optionalUser = userService.findUserById(Integer.parseInt(uid)); String fileName = fileUtility.getFileNameWithoutExtension(fullFileName); String documentType = fileUtility.getDocumentType(fullFileName).toString().toLowerCase(); if(optionalUser.isPresent()){ User user = optionalUser.get(); documentManager.createMeta(fileName, String.valueOf(user.getId()), user.getName(), null); } return "{ \"filename\": \"" + fullFileName + "\", \"documentType\": \"" + documentType + "\" }"; } private ResponseEntity<Resource> downloadFile(String fileName){ String fileLocation = documentManager.forceSavePath(fileName, null, false); if (fileLocation.equals("")){ fileLocation = documentManager.storagePath(fileName, null); } Resource resource = documentManager.loadFileAsResource(fileLocation); String contentType = null; if(contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file, @CookieValue("uid") String uid){ try { String fullFileName = file.getOriginalFilename(); String fileExtension = fileUtility.getFileExtension(fullFileName); long fileSize = file.getSize(); byte[] bytes = file.getBytes(); String directory = documentManager.filesRootPath(null); if(documentManager.getMaxFileSize() < fileSize || fileSize <= 0){ return "{ \"error\": \"File size is incorrect\"}"; } if(!documentManagerExts.getFileExts().contains(fileExtension)){ return "{ \"error\": \"File type is not supported\"}"; } Path path = fileUtility.generateFilepath(directory, fullFileName); String fileName = fileUtility.getFileNameWithoutExtension(path.getFileName().toString()); Files.write(path, bytes); return createUserMetadata(uid, fileName+fileExtension); } catch (Exception e) { e.printStackTrace(); } return "{ \"error\": \"Something went wrong when uploading the file.\"}"; } @PostMapping(path = "${url.converter}") @ResponseBody public String convert(@RequestBody ConverterBody body, @CookieValue("uid") String uid){ String fileName = body.getFileName(); String fileUri = documentManager.getFileUri(fileName, true); String filePass = body.getFilePass() != null ? body.getFilePass() : null; String fileExt = fileUtility.getFileExtension(fileName); DocumentType type = fileUtility.getDocumentType(fileName); String internalFileExt = fileUtility.getInternalExtension(type); try{ if(documentManagerExts.getConvertExts().contains(fileExt)){ String key = serviceConverter.generateRevisionId(fileUri); String newFileUri = serviceConverter .getConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true); if(newFileUri.isEmpty()){ return "{ \"step\" : \"0\", \"filename\" : \"" + fileName + "\"}"; } String correctedName = documentManager .getCorrectName(fileUtility.getFileNameWithoutExtension(fileName)+internalFileExt, null); URL url = new URL(newFileUri); java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); InputStream stream = connection.getInputStream(); if (stream == null) { throw new Exception("Stream is null"); } File convertedFile = new File(documentManager.storagePath(correctedName, null)); try (FileOutputStream out = new FileOutputStream(convertedFile)) { int read; final byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); } connection.disconnect(); fileName = correctedName; } return createUserMetadata(uid, fileName+fileExt); }catch (Exception e) { e.printStackTrace(); } return "{ \"error\": \"" + "The file can't be converted.\"}"; } @PostMapping("/delete") @ResponseBody public String delete(@RequestBody ConverterBody body){ try { String fullFileName = fileUtility.getFileName(body.getFileName()); String fileName = fileUtility.getFileNameWithoutExtension(body.getFileName()); String fileLocation = documentManager.storagePath(fullFileName, null); String historyLocation = documentManager.historyDir(documentManager .storagePath(fileName, null)); String convertedHistoryLocation = documentManager.historyDir(documentManager .storagePath(fullFileName, null)); documentManager.deleteFilesRecursively(Paths.get(fileLocation)); documentManager.deleteFilesRecursively(Paths.get(historyLocation)); documentManager.deleteFilesRecursively(Paths.get(convertedHistoryLocation)); return "{ \"success\": true }"; } catch (Exception e) { return "{ \"error\": \"" + e.getMessage() + "\"}"; } } @GetMapping("/download") public ResponseEntity<Resource> download(@RequestParam("fileName") String fileName, HttpServletRequest request){ try{ if(documentTokenManager.tokenEnabled()){ String header = request.getHeader(documentJwtHeader == null || documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader); if(header != null && !header.isEmpty()){ String token = header.startsWith("Bearer ") ? header.substring(7) : header; try { Verifier verifier = HMACVerifier.newVerifier(tokenSecret); JWT.getDecoder().decode(token, verifier); } catch (Exception e) { return null; } } } return downloadFile(fileName); } catch(Exception e){ return null; } } @GetMapping("/create") public String create(@RequestParam("fileExt") String fileExt, @RequestParam(value = "sample", required = false) Optional<Boolean> isSample, @CookieValue(value = "uid", required = false) String uid, Model model){ Boolean sampleData=(isSample.isPresent() && !isSample.isEmpty()) && isSample.get(); if(fileExt!=null){ try{ Optional<User> user = userService.findUserById(Integer.parseInt(uid)); String uname = user.get().getName(); String fileName = documentManager.createDemo(fileExt, sampleData, uid, uname); return "redirect:editor?fileName=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8); }catch (Exception ex){ // return "Error: "+ex.getMessage(); model.addAttribute("error",ex.getMessage()); return "error.html"; } } return "redirect:/"; } @GetMapping("/assets") public ResponseEntity<Resource> assets(@RequestParam("name") String name) { String fileName = "assets/sample/" + fileUtility.getFileName(name); return downloadFile(fileName); } @GetMapping("/csv") public ResponseEntity<Resource> csv() { String fileName = "assets/sample/csv.csv"; return downloadFile(fileName); } @GetMapping("/files") @ResponseBody public ArrayList<Map<String, Object>> files(@RequestParam(value = "fileId", required = false) String fileId){ ArrayList<Map<String, Object>> files = null; if(fileId == null){ files = documentManager.getFilesInfo(); } else { files = documentManager.getFilesInfo(fileId); } return files; } @PostMapping("/track") @ResponseBody public String track(@RequestParam("fileName") String fileName, @RequestParam("userAddress") String userAddress, @RequestBody TrackManagerRequestBody body){ try { JSONObject bodyCheck = trackManager.readBody(body); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } int status = body.getStatus(); int saved = 0; if (status == 1) { //Editing List<ActionObject> actions = body.getActions(); List<String> users = body.getUsers(); ActionObject action = actions.get(0); if (actions != null && action.getType().equals("0")) { //finished edit String user = action.getUserid(); if (users.indexOf(user) == -1) { String key = body.getKey(); try { trackManager.commandRequest("forcesave", key); } catch (Exception e) { e.printStackTrace(); } } } } fileName = fileUtility.getFileName(fileName); if (status == 2 || status == 3) { //MustSave, Corrupted try { trackManager.processSave(body, fileName, userAddress); } catch (Exception ex) { ex.printStackTrace(); saved = 1; } } if (status == 6 || status == 7) { //MustForceSave, CorruptedForceSave try { trackManager.processForceSave(body, fileName, userAddress); } catch (Exception ex) { ex.printStackTrace(); saved = 1; } } return"{\"error\":" + saved + "}"; } }
java-spring: fix delete file
web/documentserver-example/java-spring/src/main/java/com/onlyoffice/integration/controllers/FileController.java
java-spring: fix delete file
Java
apache-2.0
1242a6c2d5bf0a048137ca30b92cf3ed262a42a3
0
RaffaelBild/arx,arx-deidentifier/arx,arx-deidentifier/arx,RaffaelBild/arx
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2017 Fabian Prasser, Florian Kohlmayer and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.gui.view.impl.utility; import org.deidentifier.arx.gui.Controller; import org.deidentifier.arx.gui.model.ModelEvent; import org.deidentifier.arx.gui.model.ModelEvent.ModelPart; import org.deidentifier.arx.gui.resources.Resources; import org.deidentifier.arx.gui.view.SWTUtil; import org.deidentifier.arx.gui.view.def.ILayout; import org.deidentifier.arx.gui.view.impl.common.DelayedChangeListener; import org.deidentifier.arx.gui.view.impl.common.ViewData; import org.deidentifier.arx.gui.view.impl.common.ViewDataInput; import org.deidentifier.arx.gui.view.impl.common.ViewDataOutput; import org.eclipse.nebula.widgets.nattable.coordinate.PixelCoordinate; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * This class layouts the analysis view. * * @author Fabian Prasser */ public class LayoutUtility implements ILayout { /** * Type of view which is displayed * * @author Fabian Prasser */ public static enum ViewUtilityType { CLASSIFICATION, LOGISTIC_REGRESSION, DATA, CONTINGENCY, CONTINGENCY_TABLE, HISTOGRAM, HISTOGRAM_TABLE, EQUIVALENCE_CLASSES, SUMMARY, PROPERTIES, LOCAL_RECODING } /** Constant */ private static final int WEIGHT_TOP = 75; /** Constant */ private static final int WEIGHT_BOTTOM = 25; /** Constant */ private static final int WEIGHT_LEFT = 50; /** Constant */ private static final int WEIGHT_RIGHT = 50; /** View */ private final Composite centerLeft; /** View */ private final Composite centerRight; /** View */ private final Composite bottomLeft; /** View */ private final Composite bottomRight; /** View */ private final SashForm centerSash; /** View */ private final ViewData dataInputView; /** View */ private final ViewData dataOutputView; /** View */ private final LayoutUtilityStatistics statisticsInputLayout; /** View */ private final LayoutUtilityStatistics statisticsOutputLayout; /** * Creates a new instance. * * @param parent * @param controller */ public LayoutUtility(final Composite parent, final Controller controller) { // Create the SashForm with HORIZONTAL centerSash = new SashForm(parent, SWT.VERTICAL); centerSash.setLayoutData(SWTUtil.createFillGridData()); // Create center composite final Composite center = new Composite(centerSash, SWT.NONE); center.setLayoutData(SWTUtil.createFillGridData()); center.setLayout(SWTUtil.createGridLayoutWithEqualWidth(2)); // Create left composite centerLeft = new Composite(center, SWT.NONE); centerLeft.setLayoutData(SWTUtil.createFillGridData()); centerLeft.setLayout(SWTUtil.createGridLayout(1)); // Create right composite centerRight = new Composite(center, SWT.NONE); centerRight.setLayoutData(SWTUtil.createFillGridData()); centerRight.setLayout(SWTUtil.createGridLayout(1)); // Create views dataInputView = new ViewDataInput(centerLeft, controller, "help.utility.data"); //$NON-NLS-1$ dataOutputView = new ViewDataOutput(centerRight, controller, "help.utility.data"); //$NON-NLS-1$ // Sync tables dataInputView.addScrollBarListener(new Listener() { @Override public void handleEvent(final Event arg0) { synchronize(dataInputView, dataOutputView); } }); dataInputView.addScrollBarListener(new DelayedChangeListener(100) { @Override public void delayedEvent() { synchronize(dataInputView, dataOutputView); } }); dataOutputView.addScrollBarListener(new Listener() { @Override public void handleEvent(final Event arg0) { synchronize(dataOutputView, dataInputView); } }); dataOutputView.addScrollBarListener(new DelayedChangeListener(100) { @Override public void delayedEvent() { synchronize(dataOutputView, dataInputView); } }); Composite classificationInput = dataInputView.createAdditionalItem(Resources.getMessage("StatisticsView.10"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationInput.setLayout(new FillLayout()); new ViewStatisticsClassificationInput(classificationInput, controller); Composite classificationInputROCCurves = dataInputView.createAdditionalItem(Resources.getMessage("StatisticsView.11"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationInputROCCurves.setLayout(new FillLayout()); new ViewStatisticsClassificationROCCurves(classificationInputROCCurves, controller, ModelPart.INPUT); Composite classificationOutput = dataOutputView.createAdditionalItem(Resources.getMessage("StatisticsView.10"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationOutput.setLayout(new FillLayout()); new ViewStatisticsClassificationOutput(classificationOutput, controller); Composite classificationOutputROCCurves = dataOutputView.createAdditionalItem(Resources.getMessage("StatisticsView.11"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationOutputROCCurves.setLayout(new FillLayout()); new ViewStatisticsClassificationROCCurves(classificationOutputROCCurves, controller, ModelPart.OUTPUT); // Create bottom composite final Composite compositeBottom = new Composite(centerSash, SWT.NONE); compositeBottom.setLayout(new FillLayout()); final SashForm bottomSash = new SashForm(compositeBottom, SWT.HORIZONTAL | SWT.SMOOTH); bottomLeft = new Composite(bottomSash, SWT.NONE); bottomLeft.setLayout(new FillLayout()); bottomRight = new Composite(bottomSash, SWT.NONE); bottomRight.setLayout(new FillLayout()); statisticsInputLayout = new LayoutUtilityStatistics(bottomLeft, controller, ModelPart.INPUT, null); statisticsOutputLayout = new LayoutUtilityStatistics(bottomRight, controller, ModelPart.OUTPUT, ModelPart.INPUT); // Sync folders dataInputView.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { dataOutputView.setSelectionIndex(dataInputView.getSelectionIndex()); // Hack to show summary for input if (dataInputView.getSelectionIndex() == 0) { statisticsInputLayout.setSelectedView(ViewUtilityType.SUMMARY); statisticsOutputLayout.setSelectedView(ViewUtilityType.SUMMARY); } // Hack to show classification stuff if (dataInputView.getSelectionIndex() == 1 || dataInputView.getSelectionIndex() == 2) { statisticsInputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); statisticsOutputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); dataOutputView.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { dataInputView.setSelectionIndex(dataOutputView.getSelectionIndex()); // Hack to show summary for output if (dataOutputView.getSelectionIndex() == 0) { statisticsInputLayout.setSelectedView(ViewUtilityType.SUMMARY); statisticsOutputLayout.setSelectedView(ViewUtilityType.SUMMARY); } // Hack to show classification stuff if (dataOutputView.getSelectionIndex() == 1 || dataOutputView.getSelectionIndex() == 2) { statisticsInputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); statisticsOutputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsInputLayout.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsOutputLayout.setSelectedView(statisticsInputLayout.getSelectedView()); // Hack to show classification stuff if (statisticsInputLayout.getSelectedView() == ViewUtilityType.CLASSIFICATION) { dataOutputView.setSelectionIndex(1); dataInputView.setSelectionIndex(1); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsOutputLayout.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsInputLayout.setSelectedView(statisticsOutputLayout.getSelectedView()); // Hack to show classification stuff if (statisticsOutputLayout.getSelectedView() == ViewUtilityType.CLASSIFICATION) { dataOutputView.setSelectionIndex(1); dataInputView.setSelectionIndex(1); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsInputLayout.setItemVisibilityListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsOutputLayout.setVisibleItems(statisticsInputLayout.getVisibleItems()); // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsOutputLayout.setItemVisibilityListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsInputLayout.setVisibleItems(statisticsOutputLayout.getVisibleItems()); // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); // Set sash weights centerSash.setWeights(new int[] { WEIGHT_TOP, WEIGHT_BOTTOM }); bottomSash.setWeights(new int[] { WEIGHT_LEFT, WEIGHT_RIGHT }); // Fix resize bug SWTUtil.fixOSXSashBug(centerSash); SWTUtil.fixOSXSashBug(bottomSash); } /** * Synchronizes the position of both tables * @param in * @param out * @return */ private void synchronize(ViewData in, ViewData out) { if (in == null || out == null) { return; } PixelCoordinate coordinate = in.getViewportLayer().getOrigin(); final int x = coordinate.getY(); final int y = coordinate.getX(); out.getViewportLayer().setOriginY(x); out.getViewportLayer().setOriginX(y); } }
src/gui/org/deidentifier/arx/gui/view/impl/utility/LayoutUtility.java
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2017 Fabian Prasser, Florian Kohlmayer and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.gui.view.impl.utility; import org.deidentifier.arx.gui.Controller; import org.deidentifier.arx.gui.model.ModelEvent; import org.deidentifier.arx.gui.model.ModelEvent.ModelPart; import org.deidentifier.arx.gui.resources.Resources; import org.deidentifier.arx.gui.view.SWTUtil; import org.deidentifier.arx.gui.view.def.ILayout; import org.deidentifier.arx.gui.view.impl.common.DelayedChangeListener; import org.deidentifier.arx.gui.view.impl.common.ViewData; import org.deidentifier.arx.gui.view.impl.common.ViewDataInput; import org.deidentifier.arx.gui.view.impl.common.ViewDataOutput; import org.eclipse.nebula.widgets.nattable.coordinate.PixelCoordinate; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * This class layouts the analysis view. * * @author Fabian Prasser */ public class LayoutUtility implements ILayout { /** * Type of view which is displayed * * @author Fabian Prasser */ public static enum ViewUtilityType { CLASSIFICATION, LOGISTIC_REGRESSION, DATA, CONTINGENCY, CONTINGENCY_TABLE, HISTOGRAM, HISTOGRAM_TABLE, EQUIVALENCE_CLASSES, SUMMARY, PROPERTIES, LOCAL_RECODING } /** Constant */ private static final int WEIGHT_TOP = 75; /** Constant */ private static final int WEIGHT_BOTTOM = 25; /** Constant */ private static final int WEIGHT_LEFT = 50; /** Constant */ private static final int WEIGHT_RIGHT = 50; /** View */ private final Composite centerLeft; /** View */ private final Composite centerRight; /** View */ private final Composite bottomLeft; /** View */ private final Composite bottomRight; /** View */ private final SashForm centerSash; /** View */ private final ViewData dataInputView; /** View */ private final ViewData dataOutputView; /** View */ private final LayoutUtilityStatistics statisticsInputLayout; /** View */ private final LayoutUtilityStatistics statisticsOutputLayout; /** * Creates a new instance. * * @param parent * @param controller */ public LayoutUtility(final Composite parent, final Controller controller) { // Create the SashForm with HORIZONTAL centerSash = new SashForm(parent, SWT.VERTICAL); centerSash.setLayoutData(SWTUtil.createFillGridData()); // Create center composite final Composite center = new Composite(centerSash, SWT.NONE); center.setLayoutData(SWTUtil.createFillGridData()); center.setLayout(SWTUtil.createGridLayoutWithEqualWidth(2)); // Create left composite centerLeft = new Composite(center, SWT.NONE); centerLeft.setLayoutData(SWTUtil.createFillGridData()); centerLeft.setLayout(SWTUtil.createGridLayout(1)); // Create right composite centerRight = new Composite(center, SWT.NONE); centerRight.setLayoutData(SWTUtil.createFillGridData()); centerRight.setLayout(SWTUtil.createGridLayout(1)); // Create views dataInputView = new ViewDataInput(centerLeft, controller, "help.utility.data"); //$NON-NLS-1$ dataOutputView = new ViewDataOutput(centerRight, controller, "help.utility.data"); //$NON-NLS-1$ // Sync tables dataInputView.addScrollBarListener(new Listener() { @Override public void handleEvent(final Event arg0) { synchronize(dataInputView, dataOutputView); } }); dataInputView.addScrollBarListener(new DelayedChangeListener(100) { @Override public void delayedEvent() { synchronize(dataInputView, dataOutputView); } }); dataOutputView.addScrollBarListener(new Listener() { @Override public void handleEvent(final Event arg0) { synchronize(dataOutputView, dataInputView); } }); dataOutputView.addScrollBarListener(new DelayedChangeListener(100) { @Override public void delayedEvent() { synchronize(dataOutputView, dataInputView); } }); Composite classificationInput = dataInputView.createAdditionalItem(Resources.getMessage("StatisticsView.10"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationInput.setLayout(new FillLayout()); new ViewStatisticsClassificationInput(classificationInput, controller); Composite classificationInputROCCurves = dataInputView.createAdditionalItem(Resources.getMessage("StatisticsView.11"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationInputROCCurves.setLayout(new FillLayout()); new ViewStatisticsClassificationROCCurves(classificationInputROCCurves, controller, ModelPart.INPUT); Composite classificationOutput = dataOutputView.createAdditionalItem(Resources.getMessage("StatisticsView.10"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationOutput.setLayout(new FillLayout()); new ViewStatisticsClassificationOutput(classificationOutput, controller); Composite classificationOutputROCCurves = dataOutputView.createAdditionalItem(Resources.getMessage("StatisticsView.11"), "help.utility.accuracy"); //$NON-NLS-1$ //$NON-NLS-2$ classificationOutputROCCurves.setLayout(new FillLayout()); new ViewStatisticsClassificationROCCurves(classificationOutputROCCurves, controller, ModelPart.OUTPUT); // Create bottom composite final Composite compositeBottom = new Composite(centerSash, SWT.NONE); compositeBottom.setLayout(new FillLayout()); final SashForm bottomSash = new SashForm(compositeBottom, SWT.HORIZONTAL | SWT.SMOOTH); bottomLeft = new Composite(bottomSash, SWT.NONE); bottomLeft.setLayout(new FillLayout()); bottomRight = new Composite(bottomSash, SWT.NONE); bottomRight.setLayout(new FillLayout()); statisticsInputLayout = new LayoutUtilityStatistics(bottomLeft, controller, ModelPart.INPUT, null); statisticsOutputLayout = new LayoutUtilityStatistics(bottomRight, controller, ModelPart.OUTPUT, ModelPart.INPUT); // Sync folders dataInputView.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { dataOutputView.setSelectionIndex(dataInputView.getSelectionIndex()); // Hack to show classification stuff if (dataInputView.getSelectionIndex()==1) { statisticsInputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); statisticsOutputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); dataOutputView.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { dataInputView.setSelectionIndex(dataOutputView.getSelectionIndex()); // Hack to show classification stuff if (dataOutputView.getSelectionIndex()==1) { statisticsInputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); statisticsOutputLayout.setSelectedView(ViewUtilityType.CLASSIFICATION); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsInputLayout.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsOutputLayout.setSelectedView(statisticsInputLayout.getSelectedView()); // Hack to show classification stuff if (statisticsInputLayout.getSelectedView() == ViewUtilityType.CLASSIFICATION) { dataOutputView.setSelectionIndex(1); dataInputView.setSelectionIndex(1); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsOutputLayout.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsInputLayout.setSelectedView(statisticsOutputLayout.getSelectedView()); // Hack to show classification stuff if (statisticsOutputLayout.getSelectedView() == ViewUtilityType.CLASSIFICATION) { dataOutputView.setSelectionIndex(1); dataInputView.setSelectionIndex(1); } // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsInputLayout.setItemVisibilityListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsOutputLayout.setVisibleItems(statisticsInputLayout.getVisibleItems()); // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); statisticsOutputLayout.setItemVisibilityListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent arg0) { statisticsInputLayout.setVisibleItems(statisticsOutputLayout.getVisibleItems()); // Hack to update visualizations controller.update(new ModelEvent(this, ModelPart.SELECTED_UTILITY_VISUALIZATION, null)); } }); // Set sash weights centerSash.setWeights(new int[] { WEIGHT_TOP, WEIGHT_BOTTOM }); bottomSash.setWeights(new int[] { WEIGHT_LEFT, WEIGHT_RIGHT }); // Fix resize bug SWTUtil.fixOSXSashBug(centerSash); SWTUtil.fixOSXSashBug(bottomSash); } /** * Synchronizes the position of both tables * @param in * @param out * @return */ private void synchronize(ViewData in, ViewData out) { if (in == null || out == null) { return; } PixelCoordinate coordinate = in.getViewportLayer().getOrigin(); final int x = coordinate.getY(); final int y = coordinate.getX(); out.getViewportLayer().setOriginY(x); out.getViewportLayer().setOriginX(y); } }
Synchchronize views for input/output, classification, roc curves
src/gui/org/deidentifier/arx/gui/view/impl/utility/LayoutUtility.java
Synchchronize views for input/output, classification, roc curves
Java
apache-2.0
f694b70d38e7f59410e215fa6e503c6dbbed87a7
0
psoreide/bnd,psoreide/bnd,psoreide/bnd
package aQute.bnd.main; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.BufferedReader; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import aQute.bnd.build.Container; import aQute.bnd.build.Project; import aQute.bnd.build.ProjectBuilder; import aQute.bnd.build.ProjectLauncher; import aQute.bnd.build.ProjectTester; import aQute.bnd.build.Run; import aQute.bnd.build.Workspace; import aQute.bnd.enroute.commands.EnrouteCommand; import aQute.bnd.enroute.commands.EnrouteOptions; import aQute.bnd.header.Attrs; import aQute.bnd.header.OSGiHeader; import aQute.bnd.header.Parameters; import aQute.bnd.help.Syntax; import aQute.bnd.main.BaselineCommands.baseLineOptions; import aQute.bnd.main.BaselineCommands.schemaOptions; import aQute.bnd.main.DiffCommand.diffOptions; import aQute.bnd.main.RepoCommand.repoOptions; import aQute.bnd.maven.MavenCommand; import aQute.bnd.maven.PomFromManifest; import aQute.bnd.osgi.About; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Builder; import aQute.bnd.osgi.Clazz; import aQute.bnd.osgi.Clazz.Def; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Descriptors.PackageRef; import aQute.bnd.osgi.Descriptors.TypeRef; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.FileResource; import aQute.bnd.osgi.Instruction; import aQute.bnd.osgi.Instructions; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.Macro; import aQute.bnd.osgi.Packages; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.Resource; import aQute.bnd.osgi.Verifier; import aQute.bnd.osgi.eclipse.EclipseClasspath; import aQute.bnd.repository.maven.provider.NexusCommand; import aQute.bnd.service.Actionable; import aQute.bnd.service.RepositoryPlugin; import aQute.bnd.service.action.Action; import aQute.bnd.service.repository.InfoRepository; import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor; import aQute.bnd.version.Version; import aQute.bnd.version.VersionRange; import aQute.configurable.Config; import aQute.lib.base64.Base64; import aQute.lib.collections.ExtList; import aQute.lib.collections.MultiMap; import aQute.lib.collections.SortedList; import aQute.lib.filter.Filter; import aQute.lib.getopt.Arguments; import aQute.lib.getopt.CommandLine; import aQute.lib.getopt.Description; import aQute.lib.getopt.Options; import aQute.lib.hex.Hex; import aQute.lib.io.IO; import aQute.lib.justif.Justif; import aQute.lib.settings.Settings; import aQute.lib.strings.Strings; import aQute.lib.tag.Tag; import aQute.lib.utf8properties.UTF8Properties; import aQute.libg.classdump.ClassDumper; import aQute.libg.cryptography.MD5; import aQute.libg.cryptography.SHA1; import aQute.libg.forker.Forker; import aQute.libg.generics.Create; import aQute.libg.glob.Glob; import aQute.libg.qtokens.QuotedTokenizer; import aQute.libg.reporter.ReporterAdapter; import aQute.libg.reporter.ReporterMessages; import aQute.libg.sed.Sed; import aQute.service.reporter.Reporter; /** * Utility to make bundles. @version $Revision: 1.14 $ */ public class bnd extends Processor { private final static Logger logger = LoggerFactory.getLogger(bnd.class); static Pattern ASSIGNMENT = Pattern.compile( // "([^=]+) (= ( ?: (\"|'|) (.+) \\3 )? ) ?", Pattern.COMMENTS); Settings settings = new Settings(); final PrintStream err = System.err; final public PrintStream out = System.out; Justif justif = new Justif(80, 40, 42, 70); BndMessages messages = ReporterMessages.base(this, BndMessages.class); private Workspace ws; private char[] password; private static final ThreadLocal<Boolean> noExit = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; }; }; private static final String DEFAULT_LOG_LEVEL_KEY = "org.slf4j.simpleLogger.defaultLogLevel"; static Pattern JARCOMMANDS = Pattern .compile("(cv?0?(m|M)?f?)|(uv?0?M?f?)|(xv?f?)|(tv?f?)|(i)"); static Pattern COMMAND = Pattern.compile("\\w[\\w\\d]+"); static Pattern EMAIL_P = Pattern.compile( "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", Pattern.CASE_INSENSITIVE); @Description("OSGi Bundle Tool") interface bndOptions extends Options { @Description("Turns errors into warnings so command always succeeds") boolean failok(); @Description("Report errors pedantically") boolean pedantic(); @Description("Print out stack traces when there is an unexpected exception") boolean exceptions(); @Description("Redirect output") File output(); @Description("Use as base directory") String base(); @Description("Trace progress") boolean trace(); @Description("Error/Warning ignore patterns") String[] ignore(); @Description("Provide a settings password") char[] secret(); } public bnd(Workspace ws) { super(ws); } public bnd() {} public static void main(String args[]) throws Exception { Workspace.setDriver(Constants.BNDDRIVER_BND); Workspace.addGestalt(Constants.GESTALT_SHELL, null); Workspace.addGestalt(Constants.GESTALT_INTERACTIVE, null); Workspace ws = Workspace.findWorkspace(IO.work); try (bnd main = new bnd()) { // ws == null ? new bnd() : new bnd(ws); main.start(args); } exitWithCode(0); } /** * For testing */ static void mainNoExit(String args[]) throws Exception { noExit.set(true); main(args); } public void start(String args[]) throws Exception { CommandLine cl = new CommandLine(this); String help = cl.execute(this, "bnd", new ExtList<>(args)); check(); if (help != null) err.println(help); } /** * Rewrite the command line to mimic the jar command * * @param args * @throws Exception */ private void rewrite(List<String> args) throws Exception { if (args.isEmpty()) return; String arg = args.get(0); if (arg.equals("maven")) { // ensure that we do not much with options // because the maven command does not like // that args.add(0, "maven"); return; } if (arg.equals("-version")) { args.set(0, "version"); return; } Matcher m = JARCOMMANDS.matcher(arg); if (m.matches()) { rewriteJarCmd(args); return; } // Project project = getProject(); // if (project != null) { // Action a = project.getActions().get(arg); // if (a != null) { // args.add(0, "project"); // } // } m = COMMAND.matcher(args.get(0)); if (!m.matches()) { args.add(0, "do"); } } private void rewriteJarCmd(List<String> args) { String jarcmd = args.remove(0); char cmd = jarcmd.charAt(0); switch (cmd) { case 'c' : args.add(0, "create"); break; case 'u' : args.add(0, "update"); break; case 'x' : args.add(0, "extract"); break; case 't' : args.add(0, "type"); break; case 'i' : args.add(0, "index"); break; } int start = 1; for (int i = 1; i < jarcmd.length(); i++) { switch (jarcmd.charAt(i)) { case 'v' : args.add(start++, "--verbose"); break; case '0' : args.add(start++, "--nocompression"); break; case 'm' : args.add(start++, "--manifest"); start++; // make the manifest file the parameter break; case 'M' : args.add(start++, "--nomanifest"); break; case 'f' : args.add(start++, "--file"); break; } } } /** * Main command. This has options the bnd base options and will then run * another command. * * @param options * @throws Exception */ @Description("The swiss army tool for OSGi") public void _bnd(bndOptions options) throws Exception { try { set(FAIL_OK, options.failok() + ""); setExceptions(options.exceptions()); setTrace(options.trace()); if (options.trace()) { System.setProperty(DEFAULT_LOG_LEVEL_KEY, "trace"); } else { System.setProperty(DEFAULT_LOG_LEVEL_KEY, "warn"); } setPedantic(options.pedantic()); if (options.base() != null) setBase(getFile(getBase(), options.base())); // And the properties for (Entry<String, String> entry : options._properties() .entrySet()) { setProperty(entry.getKey(), entry.getValue()); } CommandLine handler = options._command(); List<String> arguments = options._arguments(); // Rewrite command line to match jar commands and // handle commands that provide file names rewrite(arguments); logger.debug("rewritten {}", arguments); if (arguments.isEmpty()) { Justif f = new Justif(80, 20, 22, 72); handler.help(f.formatter(), this); err.append(f.wrap()); } else { String cmd = arguments.remove(0); String help = handler.execute(this, cmd, arguments); if (help != null) { err.println(help); } } if (options.secret() != null) { password = options.secret(); settings.load(password); } } catch (Throwable t) { while (t instanceof InvocationTargetException) t = t.getCause(); exception(t, "%s", t); } out.flush(); err.flush(); if (ws != null) getInfo(ws); if (!check(options.ignore())) { System.err.flush(); System.err.flush(); Thread.sleep(1000); exitWithCode(getErrors().size()); } } /** * Options for the jar create command. */ @Description("Equivalent jar command c[v0mf] command (supports the jar tool's syntax). Will wrap the bundle unless --wrapnot is specified") interface createOptions extends Options { @Description("Verbose (v option)") boolean verbose(); @Description("No compression (0 option)") boolean nocompression(); @Description("No manifest (M option)") boolean Manifest(); @Description("Use manifest (m option)") String manifest(); @Description("Jar file (f option)") String file(); @Description("directory") String cdir(); @Description("Wrap") boolean wrap(); @Description("Properties for wrapping") String properties(); @Description("Bundle Symbolic Name for wrap") String bsn(); @Description("Bundle Version for wrap") Version version(); @Description("Force write event if there are errors") boolean force(); } /** * Create jar file * * <pre> * jar c[v0M]f jarfile [-C dir] inputfiles [-Joption] * jar c[v0]mf manifest jarfile [-C dir] inputfiles [-Joption] jar c[v0M] * [-C dir] inputfiles [-Joption] jar c[v0]m manifest [-C dir] inputfiles * [-Joption] * </pre> * * @param options * @throws Exception */ @Description("Create jar, used to support backward compatible java jar commands") public void _create(createOptions options) throws Exception { Jar jar = new Jar("dot"); File dir = getBase().getAbsoluteFile(); String sdir = options.cdir(); if (sdir != null) dir = getFile(sdir); if (options._arguments() .isEmpty()) add(jar, dir, ".", options.verbose()); else for (String f : options._arguments()) { f = IO.normalizePath(f); add(jar, dir, f, options.verbose()); } String manifest = options.manifest(); if (manifest != null) { if (options.verbose()) err.printf("Adding manifest from %s\n", manifest); jar.setManifest(getFile(manifest)); } if (options.Manifest()) { jar.setManifest((Manifest) null); } else { if (options.wrap()) { Analyzer w = new Analyzer(this); addClose(w); w.setBase(getBase()); w.use(this); w.setDefaults(options.bsn(), options.version()); w.calcManifest(); getInfo(w); w.setJar((Jar) null); w.close(); } } if (options.nocompression()) jar.setCompression(Jar.Compression.STORE); if (isOk()) { String jarFile = options.file(); if (jarFile == null) jar.write(System.out); else jar.write(jarFile); } jar.close(); } /** * Helper for the jar create function, adds files to the jar * * @param jar * @param base * @param path * @param report * @throws IOException */ private void add(Jar jar, File base, String path, boolean report) throws IOException { if (path.endsWith("/")) path = path.substring(0, path.length() - 1); File f; if (path.equals(".")) f = base; else f = getFile(base, path); err.printf("Adding: %s\n", path); if (f.isFile()) { jar.putResource(path, new FileResource(f)); } else if (f.isDirectory()) { if (path.equals(".")) path = ""; else path += "/"; String[] subs = f.list(); for (String sub : subs) { add(jar, base, path + sub, report); } } } /** * Extract a file from the JAR */ @Description("Extract files from a JAR file, equivalent jar command x[vf] (syntax supported)") interface extractOptions extends Options { @Description("Verbose (v option)") boolean verbose(); @Description("Jar file (f option)") String file(); @Description("Directory where to store") String cdir(); } @Description("Extract files from a JAR file, equivalent jar command x[vf] (syntax supported)") public void _extract(extractOptions opts) throws Exception { Jar jar; if (opts.file() != null) { File f = getFile(opts.file()); if (!f.isFile()) { messages.NoSuchFile_(f); return; } jar = new Jar(f); } else { jar = new Jar("cin", System.in); } try { Instructions instructions = new Instructions(opts._arguments()); Collection<String> selected = instructions.select(jar.getResources() .keySet(), true); File store = getBase(); if (opts.cdir() != null) store = getFile(opts.cdir()); IO.mkdirs(store); Jar.Compression compression = jar.hasCompression(); for (String path : selected) { if (opts.verbose()) System.err.printf("%8s: %s\n", compression.toString() .toLowerCase(), path); File f = getFile(store, path); File pf = f.getParentFile(); IO.mkdirs(pf); Resource r = jar.getResource(path); IO.copy(r.openInputStream(), f); } } finally { jar.close(); } } /** * List the contents of the JAR */ @Description("List files int a JAR file, equivalent jar command t[vf] (syntax supported)") interface typeOptions extends Options { @Description("Verbose (v option)") boolean verbose(); @Description("Jar file (f option)") String file(); } @Description("List files int a JAR file, equivalent jar command t[vf] (syntax supported)") public void _type(typeOptions opts) throws Exception { Jar jar; if (opts.file() != null) { File f = getFile(opts.file()); if (!f.isFile()) { messages.NoSuchFile_(f); return; } jar = new Jar(f); } else { jar = new Jar("cin", System.in); } try { Instructions instructions = new Instructions(opts._arguments()); Collection<String> selected = instructions.select(jar.getResources() .keySet(), true); for (String path : selected) { if (opts.verbose()) { Resource r = jar.getResource(path); err.printf("%8s %-32s %s\n", r.size(), new Date(r.lastModified()), path); } else err.printf("%s\n", path); } } finally { jar.close(); } } @Description("Execute a file based on its extension. Supported extensions are: bnd (build), bndrun (run), and jar (print)") interface dooptions extends Options { @Description("The output file") String output(); @Description("Force even when there are errors") boolean force(); } /** * The do command interprets files and does a default action for each file * * @throws Exception */ @Description("Execute a file based on its extension. Supported extensions are: bnd (build), bndrun (run), and jar (print)") public void _do(dooptions options) throws Exception { for (String path : options._arguments()) { if (path.endsWith(Constants.DEFAULT_BND_EXTENSION)) { build(options.output(), options.force(), path); } else if (path.endsWith(Constants.DEFAULT_JAR_EXTENSION) || path.endsWith(Constants.DEFAULT_BAR_EXTENSION)) { try (Jar jar = getJar(path)) { doPrint(jar, MANIFEST, null); } } else if (path.endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { doRun(Arrays.asList(path), false, null); } else messages.UnrecognizedFileType_(path); } } public void build(String dest, boolean force, String path) throws IOException, Exception { try (Builder b = new Builder()) { File f = getFile(path); if (!f.isFile()) { error("No such file %s", f); return; } b.use(this); b.setProperties(f); List<Builder> subs = b.getSubBuilders(); for (Builder bb : subs) { logger.debug("building {}", bb.getPropertiesFile()); bb.build(); File out = bb.getOutputFile(dest); getInfo(bb, bb.getBsn() + ": "); if (isOk()) { bb.save(out, force); } getInfo(bb, bb.getBsn() + ": "); // pickup any save errors if (!isOk()) { IO.delete(out); } } } } /** * Project command, executes actions. */ @Description("Execute a Project action, or if no parms given, show information about the project") @Arguments(arg = {}) interface projectOptions extends Options { @Description("Identify another project") String project(); } @Description("Execute a Project action, or if no parms given, show information about the project") public void _project(projectOptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } List<String> l = new ArrayList<>(options._arguments()); if (l.isEmpty()) { err.printf("Name %s\n", project.getName()); err.printf("Actions %s\n", project.getActions() .keySet()); err.printf("Directory %s\n", project.getBase()); err.printf("Depends on %s\n", project.getDependson()); try (ProjectBuilder pb = project.getBuilder(null)) { err.printf("Sub builders %s\n", pb.getSubBuilders()); } return; } String cmd = null; String arg = null; if (!l.isEmpty()) cmd = l.remove(0); if (!l.isEmpty()) arg = l.remove(0); if (!l.isEmpty()) { messages.MoreArgumentsThanNeeded_(options._arguments()); return; } if (cmd == null) { messages.NoCommandForProject(project); return; } Action a = project.getActions() .get(cmd); if (a != null) { a.execute(project, arg); getInfo(project); return; } } @Description("Bumps the version of a project. Will take the current version and then increment " + "with a major, minor, or micro increment. The default bump is minor.") @Arguments(arg = "<major|minor|micro>") interface bumpoptions extends Options { @Description("Path to another project than the current project") String project(); } /** * Bump a version number * * @throws Exception */ @Description("Bumps the version of a project") public void _bump(bumpoptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } String mask = null; if (!options._arguments() .isEmpty()) { mask = options._arguments() .get(0); if (mask.equalsIgnoreCase("major")) mask = "+00"; else if (mask.equalsIgnoreCase("minor")) mask = "=+0"; else if (mask.equalsIgnoreCase("micro")) mask = "==+"; else if (!mask.matches("[+=0]{1,3}")) { messages.InvalidBumpMask_(mask); return; } } if (mask == null) project.bump(); else project.bump(mask); getInfo(project); err.println(project.getProperty(BUNDLE_VERSION, "No version found")); } interface PerProject { void doit(Project p) throws Exception; } public void perProject(projectOptions opts, PerProject run) throws Exception { Collection<Project> list; Project project = getProject(opts.project()); if (project == null) { Workspace ws = Workspace.findWorkspace(getBase()); if (!ws.isValid()) { messages.NoValidWorkspace(getBase()); } list = ws.getAllProjects(); if (list.isEmpty()) { out.println("No projects"); } } else { list = Arrays.asList(project); } for (Project p : list) { run.doit(p); getInfo(p, p + ": "); } } @Description("Build a project. This will create the jars defined in the bnd.bnd and sub-builders.") @Arguments(arg = {}) interface buildoptions extends projectOptions { @Description("Build for test") boolean test(); @Description("Do full") boolean full(); } @Description("Build a project. This will create the jars defined in the bnd.bnd and sub-builders.") public void _build(final buildoptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project p) throws Exception { p.build(opts.test()); } }); } @Arguments(arg = {}) interface CompileOptions extends projectOptions { @Description("Compile for test") boolean test(); } @Description("Compile a project or the workspace") public void _compile(final CompileOptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project p) throws Exception { p.compile(opts.test()); } }); } @Description("Test a project according to an OSGi test") @Arguments(arg = { "testclass[:method]..." }) interface testOptions extends projectOptions { @Description("Verify all the dependencies before launching (runpath, runbundles, testpath)") boolean verify(); @Description("Launch the test even if this bundle does not contain " + Constants.TESTCASES) boolean force(); @Description("Set the -testcontinuous flag") boolean continuous(); @Description("Set the -runtrace flag") boolean trace(); } @Description("Test a project according to an OSGi test") public void _test(final testOptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project project) throws Exception { List<String> testNames = opts._arguments(); if (!testNames.isEmpty()) project.setProperty(TESTCASES, ""); if (project.is(NOJUNITOSGI) && !opts.force()) { warning("%s is set to true on this bundle. Use -f/--force to try this test anyway", NOJUNITOSGI); return; } if (project.getProperty(TESTCASES) == null) if (opts.force()) project.setProperty(TESTCASES, ""); else { warning( "No %s set on this bundle. Use -f/--force to try this test anyway (this works if another bundle provides the testcases)", TESTCASES); return; } if (opts.continuous()) project.setProperty(TESTCONTINUOUS, "true"); if (opts.trace() || isTrace()) project.setProperty(RUNTRACE, "true"); project.test(testNames); } }); } @Description("Test a project with plain JUnit") public void _junit(testOptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project p) throws Exception { p.junit(); } }); } private boolean verifyDependencies(Project project, boolean implies, boolean test) throws Exception { if (!implies) { return true; } project.verifyDependencies(test); getInfo(project); if (isOk()) return true; return false; } @Description("Run a project in the OSGi launcher. If not bndrun is specified, the current project is used for the run specification") @Arguments(arg = "[bndrun]") interface runOptions extends Options { @Description("Path to another project than the current project. Only valid if no bndrun is specified") String project(); @Description("Verify all the dependencies before launching (runpath, runbundles)") boolean verify(); } @Description("Run a project in the OSGi launcher") public void _run(runOptions opts) throws Exception { doRun(opts._arguments(), opts.verify(), opts.project()); } private void doRun(List<String> args, boolean verify, String project) throws Exception { Project run = null; if (args.isEmpty()) { run = getProject(project); if (run == null) { messages.NoProject(); return; } } else { File f = getFile(args.get(0)); File dir = f.getParentFile(); File wsdir = dir.getParentFile(); if (wsdir == null) { // We are in the filesystem root?? Create a standalone run. run = Run.createRun(null, f); } else { Workspace workspace = Workspace.getWorkspaceWithoutException(wsdir); run = Run.createRun(workspace, f); } } verifyDependencies(run, verify, false); try { run.run(); } catch (Exception e) { messages.Failed__(e, "Running " + run); } getInfo(run); getInfo(run.getWorkspace()); } @Description("Clean a project") interface cleanOptions extends projectOptions { } @Description("Clean a project or workspace") public void _clean(cleanOptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project p) throws Exception { p.clean(); } }); } @Description("Access the internal bnd database of keywords and options") @Arguments(arg = { "header|instruction", "..." }) interface syntaxOptions extends Options { @Description("The width of the printout") int width(); } @Description("Access the internal bnd database of keywords and options") public void _syntax(syntaxOptions opts) throws Exception { int w = opts.width() < 80 ? 120 : opts.width(); Justif justif = new Justif(w, opts.width(), 40, 42, w - 10); List<String> args = opts._arguments(); StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); for (String s : args) { f.format(" \n[%s]\n", s); Syntax sx = Syntax.HELP.get(s); if (s == null) f.format("Unknown"); else { print(f, sx, " "); } } f.flush(); justif.wrap(sb); err.println(sb); } private void print(Formatter f, Syntax sx, String indent) { if (sx == null) return; f.format("%s%s\n\n", indent, sx.getLead()); if (sx.getValues() != null) f.format("%sValues\t1:\t2%s\n", indent, sx.getValues()); if (sx.getPattern() != null) f.format("%sPattern \t1:\t2%s\n", indent, sx.getPattern()); if (sx.getExample() != null) f.format("%sExample \t1:\t2%s\n", indent, sx.getExample()); if (sx.getChildren() != null) { for (Syntax child : sx.getChildren()) { f.format("\n%s[%s]\t1:\t2", indent, child.getHeader()); print(f, child, indent + " "); } } } @Description("Package a bnd or bndrun file into a single jar that executes with java -jar <>.jar. The JAR contains all dependencies, including the framework and the launcher. " + "A profile can be specified which will be used to find properties. If a property is not found, a property with the name [<profile>]NAME will be looked up. This allows " + "you to make different profiles for testing and runtime.") @Arguments(arg = { "<bnd|bndrun>", "[...]" }) interface packageOptions extends Options { @Description("Where to store the resulting file. Default the name of the bnd file with a .jar extension.") String output(); @Description("Profile name. Default no profile") String profile(); } /** * Package a bnd or bndrun file for packaging. * * @throws Exception */ @Description("Package a bnd or bndrun file into a single jar that executes with java -jar <>.jar") public void _package(packageOptions opts) throws Exception { List<String> cmdline = opts._arguments(); File output = null; if (opts.output() != null) { output = getFile(opts.output()); } else output = getBase(); if (opts._arguments() .size() > 1) { IO.mkdirs(output); } else { File pf = output.getParentFile(); IO.mkdirs(pf); } String profile = opts.profile() == null ? "exec" : opts.profile(); if (cmdline.isEmpty()) cmdline.add(Project.BNDFILE); // default project itself for (String path : cmdline) { Run run; File file = getFile(path); if (file.isDirectory()) file = new File(file, Project.BNDFILE); if (!file.isFile()) { messages.NoSuchFile_(file); continue; } File dir = file.getParentFile(); File workspaceDir = dir.getParentFile(); if (workspaceDir == null) { // We are in the filesystem root?? Create a standalone run. run = Run.createRun(null, file); } else { Workspace ws = Workspace.getWorkspaceWithoutException(workspaceDir); run = Run.createRun(ws, file); } // Tricky because we can be run inside the context of a // project (in which case // we need to inherit from the project or outside. run.setProperty(PROFILE, profile); run.use(this); try { Jar jar = run.pack(profile); path = path.replaceAll(".bnd(run)?$", "") + ".jar"; File out = output; if (output.isDirectory()) out = new File(output, path); jar.write(out); jar.close(); } catch (Exception e) { messages.ForProject_File_FailedToCreateExecutableException_(run, path, e); } getInfo(run); } } /** * List all deliverables for this workspace. */ @Description("Show all deliverables from this workspace. with their current version and path.") @Arguments(arg = {}) interface deliverableOptions extends Options { @Description("Path to project, default current directory") String project(); @Description("Only provide deliverables of this project") boolean limit(); } @Description("Show all deliverables from this workspace. with their current version and path.") public void _deliverables(deliverableOptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } Collection<Project> projects; if (options.limit()) projects = Arrays.asList(project); else projects = project.getWorkspace() .getAllProjects(); List<Container> containers = new ArrayList<>(); for (Project p : projects) { containers.addAll(p.getDeliverables()); } for (Container c : containers) { Version v = new Version(c.getVersion()); err.printf("%-40s %8s %s\n", c.getBundleSymbolicName(), v.getWithoutQualifier(), c.getFile()); } getInfo(project); } @Description("Show macro value. Macro can contain the ${ and } parentheses but it is also ok without. You can use the ':' instead of the ';' in a macro") @Arguments(arg = { "<macro>", "[...]" }) interface macroOptions extends Options { @Description("Path to project, default current directory") String project(); } /** * Show the value of a macro * * @throws Exception */ @Description("Show macro value") public void _macro(macroOptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } StringBuilder sb = new StringBuilder(); Macro r = project.getReplacer(); getInfo(project); String del = ""; for (String s : options._arguments()) { if (!s.startsWith("${")) { s = "${" + s; } if (!s.endsWith("}")) { s += "}"; } s = s.replace(':', ';'); String p = r.process(s); sb.append(del); sb.append(p); del = " "; } getInfo(project); err.println(sb); } @Description("Release this project") interface releaseOptions extends Options { @Description("Path to project, default is current project") String project(); @Description("Release with test build") boolean test(); @Description("Set the release repository") String repo(); @Description("Release all bundles in in the workspace") boolean workspace(); } /** * Release the project * * @throws Exception */ @Description("Release this project") public void _release(releaseOptions options) throws Exception { Set<Project> projects = new LinkedHashSet<>(); Workspace ws = Workspace.findWorkspace(getBase()); if (ws == null) { error("Workspace option was specified but cannot find a workspace from %s", getBase()); return; } if (options.workspace()) { projects.addAll(ws.getAllProjects()); } Project project = getProject(options.project()); if (project != null) { projects.add(project); } if (projects.isEmpty()) { error("Cannot find any projects"); return; } String repo = options.repo(); if (repo != null) { RepositoryPlugin repository = ws.getRepository(repo); if (repository == null) { error("No such release repo %s%nFound:%n%s", repository, Strings.join("\n", ws.getRepositories())); } } for (Project p : projects) { if (repo != null) { p.setProperty(Constants.RELEASEREPO, repo); } p.release(options.test()); } if (project != null) { getInfo(project); } } @Description("Show a cross references for all classes in a set of jars.") @Arguments(arg = { "<jar path>", "[...]" }) interface xrefOptions extends Options { @Description("Show classes instead of packages") boolean classes(); @Description("Show references to other classes/packages (>)") boolean to(); @Description("Show references from other classes/packages (<)") boolean from(); @Description("Filter for class names, a globbing expression") List<String> match(); } static public class All { public Map<TypeRef, List<TypeRef>> classes = new HashMap<>(); public Map<PackageRef, List<PackageRef>> packages = new HashMap<>(); } /** * Cross reference every class in the jar file to the files it references */ @Description("Show a cross references for all classes in a set of jars.") public void _xref(xrefOptions options) throws IOException, Exception { Analyzer analyzer = new Analyzer(); final MultiMap<TypeRef, TypeRef> table = new MultiMap<>(); final MultiMap<PackageRef, PackageRef> packages = new MultiMap<>(); Set<TypeRef> set = Create.set(); Instructions filter = new Instructions(options.match()); for (String arg : options._arguments()) { try { File file = new File(arg); try (Jar jar = new Jar(file.getName(), file)) { for (Map.Entry<String, Resource> entry : jar.getResources() .entrySet()) { String key = entry.getKey(); Resource r = entry.getValue(); if (key.endsWith(".class")) { TypeRef ref = analyzer.getTypeRefFromPath(key); if (filter.matches(ref.toString())) { set.add(ref); try (InputStream in = r.openInputStream()) { Clazz clazz = new Clazz(analyzer, key, r); // TODO use the proper bcp instead // of using the default layout Set<TypeRef> s = clazz.parseClassFile(); for (Iterator<TypeRef> t = s.iterator(); t.hasNext();) { TypeRef tr = t.next(); if (tr.isJava() || tr.isPrimitive()) t.remove(); else packages.add(ref.getPackageRef(), tr.getPackageRef()); } table.addAll(ref, s); set.addAll(s); } } } } } } catch (Exception e) { e.printStackTrace(); } } boolean to = options.to(); boolean from = options.from(); if (to == false && from == false) to = from = true; if (options.classes()) { if (to) printxref(table, ">"); if (from) printxref(table.transpose(), "<"); } else { if (to) printxref(packages, ">"); if (from) printxref(packages.transpose(), "<"); } } private void printxref(MultiMap<?, ?> map, String direction) { SortedList<?> labels = new SortedList<Object>(map.keySet(), null); for (Object element : labels) { List<?> e = map.get(element); if (e == null) { // ignore } else { Set<Object> set = new LinkedHashSet<>(e); set.remove(element); Iterator<?> row = set.iterator(); String first = ""; if (row.hasNext()) first = row.next() .toString(); out.printf("%50s %s %s\n", element, direction, first); while (row.hasNext()) { out.printf("%50s %s\n", "", row.next()); } } } } @Description("Show info about the current directory's eclipse project") @Arguments(arg = {}) interface eclipseOptions extends Options { @Description("Path to the project") String dir(); } @Description("Show info about the current directory's eclipse project") public void _eclipse(eclipseOptions options) throws Exception { File dir = getBase(); if (options.dir() != null) dir = getFile(options.dir()); if (!dir.isDirectory()) error("Eclipse requires a path to a directory: %s", dir.getAbsolutePath()); if (options._arguments() .size() != 0) error("Unnecessary arguments %s", options._arguments()); if (!isOk()) return; File cp = new File(dir, ".classpath"); if (!cp.exists()) { error("Cannot find .classpath in project directory: %s", dir.getAbsolutePath()); } else { EclipseClasspath eclipse = new EclipseClasspath(this, dir.getParentFile(), dir); err.println("Classpath " + eclipse.getClasspath()); err.println("Dependents " + eclipse.getDependents()); err.println("Sourcepath " + eclipse.getSourcepath()); err.println("Output " + eclipse.getOutput()); err.println(); } } /** * Buildx */ final static int BUILD_SOURCES = 1; final static int BUILD_POM = 2; final static int BUILD_FORCE = 4; @Description("Build project, is deprecated but here for backward compatibility. If you use it, you should know how to use it so no more info is provided.") interface buildxOptions extends Options { String output(); List<String> classpath(); List<String> sourcepath(); boolean eclipse(); boolean noeclipse(); boolean sources(); boolean pom(); boolean force(); } @Description("Build project, is deprecated but here for backward compatibility") public void _buildx(buildxOptions options) throws Exception { // Create a build order List<Builder> builders = new ArrayList<>(); List<String> order = new ArrayList<>(); List<String> active = new ArrayList<>(); for (String s : options._arguments()) { prebuild(active, order, builders, s); } for (Builder b : builders) { if (options.classpath() != null) { for (String f : options.classpath()) { b.addClasspath(getFile(f)); } } if (options.sourcepath() != null) { for (String f : options.sourcepath()) { b.addSourcepath(getFile(f)); } } if (options.sources()) b.setSources(true); if (options.eclipse()) { EclipseClasspath ep = new EclipseClasspath(this, getBase().getParentFile(), getBase()); b.addClasspath(ep.getClasspath()); b.addClasspath(ep.getBootclasspath()); b.addSourcepath(ep.getSourcepath()); } Jar jar = b.build(); File outputFile = b.getOutputFile(options.output()); if (options.pom()) { Resource r = new PomFromManifest(jar.getManifest()); jar.putResource("pom.xml", r); String path = outputFile.getName() .replaceAll("\\.jar$", ".pom"); if (path.equals(outputFile.getName())) path = outputFile.getName() + ".pom"; File pom = new File(outputFile.getParentFile(), path); try (OutputStream os = IO.outputStream(pom)) { r.write(os); } } getInfo(b, b.getPropertiesFile() .getName()); if (isOk()) { b.save(outputFile, options.force()); } b.close(); } } // Find the build order // by recursively passing // through the builders. private void prebuild(List<String> set, List<String> order, List<Builder> builders, String s) throws IOException { if (order.contains(s)) // Already done return; if (set.contains(s)) error("Cyclic -prebuild dependency %s from %s", s, set); Builder b = new Builder(this); b.setProperties(getFile(s)); String prebuild = b.get("prebuild"); if (prebuild != null) { set.add(s); try { Collection<String> parts = split(prebuild); for (String p : parts) { prebuild(set, order, builders, p); } } finally { set.remove(s); } } order.add(s); builders.add(b); } @Description("View a resource from a JAR file. Manifest will be pretty printed and class files are shown disassembled.") @Arguments(arg = { "<jar-file>", "<resource>", "[...]" }) interface viewOptions extends Options { @Description("Character set to use for viewing") String charset(); } /** * View files from JARs We parse the commandline and print each file on it. * * @throws Exception */ @Description("View a resource from a JAR file.") public void _view(viewOptions options) throws Exception { Charset charset = UTF_8; if (options.charset() != null) charset = Charset.forName(options.charset()); if (options._arguments() .isEmpty()) { error("Need a jarfile as source"); return; } List<String> args = options._arguments(); File file = getFile(args.remove(0)); if (!file.isFile()) { error("File does not exist %s", file); return; } try (Jar jar = new Jar(file)) { if (args.isEmpty()) args.add("*"); Instructions instructions = new Instructions(args); Collection<String> selected = instructions.select(jar.getResources() .keySet(), true); for (String selection : selected) { Resource r = jar.getResource(selection); if (selection.endsWith(".MF")) { Manifest m = new Manifest(r.openInputStream()); printManifest(m); } else if (selection.endsWith(".class")) { ClassDumper clsd = new ClassDumper(selection, r.openInputStream()); clsd.dump(out); } else { InputStreamReader isr = new InputStreamReader(r.openInputStream(), charset); IO.copy(isr, out); } } } } @Description("Wrap a jar into a bundle. This is a poor man's facility to " + "quickly turn a non-OSGi JAR into an OSGi bundle. " + "It is usually better to write a bnd file and use the bnd <file>.bnd " + "command because that has greater control. Even better is to wrap in bndtools.") @Arguments(arg = { "<jar-file>", "[...]" }) interface wrapOptions extends Options { @Description("Path to the output, default the name of the input jar with the '.bar' extension. If this is a directory, the output is place there.") String output(); @Description("A file with properties in bnd format.") String properties(); @Description("A classpath specification") List<String> classpath(); @Description("Allow override of an existing file") boolean force(); @Description("Set the bundle symbolic name to use") String bsn(); @Description("Set the version to use") Version version(); } /** * Wrap a jar to a bundle. * * @throws Exception */ @Description("Wrap a jar") public void _wrap(wrapOptions options) throws Exception { List<File> classpath = Create.list(); File properties = getBase(); if (options.properties() != null) { properties = getFile(options.properties()); } if (options.classpath() != null) for (String cp : options.classpath()) { classpath.add(getFile(cp)); } for (String j : options._arguments()) { File file = getFile(j); if (!file.isFile()) { error("File does not exist %s", file); continue; } try (Analyzer wrapper = new Analyzer(this)) { wrapper.use(this); for (File f : classpath) wrapper.addClasspath(f); wrapper.setJar(file); File outputFile = wrapper.getOutputFile(options.output()); if (outputFile.getCanonicalFile() .equals(file.getCanonicalFile())) { // #267: CommandLine wrap deletes target even if file equals // source error("Output file %s and source file %s are the same file, they must be different", outputFile, file); return; } IO.delete(outputFile); String stem = file.getName(); if (stem.endsWith(".jar")) stem = stem.substring(0, stem.length() - 4) + ".bnd"; File p = getPropertiesFile(properties, file, stem); if (p == null) { wrapper.setImportPackage("*;resolution:=optional"); wrapper.setExportPackage("*"); warning("Using defaults for wrap, which means no export versions"); } else if (p.isFile()) wrapper.setProperties(p); else { error("No valid property file: %s", p); } if (options.bsn() != null) wrapper.setBundleSymbolicName(options.bsn()); if (options.version() != null) wrapper.setBundleVersion(options.version()); Manifest m = wrapper.calcManifest(); if (wrapper.isOk()) { wrapper.getJar() .setManifest(m); wrapper.save(outputFile, options.force()); } getInfo(wrapper, file.toString()); } } } private File getPropertiesFile(File properties, File file, String stem) { if (properties.isFile()) return properties; File p = getFile(file.getParentFile(), stem); if (p.isFile()) return p; if (properties.isDirectory()) { p = getFile(properties, stem); if (p.isFile()) return p; } return null; } @Description("Show a lot of info about the project you're in") interface debugOptions extends Options { @Description("Path to a project, default is current directory") String project(); @Description("Show the flattened properties") boolean flattened(); } /** * Printout all the variables in scope. * * @throws Exception */ @SuppressWarnings("unchecked") @Description("Show a lot of info about the project you're in") public void _debug(debugOptions options) throws Exception { Project project = getProject(options.project()); Justif justif = new Justif(120, 40, 50, 52, 80); logger.debug("using {}", project); Processor target = project; if (project != null) { Workspace ws = project.getWorkspace(); ws.checkStructure(); getInfo(project.getWorkspace()); report(justif, "Workspace", project.getWorkspace()); report(justif, "Project", project); try (ProjectBuilder pb = project.getBuilder(null)) { List<Builder> builders = pb.getSubBuilders(); if (builders != null) { for (Builder sub : builders) { report(justif, "Sub-Builder", sub); getInfo(sub); } } } for (File file : project.getBase() .listFiles()) { if (file.getName() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { Run run = Workspace.getRun(file); if (run == null) { error("No such run file %s", file); } else { report(justif, "bndrun", run); getInfo(run); } } } if (options.flattened()) { @SuppressWarnings("rawtypes") Map fp = project.getFlattenedProperties(); Justif j = new Justif(140, 40, 44, 48, 100); j.table(fp, "-"); out.println(j.wrap()); } getInfo(project.getWorkspace()); getInfo(project); } else err.println("No project"); } private void report(Justif justif, String string, Processor processor) throws Exception { Map<String, Object> table = new LinkedHashMap<>(); processor.report(table); Justif j = new Justif(140, 40, 44, 48, 100); j.formatter() .format("$-\n%s %s\n$-\n", string, processor); j.table(table, "-"); out.println(j.wrap()); out.println(); } /** * Manage the repo. * * <pre> * out.println(&quot; bnd repo [--repo|-r ('maven'| * &lt;dir&gt;)]*&quot;); out.println(&quot; repos # list the * repositories&quot;); out.println(&quot; list # list all content (not * always possible)&quot;); out.println(&quot; get &lt;bsn&gt; * &lt;version&gt; &lt;file&gt;? # get an artifact&quot;); * out.println(&quot; put &lt;file&gt;+ # put in artifacts&quot;); * out.println(&quot; help&quot;); * </pre> */ @Description("Manage the repositories") public void _repo(repoOptions opts) throws Exception { new RepoCommand(this, opts); } /** * Run enroute commands */ @Description("OSGi enRoute commands to maintain bnd workspaces (create workspace, add project, etc)") public void _enroute(EnrouteOptions opts) throws Exception { new EnrouteCommand(this, opts); } /** * Print out a JAR */ final static int VERIFY = 1; final static int MANIFEST = 2; final static int LIST = 4; final static int IMPEXP = 16; final static int USES = 32; final static int USEDBY = 64; final static int COMPONENT = 128; final static int METATYPE = 256; final static int API = 512; final static int CAPABILITIES = 1024; static final int HEX = 0; @Arguments(arg = "jar-file...") @Description("Provides detailed view of the bundle. It will analyze the bundle and then show its contents from different perspectives. If no options are specified, prints the manifest.") interface printOptions extends Options { @Description("Print the api usage. This shows the usage constraints on exported packages when only public API is used.") boolean api(); @Description("Before printing, verify that the bundle is correct.") boolean verify(); @Description("Print the manifest.") boolean manifest(); @Description("List the resources") boolean list(); @Description("List the imports exports, versions and ranges") boolean impexp(); @Description("Show for each contained package, what other package it uses. Is either an private, exported, or imported package") boolean uses(); @Description("Transposed uses. Will show for each known package who it is used by.") boolean by(); @Description("Show components in detail") boolean component(); @Description("Show any metatype data") boolean typemeta(); @Description("Keep references to java in --api, --uses, and --usedby.") boolean java(); @Description("Show all packages, not just exported, in the API view") boolean xport(); @Description("Show the capabilities") boolean capabilities(); } @Description("Printout the JAR") public void _print(printOptions options) throws Exception { for (String s : options._arguments()) { int opts = 0; if (options.verify()) opts |= VERIFY; if (options.manifest()) opts |= MANIFEST; if (options.api()) opts |= API; if (options.list()) opts |= LIST; if (options.impexp()) opts |= IMPEXP; if (options.uses()) opts |= USES; if (options.by()) opts |= USEDBY; if (options.component()) opts |= COMPONENT; if (options.typemeta()) opts |= METATYPE; if (options.capabilities()) opts |= CAPABILITIES; if (opts == 0) opts = MANIFEST | IMPEXP; try (Jar jar = getJar(s)) { doPrint(jar, opts, options); } } } private void doPrint(Jar jar, int options, printOptions po) throws ZipException, IOException, Exception { if ((options & VERIFY) != 0) { Verifier verifier = new Verifier(jar); verifier.setPedantic(isPedantic()); verifier.verify(); getInfo(verifier); } if ((options & MANIFEST) != 0) { Manifest manifest = jar.getManifest(); if (manifest == null) warning("JAR has no manifest %s", jar); else { err.println("[MANIFEST " + jar.getName() + "]"); printManifest(manifest); } out.println(); } if ((options & IMPEXP) != 0) { out.println("[IMPEXP]"); Manifest m = jar.getManifest(); Domain domain = Domain.domain(m); if (m != null) { Parameters imports = domain.getImportPackage(); Parameters exports = domain.getExportPackage(); for (String p : exports.keySet()) { if (imports.containsKey(p)) { Attrs attrs = imports.get(p); if (attrs.containsKey(VERSION_ATTRIBUTE)) { exports.get(p) .put("imported-as", attrs.get(VERSION_ATTRIBUTE)); } } } print(Constants.IMPORT_PACKAGE, new TreeMap<>(imports)); print(Constants.EXPORT_PACKAGE, new TreeMap<>(exports)); } else warning("File has no manifest"); } if ((options & CAPABILITIES) != 0) { out.println("[CAPABILITIES]"); Manifest m = jar.getManifest(); Domain domain = Domain.domain(m); if (m != null) { Parameters provide = domain.getProvideCapability(); Parameters require = domain.getRequireCapability(); print(Constants.PROVIDE_CAPABILITY, new TreeMap<>(provide)); print(Constants.REQUIRE_CAPABILITY, new TreeMap<>(require)); } else warning("File has no manifest"); } if ((options & (USES | USEDBY | API)) != 0) { out.println(); try (Analyzer analyzer = new Analyzer()) { analyzer.setPedantic(isPedantic()); analyzer.setJar(jar); Manifest m = jar.getManifest(); if (m != null) { String s = m.getMainAttributes() .getValue(Constants.EXPORT_PACKAGE); if (s != null) analyzer.setExportPackage(s); } analyzer.analyze(); boolean java = po.java(); Packages exports = analyzer.getExports(); if ((options & API) != 0) { Map<PackageRef, List<PackageRef>> apiUses = analyzer.cleanupUses(analyzer.getAPIUses(), !po.java()); if (!po.xport()) { if (exports.isEmpty()) warning("Not filtering on exported only since exports are empty"); else apiUses.keySet() .retainAll(analyzer.getExports() .keySet()); } out.println("[API USES]"); printMultiMap(apiUses); Set<PackageRef> privates = analyzer.getPrivates(); for (PackageRef export : exports.keySet()) { Map<Def, List<TypeRef>> xRef = analyzer.getXRef(export, privates, Modifier.PROTECTED + Modifier.PUBLIC); if (!xRef.isEmpty()) { out.println(); out.printf("%s refers to private Packages (not good)\n\n", export); for (Entry<Def, List<TypeRef>> e : xRef.entrySet()) { TreeSet<PackageRef> refs = new TreeSet<>(); for (TypeRef ref : e.getValue()) refs.add(ref.getPackageRef()); refs.retainAll(privates); out.printf("%60s %-40s %s\n", e.getKey() .getOwnerType() .getFQN() // , e.getKey() .getName(), refs); } out.println(); } } out.println(); } Map<PackageRef, List<PackageRef>> uses = analyzer.cleanupUses(analyzer.getUses(), !po.java()); if ((options & USES) != 0) { out.println("[USES]"); printMultiMap(uses); out.println(); } if ((options & USEDBY) != 0) { out.println("[USEDBY]"); MultiMap<PackageRef, PackageRef> usedBy = new MultiMap<>(uses).transpose(); printMultiMap(usedBy); } } } if ((options & COMPONENT) != 0) { printComponents(out, jar); } if ((options & METATYPE) != 0) { printMetatype(out, jar); } if ((options & LIST) != 0) { out.println("[LIST]"); for (Map.Entry<String, Map<String, Resource>> entry : jar.getDirectories() .entrySet()) { String name = entry.getKey(); Map<String, Resource> contents = entry.getValue(); out.println(name); if (contents != null) { for (String element : contents.keySet()) { int n = element.lastIndexOf('/'); if (n > 0) element = element.substring(n + 1); out.print(" "); out.print(element); String path = element; if (name.length() != 0) path = name + "/" + element; Resource r = contents.get(path); if (r != null) { String extra = r.getExtra(); if (extra != null) { out.print(" extra='" + escapeUnicode(extra) + "'"); } } out.println(); } } else { out.println(name + " <no contents>"); } } out.println(); } } /** * @param manifest */ void printManifest(Manifest manifest) { SortedSet<String> sorted = new TreeSet<>(); for (Object element : manifest.getMainAttributes() .keySet()) { sorted.add(element.toString()); } for (String key : sorted) { Object value = manifest.getMainAttributes() .getValue(key); out.printf("%-40s %-40s\n", key, value); } } private final char nibble(int i) { return "0123456789ABCDEF".charAt(i & 0xF); } private final String escapeUnicode(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= ' ' && c <= '~' && c != '\\') sb.append(c); else { sb.append("\\u"); sb.append(nibble(c >> 12)); sb.append(nibble(c >> 8)); sb.append(nibble(c >> 4)); sb.append(nibble(c)); } } return sb.toString(); } /** * Print the components in this JAR. * * @param jar */ private void printComponents(PrintStream out, Jar jar) throws Exception { out.println("[COMPONENTS]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } String componentHeader = manifest.getMainAttributes() .getValue(Constants.SERVICE_COMPONENT); Parameters clauses = new Parameters(componentHeader, this); for (String path : clauses.keySet()) { out.println(path); Resource r = jar.getResource(path); if (r != null) { InputStreamReader ir = new InputStreamReader(r.openInputStream(), Constants.DEFAULT_CHARSET); OutputStreamWriter or = new OutputStreamWriter(out, Constants.DEFAULT_CHARSET); try { IO.copy(ir, or); } finally { or.flush(); ir.close(); } } else { out.println(" - no resource"); warning("No Resource found for service component: %s", path); } } out.println(); } /** * Print the metatypes in this JAR. * * @param jar */ private void printMetatype(PrintStream out, Jar jar) throws Exception { out.println("[METATYPE]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } Map<String, Resource> map = jar.getDirectories() .get("OSGI-INF/metatype"); if (map != null) { for (Map.Entry<String, Resource> entry : map.entrySet()) { out.println(entry.getKey()); IO.copy(entry.getValue() .openInputStream(), out); out.println(); } out.println(); } } <T extends Comparable<? super T>> void printMultiMap(Map<T, ? extends Collection<?>> map) { SortedList<T> keys = new SortedList<>(map.keySet()); for (Object key : keys) { String name = key.toString(); SortedList<Object> values = new SortedList<>(map.get(key), null); String list = vertical(40, values); out.printf("%-40s %s\n", name, list); } } String vertical(int padding, Collection<?> used) { StringBuilder sb = new StringBuilder(); String del = ""; for (Object s : used) { String name = s.toString(); sb.append(del); sb.append(name); sb.append("\r\n"); del = pad(padding); } if (sb.length() == 0) sb.append("\r\n"); return sb.toString(); } String pad(int i) { StringBuilder sb = new StringBuilder(); while (i-- > 0) sb.append(' '); return sb.toString(); } /** * @param msg * @param ports */ private void print(String msg, Map<?, ? extends Map<?, ?>> ports) { if (ports.isEmpty()) return; out.println(msg); for (Entry<?, ? extends Map<?, ?>> entry : ports.entrySet()) { Object key = entry.getKey(); Map<?, ?> clause = Create.copy((Map<?, ?>) entry.getValue()); clause.remove("uses:"); out.printf(" %-38s %s\n", key.toString() .trim(), clause.isEmpty() ? "" : clause.toString()); } } /** * Patch */ interface patchOptions extends Options { } public void patch(patchOptions opts) throws Exception { PatchCommand pcmd = new PatchCommand(this); List<String> args = opts._arguments(); opts._command() .execute(pcmd, args.remove(0), args); } @Description("Run OSGi tests and create report") interface runtestsOptions extends Options { @Description("Report directory") String reportdir(); @Description("Title in the report") String title(); @Description("Path to work directory") String dir(); @Description("Path to workspace") String workspace(); } /** * Run the tests from a prepared bnd file. * * @throws Exception */ @Description("Run OSGi tests and create report") public void _runtests(runtestsOptions opts) throws Exception { int errors = 0; File cwd = new File("").getAbsoluteFile(); Workspace ws = new Workspace(cwd); try { File reportDir = getFile("reports"); IO.delete(reportDir); Tag summary = new Tag("summary"); summary.addAttribute("date", new Date()); summary.addAttribute("ws", ws.getBase()); if (opts.reportdir() != null) { reportDir = getFile(opts.reportdir()); } IO.mkdirs(reportDir); if (!reportDir.isDirectory()) error("reportdir must be a directory %s (tried to create it ...)", reportDir); if (opts.title() != null) summary.addAttribute("title", opts.title()); if (opts.dir() != null) cwd = getFile(opts.dir()); if (opts.workspace() != null) { ws.close(); ws = Workspace.getWorkspace(getFile(opts.workspace())); } // TODO check all the arguments boolean hadOne = false; try { for (String arg : opts._arguments()) { logger.debug("will run test {}", arg); File f = getFile(arg); errors += runtTest(f, ws, reportDir, summary); hadOne = true; } if (!hadOne) { // See if we had any, if so, just use all files in // the current directory File[] files = cwd.listFiles(); for (File f : files) { if (f.getName() .endsWith(".bnd")) { errors += runtTest(f, ws, reportDir, summary); } } } } catch (Throwable e) { if (isExceptions()) { printExceptionSummary(e, out); } exception(e, "FAILURE IN RUNTESTS"); errors++; } if (errors > 0) summary.addAttribute("errors", errors); for (String error : getErrors()) { Tag e = new Tag("error"); e.addContent(error); } for (String warning : getWarnings()) { Tag e = new Tag("warning"); e.addContent(warning); } File r = getFile(reportDir, "summary.xml"); try (PrintWriter pw = IO.writer(r, UTF_8)) { summary.print(0, pw); } if (errors != 0) error("Errors found %s", errors); } finally { ws.close(); } } /** * Help function to run the tests */ private int runtTest(File testFile, Workspace ws, File reportDir, Tag summary) throws Exception { File tmpDir = new File(reportDir, "tmp"); IO.mkdirs(tmpDir); tmpDir.deleteOnExit(); Tag test = new Tag(summary, "test"); test.addAttribute("path", testFile.getAbsolutePath()); if (!testFile.isFile()) { error("No bnd file: %s", testFile); test.addAttribute("exception", "No bnd file found"); error("No bnd file found for %s", testFile.getAbsolutePath()); return 1; } Project project = new Project(ws, testFile.getAbsoluteFile() .getParentFile(), testFile.getAbsoluteFile()); project.use(this); project.setProperty(NOBUNDLES, "true"); ProjectTester tester = project.getProjectTester(); if (!project.isOk()) { getInfo(project, project.toString() + ": " + testFile.getName() + ":"); return 1; // Indicate failure but do not abort } tester.setContinuous(false); tester.setReportDir(tmpDir); test.addAttribute("title", project.toString()); long start = System.currentTimeMillis(); try { int errors = tester.test(); Collection<File> reports = tester.getReports(); for (File report : reports) { Tag bundle = new Tag(test, "bundle"); File dest = new File(reportDir, report.getName()); IO.rename(report, dest); bundle.addAttribute("file", dest.getAbsolutePath()); doPerReport(bundle, dest); } switch (errors) { case ProjectLauncher.OK : return 0; case ProjectLauncher.CANCELED : test.addAttribute("failed", "canceled"); return 1; case ProjectLauncher.DUPLICATE_BUNDLE : test.addAttribute("failed", "duplicate bundle"); return 1; case ProjectLauncher.ERROR : test.addAttribute("failed", "unknown reason"); return 1; case ProjectLauncher.RESOLVE_ERROR : test.addAttribute("failed", "resolve error"); return 1; case ProjectLauncher.TIMEDOUT : test.addAttribute("failed", "timed out"); return 1; case ProjectLauncher.WARNING : test.addAttribute("warning", "true"); return 1; case ProjectLauncher.ACTIVATOR_ERROR : test.addAttribute("failed", "activator error"); return 1; default : if (errors > 0) { test.addAttribute("errors", errors); return errors; } test.addAttribute("failed", "unknown reason"); return errors; } } catch (Exception e) { test.addAttribute("failed", e); exception(e, "Exception in run %s", e); return 1; } finally { long duration = System.currentTimeMillis() - start; test.addAttribute("duration", (duration + 500) / 1000); getInfo(project, project.toString() + ": "); } } /** * Calculate the coverage if there is coverage info in the test file. */ private void doPerReport(Tag report, File file) throws Exception { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); doCoverage(report, doc, xpath); doHtmlReport(report, file, doc, xpath); } catch (Exception e) { report.addAttribute("coverage-failed", e.toString()); } } private void doCoverage(Tag report, Document doc, XPath xpath) throws XPathExpressionException { int bad = Integer.parseInt(xpath.evaluate("count(//method[count(ref)<2])", doc)); int all = Integer.parseInt(xpath.evaluate("count(//method)", doc)); report.addAttribute("coverage-bad", bad); report.addAttribute("coverage-all", all); } private void doHtmlReport(@SuppressWarnings("unused") Tag report, File file, Document doc, @SuppressWarnings("unused") XPath xpath) throws Exception { String path = file.getAbsolutePath(); if (path.endsWith(".xml")) path = path.substring(0, path.length() - 4); path += ".html"; File html = new File(path); logger.debug("Creating html report: {}", html); TransformerFactory fact = TransformerFactory.newInstance(); try (InputStream in = getClass().getResourceAsStream("testreport.xsl")) { if (in == null) { warning("Resource not found: test-report.xsl, no html report"); } else { try (Writer out = IO.writer(html, UTF_8)) { Transformer transformer = fact.newTransformer(new StreamSource(in)); transformer.transform(new DOMSource(doc), new StreamResult(out)); logger.debug("Transformed"); } } } } @Description("Verify jars") @Arguments(arg = { "<jar path>", "[...]" }) interface verifyOptions extends Options {} /** * Verify jars. * * @throws Exception */ @Description("Verify jars") public void _verify(verifyOptions opts) throws Exception { for (String path : opts._arguments()) { File f = getFile(path); if (!f.isFile()) { error("No such file: %s", f); } else { Jar jar = new Jar(f); if (jar.getManifest() == null || jar.getBsn() == null) error("Not a bundle %s", f); else { Verifier v = new Verifier(jar); getInfo(v, f.getName()); v.close(); } jar.close(); } } } @Description("Merge a binary jar with its sources. It is possible to specify source path") // @Arguments(arg = { "<jar path>", "<source path>" }) // interface sourceOptions extends Options { @Description("The output file") String output(); } /** * Merge a bundle with its source. * * @throws Exception */ @Description("Merge a binary jar with its sources. It is possible to specify source path") public void _source(sourceOptions opts) throws Exception { List<String> arguments = opts._arguments(); File jarFile = getFile(arguments.remove(0)); if (!jarFile.exists()) { error("File %s does not exist ", jarFile); return; } File sourceFile = getFile(arguments.remove(0)); if (!sourceFile.exists()) { error("Source file %s does not exist ", sourceFile); return; } File output = jarFile; if (opts.output() != null) output = getFile(opts.output()); File tmp = File.createTempFile("tmp", ".jar", jarFile.getParentFile()); tmp.deleteOnExit(); try (Jar bin = new Jar(jarFile); Jar src = new Jar(sourceFile)) { bin.setDoNotTouchManifest(); for (String path : src.getResources() .keySet()) bin.putResource("OSGI-OPT/src/" + path, src.getResource(path)); bin.write(tmp); } IO.rename(tmp, output); } /** * Diff two jar files * * @throws Exception */ @Description("Diff jars") public void _diff(diffOptions opts) throws Exception { DiffCommand diff = new DiffCommand(this); diff.diff(opts); } /** * Baseline * * @throws Exception */ @Description("Compare a newer bundle to a baselined bundle and provide versioning advice") public void _baseline(baseLineOptions opts) throws Exception { BaselineCommands baseliner = new BaselineCommands(this); baseliner._baseline(opts); } /** * Create a schema of package deltas and versions * * @throws Exception */ @Description("Highly specialized function to create an overview of package deltas in ees") public void _schema(schemaOptions opts) throws Exception { BaselineCommands baseliner = new BaselineCommands(this); baseliner._schema(opts); } public Project getProject() throws Exception { return getProject(null); } public Workspace getWorkspace(File workspaceDir) throws Exception { if (workspaceDir == null) { workspaceDir = getBase(); } ws = Workspace.findWorkspace(workspaceDir); if (ws == null) return null; ws.use(this); return ws; } public Project getProject(String where) throws Exception { if (where == null || where.equals(".")) where = Project.BNDFILE; File f = getFile(where); if (f.isDirectory()) { f = new File(f, Project.BNDFILE); } if (f.isFile()) { if (f.getName() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { Workspace ws = Workspace.findWorkspace(f.getParentFile()); Run run = Run.createRun(ws, f); return run; } File projectDir = f.getParentFile(); File workspaceDir = projectDir.getParentFile(); ws = Workspace.findWorkspace(workspaceDir); Project project = ws.getProject(projectDir.getName()); if (project.isValid()) { project.use(this); return project; } } if (where.equals(Project.BNDFILE)) { return null; } error("Project not found: %s", f); return null; } public Workspace getWorkspace(String where) throws Exception { Workspace ws; if (where == null) { ws = Workspace.findWorkspace(IO.work); if (ws == null) ws = Workspace.createStandaloneWorkspace(new Processor(), IO.work.toURI()); } else { File f = getFile(where); ws = Workspace.findWorkspace(f); if (f.isFile() && f.getName() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { Run run = Run.createRun(ws, f); ws = run.getWorkspace(); } } return ws; } /** * Convert files */ @Description("Converter to different formats") @Arguments(arg = { "from", "to" }) interface convertOptions extends Options { @Config(description = "Convert a manifest to a properties files") boolean m2p(); @Config(description = "Save as xml") boolean xml(); } @Description("Converter to different formats") public void _convert(convertOptions opts) throws IOException { File from = getFile(opts._arguments() .get(0)); File to = getFile(opts._arguments() .get(1)); if (opts.m2p()) { try (InputStream in = IO.stream(from)) { Properties p = new UTF8Properties(); Manifest m = new Manifest(in); Attributes attrs = m.getMainAttributes(); for (Map.Entry<Object, Object> i : attrs.entrySet()) { p.put(i.getKey() .toString(), i.getValue() .toString()); } try (OutputStream fout = IO.outputStream(to)) { if (opts.xml()) p.storeToXML(fout, "converted from " + from); else { try (Writer osw = IO.writer(fout, UTF_8)) { p.store(osw, "converted from " + from); } } } } return; } error("no conversion specified"); } /** * Create a list of file names that match manifest headers bnd select -h * Bundle-SymbolicName --where (...) * */ @Description("Helps finding information in a set of JARs by filtering on manifest data and printing out selected information.") @Arguments(arg = { "<jar-path>", "[...]" }) interface selectOptions extends Options { @Description("A simple assertion on a manifest header (e.g. " + Constants.BUNDLE_VERSION + "=1.0.1) or an OSGi filter that is asserted on all manifest headers. Comparisons are case insensitive. The key 'resources' holds the pathnames of all resources and can also be asserted to check for the presence of a header.") String where(); @Description("A manifest header to print or: path, name, size, length, modified for information about the file, wildcards are allowed to print multiple headers. ") Collection<String> header(); @Description("Print the key before the value") boolean key(); @Description("Print the file name before the value") boolean name(); @Description("Print the file path before the value") boolean path(); } @Description("Helps finding information in a set of JARs by filtering on manifest data and printing out selected information.") public void _select(selectOptions opts) throws Exception { PrintStream out = this.out; Filter filter = null; if (opts.where() != null) { String w = opts.where(); if (!w.startsWith("(")) w = "(" + w + ")"; filter = new Filter(w); } Instructions instructions = new Instructions(opts.header()); for (String s : opts._arguments()) { Jar jar = getJar(s); if (jar == null) { err.println("no file " + s); continue; } Domain domain = Domain.domain(jar.getManifest()); Hashtable<String, Object> ht = new Hashtable<>(); Iterator<String> i = domain.iterator(); Set<String> realNames = new HashSet<>(); while (i.hasNext()) { String key = i.next(); String value = domain.get(key) .trim(); ht.put(key.trim() .toLowerCase(), value); realNames.add(key); } ht.put("resources", jar.getResources() .keySet()); realNames.add("resources"); if (filter != null) { if (!filter.match(ht)) continue; } Set<Instruction> unused = new HashSet<>(); Collection<String> select = instructions.select(realNames, unused, true); for (String h : select) { if (opts.path()) { out.print(jar.getSource() .getAbsolutePath() + ":"); } if (opts.name()) { out.print(jar.getSource() .getName() + ":"); } if (opts.key()) { out.print(h + ":"); } out.println(ht.get(h.toLowerCase())); } for (Instruction ins : unused) { String literal = ins.getLiteral(); if (literal.equals("name")) out.println(jar.getSource() .getName()); else if (literal.equals("path")) out.println(jar.getSource() .getAbsolutePath()); else if (literal.equals("size") || literal.equals("length")) out.println(jar.getSource() .length()); else if (literal.equals("modified")) out.println(new Date(jar.getSource() .lastModified())); } } } /** * Central routine to get a JAR with error checking * * @param s */ Jar getJar(String s) { File f = getFile(s); if (f.isFile()) { try { return new Jar(f); } catch (ZipException e) { exception(e, "Not a jar/zip file: %s", f); } catch (Exception e) { exception(e, "Opening file: %s", f); } return null; } try { URL url = new URL(s); return new Jar(s, url.openStream()); } catch (Exception e) { // Ignore } error("Not a file or proper url: %s", f); return null; } @Description("Show version information about bnd") @Arguments(arg = {}) public interface versionOptions extends Options { @Description("Show licensing, copyright, sha, scm, etc") boolean xtra(); } /** * Show the version of this bnd * * @throws IOException */ @Description("Show version information about bnd") public void _version(versionOptions o) throws IOException { if (!o.xtra()) { Analyzer a = new Analyzer(); out.println(a.getBndVersion()); a.close(); return; } Enumeration<URL> e = getClass().getClassLoader() .getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { URL u = e.nextElement(); Manifest m = new Manifest(u.openStream()); String bsn = m.getMainAttributes() .getValue(Constants.BUNDLE_SYMBOLICNAME); if (bsn != null && bsn.equals("biz.aQute.bnd")) { Attributes attrs = m.getMainAttributes(); long lastModified = 0; try { lastModified = Long.parseLong(attrs.getValue(Constants.BND_LASTMODIFIED)); } catch (Exception ee) { // Ignore } out.printf("%-40s %s\n", "Version", attrs.getValue(Constants.BUNDLE_VERSION)); if (lastModified > 0) out.printf("%-40s %s\n", "From", new Date(lastModified)); Parameters p = OSGiHeader.parseHeader(attrs.getValue(Constants.BUNDLE_LICENSE)); for (String l : p.keySet()) out.printf("%-40s %s\n", "License", p.get(l) .get("description")); out.printf("%-40s %s\n", "Copyright", attrs.getValue(Constants.BUNDLE_COPYRIGHT)); out.printf("%-40s %s\n", "Git-SHA", attrs.getValue("Git-SHA")); out.printf("%-40s %s\n", "Git-Descriptor", attrs.getValue("Git-Descriptor")); out.printf("%-40s %s\n", "Sources", attrs.getValue(Constants.BUNDLE_SCM)); return; } } error("Could not locate version"); } /** * Show some key info of the project */ @Arguments(arg = {}) @Description("Show key project variables") interface infoOptions extends Options { boolean runbundles(); boolean buildpath(); boolean dependsOn(); boolean sourcepath(); boolean classpath(); boolean vmpath(); String project(); } @Description("Show key project variables") public void _info(infoOptions options) throws Exception { Project p = getProject(options.project()); if (p == null) { messages.NoProject(); return; } boolean any = options.runbundles() || options.buildpath() || options.classpath() || options.dependsOn() || options.vmpath(); MultiMap<String, Object> table = new MultiMap<>(); if (any || options.runbundles()) { table.addAll("Run", p.getRunbundles()); } if (any || options.buildpath()) { table.addAll("Build", p.getBuildpath()); } if (any || options.buildpath()) { table.addAll("Depends on", p.getDependson()); } if (any || options.sourcepath()) { table.addAll("Source", p.getSourcePath()); } if (any || options.classpath()) { table.addAll("Class path", p.getClasspath()); } if (any || options.vmpath()) { table.addAll("Run path", p.getRunpath()); } printMultiMap(table); } /** * Grep in jars */ @Arguments(arg = { "pattern", "file..." }) @Description("Grep the manifest of bundles/jar files. ") interface grepOptions extends Options { @Description("Search in exports") boolean exports(); @Description("Search in imports") boolean imports(); @Description("Search in bsn") boolean bsn(); @Description("Set header(s) to search, can be wildcarded. The default is all headers (*).") Set<String> headers(); } @Description("Grep the manifest of bundles/jar files. ") public void _grep(grepOptions opts) throws Exception { List<String> args = opts._arguments(); String s = args.remove(0); Pattern pattern = Glob.toPattern(s); if (pattern == null) { messages.InvalidGlobPattern_(s); return; } if (args.isEmpty()) { args = new ExtList<>(getBase().list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".jar"); } })); } Set<String> headers = opts.headers(); if (headers == null) headers = new TreeSet<>(); if (opts.exports()) headers.add(Constants.EXPORT_PACKAGE); if (opts.bsn()) headers.add(Constants.BUNDLE_SYMBOLICNAME); if (opts.imports()) headers.add(Constants.IMPORT_PACKAGE); Instructions instructions = new Instructions(headers); for (String fileName : args) { File file = getFile(fileName); if (!file.isFile()) { messages.NoSuchFile_(file); continue; } try (JarInputStream in = new JarInputStream(IO.stream(file))) { Manifest m = in.getManifest(); for (Object header : m.getMainAttributes() .keySet()) { Attributes.Name name = (Name) header; if (instructions.isEmpty() || instructions.matches(name.toString())) { String h = m.getMainAttributes() .getValue(name); QuotedTokenizer qt = new QuotedTokenizer(h, ",;="); for (String value : qt.getTokenSet()) { Matcher matcher = pattern.matcher(value); while (matcher.find()) { int start = matcher.start() - 8; if (start < 0) start = 0; int end = matcher.end() + 8; if (end > value.length()) end = value.length(); out.printf("%40s : %20s ...%s[%s]%s...\n", fileName, name, value.substring(start, matcher.start()), value.substring(matcher.start(), matcher.end()), value.substring(matcher.end(), end)); } } } } } } } /** * Handle the global settings */ @Description("Set bnd global variables. The key can be wildcard.") @Arguments(arg = { "<key>[=<value>]..." }) interface settingOptions extends Options { @Description("Clear all the settings, including the public and private key") boolean clear(); @Description("Show the public key") boolean publicKey(); @Description("Show the private secret key") boolean secretKey(); @Description("Sign the strings on the commandline") boolean mac(); @Description("Show key in base64") boolean base64(); @Description("Override the default \"~/.bnd/settings.json\" location") String location(); @Description("Generate a new private/public key pair") boolean generate(); @Description("Password for local file") char[] password(); } @Description("Set bnd global variables") public void _settings(settingOptions opts) throws Exception { try { Settings settings = this.settings; char[] password = this.password; if (opts.location() != null) { password = opts.password(); File f = getFile(opts.location()); settings = new Settings(f.getAbsolutePath()); settings.load(password); logger.debug("getting settings from {}", f); } if (opts.clear()) { settings.clear(); logger.debug("clear {}", settings.entrySet()); } if (opts.generate()) { logger.debug("Generating new key pair"); settings.generate(password); } logger.debug("settings {}", opts.clear()); List<String> rest = opts._arguments(); if (opts.publicKey()) { out.println(tos(!opts.base64(), settings.getPublicKey())); } if (opts.secretKey()) { out.println(tos(!opts.base64(), settings.getPrivateKey())); } if (opts.mac()) { for (String s : rest) { byte[] data = s.getBytes(UTF_8); byte[] signature = settings.sign(data); out.printf("%s\n", tos(!opts.base64(), signature)); } } if (rest.isEmpty()) { list(null, settings); } else { boolean set = false; for (String s : rest) { s = s.trim(); Matcher m = ASSIGNMENT.matcher(s); logger.debug("try {}", s); if (m.matches()) { String key = m.group(1); Instructions instr = new Instructions(key); Collection<String> select = instr.select(settings.keySet(), true); // check if there is a value a='b' String value = m.group(4); if (value == null || value.trim() .length() == 0) { // no value // check '=' presence if (m.group(2) == null) { list(select, settings); } else { // we have 'a=', remove for (String k : select) { logger.debug("remove {}={}", k, settings.get(k)); settings.remove(k); set = true; } } } else { logger.debug("assignment {}={}", key, value); settings.put(key, value); set = true; } } else { err.printf("Cannot assign %s\n", s); } } if (set) { logger.debug("saving"); settings.save(password); } } } catch (Exception e) { e.printStackTrace(); } } /** * Set the private key in the settings for this machine * * @param hex * @param data * @throws Exception */ private String tos(boolean hex, byte[] data) { return data.length + " : " + (hex ? Hex.toHexString(data) : Base64.encodeBase64(data)); } private void list(Collection<String> keys, Map<String, String> map) { for (Entry<String, String> e : map.entrySet()) { if (keys == null || keys.contains(e.getKey())) out.printf("%-40s = %s\n", e.getKey(), e.getValue()); } } enum Alg { SHA1, MD5, TIMELESS }; @Description("Digest a number of files") @Arguments(arg = "file...") interface hashOptions extends Options { @Description("Show hex output (default)") boolean hex(); @Description("Show base64 output") boolean b64(); @Description("Show process info") boolean process(); @Description("Show the file name") boolean name(); @Description("Specify the algorithms") List<Alg> algorithm(); } /** * hash a file * * @throws Exception * @throws NoSuchAlgorithmException */ @Description("Digests a number of files") public void _digest(hashOptions o) throws NoSuchAlgorithmException, Exception { long start = System.currentTimeMillis(); long total = 0; List<Alg> algs = o.algorithm(); if (algs == null) algs = Arrays.asList(Alg.SHA1); for (String s : o._arguments()) { File f = getFile(s); if (f.isFile()) { outer: for (Alg alg : algs) { long now = System.currentTimeMillis(); byte[] digest; switch (alg) { default : error("no such algorithm %s", alg); continue outer; case SHA1 : digest = SHA1.digest(f) .digest(); break; case MD5 : digest = MD5.digest(f) .digest(); break; case TIMELESS : Jar j = new Jar(f); digest = j.getTimelessDigest(); break; } StringBuilder sb = new StringBuilder(); String del = ""; if (o.hex() || !o.b64()) { sb.append(del) .append(Hex.toHexString(digest)); del = " "; } if (o.b64()) { sb.append(del) .append(Base64.encodeBase64(digest)); del = " "; } if (o.name()) { sb.append(del) .append(f.getAbsolutePath()); del = " "; } if (o.process()) { sb.append(del) .append(System.currentTimeMillis() - now) .append(" ms ") .append(f.length() / 1000) .append(" Kb"); total += f.length(); } out.println(sb); } } else error("file does not exist %s", f); } if (o.process()) { long time = (System.currentTimeMillis() - start); float mb = total / 1000000; out.format("Total %s Mb, %s ms, %s Mb/sec %s files\n", mb, time, (total / time) / 1024, o._arguments() .size()); } } /** * Maven command * * @throws Exception */ @Description("Maven bundle command") public void _maven(Options options) throws Exception { MavenCommand mc = new MavenCommand(this); mc.use(this); mc.run(options._arguments() .toArray(new String[0]), 1); getInfo(mc); } @Description("Generate autocompletion file for bash") public void _bash(Options options) throws Exception { File tmp = File.createTempFile("bnd-completion", ".tmp"); tmp.deleteOnExit(); try { IO.copy(getClass().getResource("bnd-completion.bash"), tmp); Sed sed = new Sed(tmp); sed.setBackup(false); Reporter r = new ReporterAdapter(); CommandLine c = new CommandLine(r); Map<String, Method> commands = c.getCommands(this); StringBuilder sb = new StringBuilder(); for (String commandName : commands.keySet()) { sb.append(" " + commandName); } sb.append(" help"); sed.replace("%listCommands%", sb.toString() .substring(1)); sed.doIt(); IO.copy(tmp, out); } finally { IO.delete(tmp); } } /** * List actions of the repositories if they implement Actionable and allow * them to be executed */ @Description("Execute an action on a repo, or if no name is give, list the actions") interface ActionOptions extends projectOptions { Glob filter(); boolean tooltip(); } @Description("Execute an action on a repo, or if no name is give, list the actions") public void _action(ActionOptions opts) throws Exception { Project project = getProject(opts.project()); if (project == null) { error("Not in a project directory"); return; } Glob filter = opts.filter(); if (filter == null) filter = new Glob("*"); List<Actionable> actionables = project.getPlugins(Actionable.class); if (actionables.isEmpty()) { error("No actionables in [%s]", project.getPlugins()); return; } for (Actionable o : actionables) { if (filter.matcher(o.title()) .matches()) { logger.debug("actionable {} - {}", o, o.title()); Map<String, Runnable> map = o.actions(); if (map != null) { if (opts._arguments() .isEmpty()) { out.printf("# %s%n", o.title()); if (opts.tooltip() && o.tooltip() != null) { out.printf("%s%n", o.tooltip()); } out.printf("## actions%n"); for (String entry : map.keySet()) { out.printf(" %s%n", entry); } } else { for (String entry : opts._arguments()) { Runnable r = map.get(entry); if (r != null) { r.run(); } } } } } } getInfo(project); } /** * Show the changes in the releases */ @Arguments(arg = {}) @Description("Show the changes in this release of bnd") interface ChangesOptions extends Options { @Description("Print all releases") boolean all(); } static Pattern BUG_P = Pattern.compile("#([0-9]+)"); static Pattern BND_COMMAND_P = Pattern.compile("\\[bnd\\s+([\\w\\d]+)\\s*\\]"); public void _changes(ChangesOptions options) { boolean first = true; Justif j = new Justif(80, 10); Formatter f = j.formatter(); for (Map.Entry<Version, String[]> e : About.CHANGES.entrySet()) { if (options.all() || first) { f.format("$-\nRelease %s\n$-\n", e.getKey()); for (String s : e.getValue()) { f.format("- \t1%s", s.replace('\n', '\f')); Matcher m = BND_COMMAND_P.matcher(s); while (m.find()) { Formatter ff = new Formatter(); ff.format("\n\n"); CommandLine cli = options._command(); cli.help(ff, this, m.group(1)); j.indent(10, ff.out() .toString()); } m = BUG_P.matcher(s); while (m.find()) { f.format("\f-> https://github.com/bndtools/bnd/issues/%s", m.group(1)); } f.format("\n\n"); } } first = false; } j.wrap(); out.println(f.out()); } /** * Find a package in the current project or a set of jars */ @Arguments(arg = "[file]...") @Description("Go through the exports and/or imports and match the given " + "exports/imports globs. If thet match print the file, package and version.") interface FindOptions extends Options { @Description("Glob expression on the imports.") Glob[] imports(); @Description("Glob expression on the exports.") Glob[] exports(); } public void _find(FindOptions options) throws Exception { List<File> files = new ArrayList<>(); List<String> args = options._arguments(); if (args.size() == 0) { Project p = getProject(); if (p == null) { error("This is not a project directory and you have specified no jar files ..."); return; } File output = p.getOutput(); if (output.exists()) { files.add(output); } for (Container c : p.getBuildpath()) { files.add(c.getFile()); } } else { for (String f : args) { File file = getFile(f); files.add(file); } } for (File f : files) { logger.debug("find {}", f); try (Jar jar = new Jar(f)) { Manifest m = jar.getManifest(); if (m != null) { Domain domain = Domain.domain(m); if (options.exports() != null) { Parameters ep = domain.getExportPackage(); for (Glob g : options.exports()) { for (Entry<String, Attrs> exp : ep.entrySet()) { if (g.matcher(exp.getKey()) .matches()) { String v = exp.getValue() .get(VERSION_ATTRIBUTE); if (v == null) v = "0"; out.printf(">%s: %s-%s%n", f.getPath(), exp.getKey(), v); } } } } if (options.imports() != null) { Parameters ip = domain.getImportPackage(); for (Glob g : options.imports()) { for (Entry<String, Attrs> imp : ip.entrySet()) { if (g.matcher(imp.getKey()) .matches()) { String v = imp.getValue() .get(VERSION_ATTRIBUTE); if (v == null) v = "0"; out.printf("<%s: %s-%s%n", f.getPath(), imp.getKey(), v); } } } } } } } } /** * Merge n JARs into a new JAR */ @Arguments(arg = "jarfile...") interface MergeOptions extends Options { @Description("Specify the output file path. The default is output.jar in the current directory") String output(); } @Description("Merge a number of jar files into a new jar file. The used manifest is that of the first" + "given JAR file. The order of the JAR file is the class path order. I.e. earlier resources" + "are preferred over later resources with the same name.") public void __merge(MergeOptions options) throws Exception { String name = options.output() == null ? "output.jar" : options.output(); File out = getFile(name); if (!out.getParentFile() .isDirectory()) { error("Output file is not in a valid directory: %s", out.getParentFile()); } List<String> list = options._arguments(); Collections.reverse(list); try (Jar jar = new Jar(name)) { Jar last = null; for (String member : list) { File m = getFile(member); if (!m.isFile()) { error("%s is not a file", m.getAbsolutePath()); } else { Jar jm = new Jar(m); last = jm; addClose(jm); jar.addAll(jm); } } if (last != null) { jar.setManifest(last.getManifest()); } jar.write(out); } } @Arguments(arg = "<jar-file>...") @Description("Show the Execution Environments of a JAR") interface EEOptions extends Options { } /** * Show the class versions used in a JAR * * @throws Exception */ @Description("Show the Execution Environments of a JAR") public void _ees(EEOptions options) throws Exception { for (String path : options._arguments()) { File f = getFile(path); if (!f.isFile()) { error("Not a file"); } else { try (Analyzer a = new Analyzer(this)) { a.setJar(f); a.analyze(); out.printf("%s %s%n", a.getJar() .getName(), a.getEEs()); } } } } @Description("experimental - parallel build") interface ParallelBuildOptions extends buildoptions { } /** * Lets see if we can build in parallel * * @throws Exception */ public void __par(final ParallelBuildOptions options) throws Exception { ExecutorService pool = Executors.newCachedThreadPool(); final AtomicBoolean quit = new AtomicBoolean(); try { final Project p = getProject(options.project()); final Workspace workspace = p == null || options.full() ? Workspace.getWorkspace(getBase()) : p.getWorkspace(); if (!workspace.exists()) { error("cannot find workspace"); return; } final Collection<Project> targets = p == null ? workspace.getAllProjects() : p.getDependson(); final Forker<Project> forker = new Forker<>(pool); for (final Project dep : targets) { forker.doWhen(dep.getDependson(), dep, new Runnable() { @Override public void run() { if (!quit.get()) { try { dep.compile(false); if (!quit.get()) dep.build(); if (!dep.isOk()) quit.set(true); } catch (Exception e) { e.printStackTrace(); } } } }); } System.err.flush(); forker.start(20000); for (Project dep : targets) { getInfo(dep, dep + ": "); } if (p != null && p.isOk() && !options.full()) { p.compile(options.test()); p.build(); if (options.test() && p.isOk()) p.test(); getInfo(p); } workspace.close(); } finally { pool.shutdownNow(); } } /** * Force a cache update of the workspace * * @throws Exception */ public void _sync(projectOptions options) throws Exception { Workspace ws = getWorkspace((File) null); if (ws == null) { error( "Cannot find workspace, either reside in a project directory, point to a project with --project, or reside in the workspace directory"); return; } ws.syncCache(); } /** * From a set of bsns, create a list of urls */ interface Bsn2UrlOptions extends projectOptions { } static Pattern LINE_P = Pattern.compile("\\s*(([^\\s]#|[^#])+)(\\s*#.*)?"); public void _bsn2url(Bsn2UrlOptions opts) throws Exception { Project p = getProject(opts.project()); if (p == null) { error("You need to be in a project or specify the project with -p/--project"); return; } MultiMap<String, Version> revisions = new MultiMap<>(); for (RepositoryPlugin repo : p.getPlugins(RepositoryPlugin.class)) { if (!(repo instanceof InfoRepository)) continue; for (String bsn : repo.list(null)) { revisions.addAll(bsn, repo.versions(bsn)); } } for (List<Version> versions : revisions.values()) { Collections.sort(versions, Collections.reverseOrder()); } List<String> files = opts._arguments(); for (String f : files) { try (BufferedReader r = IO.reader(getFile(f))) { String line; nextLine: while ((line = r.readLine()) != null) { Matcher matcher = LINE_P.matcher(line); if (!matcher.matches()) continue nextLine; line = matcher.group(1); Parameters bundles = new Parameters(line, this); for (Map.Entry<String, Attrs> entry : bundles.entrySet()) { String bsn = entry.getKey(); VersionRange range = new VersionRange(entry.getValue() .getVersion()); List<Version> versions = revisions.get(bsn); if (versions == null) { error("No for versions for %s", bsn); break nextLine; } for (Version version : versions) { if (range.includes(version)) { for (RepositoryPlugin repo : p.getPlugins(RepositoryPlugin.class)) { if (!(repo instanceof InfoRepository)) continue; InfoRepository rp = (InfoRepository) repo; ResourceDescriptor descriptor = rp.getDescriptor(bsn, version); if (descriptor == null) { error("Found bundle, but no descriptor %s;version=%s", bsn, version); return; } out.println( descriptor.url + " #" + descriptor.bsn + ";version=" + descriptor.version); } } } } } } catch (Exception e) { error("failed to create url list from file %s : %s", f, e); } } } /** * Show the loaded workspace plugins * * @throws Exception */ public void _plugins(projectOptions opts) throws Exception { Workspace ws = getWorkspace(opts.project()); if (ws == null) { error("Can't find a workspace"); return; } int n = 0; for (Object o : ws.getPlugins()) { String s = o.toString(); if (s.trim() .length() == 0) s = o.getClass() .getName(); out.printf("%03d %s%n", n++, s); } } /** * start a local framework */ interface BootstrapOptions extends Options { } public void _bootstrap(BootstrapOptions options) throws Exception { Workspace ws = getWorkspace(getBase()); File buildDir = ws.getBuildDir(); File bndFile = IO.getFile(buildDir, "bnd.bnd"); if (!bndFile.isFile()) { error("No bnd.bnd file found in cnf directory %s", bndFile); return; } Run run = new Run(ws, buildDir, bndFile); run.runLocal(); getInfo(run); } /** * Show all the defaults in bnd */ public void _defaults(Options o) { Processor defaults = Workspace.getDefaults(); out.println(Strings.join("\n", defaults.getProperties() .entrySet())); } /* * Cop a bundle, potentially stripping it */ @Arguments(arg = { "src...", "dest" }) interface CopyOptions extends Options { @Description("Remove all metadata manifest") boolean strip(); @Description("Remove OSGi metadata from the manifest") boolean specific(); @Description("Remove OSGI-OPT") boolean optional(); } public void _copy(CopyOptions options) throws Exception { List<String> files = options._arguments(); if (files.size() < 2) { error("Need at least a source and a destination"); return; } String output = files.remove(files.size() - 1); File dest = new File(getBase(), output); if (files.size() > 1) { if (dest.isFile()) { error("Multiple files require that the output is a directory"); return; } IO.mkdirs(dest); } for (String f : files) { Jar jar = getJar(f); if (jar == null) { error("No such JAR %s", f); continue; } if (options.strip()) { Manifest m = new Manifest(); jar.setManifest(m); } if (options.specific()) { Manifest m = new Manifest(); if (jar.getManifest() != null) { for (Entry<Object, Object> e : jar.getManifest() .getMainAttributes() .entrySet()) { String header = e.getKey() .toString() .toLowerCase(); if (header.startsWith("bundle-")) continue; if (!isIn(Constants.BUNDLE_SPECIFIC_HEADERS, header)) m.getMainAttributes() .put(e.getKey(), e.getValue()); } } jar.setManifest(m); } if (options.optional()) { jar.getDirectories() .remove("OSGI-OPT"); } String name = getJarFileNameFrom(jar.getName()); File out = dest.isDirectory() ? getFile(dest, name) : dest; File tmp = new File("tmp"); jar.write(tmp); jar.close(); IO.rename(tmp, out); } } private boolean isIn(String[] bundleSpecificHeaders, String key) { for (int i = 0; i < bundleSpecificHeaders.length; i++) { if (key.equalsIgnoreCase(bundleSpecificHeaders[i])) return true; } return false; } private String getJarFileNameFrom(String name) { String out = name; int n = out.lastIndexOf('/'); if (n >= 0) { out = out.substring(n + 1); } if (out.endsWith(".jar")) return out; return out + ".jar"; } /** * Add a project, workspace, or plugin */ @Arguments(arg = { "what", "name..." }) interface AddOptions extends Options { } @Description("Add a workspace, or a project or a plugin to the workspace") public void _add(AddOptions opts) throws Exception { List<String> args = opts._arguments(); String what = args.remove(0); if ("project".equals(what)) { Workspace ws = Workspace.findWorkspace(getBase()); if (ws == null) { error("No workspace found from %s", getBase()); return; } for (String pname : args) { ws.createProject(pname); } getInfo(ws); return; } if ("workspace".equals(what)) { for (String pname : args) { File wsdir = getFile(pname); ws = Workspace.createWorkspace(wsdir); if (ws == null) { error("Could not create workspace"); } } getInfo(ws); return; } if ("plugin".equals(what)) { Workspace ws = getWorkspace(getBase()); if (ws == null) { error("No workspace found from %s", getBase()); return; } CommandLine cl = new CommandLine(this); String help = cl.execute(new Plugins(this, ws), "add", new ExtList<>(args)); if (help != null) out.println(help); getInfo(ws); return; } } @Arguments(arg = { "what", "name..." }) interface RemoveOptions extends Options {} @Description("Remove a project or a plugin from the workspace") public void _remove(RemoveOptions opts) throws Exception { List<String> args = opts._arguments(); String what = args.remove(0); Workspace ws = Workspace.findWorkspace(getBase()); if (ws == null) { error("No workspace found from %s", getBase()); return; } if ("project".equals(what)) { for (String pname : args) { Project project = ws.getProject(pname); if (project == null) { error("No such project %s", pname); } else project.remove(); } getInfo(ws); return; } if ("workspace".equals(what)) { error("To delete a workspace, delete the directory"); return; } if ("plugin".equals(what)) { CommandLine cl = new CommandLine(this); String help = cl.execute(new Plugins(this, ws), "remove", new ExtList<>(args)); if (help != null) out.println(help); return; } } /** * Profiles subcmd */ @Description("Profile management. A profile is a JAR that only contains packages and capabilities") @Arguments(arg = { "create", "..." }) public interface ProfileOptions extends Options { } @Description("Profile management. A profile is a JAR that only contains packages and capabilities") public void _profile(ProfileOptions options) throws Exception { Profiles profiles = new Profiles(this, options); CommandLine cmd = options._command(); cmd.subCmd(options, profiles); getInfo(profiles); } /** * Resolve command * * @throws Exception */ public void _resolve(ResolveCommand.ResolveOptions options) throws Exception { ResolveCommand rc = new ResolveCommand(this); String help = options._command() .subCmd(options, rc); if (help != null) out.println(help); getInfo(rc); rc.close(); } /** * Remote command * * @throws Exception */ public void _remote(RemoteCommand.RemoteOptions options) throws Exception { RemoteCommand rc = new RemoteCommand(this, options); String help = options._command() .subCmd(options, rc); if (help != null) out.println(help); getInfo(rc); rc.close(); } /** * Nexus commands * * @throws Exception */ public void _nexus(NexusCommand.NexusOptions options) throws Exception { NexusCommand rc = new NexusCommand(this, options); String help = options._command() .subCmd(options, rc); if (help != null) out.println(help); getInfo(rc); rc.close(); } /** * Export a bndrun file */ interface ExportOptions extends projectOptions { List<String> exporter(); String output(); } public void _export(ExportOptions opts) throws Exception { Project project = getProject(opts.project()); if (project == null) { error("No project"); return; } // temporary project.getWorkspace() .addBasicPlugin(new SubsystemExporter()); for (String bndrun : opts._arguments()) { File f = getFile(bndrun); if (!f.isFile()) { error("No such file: %s", f); continue; } Run run = new Run(project.getWorkspace(), getBase(), f); run.getSettings(this); Parameters exports = new Parameters(); List<String> types = opts.exporter(); if (types != null) { for (String type : types) { exports.putAll(new Parameters(type, this)); } } else { String exportTypes = run.getProperty(Constants.EXPORTTYPE); exports.putAll(new Parameters(exportTypes, this)); } for (Entry<String, Attrs> e : exports.entrySet()) { logger.debug("exporting {} to {} with {}", run, e.getKey(), e.getValue()); Map.Entry<String, Resource> result = run.export(e.getKey(), e.getValue()); getInfo(run); if (result != null && isOk()) { String name = result.getKey(); File output = new File(project.getTarget(), opts.output() == null ? name : opts.output()); if (output.isDirectory()) output = new File(output, name); IO.mkdirs(output.getParentFile()); logger.debug("Got a result for {}, store in {}", e.getKey(), output); IO.copy(result.getValue() .openInputStream(), output); } } } } /** * Flatten a jar */ @Arguments(arg = { "input", "output" }) @Description("Flatten a bundle by expanding all entries on the Bundle-ClassPath") interface FlattenOptions extends Options {} @Description("Flatten a bundle by expanding all entries on the Bundle-ClassPath") public void _flatten(FlattenOptions opts) throws Exception { List<String> inputs = opts._arguments(); String inputPath = inputs.remove(0); String outputPath = inputs.remove(0); File source = getFile(inputPath); if (!source.isFile()) { error("Not a source file %s", source); return; } File destination = getFile(outputPath); IO.mkdirs(destination.getParentFile()); if (!destination.getParentFile() .isDirectory()) { error("Could not create directory for output file %s", outputPath); } Jar input = new Jar(source); addClose(input); Manifest manifest = input.getManifest(); Domain domain = Domain.domain(manifest); List<String> bundleClassPath = new ArrayList<>(domain.getBundleClasspath() .keySet()); if (bundleClassPath.isEmpty()) { warning("%s has no bundle class path", source); return; } Collections.reverse(bundleClassPath); Jar output = new Jar(source.getName()); for (String path : bundleClassPath) { logger.debug("bcp entry {}", path); Resource r = input.getResource(path); if (r == null) { logger.debug("Is directory {}", path); if (path.equals(".")) { addAll(output, input, "", bundleClassPath); } else addAll(output, input, path, null); } else { logger.debug("Is jar {}", path); Jar sub = new Jar(path, r.openInputStream()); addClose(sub); addAll(output, sub, "", null); } } domain.setBundleClasspath("."); output.setManifest(manifest); output.stripSignatures(); output.write(destination); } private void addAll(Jar output, Jar sub, String prefix, List<String> bundleClassPath) { if (prefix.length() > 0 && !prefix.endsWith("/")) prefix += "/"; for (Map.Entry<String, Resource> e : sub.getResources() .entrySet()) { String path = e.getKey(); if (bundleClassPath != null && bundleClassPath.contains(path)) continue; logger.debug("Add {}", path); if (path.equals("META-INF/MANIFEST.MF")) continue; Resource r = e.getValue(); if (path.startsWith(prefix)) { logger.debug("Add {}", path); path = path.substring(prefix.length()); output.putResource(path, r); } else logger.debug("Ignore {} because it does not start with prefix {}", path, prefix); } } private static void exitWithCode(int code) { if (!noExit.get()) { System.exit(code); } } /** * Index command * * @throws Exception */ @Description("Index bundles from the local file system") public void _index(IndexCommand.indexOptions options) throws Exception { IndexCommand ic = new IndexCommand(this); ic.use(this); ic._index(options); ic.close(); } }
biz.aQute.bnd/src/aQute/bnd/main/bnd.java
package aQute.bnd.main; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.BufferedReader; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import aQute.bnd.build.Container; import aQute.bnd.build.Project; import aQute.bnd.build.ProjectBuilder; import aQute.bnd.build.ProjectLauncher; import aQute.bnd.build.ProjectTester; import aQute.bnd.build.Run; import aQute.bnd.build.Workspace; import aQute.bnd.enroute.commands.EnrouteCommand; import aQute.bnd.enroute.commands.EnrouteOptions; import aQute.bnd.header.Attrs; import aQute.bnd.header.OSGiHeader; import aQute.bnd.header.Parameters; import aQute.bnd.help.Syntax; import aQute.bnd.main.BaselineCommands.baseLineOptions; import aQute.bnd.main.BaselineCommands.schemaOptions; import aQute.bnd.main.DiffCommand.diffOptions; import aQute.bnd.main.RepoCommand.repoOptions; import aQute.bnd.maven.MavenCommand; import aQute.bnd.maven.PomFromManifest; import aQute.bnd.osgi.About; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Builder; import aQute.bnd.osgi.Clazz; import aQute.bnd.osgi.Clazz.Def; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Descriptors.PackageRef; import aQute.bnd.osgi.Descriptors.TypeRef; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.FileResource; import aQute.bnd.osgi.Instruction; import aQute.bnd.osgi.Instructions; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.Macro; import aQute.bnd.osgi.Packages; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.Resource; import aQute.bnd.osgi.Verifier; import aQute.bnd.osgi.eclipse.EclipseClasspath; import aQute.bnd.repository.maven.provider.NexusCommand; import aQute.bnd.service.Actionable; import aQute.bnd.service.RepositoryPlugin; import aQute.bnd.service.action.Action; import aQute.bnd.service.repository.InfoRepository; import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor; import aQute.bnd.version.Version; import aQute.bnd.version.VersionRange; import aQute.configurable.Config; import aQute.lib.base64.Base64; import aQute.lib.collections.ExtList; import aQute.lib.collections.MultiMap; import aQute.lib.collections.SortedList; import aQute.lib.filter.Filter; import aQute.lib.getopt.Arguments; import aQute.lib.getopt.CommandLine; import aQute.lib.getopt.Description; import aQute.lib.getopt.Options; import aQute.lib.hex.Hex; import aQute.lib.io.IO; import aQute.lib.justif.Justif; import aQute.lib.settings.Settings; import aQute.lib.strings.Strings; import aQute.lib.tag.Tag; import aQute.lib.utf8properties.UTF8Properties; import aQute.libg.classdump.ClassDumper; import aQute.libg.cryptography.MD5; import aQute.libg.cryptography.SHA1; import aQute.libg.forker.Forker; import aQute.libg.generics.Create; import aQute.libg.glob.Glob; import aQute.libg.qtokens.QuotedTokenizer; import aQute.libg.reporter.ReporterAdapter; import aQute.libg.reporter.ReporterMessages; import aQute.libg.sed.Sed; import aQute.service.reporter.Reporter; /** * Utility to make bundles. @version $Revision: 1.14 $ */ public class bnd extends Processor { private final static Logger logger = LoggerFactory.getLogger(bnd.class); static Pattern ASSIGNMENT = Pattern.compile( // "([^=]+) (= ( ?: (\"|'|) (.+) \\3 )? ) ?", Pattern.COMMENTS); Settings settings = new Settings(); final PrintStream err = System.err; final public PrintStream out = System.out; Justif justif = new Justif(80, 40, 42, 70); BndMessages messages = ReporterMessages.base(this, BndMessages.class); private Workspace ws; private char[] password; private static final ThreadLocal<Boolean> noExit = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; }; }; private static final String DEFAULT_LOG_LEVEL_KEY = "org.slf4j.simpleLogger.defaultLogLevel"; static Pattern JARCOMMANDS = Pattern .compile("(cv?0?(m|M)?f?)|(uv?0?M?f?)|(xv?f?)|(tv?f?)|(i)"); static Pattern COMMAND = Pattern.compile("\\w[\\w\\d]+"); static Pattern EMAIL_P = Pattern.compile( "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", Pattern.CASE_INSENSITIVE); @Description("OSGi Bundle Tool") interface bndOptions extends Options { @Description("Turns errors into warnings so command always succeeds") boolean failok(); @Description("Report errors pedantically") boolean pedantic(); @Description("Print out stack traces when there is an unexpected exception") boolean exceptions(); @Description("Redirect output") File output(); @Description("Use as base directory") String base(); @Description("Trace progress") boolean trace(); @Description("Error/Warning ignore patterns") String[] ignore(); @Description("Provide a settings password") char[] secret(); } public bnd(Workspace ws) { super(ws); } public bnd() {} public static void main(String args[]) throws Exception { Workspace.setDriver(Constants.BNDDRIVER_BND); Workspace.addGestalt(Constants.GESTALT_SHELL, null); Workspace.addGestalt(Constants.GESTALT_INTERACTIVE, null); Workspace ws = Workspace.findWorkspace(IO.work); try (bnd main = new bnd()) { // ws == null ? new bnd() : new bnd(ws); main.start(args); } exitWithCode(0); } /** * For testing */ static void mainNoExit(String args[]) throws Exception { noExit.set(true); main(args); } public void start(String args[]) throws Exception { CommandLine cl = new CommandLine(this); String help = cl.execute(this, "bnd", new ExtList<>(args)); check(); if (help != null) err.println(help); } /** * Rewrite the command line to mimic the jar command * * @param args * @throws Exception */ private void rewrite(List<String> args) throws Exception { if (args.isEmpty()) return; String arg = args.get(0); if (arg.equals("maven")) { // ensure that we do not much with options // because the maven command does not like // that args.add(0, "maven"); return; } if (arg.equals("-version")) { args.set(0, "version"); return; } Matcher m = JARCOMMANDS.matcher(arg); if (m.matches()) { rewriteJarCmd(args); return; } // Project project = getProject(); // if (project != null) { // Action a = project.getActions().get(arg); // if (a != null) { // args.add(0, "project"); // } // } m = COMMAND.matcher(args.get(0)); if (!m.matches()) { args.add(0, "do"); } } private void rewriteJarCmd(List<String> args) { String jarcmd = args.remove(0); char cmd = jarcmd.charAt(0); switch (cmd) { case 'c' : args.add(0, "create"); break; case 'u' : args.add(0, "update"); break; case 'x' : args.add(0, "extract"); break; case 't' : args.add(0, "type"); break; case 'i' : args.add(0, "index"); break; } int start = 1; for (int i = 1; i < jarcmd.length(); i++) { switch (jarcmd.charAt(i)) { case 'v' : args.add(start++, "--verbose"); break; case '0' : args.add(start++, "--nocompression"); break; case 'm' : args.add(start++, "--manifest"); start++; // make the manifest file the parameter break; case 'M' : args.add(start++, "--nomanifest"); break; case 'f' : args.add(start++, "--file"); break; } } } /** * Main command. This has options the bnd base options and will then run * another command. * * @param options * @throws Exception */ @Description("The swiss army tool for OSGi") public void _bnd(bndOptions options) throws Exception { try { set(FAIL_OK, options.failok() + ""); setExceptions(options.exceptions()); setTrace(options.trace()); if (options.trace()) { System.setProperty(DEFAULT_LOG_LEVEL_KEY, "trace"); } else { System.setProperty(DEFAULT_LOG_LEVEL_KEY, "warn"); } setPedantic(options.pedantic()); if (options.base() != null) setBase(getFile(getBase(), options.base())); // And the properties for (Entry<String, String> entry : options._properties() .entrySet()) { setProperty(entry.getKey(), entry.getValue()); } CommandLine handler = options._command(); List<String> arguments = options._arguments(); // Rewrite command line to match jar commands and // handle commands that provide file names rewrite(arguments); logger.debug("rewritten {}", arguments); if (arguments.isEmpty()) { Justif f = new Justif(80, 20, 22, 72); handler.help(f.formatter(), this); err.append(f.wrap()); } else { String cmd = arguments.remove(0); String help = handler.execute(this, cmd, arguments); if (help != null) { err.println(help); } } if (options.secret() != null) { password = options.secret(); settings.load(password); } } catch (Throwable t) { while (t instanceof InvocationTargetException) t = t.getCause(); exception(t, "%s", t); } out.flush(); err.flush(); if (ws != null) getInfo(ws); if (!check(options.ignore())) { System.err.flush(); System.err.flush(); Thread.sleep(1000); exitWithCode(getErrors().size()); } } /** * Options for the jar create command. */ @Description("Equivalent jar command c[v0mf] command (supports the jar tool's syntax). Will wrap the bundle unless --wrapnot is specified") interface createOptions extends Options { @Description("Verbose (v option)") boolean verbose(); @Description("No compression (0 option)") boolean nocompression(); @Description("No manifest (M option)") boolean Manifest(); @Description("Use manifest (m option)") String manifest(); @Description("Jar file (f option)") String file(); @Description("directory") String cdir(); @Description("Wrap") boolean wrap(); @Description("Properties for wrapping") String properties(); @Description("Bundle Symbolic Name for wrap") String bsn(); @Description("Bundle Version for wrap") Version version(); @Description("Force write event if there are errors") boolean force(); } /** * Create jar file * * <pre> * jar c[v0M]f jarfile [-C dir] inputfiles [-Joption] * jar c[v0]mf manifest jarfile [-C dir] inputfiles [-Joption] jar c[v0M] * [-C dir] inputfiles [-Joption] jar c[v0]m manifest [-C dir] inputfiles * [-Joption] * </pre> * * @param options * @throws Exception */ @Description("Create jar, used to support backward compatible java jar commands") public void _create(createOptions options) throws Exception { Jar jar = new Jar("dot"); File dir = getBase().getAbsoluteFile(); String sdir = options.cdir(); if (sdir != null) dir = getFile(sdir); if (options._arguments() .isEmpty()) add(jar, dir, ".", options.verbose()); else for (String f : options._arguments()) { f = IO.normalizePath(f); add(jar, dir, f, options.verbose()); } String manifest = options.manifest(); if (manifest != null) { if (options.verbose()) err.printf("Adding manifest from %s\n", manifest); jar.setManifest(getFile(manifest)); } if (options.Manifest()) { jar.setManifest((Manifest) null); } else { if (options.wrap()) { Analyzer w = new Analyzer(this); addClose(w); w.setBase(getBase()); w.use(this); w.setDefaults(options.bsn(), options.version()); w.calcManifest(); getInfo(w); w.setJar((Jar) null); w.close(); } } if (options.nocompression()) jar.setCompression(Jar.Compression.STORE); if (isOk()) { String jarFile = options.file(); if (jarFile == null) jar.write(System.out); else jar.write(jarFile); } jar.close(); } /** * Helper for the jar create function, adds files to the jar * * @param jar * @param base * @param path * @param report * @throws IOException */ private void add(Jar jar, File base, String path, boolean report) throws IOException { if (path.endsWith("/")) path = path.substring(0, path.length() - 1); File f; if (path.equals(".")) f = base; else f = getFile(base, path); err.printf("Adding: %s\n", path); if (f.isFile()) { jar.putResource(path, new FileResource(f)); } else if (f.isDirectory()) { if (path.equals(".")) path = ""; else path += "/"; String[] subs = f.list(); for (String sub : subs) { add(jar, base, path + sub, report); } } } /** * Extract a file from the JAR */ @Description("Extract files from a JAR file, equivalent jar command x[vf] (syntax supported)") interface extractOptions extends Options { @Description("Verbose (v option)") boolean verbose(); @Description("Jar file (f option)") String file(); @Description("Directory where to store") String cdir(); } @Description("Extract files from a JAR file, equivalent jar command x[vf] (syntax supported)") public void _extract(extractOptions opts) throws Exception { Jar jar; if (opts.file() != null) { File f = getFile(opts.file()); if (!f.isFile()) { messages.NoSuchFile_(f); return; } jar = new Jar(f); } else { jar = new Jar("cin", System.in); } try { Instructions instructions = new Instructions(opts._arguments()); Collection<String> selected = instructions.select(jar.getResources() .keySet(), true); File store = getBase(); if (opts.cdir() != null) store = getFile(opts.cdir()); IO.mkdirs(store); Jar.Compression compression = jar.hasCompression(); for (String path : selected) { if (opts.verbose()) System.err.printf("%8s: %s\n", compression.toString() .toLowerCase(), path); File f = getFile(store, path); File pf = f.getParentFile(); IO.mkdirs(pf); Resource r = jar.getResource(path); IO.copy(r.openInputStream(), f); } } finally { jar.close(); } } /** * List the contents of the JAR */ @Description("List files int a JAR file, equivalent jar command t[vf] (syntax supported)") interface typeOptions extends Options { @Description("Verbose (v option)") boolean verbose(); @Description("Jar file (f option)") String file(); } @Description("List files int a JAR file, equivalent jar command t[vf] (syntax supported)") public void _type(typeOptions opts) throws Exception { Jar jar; if (opts.file() != null) { File f = getFile(opts.file()); if (!f.isFile()) { messages.NoSuchFile_(f); return; } jar = new Jar(f); } else { jar = new Jar("cin", System.in); } try { Instructions instructions = new Instructions(opts._arguments()); Collection<String> selected = instructions.select(jar.getResources() .keySet(), true); for (String path : selected) { if (opts.verbose()) { Resource r = jar.getResource(path); err.printf("%8s %-32s %s\n", r.size(), new Date(r.lastModified()), path); } else err.printf("%s\n", path); } } finally { jar.close(); } } @Description("Execute a file based on its extension. Supported extensions are: bnd (build), bndrun (run), and jar (print)") interface dooptions extends Options { @Description("The output file") String output(); @Description("Force even when there are errors") boolean force(); } /** * The do command interprets files and does a default action for each file * * @throws Exception */ @Description("Execute a file based on its extension. Supported extensions are: bnd (build), bndrun (run), and jar (print)") public void _do(dooptions options) throws Exception { for (String path : options._arguments()) { if (path.endsWith(Constants.DEFAULT_BND_EXTENSION)) { build(options.output(), options.force(), path); } else if (path.endsWith(Constants.DEFAULT_JAR_EXTENSION) || path.endsWith(Constants.DEFAULT_BAR_EXTENSION)) { try (Jar jar = getJar(path)) { doPrint(jar, MANIFEST, null); } } else if (path.endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { doRun(Arrays.asList(path), false, null); } else messages.UnrecognizedFileType_(path); } } public void build(String dest, boolean force, String path) throws IOException, Exception { try (Builder b = new Builder()) { File f = getFile(path); if (!f.isFile()) { error("No such file %s", f); return; } b.use(this); b.setProperties(f); List<Builder> subs = b.getSubBuilders(); for (Builder bb : subs) { logger.debug("building {}", bb.getPropertiesFile()); bb.build(); File out = bb.getOutputFile(dest); getInfo(bb, bb.getBsn() + ": "); if (isOk()) { bb.save(out, force); } getInfo(bb, bb.getBsn() + ": "); // pickup any save errors if (!isOk()) { IO.delete(out); } } } } /** * Project command, executes actions. */ @Description("Execute a Project action, or if no parms given, show information about the project") @Arguments(arg = {}) interface projectOptions extends Options { @Description("Identify another project") String project(); } @Description("Execute a Project action, or if no parms given, show information about the project") public void _project(projectOptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } List<String> l = new ArrayList<>(options._arguments()); if (l.isEmpty()) { err.printf("Name %s\n", project.getName()); err.printf("Actions %s\n", project.getActions() .keySet()); err.printf("Directory %s\n", project.getBase()); err.printf("Depends on %s\n", project.getDependson()); try (ProjectBuilder pb = project.getBuilder(null)) { err.printf("Sub builders %s\n", pb.getSubBuilders()); } return; } String cmd = null; String arg = null; if (!l.isEmpty()) cmd = l.remove(0); if (!l.isEmpty()) arg = l.remove(0); if (!l.isEmpty()) { messages.MoreArgumentsThanNeeded_(options._arguments()); return; } if (cmd == null) { messages.NoCommandForProject(project); return; } Action a = project.getActions() .get(cmd); if (a != null) { a.execute(project, arg); getInfo(project); return; } } @Description("Bumps the version of a project. Will take the current version and then increment " + "with a major, minor, or micro increment. The default bump is minor.") @Arguments(arg = "<major|minor|micro>") interface bumpoptions extends Options { @Description("Path to another project than the current project") String project(); } /** * Bump a version number * * @throws Exception */ @Description("Bumps the version of a project") public void _bump(bumpoptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } String mask = null; if (!options._arguments() .isEmpty()) { mask = options._arguments() .get(0); if (mask.equalsIgnoreCase("major")) mask = "+00"; else if (mask.equalsIgnoreCase("minor")) mask = "=+0"; else if (mask.equalsIgnoreCase("micro")) mask = "==+"; else if (!mask.matches("[+=0]{1,3}")) { messages.InvalidBumpMask_(mask); return; } } if (mask == null) project.bump(); else project.bump(mask); getInfo(project); err.println(project.getProperty(BUNDLE_VERSION, "No version found")); } interface PerProject { void doit(Project p) throws Exception; } public void perProject(projectOptions opts, PerProject run) throws Exception { Collection<Project> list; Project project = getProject(opts.project()); if (project == null) { Workspace ws = Workspace.findWorkspace(getBase()); if (!ws.isValid()) { messages.NoValidWorkspace(getBase()); } list = ws.getAllProjects(); if (list.isEmpty()) { out.println("No projects"); } return; } else { list = Arrays.asList(project); } for (Project p : list) { run.doit(p); getInfo(p, p + ": "); } } @Description("Build a project. This will create the jars defined in the bnd.bnd and sub-builders.") @Arguments(arg = {}) interface buildoptions extends projectOptions { @Description("Build for test") boolean test(); @Description("Do full") boolean full(); } @Description("Build a project. This will create the jars defined in the bnd.bnd and sub-builders.") public void _build(final buildoptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project p) throws Exception { p.build(opts.test()); } }); } @Arguments(arg = {}) interface CompileOptions extends projectOptions { @Description("Compile for test") boolean test(); } @Description("Compile a project or the workspace") public void _compile(final CompileOptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project p) throws Exception { p.compile(opts.test()); } }); } @Description("Test a project according to an OSGi test") @Arguments(arg = { "testclass[:method]..." }) interface testOptions extends projectOptions { @Description("Verify all the dependencies before launching (runpath, runbundles, testpath)") boolean verify(); @Description("Launch the test even if this bundle does not contain " + Constants.TESTCASES) boolean force(); @Description("Set the -testcontinuous flag") boolean continuous(); @Description("Set the -runtrace flag") boolean trace(); } @Description("Test a project according to an OSGi test") public void _test(final testOptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project project) throws Exception { List<String> testNames = opts._arguments(); if (!testNames.isEmpty()) project.setProperty(TESTCASES, ""); if (project.is(NOJUNITOSGI) && !opts.force()) { warning("%s is set to true on this bundle. Use -f/--force to try this test anyway", NOJUNITOSGI); return; } if (project.getProperty(TESTCASES) == null) if (opts.force()) project.setProperty(TESTCASES, ""); else { warning( "No %s set on this bundle. Use -f/--force to try this test anyway (this works if another bundle provides the testcases)", TESTCASES); return; } if (opts.continuous()) project.setProperty(TESTCONTINUOUS, "true"); if (opts.trace() || isTrace()) project.setProperty(RUNTRACE, "true"); project.test(testNames); } }); } @Description("Test a project with plain JUnit") public void _junit(testOptions opts) throws Exception { perProject(opts, new PerProject() { @Override public void doit(Project p) throws Exception { p.junit(); } }); } private boolean verifyDependencies(Project project, boolean implies, boolean test) throws Exception { if (!implies) { return true; } project.verifyDependencies(test); getInfo(project); if (isOk()) return true; return false; } @Description("Run a project in the OSGi launcher. If not bndrun is specified, the current project is used for the run specification") @Arguments(arg = "[bndrun]") interface runOptions extends Options { @Description("Path to another project than the current project. Only valid if no bndrun is specified") String project(); @Description("Verify all the dependencies before launching (runpath, runbundles)") boolean verify(); } @Description("Run a project in the OSGi launcher") public void _run(runOptions opts) throws Exception { doRun(opts._arguments(), opts.verify(), opts.project()); } private void doRun(List<String> args, boolean verify, String project) throws Exception { Project run = null; if (args.isEmpty()) { run = getProject(project); if (run == null) { messages.NoProject(); return; } } else { File f = getFile(args.get(0)); File dir = f.getParentFile(); File wsdir = dir.getParentFile(); if (wsdir == null) { // We are in the filesystem root?? Create a standalone run. run = Run.createRun(null, f); } else { Workspace workspace = Workspace.getWorkspaceWithoutException(wsdir); run = Run.createRun(workspace, f); } } verifyDependencies(run, verify, false); try { run.run(); } catch (Exception e) { messages.Failed__(e, "Running " + run); } getInfo(run); getInfo(run.getWorkspace()); } @Description("Clean a project") interface cleanOptions extends Options { @Description("Path to another project than the current project") String project(); } @Description("Clean a project") public void _clean(cleanOptions opts) throws Exception { Project project = getProject(opts.project()); if (project == null) { messages.NoProject(); return; } project.clean(); getInfo(project); } @Description("Access the internal bnd database of keywords and options") @Arguments(arg = { "header|instruction", "..." }) interface syntaxOptions extends Options { @Description("The width of the printout") int width(); } @Description("Access the internal bnd database of keywords and options") public void _syntax(syntaxOptions opts) throws Exception { int w = opts.width() < 80 ? 120 : opts.width(); Justif justif = new Justif(w, opts.width(), 40, 42, w - 10); List<String> args = opts._arguments(); StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); for (String s : args) { f.format(" \n[%s]\n", s); Syntax sx = Syntax.HELP.get(s); if (s == null) f.format("Unknown"); else { print(f, sx, " "); } } f.flush(); justif.wrap(sb); err.println(sb); } private void print(Formatter f, Syntax sx, String indent) { if (sx == null) return; f.format("%s%s\n\n", indent, sx.getLead()); if (sx.getValues() != null) f.format("%sValues\t1:\t2%s\n", indent, sx.getValues()); if (sx.getPattern() != null) f.format("%sPattern \t1:\t2%s\n", indent, sx.getPattern()); if (sx.getExample() != null) f.format("%sExample \t1:\t2%s\n", indent, sx.getExample()); if (sx.getChildren() != null) { for (Syntax child : sx.getChildren()) { f.format("\n%s[%s]\t1:\t2", indent, child.getHeader()); print(f, child, indent + " "); } } } @Description("Package a bnd or bndrun file into a single jar that executes with java -jar <>.jar. The JAR contains all dependencies, including the framework and the launcher. " + "A profile can be specified which will be used to find properties. If a property is not found, a property with the name [<profile>]NAME will be looked up. This allows " + "you to make different profiles for testing and runtime.") @Arguments(arg = { "<bnd|bndrun>", "[...]" }) interface packageOptions extends Options { @Description("Where to store the resulting file. Default the name of the bnd file with a .jar extension.") String output(); @Description("Profile name. Default no profile") String profile(); } /** * Package a bnd or bndrun file for packaging. * * @throws Exception */ @Description("Package a bnd or bndrun file into a single jar that executes with java -jar <>.jar") public void _package(packageOptions opts) throws Exception { List<String> cmdline = opts._arguments(); File output = null; if (opts.output() != null) { output = getFile(opts.output()); } else output = getBase(); if (opts._arguments() .size() > 1) { IO.mkdirs(output); } else { File pf = output.getParentFile(); IO.mkdirs(pf); } String profile = opts.profile() == null ? "exec" : opts.profile(); if (cmdline.isEmpty()) cmdline.add(Project.BNDFILE); // default project itself for (String path : cmdline) { Run run; File file = getFile(path); if (file.isDirectory()) file = new File(file, Project.BNDFILE); if (!file.isFile()) { messages.NoSuchFile_(file); continue; } File dir = file.getParentFile(); File workspaceDir = dir.getParentFile(); if (workspaceDir == null) { // We are in the filesystem root?? Create a standalone run. run = Run.createRun(null, file); } else { Workspace ws = Workspace.getWorkspaceWithoutException(workspaceDir); run = Run.createRun(ws, file); } // Tricky because we can be run inside the context of a // project (in which case // we need to inherit from the project or outside. run.setProperty(PROFILE, profile); run.use(this); try { Jar jar = run.pack(profile); path = path.replaceAll(".bnd(run)?$", "") + ".jar"; File out = output; if (output.isDirectory()) out = new File(output, path); jar.write(out); jar.close(); } catch (Exception e) { messages.ForProject_File_FailedToCreateExecutableException_(run, path, e); } getInfo(run); } } /** * List all deliverables for this workspace. */ @Description("Show all deliverables from this workspace. with their current version and path.") @Arguments(arg = {}) interface deliverableOptions extends Options { @Description("Path to project, default current directory") String project(); @Description("Only provide deliverables of this project") boolean limit(); } @Description("Show all deliverables from this workspace. with their current version and path.") public void _deliverables(deliverableOptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } Collection<Project> projects; if (options.limit()) projects = Arrays.asList(project); else projects = project.getWorkspace() .getAllProjects(); List<Container> containers = new ArrayList<>(); for (Project p : projects) { containers.addAll(p.getDeliverables()); } for (Container c : containers) { Version v = new Version(c.getVersion()); err.printf("%-40s %8s %s\n", c.getBundleSymbolicName(), v.getWithoutQualifier(), c.getFile()); } getInfo(project); } @Description("Show macro value. Macro can contain the ${ and } parentheses but it is also ok without. You can use the ':' instead of the ';' in a macro") @Arguments(arg = { "<macro>", "[...]" }) interface macroOptions extends Options { @Description("Path to project, default current directory") String project(); } /** * Show the value of a macro * * @throws Exception */ @Description("Show macro value") public void _macro(macroOptions options) throws Exception { Project project = getProject(options.project()); if (project == null) { messages.NoProject(); return; } StringBuilder sb = new StringBuilder(); Macro r = project.getReplacer(); getInfo(project); String del = ""; for (String s : options._arguments()) { if (!s.startsWith("${")) { s = "${" + s; } if (!s.endsWith("}")) { s += "}"; } s = s.replace(':', ';'); String p = r.process(s); sb.append(del); sb.append(p); del = " "; } getInfo(project); err.println(sb); } @Description("Release this project") interface releaseOptions extends Options { @Description("Path to project, default is current project") String project(); @Description("Release with test build") boolean test(); @Description("Set the release repository") String repo(); @Description("Release all bundles in in the workspace") boolean workspace(); } /** * Release the project * * @throws Exception */ @Description("Release this project") public void _release(releaseOptions options) throws Exception { Set<Project> projects = new LinkedHashSet<>(); Workspace ws = Workspace.findWorkspace(getBase()); if (ws == null) { error("Workspace option was specified but cannot find a workspace from %s", getBase()); return; } if (options.workspace()) { projects.addAll(ws.getAllProjects()); } Project project = getProject(options.project()); if (project != null) { projects.add(project); } if (projects.isEmpty()) { error("Cannot find any projects"); return; } String repo = options.repo(); if (repo != null) { RepositoryPlugin repository = ws.getRepository(repo); if (repository == null) { error("No such release repo %s%nFound:%n%s", repository, Strings.join("\n", ws.getRepositories())); } } for (Project p : projects) { if (repo != null) { p.setProperty(Constants.RELEASEREPO, repo); } p.release(options.test()); } getInfo(project); } @Description("Show a cross references for all classes in a set of jars.") @Arguments(arg = { "<jar path>", "[...]" }) interface xrefOptions extends Options { @Description("Show classes instead of packages") boolean classes(); @Description("Show references to other classes/packages (>)") boolean to(); @Description("Show references from other classes/packages (<)") boolean from(); @Description("Filter for class names, a globbing expression") List<String> match(); } static public class All { public Map<TypeRef, List<TypeRef>> classes = new HashMap<>(); public Map<PackageRef, List<PackageRef>> packages = new HashMap<>(); } /** * Cross reference every class in the jar file to the files it references */ @Description("Show a cross references for all classes in a set of jars.") public void _xref(xrefOptions options) throws IOException, Exception { Analyzer analyzer = new Analyzer(); final MultiMap<TypeRef, TypeRef> table = new MultiMap<>(); final MultiMap<PackageRef, PackageRef> packages = new MultiMap<>(); Set<TypeRef> set = Create.set(); Instructions filter = new Instructions(options.match()); for (String arg : options._arguments()) { try { File file = new File(arg); try (Jar jar = new Jar(file.getName(), file)) { for (Map.Entry<String, Resource> entry : jar.getResources() .entrySet()) { String key = entry.getKey(); Resource r = entry.getValue(); if (key.endsWith(".class")) { TypeRef ref = analyzer.getTypeRefFromPath(key); if (filter.matches(ref.toString())) { set.add(ref); try (InputStream in = r.openInputStream()) { Clazz clazz = new Clazz(analyzer, key, r); // TODO use the proper bcp instead // of using the default layout Set<TypeRef> s = clazz.parseClassFile(); for (Iterator<TypeRef> t = s.iterator(); t.hasNext();) { TypeRef tr = t.next(); if (tr.isJava() || tr.isPrimitive()) t.remove(); else packages.add(ref.getPackageRef(), tr.getPackageRef()); } table.addAll(ref, s); set.addAll(s); } } } } } } catch (Exception e) { e.printStackTrace(); } } boolean to = options.to(); boolean from = options.from(); if (to == false && from == false) to = from = true; if (options.classes()) { if (to) printxref(table, ">"); if (from) printxref(table.transpose(), "<"); } else { if (to) printxref(packages, ">"); if (from) printxref(packages.transpose(), "<"); } } private void printxref(MultiMap<?, ?> map, String direction) { SortedList<?> labels = new SortedList<Object>(map.keySet(), null); for (Object element : labels) { List<?> e = map.get(element); if (e == null) { // ignore } else { Set<Object> set = new LinkedHashSet<>(e); set.remove(element); Iterator<?> row = set.iterator(); String first = ""; if (row.hasNext()) first = row.next() .toString(); out.printf("%50s %s %s\n", element, direction, first); while (row.hasNext()) { out.printf("%50s %s\n", "", row.next()); } } } } @Description("Show info about the current directory's eclipse project") @Arguments(arg = {}) interface eclipseOptions extends Options { @Description("Path to the project") String dir(); } @Description("Show info about the current directory's eclipse project") public void _eclipse(eclipseOptions options) throws Exception { File dir = getBase(); if (options.dir() != null) dir = getFile(options.dir()); if (!dir.isDirectory()) error("Eclipse requires a path to a directory: %s", dir.getAbsolutePath()); if (options._arguments() .size() != 0) error("Unnecessary arguments %s", options._arguments()); if (!isOk()) return; File cp = new File(dir, ".classpath"); if (!cp.exists()) { error("Cannot find .classpath in project directory: %s", dir.getAbsolutePath()); } else { EclipseClasspath eclipse = new EclipseClasspath(this, dir.getParentFile(), dir); err.println("Classpath " + eclipse.getClasspath()); err.println("Dependents " + eclipse.getDependents()); err.println("Sourcepath " + eclipse.getSourcepath()); err.println("Output " + eclipse.getOutput()); err.println(); } } /** * Buildx */ final static int BUILD_SOURCES = 1; final static int BUILD_POM = 2; final static int BUILD_FORCE = 4; @Description("Build project, is deprecated but here for backward compatibility. If you use it, you should know how to use it so no more info is provided.") interface buildxOptions extends Options { String output(); List<String> classpath(); List<String> sourcepath(); boolean eclipse(); boolean noeclipse(); boolean sources(); boolean pom(); boolean force(); } @Description("Build project, is deprecated but here for backward compatibility") public void _buildx(buildxOptions options) throws Exception { // Create a build order List<Builder> builders = new ArrayList<>(); List<String> order = new ArrayList<>(); List<String> active = new ArrayList<>(); for (String s : options._arguments()) { prebuild(active, order, builders, s); } for (Builder b : builders) { if (options.classpath() != null) { for (String f : options.classpath()) { b.addClasspath(getFile(f)); } } if (options.sourcepath() != null) { for (String f : options.sourcepath()) { b.addSourcepath(getFile(f)); } } if (options.sources()) b.setSources(true); if (options.eclipse()) { EclipseClasspath ep = new EclipseClasspath(this, getBase().getParentFile(), getBase()); b.addClasspath(ep.getClasspath()); b.addClasspath(ep.getBootclasspath()); b.addSourcepath(ep.getSourcepath()); } Jar jar = b.build(); File outputFile = b.getOutputFile(options.output()); if (options.pom()) { Resource r = new PomFromManifest(jar.getManifest()); jar.putResource("pom.xml", r); String path = outputFile.getName() .replaceAll("\\.jar$", ".pom"); if (path.equals(outputFile.getName())) path = outputFile.getName() + ".pom"; File pom = new File(outputFile.getParentFile(), path); try (OutputStream os = IO.outputStream(pom)) { r.write(os); } } getInfo(b, b.getPropertiesFile() .getName()); if (isOk()) { b.save(outputFile, options.force()); } b.close(); } } // Find the build order // by recursively passing // through the builders. private void prebuild(List<String> set, List<String> order, List<Builder> builders, String s) throws IOException { if (order.contains(s)) // Already done return; if (set.contains(s)) error("Cyclic -prebuild dependency %s from %s", s, set); Builder b = new Builder(this); b.setProperties(getFile(s)); String prebuild = b.get("prebuild"); if (prebuild != null) { set.add(s); try { Collection<String> parts = split(prebuild); for (String p : parts) { prebuild(set, order, builders, p); } } finally { set.remove(s); } } order.add(s); builders.add(b); } @Description("View a resource from a JAR file. Manifest will be pretty printed and class files are shown disassembled.") @Arguments(arg = { "<jar-file>", "<resource>", "[...]" }) interface viewOptions extends Options { @Description("Character set to use for viewing") String charset(); } /** * View files from JARs We parse the commandline and print each file on it. * * @throws Exception */ @Description("View a resource from a JAR file.") public void _view(viewOptions options) throws Exception { Charset charset = UTF_8; if (options.charset() != null) charset = Charset.forName(options.charset()); if (options._arguments() .isEmpty()) { error("Need a jarfile as source"); return; } List<String> args = options._arguments(); File file = getFile(args.remove(0)); if (!file.isFile()) { error("File does not exist %s", file); return; } try (Jar jar = new Jar(file)) { if (args.isEmpty()) args.add("*"); Instructions instructions = new Instructions(args); Collection<String> selected = instructions.select(jar.getResources() .keySet(), true); for (String selection : selected) { Resource r = jar.getResource(selection); if (selection.endsWith(".MF")) { Manifest m = new Manifest(r.openInputStream()); printManifest(m); } else if (selection.endsWith(".class")) { ClassDumper clsd = new ClassDumper(selection, r.openInputStream()); clsd.dump(out); } else { InputStreamReader isr = new InputStreamReader(r.openInputStream(), charset); IO.copy(isr, out); } } } } @Description("Wrap a jar into a bundle. This is a poor man's facility to " + "quickly turn a non-OSGi JAR into an OSGi bundle. " + "It is usually better to write a bnd file and use the bnd <file>.bnd " + "command because that has greater control. Even better is to wrap in bndtools.") @Arguments(arg = { "<jar-file>", "[...]" }) interface wrapOptions extends Options { @Description("Path to the output, default the name of the input jar with the '.bar' extension. If this is a directory, the output is place there.") String output(); @Description("A file with properties in bnd format.") String properties(); @Description("A classpath specification") List<String> classpath(); @Description("Allow override of an existing file") boolean force(); @Description("Set the bundle symbolic name to use") String bsn(); @Description("Set the version to use") Version version(); } /** * Wrap a jar to a bundle. * * @throws Exception */ @Description("Wrap a jar") public void _wrap(wrapOptions options) throws Exception { List<File> classpath = Create.list(); File properties = getBase(); if (options.properties() != null) { properties = getFile(options.properties()); } if (options.classpath() != null) for (String cp : options.classpath()) { classpath.add(getFile(cp)); } for (String j : options._arguments()) { File file = getFile(j); if (!file.isFile()) { error("File does not exist %s", file); continue; } try (Analyzer wrapper = new Analyzer(this)) { wrapper.use(this); for (File f : classpath) wrapper.addClasspath(f); wrapper.setJar(file); File outputFile = wrapper.getOutputFile(options.output()); if (outputFile.getCanonicalFile() .equals(file.getCanonicalFile())) { // #267: CommandLine wrap deletes target even if file equals // source error("Output file %s and source file %s are the same file, they must be different", outputFile, file); return; } IO.delete(outputFile); String stem = file.getName(); if (stem.endsWith(".jar")) stem = stem.substring(0, stem.length() - 4) + ".bnd"; File p = getPropertiesFile(properties, file, stem); if (p == null) { wrapper.setImportPackage("*;resolution:=optional"); wrapper.setExportPackage("*"); warning("Using defaults for wrap, which means no export versions"); } else if (p.isFile()) wrapper.setProperties(p); else { error("No valid property file: %s", p); } if (options.bsn() != null) wrapper.setBundleSymbolicName(options.bsn()); if (options.version() != null) wrapper.setBundleVersion(options.version()); Manifest m = wrapper.calcManifest(); if (wrapper.isOk()) { wrapper.getJar() .setManifest(m); wrapper.save(outputFile, options.force()); } getInfo(wrapper, file.toString()); } } } private File getPropertiesFile(File properties, File file, String stem) { if (properties.isFile()) return properties; File p = getFile(file.getParentFile(), stem); if (p.isFile()) return p; if (properties.isDirectory()) { p = getFile(properties, stem); if (p.isFile()) return p; } return null; } @Description("Show a lot of info about the project you're in") interface debugOptions extends Options { @Description("Path to a project, default is current directory") String project(); @Description("Show the flattened properties") boolean flattened(); } /** * Printout all the variables in scope. * * @throws Exception */ @SuppressWarnings("unchecked") @Description("Show a lot of info about the project you're in") public void _debug(debugOptions options) throws Exception { Project project = getProject(options.project()); Justif justif = new Justif(120, 40, 50, 52, 80); logger.debug("using {}", project); Processor target = project; if (project != null) { Workspace ws = project.getWorkspace(); ws.checkStructure(); getInfo(project.getWorkspace()); report(justif, "Workspace", project.getWorkspace()); report(justif, "Project", project); try (ProjectBuilder pb = project.getBuilder(null)) { List<Builder> builders = pb.getSubBuilders(); if (builders != null) { for (Builder sub : builders) { report(justif, "Sub-Builder", sub); getInfo(sub); } } } for (File file : project.getBase() .listFiles()) { if (file.getName() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { Run run = Workspace.getRun(file); if (run == null) { error("No such run file %s", file); } else { report(justif, "bndrun", run); getInfo(run); } } } if (options.flattened()) { @SuppressWarnings("rawtypes") Map fp = project.getFlattenedProperties(); Justif j = new Justif(140, 40, 44, 48, 100); j.table(fp, "-"); out.println(j.wrap()); } getInfo(project.getWorkspace()); getInfo(project); } else err.println("No project"); } private void report(Justif justif, String string, Processor processor) throws Exception { Map<String, Object> table = new LinkedHashMap<>(); processor.report(table); Justif j = new Justif(140, 40, 44, 48, 100); j.formatter() .format("$-\n%s %s\n$-\n", string, processor); j.table(table, "-"); out.println(j.wrap()); out.println(); } /** * Manage the repo. * * <pre> * out.println(&quot; bnd repo [--repo|-r ('maven'| * &lt;dir&gt;)]*&quot;); out.println(&quot; repos # list the * repositories&quot;); out.println(&quot; list # list all content (not * always possible)&quot;); out.println(&quot; get &lt;bsn&gt; * &lt;version&gt; &lt;file&gt;? # get an artifact&quot;); * out.println(&quot; put &lt;file&gt;+ # put in artifacts&quot;); * out.println(&quot; help&quot;); * </pre> */ @Description("Manage the repositories") public void _repo(repoOptions opts) throws Exception { new RepoCommand(this, opts); } /** * Run enroute commands */ @Description("OSGi enRoute commands to maintain bnd workspaces (create workspace, add project, etc)") public void _enroute(EnrouteOptions opts) throws Exception { new EnrouteCommand(this, opts); } /** * Print out a JAR */ final static int VERIFY = 1; final static int MANIFEST = 2; final static int LIST = 4; final static int IMPEXP = 16; final static int USES = 32; final static int USEDBY = 64; final static int COMPONENT = 128; final static int METATYPE = 256; final static int API = 512; final static int CAPABILITIES = 1024; static final int HEX = 0; @Arguments(arg = "jar-file...") @Description("Provides detailed view of the bundle. It will analyze the bundle and then show its contents from different perspectives. If no options are specified, prints the manifest.") interface printOptions extends Options { @Description("Print the api usage. This shows the usage constraints on exported packages when only public API is used.") boolean api(); @Description("Before printing, verify that the bundle is correct.") boolean verify(); @Description("Print the manifest.") boolean manifest(); @Description("List the resources") boolean list(); @Description("List the imports exports, versions and ranges") boolean impexp(); @Description("Show for each contained package, what other package it uses. Is either an private, exported, or imported package") boolean uses(); @Description("Transposed uses. Will show for each known package who it is used by.") boolean by(); @Description("Show components in detail") boolean component(); @Description("Show any metatype data") boolean typemeta(); @Description("Keep references to java in --api, --uses, and --usedby.") boolean java(); @Description("Show all packages, not just exported, in the API view") boolean xport(); @Description("Show the capabilities") boolean capabilities(); } @Description("Printout the JAR") public void _print(printOptions options) throws Exception { for (String s : options._arguments()) { int opts = 0; if (options.verify()) opts |= VERIFY; if (options.manifest()) opts |= MANIFEST; if (options.api()) opts |= API; if (options.list()) opts |= LIST; if (options.impexp()) opts |= IMPEXP; if (options.uses()) opts |= USES; if (options.by()) opts |= USEDBY; if (options.component()) opts |= COMPONENT; if (options.typemeta()) opts |= METATYPE; if (options.capabilities()) opts |= CAPABILITIES; if (opts == 0) opts = MANIFEST | IMPEXP; try (Jar jar = getJar(s)) { doPrint(jar, opts, options); } } } private void doPrint(Jar jar, int options, printOptions po) throws ZipException, IOException, Exception { if ((options & VERIFY) != 0) { Verifier verifier = new Verifier(jar); verifier.setPedantic(isPedantic()); verifier.verify(); getInfo(verifier); } if ((options & MANIFEST) != 0) { Manifest manifest = jar.getManifest(); if (manifest == null) warning("JAR has no manifest %s", jar); else { err.println("[MANIFEST " + jar.getName() + "]"); printManifest(manifest); } out.println(); } if ((options & IMPEXP) != 0) { out.println("[IMPEXP]"); Manifest m = jar.getManifest(); Domain domain = Domain.domain(m); if (m != null) { Parameters imports = domain.getImportPackage(); Parameters exports = domain.getExportPackage(); for (String p : exports.keySet()) { if (imports.containsKey(p)) { Attrs attrs = imports.get(p); if (attrs.containsKey(VERSION_ATTRIBUTE)) { exports.get(p) .put("imported-as", attrs.get(VERSION_ATTRIBUTE)); } } } print(Constants.IMPORT_PACKAGE, new TreeMap<>(imports)); print(Constants.EXPORT_PACKAGE, new TreeMap<>(exports)); } else warning("File has no manifest"); } if ((options & CAPABILITIES) != 0) { out.println("[CAPABILITIES]"); Manifest m = jar.getManifest(); Domain domain = Domain.domain(m); if (m != null) { Parameters provide = domain.getProvideCapability(); Parameters require = domain.getRequireCapability(); print(Constants.PROVIDE_CAPABILITY, new TreeMap<>(provide)); print(Constants.REQUIRE_CAPABILITY, new TreeMap<>(require)); } else warning("File has no manifest"); } if ((options & (USES | USEDBY | API)) != 0) { out.println(); try (Analyzer analyzer = new Analyzer()) { analyzer.setPedantic(isPedantic()); analyzer.setJar(jar); Manifest m = jar.getManifest(); if (m != null) { String s = m.getMainAttributes() .getValue(Constants.EXPORT_PACKAGE); if (s != null) analyzer.setExportPackage(s); } analyzer.analyze(); boolean java = po.java(); Packages exports = analyzer.getExports(); if ((options & API) != 0) { Map<PackageRef, List<PackageRef>> apiUses = analyzer.cleanupUses(analyzer.getAPIUses(), !po.java()); if (!po.xport()) { if (exports.isEmpty()) warning("Not filtering on exported only since exports are empty"); else apiUses.keySet() .retainAll(analyzer.getExports() .keySet()); } out.println("[API USES]"); printMultiMap(apiUses); Set<PackageRef> privates = analyzer.getPrivates(); for (PackageRef export : exports.keySet()) { Map<Def, List<TypeRef>> xRef = analyzer.getXRef(export, privates, Modifier.PROTECTED + Modifier.PUBLIC); if (!xRef.isEmpty()) { out.println(); out.printf("%s refers to private Packages (not good)\n\n", export); for (Entry<Def, List<TypeRef>> e : xRef.entrySet()) { TreeSet<PackageRef> refs = new TreeSet<>(); for (TypeRef ref : e.getValue()) refs.add(ref.getPackageRef()); refs.retainAll(privates); out.printf("%60s %-40s %s\n", e.getKey() .getOwnerType() .getFQN() // , e.getKey() .getName(), refs); } out.println(); } } out.println(); } Map<PackageRef, List<PackageRef>> uses = analyzer.cleanupUses(analyzer.getUses(), !po.java()); if ((options & USES) != 0) { out.println("[USES]"); printMultiMap(uses); out.println(); } if ((options & USEDBY) != 0) { out.println("[USEDBY]"); MultiMap<PackageRef, PackageRef> usedBy = new MultiMap<>(uses).transpose(); printMultiMap(usedBy); } } } if ((options & COMPONENT) != 0) { printComponents(out, jar); } if ((options & METATYPE) != 0) { printMetatype(out, jar); } if ((options & LIST) != 0) { out.println("[LIST]"); for (Map.Entry<String, Map<String, Resource>> entry : jar.getDirectories() .entrySet()) { String name = entry.getKey(); Map<String, Resource> contents = entry.getValue(); out.println(name); if (contents != null) { for (String element : contents.keySet()) { int n = element.lastIndexOf('/'); if (n > 0) element = element.substring(n + 1); out.print(" "); out.print(element); String path = element; if (name.length() != 0) path = name + "/" + element; Resource r = contents.get(path); if (r != null) { String extra = r.getExtra(); if (extra != null) { out.print(" extra='" + escapeUnicode(extra) + "'"); } } out.println(); } } else { out.println(name + " <no contents>"); } } out.println(); } } /** * @param manifest */ void printManifest(Manifest manifest) { SortedSet<String> sorted = new TreeSet<>(); for (Object element : manifest.getMainAttributes() .keySet()) { sorted.add(element.toString()); } for (String key : sorted) { Object value = manifest.getMainAttributes() .getValue(key); out.printf("%-40s %-40s\n", key, value); } } private final char nibble(int i) { return "0123456789ABCDEF".charAt(i & 0xF); } private final String escapeUnicode(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= ' ' && c <= '~' && c != '\\') sb.append(c); else { sb.append("\\u"); sb.append(nibble(c >> 12)); sb.append(nibble(c >> 8)); sb.append(nibble(c >> 4)); sb.append(nibble(c)); } } return sb.toString(); } /** * Print the components in this JAR. * * @param jar */ private void printComponents(PrintStream out, Jar jar) throws Exception { out.println("[COMPONENTS]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } String componentHeader = manifest.getMainAttributes() .getValue(Constants.SERVICE_COMPONENT); Parameters clauses = new Parameters(componentHeader, this); for (String path : clauses.keySet()) { out.println(path); Resource r = jar.getResource(path); if (r != null) { InputStreamReader ir = new InputStreamReader(r.openInputStream(), Constants.DEFAULT_CHARSET); OutputStreamWriter or = new OutputStreamWriter(out, Constants.DEFAULT_CHARSET); try { IO.copy(ir, or); } finally { or.flush(); ir.close(); } } else { out.println(" - no resource"); warning("No Resource found for service component: %s", path); } } out.println(); } /** * Print the metatypes in this JAR. * * @param jar */ private void printMetatype(PrintStream out, Jar jar) throws Exception { out.println("[METATYPE]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } Map<String, Resource> map = jar.getDirectories() .get("OSGI-INF/metatype"); if (map != null) { for (Map.Entry<String, Resource> entry : map.entrySet()) { out.println(entry.getKey()); IO.copy(entry.getValue() .openInputStream(), out); out.println(); } out.println(); } } <T extends Comparable<? super T>> void printMultiMap(Map<T, ? extends Collection<?>> map) { SortedList<T> keys = new SortedList<>(map.keySet()); for (Object key : keys) { String name = key.toString(); SortedList<Object> values = new SortedList<>(map.get(key), null); String list = vertical(40, values); out.printf("%-40s %s\n", name, list); } } String vertical(int padding, Collection<?> used) { StringBuilder sb = new StringBuilder(); String del = ""; for (Object s : used) { String name = s.toString(); sb.append(del); sb.append(name); sb.append("\r\n"); del = pad(padding); } if (sb.length() == 0) sb.append("\r\n"); return sb.toString(); } String pad(int i) { StringBuilder sb = new StringBuilder(); while (i-- > 0) sb.append(' '); return sb.toString(); } /** * @param msg * @param ports */ private void print(String msg, Map<?, ? extends Map<?, ?>> ports) { if (ports.isEmpty()) return; out.println(msg); for (Entry<?, ? extends Map<?, ?>> entry : ports.entrySet()) { Object key = entry.getKey(); Map<?, ?> clause = Create.copy((Map<?, ?>) entry.getValue()); clause.remove("uses:"); out.printf(" %-38s %s\n", key.toString() .trim(), clause.isEmpty() ? "" : clause.toString()); } } /** * Patch */ interface patchOptions extends Options { } public void patch(patchOptions opts) throws Exception { PatchCommand pcmd = new PatchCommand(this); List<String> args = opts._arguments(); opts._command() .execute(pcmd, args.remove(0), args); } @Description("Run OSGi tests and create report") interface runtestsOptions extends Options { @Description("Report directory") String reportdir(); @Description("Title in the report") String title(); @Description("Path to work directory") String dir(); @Description("Path to workspace") String workspace(); } /** * Run the tests from a prepared bnd file. * * @throws Exception */ @Description("Run OSGi tests and create report") public void _runtests(runtestsOptions opts) throws Exception { int errors = 0; File cwd = new File("").getAbsoluteFile(); Workspace ws = new Workspace(cwd); try { File reportDir = getFile("reports"); IO.delete(reportDir); Tag summary = new Tag("summary"); summary.addAttribute("date", new Date()); summary.addAttribute("ws", ws.getBase()); if (opts.reportdir() != null) { reportDir = getFile(opts.reportdir()); } IO.mkdirs(reportDir); if (!reportDir.isDirectory()) error("reportdir must be a directory %s (tried to create it ...)", reportDir); if (opts.title() != null) summary.addAttribute("title", opts.title()); if (opts.dir() != null) cwd = getFile(opts.dir()); if (opts.workspace() != null) { ws.close(); ws = Workspace.getWorkspace(getFile(opts.workspace())); } // TODO check all the arguments boolean hadOne = false; try { for (String arg : opts._arguments()) { logger.debug("will run test {}", arg); File f = getFile(arg); errors += runtTest(f, ws, reportDir, summary); hadOne = true; } if (!hadOne) { // See if we had any, if so, just use all files in // the current directory File[] files = cwd.listFiles(); for (File f : files) { if (f.getName() .endsWith(".bnd")) { errors += runtTest(f, ws, reportDir, summary); } } } } catch (Throwable e) { if (isExceptions()) { printExceptionSummary(e, out); } exception(e, "FAILURE IN RUNTESTS"); errors++; } if (errors > 0) summary.addAttribute("errors", errors); for (String error : getErrors()) { Tag e = new Tag("error"); e.addContent(error); } for (String warning : getWarnings()) { Tag e = new Tag("warning"); e.addContent(warning); } File r = getFile(reportDir, "summary.xml"); try (PrintWriter pw = IO.writer(r, UTF_8)) { summary.print(0, pw); } if (errors != 0) error("Errors found %s", errors); } finally { ws.close(); } } /** * Help function to run the tests */ private int runtTest(File testFile, Workspace ws, File reportDir, Tag summary) throws Exception { File tmpDir = new File(reportDir, "tmp"); IO.mkdirs(tmpDir); tmpDir.deleteOnExit(); Tag test = new Tag(summary, "test"); test.addAttribute("path", testFile.getAbsolutePath()); if (!testFile.isFile()) { error("No bnd file: %s", testFile); test.addAttribute("exception", "No bnd file found"); error("No bnd file found for %s", testFile.getAbsolutePath()); return 1; } Project project = new Project(ws, testFile.getAbsoluteFile() .getParentFile(), testFile.getAbsoluteFile()); project.use(this); project.setProperty(NOBUNDLES, "true"); ProjectTester tester = project.getProjectTester(); if (!project.isOk()) { getInfo(project, project.toString() + ": " + testFile.getName() + ":"); return 1; // Indicate failure but do not abort } tester.setContinuous(false); tester.setReportDir(tmpDir); test.addAttribute("title", project.toString()); long start = System.currentTimeMillis(); try { int errors = tester.test(); Collection<File> reports = tester.getReports(); for (File report : reports) { Tag bundle = new Tag(test, "bundle"); File dest = new File(reportDir, report.getName()); IO.rename(report, dest); bundle.addAttribute("file", dest.getAbsolutePath()); doPerReport(bundle, dest); } switch (errors) { case ProjectLauncher.OK : return 0; case ProjectLauncher.CANCELED : test.addAttribute("failed", "canceled"); return 1; case ProjectLauncher.DUPLICATE_BUNDLE : test.addAttribute("failed", "duplicate bundle"); return 1; case ProjectLauncher.ERROR : test.addAttribute("failed", "unknown reason"); return 1; case ProjectLauncher.RESOLVE_ERROR : test.addAttribute("failed", "resolve error"); return 1; case ProjectLauncher.TIMEDOUT : test.addAttribute("failed", "timed out"); return 1; case ProjectLauncher.WARNING : test.addAttribute("warning", "true"); return 1; case ProjectLauncher.ACTIVATOR_ERROR : test.addAttribute("failed", "activator error"); return 1; default : if (errors > 0) { test.addAttribute("errors", errors); return errors; } test.addAttribute("failed", "unknown reason"); return errors; } } catch (Exception e) { test.addAttribute("failed", e); exception(e, "Exception in run %s", e); return 1; } finally { long duration = System.currentTimeMillis() - start; test.addAttribute("duration", (duration + 500) / 1000); getInfo(project, project.toString() + ": "); } } /** * Calculate the coverage if there is coverage info in the test file. */ private void doPerReport(Tag report, File file) throws Exception { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); doCoverage(report, doc, xpath); doHtmlReport(report, file, doc, xpath); } catch (Exception e) { report.addAttribute("coverage-failed", e.toString()); } } private void doCoverage(Tag report, Document doc, XPath xpath) throws XPathExpressionException { int bad = Integer.parseInt(xpath.evaluate("count(//method[count(ref)<2])", doc)); int all = Integer.parseInt(xpath.evaluate("count(//method)", doc)); report.addAttribute("coverage-bad", bad); report.addAttribute("coverage-all", all); } private void doHtmlReport(@SuppressWarnings("unused") Tag report, File file, Document doc, @SuppressWarnings("unused") XPath xpath) throws Exception { String path = file.getAbsolutePath(); if (path.endsWith(".xml")) path = path.substring(0, path.length() - 4); path += ".html"; File html = new File(path); logger.debug("Creating html report: {}", html); TransformerFactory fact = TransformerFactory.newInstance(); try (InputStream in = getClass().getResourceAsStream("testreport.xsl")) { if (in == null) { warning("Resource not found: test-report.xsl, no html report"); } else { try (Writer out = IO.writer(html, UTF_8)) { Transformer transformer = fact.newTransformer(new StreamSource(in)); transformer.transform(new DOMSource(doc), new StreamResult(out)); logger.debug("Transformed"); } } } } @Description("Verify jars") @Arguments(arg = { "<jar path>", "[...]" }) interface verifyOptions extends Options {} /** * Verify jars. * * @throws Exception */ @Description("Verify jars") public void _verify(verifyOptions opts) throws Exception { for (String path : opts._arguments()) { File f = getFile(path); if (!f.isFile()) { error("No such file: %s", f); } else { Jar jar = new Jar(f); if (jar.getManifest() == null || jar.getBsn() == null) error("Not a bundle %s", f); else { Verifier v = new Verifier(jar); getInfo(v, f.getName()); v.close(); } jar.close(); } } } @Description("Merge a binary jar with its sources. It is possible to specify source path") // @Arguments(arg = { "<jar path>", "<source path>" }) // interface sourceOptions extends Options { @Description("The output file") String output(); } /** * Merge a bundle with its source. * * @throws Exception */ @Description("Merge a binary jar with its sources. It is possible to specify source path") public void _source(sourceOptions opts) throws Exception { List<String> arguments = opts._arguments(); File jarFile = getFile(arguments.remove(0)); if (!jarFile.exists()) { error("File %s does not exist ", jarFile); return; } File sourceFile = getFile(arguments.remove(0)); if (!sourceFile.exists()) { error("Source file %s does not exist ", sourceFile); return; } File output = jarFile; if (opts.output() != null) output = getFile(opts.output()); File tmp = File.createTempFile("tmp", ".jar", jarFile.getParentFile()); tmp.deleteOnExit(); try (Jar bin = new Jar(jarFile); Jar src = new Jar(sourceFile)) { bin.setDoNotTouchManifest(); for (String path : src.getResources() .keySet()) bin.putResource("OSGI-OPT/src/" + path, src.getResource(path)); bin.write(tmp); } IO.rename(tmp, output); } /** * Diff two jar files * * @throws Exception */ @Description("Diff jars") public void _diff(diffOptions opts) throws Exception { DiffCommand diff = new DiffCommand(this); diff.diff(opts); } /** * Baseline * * @throws Exception */ @Description("Compare a newer bundle to a baselined bundle and provide versioning advice") public void _baseline(baseLineOptions opts) throws Exception { BaselineCommands baseliner = new BaselineCommands(this); baseliner._baseline(opts); } /** * Create a schema of package deltas and versions * * @throws Exception */ @Description("Highly specialized function to create an overview of package deltas in ees") public void _schema(schemaOptions opts) throws Exception { BaselineCommands baseliner = new BaselineCommands(this); baseliner._schema(opts); } public Project getProject() throws Exception { return getProject(null); } public Workspace getWorkspace(File workspaceDir) throws Exception { if (workspaceDir == null) { workspaceDir = getBase(); } ws = Workspace.findWorkspace(workspaceDir); if (ws == null) return null; ws.use(this); return ws; } public Project getProject(String where) throws Exception { if (where == null || where.equals(".")) where = Project.BNDFILE; File f = getFile(where); if (f.isDirectory()) { f = new File(f, Project.BNDFILE); } if (f.isFile()) { if (f.getName() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { Workspace ws = Workspace.findWorkspace(f.getParentFile()); Run run = Run.createRun(ws, f); return run; } File projectDir = f.getParentFile(); File workspaceDir = projectDir.getParentFile(); ws = Workspace.findWorkspace(workspaceDir); Project project = ws.getProject(projectDir.getName()); if (project.isValid()) { project.use(this); return project; } } if (where.equals(Project.BNDFILE)) { return null; } error("Project not found: %s", f); return null; } public Workspace getWorkspace(String where) throws Exception { Workspace ws; if (where == null) { ws = Workspace.findWorkspace(IO.work); if (ws == null) ws = Workspace.createStandaloneWorkspace(new Processor(), IO.work.toURI()); } else { File f = getFile(where); ws = Workspace.findWorkspace(f); if (f.isFile() && f.getName() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) { Run run = Run.createRun(ws, f); ws = run.getWorkspace(); } } return ws; } /** * Convert files */ @Description("Converter to different formats") @Arguments(arg = { "from", "to" }) interface convertOptions extends Options { @Config(description = "Convert a manifest to a properties files") boolean m2p(); @Config(description = "Save as xml") boolean xml(); } @Description("Converter to different formats") public void _convert(convertOptions opts) throws IOException { File from = getFile(opts._arguments() .get(0)); File to = getFile(opts._arguments() .get(1)); if (opts.m2p()) { try (InputStream in = IO.stream(from)) { Properties p = new UTF8Properties(); Manifest m = new Manifest(in); Attributes attrs = m.getMainAttributes(); for (Map.Entry<Object, Object> i : attrs.entrySet()) { p.put(i.getKey() .toString(), i.getValue() .toString()); } try (OutputStream fout = IO.outputStream(to)) { if (opts.xml()) p.storeToXML(fout, "converted from " + from); else { try (Writer osw = IO.writer(fout, UTF_8)) { p.store(osw, "converted from " + from); } } } } return; } error("no conversion specified"); } /** * Create a list of file names that match manifest headers bnd select -h * Bundle-SymbolicName --where (...) * */ @Description("Helps finding information in a set of JARs by filtering on manifest data and printing out selected information.") @Arguments(arg = { "<jar-path>", "[...]" }) interface selectOptions extends Options { @Description("A simple assertion on a manifest header (e.g. " + Constants.BUNDLE_VERSION + "=1.0.1) or an OSGi filter that is asserted on all manifest headers. Comparisons are case insensitive. The key 'resources' holds the pathnames of all resources and can also be asserted to check for the presence of a header.") String where(); @Description("A manifest header to print or: path, name, size, length, modified for information about the file, wildcards are allowed to print multiple headers. ") Collection<String> header(); @Description("Print the key before the value") boolean key(); @Description("Print the file name before the value") boolean name(); @Description("Print the file path before the value") boolean path(); } @Description("Helps finding information in a set of JARs by filtering on manifest data and printing out selected information.") public void _select(selectOptions opts) throws Exception { PrintStream out = this.out; Filter filter = null; if (opts.where() != null) { String w = opts.where(); if (!w.startsWith("(")) w = "(" + w + ")"; filter = new Filter(w); } Instructions instructions = new Instructions(opts.header()); for (String s : opts._arguments()) { Jar jar = getJar(s); if (jar == null) { err.println("no file " + s); continue; } Domain domain = Domain.domain(jar.getManifest()); Hashtable<String, Object> ht = new Hashtable<>(); Iterator<String> i = domain.iterator(); Set<String> realNames = new HashSet<>(); while (i.hasNext()) { String key = i.next(); String value = domain.get(key) .trim(); ht.put(key.trim() .toLowerCase(), value); realNames.add(key); } ht.put("resources", jar.getResources() .keySet()); realNames.add("resources"); if (filter != null) { if (!filter.match(ht)) continue; } Set<Instruction> unused = new HashSet<>(); Collection<String> select = instructions.select(realNames, unused, true); for (String h : select) { if (opts.path()) { out.print(jar.getSource() .getAbsolutePath() + ":"); } if (opts.name()) { out.print(jar.getSource() .getName() + ":"); } if (opts.key()) { out.print(h + ":"); } out.println(ht.get(h.toLowerCase())); } for (Instruction ins : unused) { String literal = ins.getLiteral(); if (literal.equals("name")) out.println(jar.getSource() .getName()); else if (literal.equals("path")) out.println(jar.getSource() .getAbsolutePath()); else if (literal.equals("size") || literal.equals("length")) out.println(jar.getSource() .length()); else if (literal.equals("modified")) out.println(new Date(jar.getSource() .lastModified())); } } } /** * Central routine to get a JAR with error checking * * @param s */ Jar getJar(String s) { File f = getFile(s); if (f.isFile()) { try { return new Jar(f); } catch (ZipException e) { exception(e, "Not a jar/zip file: %s", f); } catch (Exception e) { exception(e, "Opening file: %s", f); } return null; } try { URL url = new URL(s); return new Jar(s, url.openStream()); } catch (Exception e) { // Ignore } error("Not a file or proper url: %s", f); return null; } @Description("Show version information about bnd") @Arguments(arg = {}) public interface versionOptions extends Options { @Description("Show licensing, copyright, sha, scm, etc") boolean xtra(); } /** * Show the version of this bnd * * @throws IOException */ @Description("Show version information about bnd") public void _version(versionOptions o) throws IOException { if (!o.xtra()) { Analyzer a = new Analyzer(); out.println(a.getBndVersion()); a.close(); return; } Enumeration<URL> e = getClass().getClassLoader() .getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { URL u = e.nextElement(); Manifest m = new Manifest(u.openStream()); String bsn = m.getMainAttributes() .getValue(Constants.BUNDLE_SYMBOLICNAME); if (bsn != null && bsn.equals("biz.aQute.bnd")) { Attributes attrs = m.getMainAttributes(); long lastModified = 0; try { lastModified = Long.parseLong(attrs.getValue(Constants.BND_LASTMODIFIED)); } catch (Exception ee) { // Ignore } out.printf("%-40s %s\n", "Version", attrs.getValue(Constants.BUNDLE_VERSION)); if (lastModified > 0) out.printf("%-40s %s\n", "From", new Date(lastModified)); Parameters p = OSGiHeader.parseHeader(attrs.getValue(Constants.BUNDLE_LICENSE)); for (String l : p.keySet()) out.printf("%-40s %s\n", "License", p.get(l) .get("description")); out.printf("%-40s %s\n", "Copyright", attrs.getValue(Constants.BUNDLE_COPYRIGHT)); out.printf("%-40s %s\n", "Git-SHA", attrs.getValue("Git-SHA")); out.printf("%-40s %s\n", "Git-Descriptor", attrs.getValue("Git-Descriptor")); out.printf("%-40s %s\n", "Sources", attrs.getValue(Constants.BUNDLE_SCM)); return; } } error("Could not locate version"); } /** * Show some key info of the project */ @Arguments(arg = {}) @Description("Show key project variables") interface infoOptions extends Options { boolean runbundles(); boolean buildpath(); boolean dependsOn(); boolean sourcepath(); boolean classpath(); boolean vmpath(); String project(); } @Description("Show key project variables") public void _info(infoOptions options) throws Exception { Project p = getProject(options.project()); if (p == null) { messages.NoProject(); return; } boolean any = options.runbundles() || options.buildpath() || options.classpath() || options.dependsOn() || options.vmpath(); MultiMap<String, Object> table = new MultiMap<>(); if (any || options.runbundles()) { table.addAll("Run", p.getRunbundles()); } if (any || options.buildpath()) { table.addAll("Build", p.getBuildpath()); } if (any || options.buildpath()) { table.addAll("Depends on", p.getDependson()); } if (any || options.sourcepath()) { table.addAll("Source", p.getSourcePath()); } if (any || options.classpath()) { table.addAll("Class path", p.getClasspath()); } if (any || options.vmpath()) { table.addAll("Run path", p.getRunpath()); } printMultiMap(table); } /** * Grep in jars */ @Arguments(arg = { "pattern", "file..." }) @Description("Grep the manifest of bundles/jar files. ") interface grepOptions extends Options { @Description("Search in exports") boolean exports(); @Description("Search in imports") boolean imports(); @Description("Search in bsn") boolean bsn(); @Description("Set header(s) to search, can be wildcarded. The default is all headers (*).") Set<String> headers(); } @Description("Grep the manifest of bundles/jar files. ") public void _grep(grepOptions opts) throws Exception { List<String> args = opts._arguments(); String s = args.remove(0); Pattern pattern = Glob.toPattern(s); if (pattern == null) { messages.InvalidGlobPattern_(s); return; } if (args.isEmpty()) { args = new ExtList<>(getBase().list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".jar"); } })); } Set<String> headers = opts.headers(); if (headers == null) headers = new TreeSet<>(); if (opts.exports()) headers.add(Constants.EXPORT_PACKAGE); if (opts.bsn()) headers.add(Constants.BUNDLE_SYMBOLICNAME); if (opts.imports()) headers.add(Constants.IMPORT_PACKAGE); Instructions instructions = new Instructions(headers); for (String fileName : args) { File file = getFile(fileName); if (!file.isFile()) { messages.NoSuchFile_(file); continue; } try (JarInputStream in = new JarInputStream(IO.stream(file))) { Manifest m = in.getManifest(); for (Object header : m.getMainAttributes() .keySet()) { Attributes.Name name = (Name) header; if (instructions.isEmpty() || instructions.matches(name.toString())) { String h = m.getMainAttributes() .getValue(name); QuotedTokenizer qt = new QuotedTokenizer(h, ",;="); for (String value : qt.getTokenSet()) { Matcher matcher = pattern.matcher(value); while (matcher.find()) { int start = matcher.start() - 8; if (start < 0) start = 0; int end = matcher.end() + 8; if (end > value.length()) end = value.length(); out.printf("%40s : %20s ...%s[%s]%s...\n", fileName, name, value.substring(start, matcher.start()), value.substring(matcher.start(), matcher.end()), value.substring(matcher.end(), end)); } } } } } } } /** * Handle the global settings */ @Description("Set bnd global variables. The key can be wildcard.") @Arguments(arg = { "<key>[=<value>]..." }) interface settingOptions extends Options { @Description("Clear all the settings, including the public and private key") boolean clear(); @Description("Show the public key") boolean publicKey(); @Description("Show the private secret key") boolean secretKey(); @Description("Sign the strings on the commandline") boolean mac(); @Description("Show key in base64") boolean base64(); @Description("Override the default \"~/.bnd/settings.json\" location") String location(); @Description("Generate a new private/public key pair") boolean generate(); @Description("Password for local file") char[] password(); } @Description("Set bnd global variables") public void _settings(settingOptions opts) throws Exception { try { Settings settings = this.settings; char[] password = this.password; if (opts.location() != null) { password = opts.password(); File f = getFile(opts.location()); settings = new Settings(f.getAbsolutePath()); settings.load(password); logger.debug("getting settings from {}", f); } if (opts.clear()) { settings.clear(); logger.debug("clear {}", settings.entrySet()); } if (opts.generate()) { logger.debug("Generating new key pair"); settings.generate(password); } logger.debug("settings {}", opts.clear()); List<String> rest = opts._arguments(); if (opts.publicKey()) { out.println(tos(!opts.base64(), settings.getPublicKey())); } if (opts.secretKey()) { out.println(tos(!opts.base64(), settings.getPrivateKey())); } if (opts.mac()) { for (String s : rest) { byte[] data = s.getBytes(UTF_8); byte[] signature = settings.sign(data); out.printf("%s\n", tos(!opts.base64(), signature)); } } if (rest.isEmpty()) { list(null, settings); } else { boolean set = false; for (String s : rest) { s = s.trim(); Matcher m = ASSIGNMENT.matcher(s); logger.debug("try {}", s); if (m.matches()) { String key = m.group(1); Instructions instr = new Instructions(key); Collection<String> select = instr.select(settings.keySet(), true); // check if there is a value a='b' String value = m.group(4); if (value == null || value.trim() .length() == 0) { // no value // check '=' presence if (m.group(2) == null) { list(select, settings); } else { // we have 'a=', remove for (String k : select) { logger.debug("remove {}={}", k, settings.get(k)); settings.remove(k); set = true; } } } else { logger.debug("assignment {}={}", key, value); settings.put(key, value); set = true; } } else { err.printf("Cannot assign %s\n", s); } } if (set) { logger.debug("saving"); settings.save(password); } } } catch (Exception e) { e.printStackTrace(); } } /** * Set the private key in the settings for this machine * * @param hex * @param data * @throws Exception */ private String tos(boolean hex, byte[] data) { return data.length + " : " + (hex ? Hex.toHexString(data) : Base64.encodeBase64(data)); } private void list(Collection<String> keys, Map<String, String> map) { for (Entry<String, String> e : map.entrySet()) { if (keys == null || keys.contains(e.getKey())) out.printf("%-40s = %s\n", e.getKey(), e.getValue()); } } enum Alg { SHA1, MD5, TIMELESS }; @Description("Digest a number of files") @Arguments(arg = "file...") interface hashOptions extends Options { @Description("Show hex output (default)") boolean hex(); @Description("Show base64 output") boolean b64(); @Description("Show process info") boolean process(); @Description("Show the file name") boolean name(); @Description("Specify the algorithms") List<Alg> algorithm(); } /** * hash a file * * @throws Exception * @throws NoSuchAlgorithmException */ @Description("Digests a number of files") public void _digest(hashOptions o) throws NoSuchAlgorithmException, Exception { long start = System.currentTimeMillis(); long total = 0; List<Alg> algs = o.algorithm(); if (algs == null) algs = Arrays.asList(Alg.SHA1); for (String s : o._arguments()) { File f = getFile(s); if (f.isFile()) { outer: for (Alg alg : algs) { long now = System.currentTimeMillis(); byte[] digest; switch (alg) { default : error("no such algorithm %s", alg); continue outer; case SHA1 : digest = SHA1.digest(f) .digest(); break; case MD5 : digest = MD5.digest(f) .digest(); break; case TIMELESS : Jar j = new Jar(f); digest = j.getTimelessDigest(); break; } StringBuilder sb = new StringBuilder(); String del = ""; if (o.hex() || !o.b64()) { sb.append(del) .append(Hex.toHexString(digest)); del = " "; } if (o.b64()) { sb.append(del) .append(Base64.encodeBase64(digest)); del = " "; } if (o.name()) { sb.append(del) .append(f.getAbsolutePath()); del = " "; } if (o.process()) { sb.append(del) .append(System.currentTimeMillis() - now) .append(" ms ") .append(f.length() / 1000) .append(" Kb"); total += f.length(); } out.println(sb); } } else error("file does not exist %s", f); } if (o.process()) { long time = (System.currentTimeMillis() - start); float mb = total / 1000000; out.format("Total %s Mb, %s ms, %s Mb/sec %s files\n", mb, time, (total / time) / 1024, o._arguments() .size()); } } /** * Maven command * * @throws Exception */ @Description("Maven bundle command") public void _maven(Options options) throws Exception { MavenCommand mc = new MavenCommand(this); mc.use(this); mc.run(options._arguments() .toArray(new String[0]), 1); getInfo(mc); } @Description("Generate autocompletion file for bash") public void _bash(Options options) throws Exception { File tmp = File.createTempFile("bnd-completion", ".tmp"); tmp.deleteOnExit(); try { IO.copy(getClass().getResource("bnd-completion.bash"), tmp); Sed sed = new Sed(tmp); sed.setBackup(false); Reporter r = new ReporterAdapter(); CommandLine c = new CommandLine(r); Map<String, Method> commands = c.getCommands(this); StringBuilder sb = new StringBuilder(); for (String commandName : commands.keySet()) { sb.append(" " + commandName); } sb.append(" help"); sed.replace("%listCommands%", sb.toString() .substring(1)); sed.doIt(); IO.copy(tmp, out); } finally { IO.delete(tmp); } } /** * List actions of the repositories if they implement Actionable and allow * them to be executed */ @Description("Execute an action on a repo, or if no name is give, list the actions") interface ActionOptions extends projectOptions { Glob filter(); boolean tooltip(); } @Description("Execute an action on a repo, or if no name is give, list the actions") public void _action(ActionOptions opts) throws Exception { Project project = getProject(opts.project()); if (project == null) { error("Not in a project directory"); return; } Glob filter = opts.filter(); if (filter == null) filter = new Glob("*"); List<Actionable> actionables = project.getPlugins(Actionable.class); if (actionables.isEmpty()) { error("No actionables in [%s]", project.getPlugins()); return; } for (Actionable o : actionables) { if (filter.matcher(o.title()) .matches()) { logger.debug("actionable {} - {}", o, o.title()); Map<String, Runnable> map = o.actions(); if (map != null) { if (opts._arguments() .isEmpty()) { out.printf("# %s%n", o.title()); if (opts.tooltip() && o.tooltip() != null) { out.printf("%s%n", o.tooltip()); } out.printf("## actions%n"); for (String entry : map.keySet()) { out.printf(" %s%n", entry); } } else { for (String entry : opts._arguments()) { Runnable r = map.get(entry); if (r != null) { r.run(); } } } } } } getInfo(project); } /** * Show the changes in the releases */ @Arguments(arg = {}) @Description("Show the changes in this release of bnd") interface ChangesOptions extends Options { @Description("Print all releases") boolean all(); } static Pattern BUG_P = Pattern.compile("#([0-9]+)"); static Pattern BND_COMMAND_P = Pattern.compile("\\[bnd\\s+([\\w\\d]+)\\s*\\]"); public void _changes(ChangesOptions options) { boolean first = true; Justif j = new Justif(80, 10); Formatter f = j.formatter(); for (Map.Entry<Version, String[]> e : About.CHANGES.entrySet()) { if (options.all() || first) { f.format("$-\nRelease %s\n$-\n", e.getKey()); for (String s : e.getValue()) { f.format("- \t1%s", s.replace('\n', '\f')); Matcher m = BND_COMMAND_P.matcher(s); while (m.find()) { Formatter ff = new Formatter(); ff.format("\n\n"); CommandLine cli = options._command(); cli.help(ff, this, m.group(1)); j.indent(10, ff.out() .toString()); } m = BUG_P.matcher(s); while (m.find()) { f.format("\f-> https://github.com/bndtools/bnd/issues/%s", m.group(1)); } f.format("\n\n"); } } first = false; } j.wrap(); out.println(f.out()); } /** * Find a package in the current project or a set of jars */ @Arguments(arg = "[file]...") @Description("Go through the exports and/or imports and match the given " + "exports/imports globs. If thet match print the file, package and version.") interface FindOptions extends Options { @Description("Glob expression on the imports.") Glob[] imports(); @Description("Glob expression on the exports.") Glob[] exports(); } public void _find(FindOptions options) throws Exception { List<File> files = new ArrayList<>(); List<String> args = options._arguments(); if (args.size() == 0) { Project p = getProject(); if (p == null) { error("This is not a project directory and you have specified no jar files ..."); return; } File output = p.getOutput(); if (output.exists()) { files.add(output); } for (Container c : p.getBuildpath()) { files.add(c.getFile()); } } else { for (String f : args) { File file = getFile(f); files.add(file); } } for (File f : files) { logger.debug("find {}", f); try (Jar jar = new Jar(f)) { Manifest m = jar.getManifest(); if (m != null) { Domain domain = Domain.domain(m); if (options.exports() != null) { Parameters ep = domain.getExportPackage(); for (Glob g : options.exports()) { for (Entry<String, Attrs> exp : ep.entrySet()) { if (g.matcher(exp.getKey()) .matches()) { String v = exp.getValue() .get(VERSION_ATTRIBUTE); if (v == null) v = "0"; out.printf(">%s: %s-%s%n", f.getPath(), exp.getKey(), v); } } } } if (options.imports() != null) { Parameters ip = domain.getImportPackage(); for (Glob g : options.imports()) { for (Entry<String, Attrs> imp : ip.entrySet()) { if (g.matcher(imp.getKey()) .matches()) { String v = imp.getValue() .get(VERSION_ATTRIBUTE); if (v == null) v = "0"; out.printf("<%s: %s-%s%n", f.getPath(), imp.getKey(), v); } } } } } } } } /** * Merge n JARs into a new JAR */ @Arguments(arg = "jarfile...") interface MergeOptions extends Options { @Description("Specify the output file path. The default is output.jar in the current directory") String output(); } @Description("Merge a number of jar files into a new jar file. The used manifest is that of the first" + "given JAR file. The order of the JAR file is the class path order. I.e. earlier resources" + "are preferred over later resources with the same name.") public void __merge(MergeOptions options) throws Exception { String name = options.output() == null ? "output.jar" : options.output(); File out = getFile(name); if (!out.getParentFile() .isDirectory()) { error("Output file is not in a valid directory: %s", out.getParentFile()); } List<String> list = options._arguments(); Collections.reverse(list); try (Jar jar = new Jar(name)) { Jar last = null; for (String member : list) { File m = getFile(member); if (!m.isFile()) { error("%s is not a file", m.getAbsolutePath()); } else { Jar jm = new Jar(m); last = jm; addClose(jm); jar.addAll(jm); } } if (last != null) { jar.setManifest(last.getManifest()); } jar.write(out); } } @Arguments(arg = "<jar-file>...") @Description("Show the Execution Environments of a JAR") interface EEOptions extends Options { } /** * Show the class versions used in a JAR * * @throws Exception */ @Description("Show the Execution Environments of a JAR") public void _ees(EEOptions options) throws Exception { for (String path : options._arguments()) { File f = getFile(path); if (!f.isFile()) { error("Not a file"); } else { try (Analyzer a = new Analyzer(this)) { a.setJar(f); a.analyze(); out.printf("%s %s%n", a.getJar() .getName(), a.getEEs()); } } } } @Description("experimental - parallel build") interface ParallelBuildOptions extends buildoptions { } /** * Lets see if we can build in parallel * * @throws Exception */ public void __par(final ParallelBuildOptions options) throws Exception { ExecutorService pool = Executors.newCachedThreadPool(); final AtomicBoolean quit = new AtomicBoolean(); try { final Project p = getProject(options.project()); final Workspace workspace = p == null || options.full() ? Workspace.getWorkspace(getBase()) : p.getWorkspace(); if (!workspace.exists()) { error("cannot find workspace"); return; } final Collection<Project> targets = p == null ? workspace.getAllProjects() : p.getDependson(); final Forker<Project> forker = new Forker<>(pool); for (final Project dep : targets) { forker.doWhen(dep.getDependson(), dep, new Runnable() { @Override public void run() { if (!quit.get()) { try { dep.compile(false); if (!quit.get()) dep.build(); if (!dep.isOk()) quit.set(true); } catch (Exception e) { e.printStackTrace(); } } } }); } System.err.flush(); forker.start(20000); for (Project dep : targets) { getInfo(dep, dep + ": "); } if (p != null && p.isOk() && !options.full()) { p.compile(options.test()); p.build(); if (options.test() && p.isOk()) p.test(); getInfo(p); } workspace.close(); } finally { pool.shutdownNow(); } } /** * Force a cache update of the workspace * * @throws Exception */ public void _sync(projectOptions options) throws Exception { Workspace ws = getWorkspace((File) null); if (ws == null) { error( "Cannot find workspace, either reside in a project directory, point to a project with --project, or reside in the workspace directory"); return; } ws.syncCache(); } /** * From a set of bsns, create a list of urls */ interface Bsn2UrlOptions extends projectOptions { } static Pattern LINE_P = Pattern.compile("\\s*(([^\\s]#|[^#])+)(\\s*#.*)?"); public void _bsn2url(Bsn2UrlOptions opts) throws Exception { Project p = getProject(opts.project()); if (p == null) { error("You need to be in a project or specify the project with -p/--project"); return; } MultiMap<String, Version> revisions = new MultiMap<>(); for (RepositoryPlugin repo : p.getPlugins(RepositoryPlugin.class)) { if (!(repo instanceof InfoRepository)) continue; for (String bsn : repo.list(null)) { revisions.addAll(bsn, repo.versions(bsn)); } } for (List<Version> versions : revisions.values()) { Collections.sort(versions, Collections.reverseOrder()); } List<String> files = opts._arguments(); for (String f : files) { try (BufferedReader r = IO.reader(getFile(f))) { String line; nextLine: while ((line = r.readLine()) != null) { Matcher matcher = LINE_P.matcher(line); if (!matcher.matches()) continue nextLine; line = matcher.group(1); Parameters bundles = new Parameters(line, this); for (Map.Entry<String, Attrs> entry : bundles.entrySet()) { String bsn = entry.getKey(); VersionRange range = new VersionRange(entry.getValue() .getVersion()); List<Version> versions = revisions.get(bsn); if (versions == null) { error("No for versions for %s", bsn); break nextLine; } for (Version version : versions) { if (range.includes(version)) { for (RepositoryPlugin repo : p.getPlugins(RepositoryPlugin.class)) { if (!(repo instanceof InfoRepository)) continue; InfoRepository rp = (InfoRepository) repo; ResourceDescriptor descriptor = rp.getDescriptor(bsn, version); if (descriptor == null) { error("Found bundle, but no descriptor %s;version=%s", bsn, version); return; } out.println( descriptor.url + " #" + descriptor.bsn + ";version=" + descriptor.version); } } } } } } catch (Exception e) { error("failed to create url list from file %s : %s", f, e); } } } /** * Show the loaded workspace plugins * * @throws Exception */ public void _plugins(projectOptions opts) throws Exception { Workspace ws = getWorkspace(opts.project()); if (ws == null) { error("Can't find a workspace"); return; } int n = 0; for (Object o : ws.getPlugins()) { String s = o.toString(); if (s.trim() .length() == 0) s = o.getClass() .getName(); out.printf("%03d %s%n", n++, s); } } /** * start a local framework */ interface BootstrapOptions extends Options { } public void _bootstrap(BootstrapOptions options) throws Exception { Workspace ws = getWorkspace(getBase()); File buildDir = ws.getBuildDir(); File bndFile = IO.getFile(buildDir, "bnd.bnd"); if (!bndFile.isFile()) { error("No bnd.bnd file found in cnf directory %s", bndFile); return; } Run run = new Run(ws, buildDir, bndFile); run.runLocal(); getInfo(run); } /** * Show all the defaults in bnd */ public void _defaults(Options o) { Processor defaults = Workspace.getDefaults(); out.println(Strings.join("\n", defaults.getProperties() .entrySet())); } /* * Cop a bundle, potentially stripping it */ @Arguments(arg = { "src...", "dest" }) interface CopyOptions extends Options { @Description("Remove all metadata manifest") boolean strip(); @Description("Remove OSGi metadata from the manifest") boolean specific(); @Description("Remove OSGI-OPT") boolean optional(); } public void _copy(CopyOptions options) throws Exception { List<String> files = options._arguments(); if (files.size() < 2) { error("Need at least a source and a destination"); return; } String output = files.remove(files.size() - 1); File dest = new File(getBase(), output); if (files.size() > 1) { if (dest.isFile()) { error("Multiple files require that the output is a directory"); return; } IO.mkdirs(dest); } for (String f : files) { Jar jar = getJar(f); if (jar == null) { error("No such JAR %s", f); continue; } if (options.strip()) { Manifest m = new Manifest(); jar.setManifest(m); } if (options.specific()) { Manifest m = new Manifest(); if (jar.getManifest() != null) { for (Entry<Object, Object> e : jar.getManifest() .getMainAttributes() .entrySet()) { String header = e.getKey() .toString() .toLowerCase(); if (header.startsWith("bundle-")) continue; if (!isIn(Constants.BUNDLE_SPECIFIC_HEADERS, header)) m.getMainAttributes() .put(e.getKey(), e.getValue()); } } jar.setManifest(m); } if (options.optional()) { jar.getDirectories() .remove("OSGI-OPT"); } String name = getJarFileNameFrom(jar.getName()); File out = dest.isDirectory() ? getFile(dest, name) : dest; File tmp = new File("tmp"); jar.write(tmp); jar.close(); IO.rename(tmp, out); } } private boolean isIn(String[] bundleSpecificHeaders, String key) { for (int i = 0; i < bundleSpecificHeaders.length; i++) { if (key.equalsIgnoreCase(bundleSpecificHeaders[i])) return true; } return false; } private String getJarFileNameFrom(String name) { String out = name; int n = out.lastIndexOf('/'); if (n >= 0) { out = out.substring(n + 1); } if (out.endsWith(".jar")) return out; return out + ".jar"; } /** * Add a project, workspace, or plugin */ @Arguments(arg = { "what", "name..." }) interface AddOptions extends Options { } @Description("Add a workspace, or a project or a plugin to the workspace") public void _add(AddOptions opts) throws Exception { List<String> args = opts._arguments(); String what = args.remove(0); if ("project".equals(what)) { Workspace ws = Workspace.findWorkspace(getBase()); if (ws == null) { error("No workspace found from %s", getBase()); return; } for (String pname : args) { ws.createProject(pname); } getInfo(ws); return; } if ("workspace".equals(what)) { for (String pname : args) { File wsdir = getFile(pname); ws = Workspace.createWorkspace(wsdir); if (ws == null) { error("Could not create workspace"); } } getInfo(ws); return; } if ("plugin".equals(what)) { Workspace ws = getWorkspace(getBase()); if (ws == null) { error("No workspace found from %s", getBase()); return; } CommandLine cl = new CommandLine(this); String help = cl.execute(new Plugins(this, ws), "add", new ExtList<>(args)); if (help != null) out.println(help); getInfo(ws); return; } } @Arguments(arg = { "what", "name..." }) interface RemoveOptions extends Options {} @Description("Remove a project or a plugin from the workspace") public void _remove(RemoveOptions opts) throws Exception { List<String> args = opts._arguments(); String what = args.remove(0); Workspace ws = Workspace.findWorkspace(getBase()); if (ws == null) { error("No workspace found from %s", getBase()); return; } if ("project".equals(what)) { for (String pname : args) { Project project = ws.getProject(pname); if (project == null) { error("No such project %s", pname); } else project.remove(); } getInfo(ws); return; } if ("workspace".equals(what)) { error("To delete a workspace, delete the directory"); return; } if ("plugin".equals(what)) { CommandLine cl = new CommandLine(this); String help = cl.execute(new Plugins(this, ws), "remove", new ExtList<>(args)); if (help != null) out.println(help); return; } } /** * Profiles subcmd */ @Description("Profile management. A profile is a JAR that only contains packages and capabilities") @Arguments(arg = { "create", "..." }) public interface ProfileOptions extends Options { } @Description("Profile management. A profile is a JAR that only contains packages and capabilities") public void _profile(ProfileOptions options) throws Exception { Profiles profiles = new Profiles(this, options); CommandLine cmd = options._command(); cmd.subCmd(options, profiles); getInfo(profiles); } /** * Resolve command * * @throws Exception */ public void _resolve(ResolveCommand.ResolveOptions options) throws Exception { ResolveCommand rc = new ResolveCommand(this); String help = options._command() .subCmd(options, rc); if (help != null) out.println(help); getInfo(rc); rc.close(); } /** * Remote command * * @throws Exception */ public void _remote(RemoteCommand.RemoteOptions options) throws Exception { RemoteCommand rc = new RemoteCommand(this, options); String help = options._command() .subCmd(options, rc); if (help != null) out.println(help); getInfo(rc); rc.close(); } /** * Nexus commands * * @throws Exception */ public void _nexus(NexusCommand.NexusOptions options) throws Exception { NexusCommand rc = new NexusCommand(this, options); String help = options._command() .subCmd(options, rc); if (help != null) out.println(help); getInfo(rc); rc.close(); } /** * Export a bndrun file */ interface ExportOptions extends projectOptions { List<String> exporter(); String output(); } public void _export(ExportOptions opts) throws Exception { Project project = getProject(opts.project()); if (project == null) { error("No project"); return; } // temporary project.getWorkspace() .addBasicPlugin(new SubsystemExporter()); for (String bndrun : opts._arguments()) { File f = getFile(bndrun); if (!f.isFile()) { error("No such file: %s", f); continue; } Run run = new Run(project.getWorkspace(), getBase(), f); run.getSettings(this); Parameters exports = new Parameters(); List<String> types = opts.exporter(); if (types != null) { for (String type : types) { exports.putAll(new Parameters(type, this)); } } else { String exportTypes = run.getProperty(Constants.EXPORTTYPE); exports.putAll(new Parameters(exportTypes, this)); } for (Entry<String, Attrs> e : exports.entrySet()) { logger.debug("exporting {} to {} with {}", run, e.getKey(), e.getValue()); Map.Entry<String, Resource> result = run.export(e.getKey(), e.getValue()); getInfo(run); if (result != null && isOk()) { String name = result.getKey(); File output = new File(project.getTarget(), opts.output() == null ? name : opts.output()); if (output.isDirectory()) output = new File(output, name); IO.mkdirs(output.getParentFile()); logger.debug("Got a result for {}, store in {}", e.getKey(), output); IO.copy(result.getValue() .openInputStream(), output); } } } } /** * Flatten a jar */ @Arguments(arg = { "input", "output" }) @Description("Flatten a bundle by expanding all entries on the Bundle-ClassPath") interface FlattenOptions extends Options {} @Description("Flatten a bundle by expanding all entries on the Bundle-ClassPath") public void _flatten(FlattenOptions opts) throws Exception { List<String> inputs = opts._arguments(); String inputPath = inputs.remove(0); String outputPath = inputs.remove(0); File source = getFile(inputPath); if (!source.isFile()) { error("Not a source file %s", source); return; } File destination = getFile(outputPath); IO.mkdirs(destination.getParentFile()); if (!destination.getParentFile() .isDirectory()) { error("Could not create directory for output file %s", outputPath); } Jar input = new Jar(source); addClose(input); Manifest manifest = input.getManifest(); Domain domain = Domain.domain(manifest); List<String> bundleClassPath = new ArrayList<>(domain.getBundleClasspath() .keySet()); if (bundleClassPath.isEmpty()) { warning("%s has no bundle class path", source); return; } Collections.reverse(bundleClassPath); Jar output = new Jar(source.getName()); for (String path : bundleClassPath) { logger.debug("bcp entry {}", path); Resource r = input.getResource(path); if (r == null) { logger.debug("Is directory {}", path); if (path.equals(".")) { addAll(output, input, "", bundleClassPath); } else addAll(output, input, path, null); } else { logger.debug("Is jar {}", path); Jar sub = new Jar(path, r.openInputStream()); addClose(sub); addAll(output, sub, "", null); } } domain.setBundleClasspath("."); output.setManifest(manifest); output.stripSignatures(); output.write(destination); } private void addAll(Jar output, Jar sub, String prefix, List<String> bundleClassPath) { if (prefix.length() > 0 && !prefix.endsWith("/")) prefix += "/"; for (Map.Entry<String, Resource> e : sub.getResources() .entrySet()) { String path = e.getKey(); if (bundleClassPath != null && bundleClassPath.contains(path)) continue; logger.debug("Add {}", path); if (path.equals("META-INF/MANIFEST.MF")) continue; Resource r = e.getValue(); if (path.startsWith(prefix)) { logger.debug("Add {}", path); path = path.substring(prefix.length()); output.putResource(path, r); } else logger.debug("Ignore {} because it does not start with prefix {}", path, prefix); } } private static void exitWithCode(int code) { if (!noExit.get()) { System.exit(code); } } /** * Index command * * @throws Exception */ @Description("Index bundles from the local file system") public void _index(IndexCommand.indexOptions options) throws Exception { IndexCommand ic = new IndexCommand(this); ic.use(this); ic._index(options); ic.close(); } }
fix errors while iterate over projects Signed-off-by: Stefan Bischof <097c404e04fecd274c0a5794e542d39865a14fe2@bipolis.org>
biz.aQute.bnd/src/aQute/bnd/main/bnd.java
fix errors while iterate over projects
Java
apache-2.0
95333a32cfd5d7dbe9063c916261b25adbf46e6e
0
play1-maven-plugin/play1-maven-test-projects,play1-maven-plugin/play1-maven-test-projects
import models.AutoTs; import org.junit.Before; import org.junit.Test; import play.Logger; import play.test.UnitTest; public class AutoTsTest extends UnitTest { @Before public void setup() { AutoTs.deleteAll(); } @Test public void testAutoTimestamp() throws Exception { AutoTs model = new AutoTs(); model.content = "hello"; assertSame(model._getCreated(), 0L); assertSame(model._getModified(), 0L); long ts = System.currentTimeMillis(); Thread.sleep(100); model.save(); Logger.info("created: %1$s", model._getCreated()); assertTrue(model._getCreated() >= ts); assertTrue(model._getModified() >= ts); Thread.sleep(100); ts = System.currentTimeMillis(); model.content = "world"; model.save(); assertTrue(model._getCreated() < ts); assertTrue(model._getModified() >= ts); } }
external-modules/morphia/unit-tests/test/AutoTsTest.java
import models.AutoTs; import org.junit.Before; import org.junit.Test; import play.Logger; import play.test.UnitTest; public class AutoTsTest extends UnitTest { @Before public void setup() { AutoTs.deleteAll(); } @Test public void testAutoTimestamp() throws Exception { AutoTs model = new AutoTs(); model.content = "hello"; assertSame(model._getCreated(), 0L); assertSame(model._getModified(), 0L); long ts = System.currentTimeMillis(); Thread.sleep(1); model.save(); Logger.info("created: %1$s", model._getCreated()); assertTrue(model._getCreated() >= ts); assertTrue(model._getModified() >= ts); Thread.sleep(1); ts = System.currentTimeMillis(); model.content = "world"; model.save(); assertTrue(model._getCreated() < ts); assertTrue(model._getModified() >= ts); } }
Morphia test project - improved unit test (sleeping 1ms is sometimes equal to no sleeping at all, and test fails; sleep period changed to 100ms). git-svn-id: 932e37fa47f35761935fd4b140fd2dd24df10227@10640 9c2ad861-7886-cb7c-dcd7-2b8d41cd5de0
external-modules/morphia/unit-tests/test/AutoTsTest.java
Morphia test project - improved unit test (sleeping 1ms is sometimes equal to no sleeping at all, and test fails; sleep period changed to 100ms).
Java
apache-2.0
67f9ac327632ebda334786ee1544191082b095d9
0
carrotsearch/jsuffixarrays
package org.jsuffixarrays; /** * An algorithm that can produce a <i>suffix array</i> for a sequence of integer symbols. * * @see #buildSuffixArray(int[], int, int) */ public interface ISuffixArrayBuilder { /** * Computes suffix array for sequence of symbols (integers). The processed sequence is * a subsequence of <code>input</code> determined by <code>start</code> and * <code>length</code> parameters. * <p> * Concrete implementations may have additional requirements and constraints * concerning the input. For example, it is quite common that extra cells are required * after <code>start + length</code> to store special marker symbols. Also, some * algorithms may require non-negative symbols in the input. For such constrained * algorithms, use various decorators and adapters available in this package. * * @param input A sequence of input symbols, int-coded. * @param start The starting index (inclusive) in <code>input</code>. * @param length Number of symbols to process. * @return An array of indices such that the suffix of <code>input</code> at index * <code>result[i]</code> is lexicographically larger or equal to any other * suffix that precede it. Note that the output array may be larger than * <code>input.length</code>, in which case only the first * <code>input.length</code> elements are of relevance. * <p> * The returned array contains suffix indexes starting from 0 (so * <code>start</code> needs to be added manually to access a given suffix in * <code>input</code>). */ int [] buildSuffixArray(int [] input, int start, int length); }
src/java/org/jsuffixarrays/ISuffixArrayBuilder.java
package org.jsuffixarrays; /** * An algorithm that can produce a <i>suffix array</i> for a sequence of integer symbols. * * @see #buildSuffixArray(int[], int, int) */ public interface ISuffixArrayBuilder { /** * Computes suffix array for sequence of symbols (integers). The processed sequence is * a subsequence of <code>input</code> determined by <code>start</code> and * <code>length</code> parameters. * <p> * Concrete implementations may have additional requirements and constraints * concerning the input. For example, it is quite common that extra cells are required * after <code>start + length</code> to store special marker symbols. Also, some * algorithms may require non-negative symbols in the input. For such constrained * algorithms, use various decorators and adapters available in this package. * * @param input A sequence of input symbols, int-coded. * @param start The starting index (inclusive) in <code>input</code>. * @param length Number of symbols to process. * @return An array of indices such that the suffix of <code>input</code> at index * <code>result[i]</code> is lexicographically larger or equal to any other * suffix that precede it. Note that the output array may be larger than * <code>input.length</code>, in which case only the first * <code>input.length</code> elements are of relevance. */ int [] buildSuffixArray(int [] input, int start, int length); }
Clarified the contract on the returned SA content. git-svn-id: 4050ee570c0b454ed3c2eee326cdaf8b6ad603bd@19 e65ff1b4-dc2a-11dd-afbb-e3e17473af86
src/java/org/jsuffixarrays/ISuffixArrayBuilder.java
Clarified the contract on the returned SA content.
Java
apache-2.0
14bf25c8ba9b1c92953d9965ca8b6d75c498fd02
0
svetlemodry/Easy_xkcd,T-Rex96/Easy_xkcd,svetlemodry/Easy_xkcd,T-Rex96/Easy_xkcd,svetlemodry/Easy_xkcd,T-Rex96/Easy_xkcd
package de.tap.easy_xkcd.services; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.graphics.Bitmap; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.tap.xkcd_reader.BuildConfig; import com.tap.xkcd_reader.R; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import de.tap.easy_xkcd.utils.PrefHelper; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okio.BufferedSink; import okio.Okio; public class ArticleDownloadService extends IntentService { private static final String OFFLINE_WHATIF_PATH = "/easy xkcd/what if/"; private static final String OFFLINE_WHATIF_OVERVIEW_PATH = "/easy xkcd/what if/overview"; public ArticleDownloadService() { super("ArticleDownloadService"); } @Override protected void onHandleIntent(Intent intent) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setProgress(100, 0, false) .setOngoing(true) .setContentTitle(getResources().getString(R.string.loading_offline_whatif)) .setAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotificationManager.notify(1, mBuilder.build()); PrefHelper prefHelper = new PrefHelper(getApplicationContext()); File sdCard = prefHelper.getOfflinePath(); File dir = new File(sdCard.getAbsolutePath() + OFFLINE_WHATIF_OVERVIEW_PATH); OkHttpClient client = new OkHttpClient(); Document doc; if (!dir.exists()) dir.mkdirs(); //download overview if (!BuildConfig.DEBUG) { try { doc = Jsoup.connect("https://what-if.xkcd.com/archive/") .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.19 Safari/537.36") .get(); StringBuilder sb = new StringBuilder(); Elements titles = doc.select("h1"); prefHelper.setNewestWhatif(titles.size()); sb.append(titles.first().text()); titles.remove(0); for (Element title : titles) { sb.append("&&"); sb.append(title.text()); } prefHelper.setWhatIfTitles(sb.toString()); Elements img = doc.select("img.archive-image"); int count = 1; for (Element image : img) { String url = image.absUrl("src"); try { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); File file = new File(dir, String.valueOf(count) + ".png"); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); response.body().close(); } catch (Exception e) { e.printStackTrace(); } int p = (int) (count / ((float) img.size()) * 100); mBuilder.setProgress(100, p, false); mNotificationManager.notify(0, mBuilder.build()); count++; } if (prefHelper.getNewestWhatIf() == 0) prefHelper.setNewestWhatif(count - 1); } catch (IOException e) { e.printStackTrace(); } //download html int size = prefHelper.getNewestWhatIf(); for (int i = 1; i <= size; i++) { try { doc = Jsoup.connect("https://what-if.xkcd.com/" + String.valueOf(i)).get(); dir = new File(sdCard.getAbsolutePath() + OFFLINE_WHATIF_PATH + String.valueOf(i)); dir.mkdirs(); File file = new File(dir, String.valueOf(i) + ".html"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(doc.outerHtml()); writer.close(); //download images int count = 1; for (Element e : doc.select(".illustration")) { try { String url = "http://what-if.xkcd.com" + e.attr("src"); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); dir = new File(sdCard.getAbsolutePath() + OFFLINE_WHATIF_PATH + String.valueOf(i)); if (!dir.exists()) dir.mkdirs(); file = new File(dir, String.valueOf(count) + ".png"); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); response.body().close(); count++; } catch (Exception e2) { Log.e("article" + i, e2.getMessage()); } } int p = (int) (i / ((float) size) * 100); mBuilder.setProgress(100, p, false); mBuilder.setContentText(i + "/" + size); mNotificationManager.notify(0, mBuilder.build()); } catch (Exception e) { Log.e("article" + i, e.getMessage()); } } } prefHelper.setSunbeamLoaded(); Intent restart = new Intent("de.tap.easy_xkcd.ACTION_COMIC"); restart.putExtra("number", prefHelper.getLastComic()); PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, restart, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingIntent) .setContentText(getResources().getString(R.string.not_restart)); mNotificationManager.notify(0, mBuilder.build()); } }
app/src/main/java/de/tap/easy_xkcd/services/ArticleDownloadService.java
package de.tap.easy_xkcd.services; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.graphics.Bitmap; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.tap.xkcd_reader.BuildConfig; import com.tap.xkcd_reader.R; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import de.tap.easy_xkcd.utils.PrefHelper; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okio.BufferedSink; import okio.Okio; public class ArticleDownloadService extends IntentService { private static final String OFFLINE_WHATIF_PATH = "/easy xkcd/what if/"; private static final String OFFLINE_WHATIF_OVERVIEW_PATH = "/easy xkcd/what if/overview"; public ArticleDownloadService() { super("ArticleDownloadService"); } @Override protected void onHandleIntent(Intent intent) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setProgress(100, 0, false) .setOngoing(true) .setContentTitle(getResources().getString(R.string.loading_offline_whatif)) .setAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotificationManager.notify(0, mBuilder.build()); PrefHelper prefHelper = new PrefHelper(getApplicationContext()); File sdCard = prefHelper.getOfflinePath(); File dir = new File(sdCard.getAbsolutePath() + OFFLINE_WHATIF_OVERVIEW_PATH); OkHttpClient client = new OkHttpClient(); Document doc; if (!dir.exists()) dir.mkdirs(); //download overview if (!BuildConfig.DEBUG) { try { doc = Jsoup.connect("https://what-if.xkcd.com/archive/") .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.19 Safari/537.36") .get(); StringBuilder sb = new StringBuilder(); Elements titles = doc.select("h1"); prefHelper.setNewestWhatif(titles.size()); sb.append(titles.first().text()); titles.remove(0); for (Element title : titles) { sb.append("&&"); sb.append(title.text()); } prefHelper.setWhatIfTitles(sb.toString()); Elements img = doc.select("img.archive-image"); int count = 1; for (Element image : img) { String url = image.absUrl("src"); try { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); File file = new File(dir, String.valueOf(count) + ".png"); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); response.body().close(); } catch (Exception e) { e.printStackTrace(); } int p = (int) (count / ((float) img.size()) * 100); mBuilder.setProgress(100, p, false); mNotificationManager.notify(0, mBuilder.build()); count++; } if (prefHelper.getNewestWhatIf() == 0) prefHelper.setNewestWhatif(count - 1); } catch (IOException e) { e.printStackTrace(); } //download html int size = prefHelper.getNewestWhatIf(); for (int i = 1; i <= size; i++) { try { doc = Jsoup.connect("https://what-if.xkcd.com/" + String.valueOf(i)).get(); dir = new File(sdCard.getAbsolutePath() + OFFLINE_WHATIF_PATH + String.valueOf(i)); dir.mkdirs(); File file = new File(dir, String.valueOf(i) + ".html"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(doc.outerHtml()); writer.close(); //download images int count = 1; for (Element e : doc.select(".illustration")) { try { String url = "http://what-if.xkcd.com" + e.attr("src"); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); dir = new File(sdCard.getAbsolutePath() + OFFLINE_WHATIF_PATH + String.valueOf(i)); if (!dir.exists()) dir.mkdirs(); file = new File(dir, String.valueOf(count) + ".png"); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); response.body().close(); count++; } catch (Exception e2) { Log.e("article" + i, e2.getMessage()); } } int p = (int) (i / ((float) size) * 100); mBuilder.setProgress(100, p, false); mBuilder.setContentText(i + "/" + size); mNotificationManager.notify(0, mBuilder.build()); } catch (Exception e) { Log.e("article" + i, e.getMessage()); } } } prefHelper.setSunbeamLoaded(); Intent restart = new Intent("de.tap.easy_xkcd.ACTION_COMIC"); restart.putExtra("number", prefHelper.getLastComic()); PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, restart, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingIntent) .setContentText(getResources().getString(R.string.not_restart)); mNotificationManager.notify(0, mBuilder.build()); } }
fixed #71
app/src/main/java/de/tap/easy_xkcd/services/ArticleDownloadService.java
fixed #71
Java
apache-2.0
ce462dcaf6ec4eca188a3593f968e355969ea457
0
RapidPM/proxybuilder,tfeiner/proxybuilder,RapidPM/proxybuilder,ProxyBuilder/proxybuilder,ProxyBuilder/proxybuilder,tfeiner/proxybuilder,ProxyBuilder/proxybuilder
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.rapidpm.proxybuilder.staticgenerated.processors; import com.codahale.metrics.Histogram; import com.codahale.metrics.MetricRegistry; import com.squareup.javapoet.*; import com.squareup.javapoet.CodeBlock.Builder; import org.rapidpm.proxybuilder.core.metrics.RapidPMMetricsRegistry; import org.rapidpm.proxybuilder.staticgenerated.annotations.IsGeneratedProxy; import org.rapidpm.proxybuilder.staticgenerated.annotations.IsMetricsProxy; import org.rapidpm.proxybuilder.staticgenerated.annotations.StaticMetricsProxy; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; /** * Created by svenruppert on 09.12.15. * * final MetricRegistry metrics = MetricsRegistry.getInstance().getMetrics(); */ public class StaticMetricsProxyAnnotationProcessor extends BasicStaticProxyAnnotationProcessor<StaticMetricsProxy> { public static final String WITH_DELEGATOR = "withDelegator"; @Override public Class<StaticMetricsProxy> responsibleFor() { return StaticMetricsProxy.class; } @Override protected void addClassLevelSpecs(final TypeElement typeElement, final RoundEnvironment roundEnv) { final TypeName targetTypeName = TypeName.get(typeElement.asType()); typeSpecBuilderForTargetClass.addAnnotation(IsGeneratedProxy.class); typeSpecBuilderForTargetClass.addAnnotation(IsMetricsProxy.class); typeSpecBuilderForTargetClass.addField(defineDelegatorField(typeElement)); typeSpecBuilderForTargetClass.addField(defineMetricsField()); typeSpecBuilderForTargetClass.addField(defineSimpleClassNameField(typeElement)); typeSpecBuilderForTargetClass // .addMethod(MethodSpec.methodBuilder("with" + typeElement.getSimpleName()) .addMethod(MethodSpec.methodBuilder(WITH_DELEGATOR) .addModifiers(Modifier.PUBLIC) .addParameter(targetTypeName, DELEGATOR_FIELD_NAME, Modifier.FINAL) .addCode(CodeBlock.builder() .addStatement("this." + DELEGATOR_FIELD_NAME + " = " + DELEGATOR_FIELD_NAME) .addStatement("return this").build()) .returns(ClassName.get(pkgName(typeElement), targetClassNameSimple(typeElement))) .build()); } @Override protected CodeBlock defineMethodImplementation(final ExecutableElement methodElement, final String methodName2Delegate) { final TypeMirror returnType = methodElement.getReturnType(); final Builder codeBlockBuilder = CodeBlock.builder(); if (returnType.getKind() == TypeKind.VOID) { codeBlockBuilder .addStatement("final long start = System.nanoTime()") .addStatement(DELEGATOR_FIELD_NAME + "." + delegatorMethodCall(methodElement, methodName2Delegate)) .addStatement("final long stop = System.nanoTime()") .addStatement("final $T methodCalls = metrics.histogram(" + CLASS_NAME + " + \".\" + \"" + methodElement.getSimpleName() + "\")", Histogram.class) .addStatement("methodCalls.update(stop - start)"); } else { codeBlockBuilder .addStatement("final long start = System.nanoTime()") .addStatement("$T result = " + DELEGATOR_FIELD_NAME + "." + delegatorMethodCall(methodElement, methodName2Delegate), returnType) .addStatement("final long stop = System.nanoTime()") .addStatement("final $T methodCalls = metrics.histogram(" + CLASS_NAME + " + \".\" + \"" + methodElement.getSimpleName() + "\")", Histogram.class) .addStatement("methodCalls.update(stop - start)") .addStatement("return result"); } return codeBlockBuilder.build(); } protected FieldSpec defineMetricsField() { final ClassName metricsClassname = ClassName.get(MetricRegistry.class); return FieldSpec .builder(metricsClassname, "metrics") .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .initializer("$T.getInstance().getMetrics()", RapidPMMetricsRegistry.class) .build(); } }
modules/static/generated/processors/src/main/java/org/rapidpm/proxybuilder/staticgenerated/processors/StaticMetricsProxyAnnotationProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.rapidpm.proxybuilder.staticgenerated.processors; import com.codahale.metrics.Histogram; import com.codahale.metrics.MetricRegistry; import com.squareup.javapoet.*; import com.squareup.javapoet.CodeBlock.Builder; import org.rapidpm.proxybuilder.core.metrics.RapidPMMetricsRegistry; import org.rapidpm.proxybuilder.staticgenerated.annotations.IsGeneratedProxy; import org.rapidpm.proxybuilder.staticgenerated.annotations.IsMetricsProxy; import org.rapidpm.proxybuilder.staticgenerated.annotations.StaticMetricsProxy; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; /** * Created by svenruppert on 09.12.15. * * final MetricRegistry metrics = MetricsRegistry.getInstance().getMetrics(); */ public class StaticMetricsProxyAnnotationProcessor extends BasicStaticProxyAnnotationProcessor<StaticMetricsProxy> { @Override public Class<StaticMetricsProxy> responsibleFor() { return StaticMetricsProxy.class; } @Override protected void addClassLevelSpecs(final TypeElement typeElement, final RoundEnvironment roundEnv) { final TypeName targetTypeName = TypeName.get(typeElement.asType()); typeSpecBuilderForTargetClass.addAnnotation(IsGeneratedProxy.class); typeSpecBuilderForTargetClass.addAnnotation(IsMetricsProxy.class); typeSpecBuilderForTargetClass.addField(defineDelegatorField(typeElement)); typeSpecBuilderForTargetClass.addField(defineMetricsField()); typeSpecBuilderForTargetClass.addField(defineSimpleClassNameField(typeElement)); typeSpecBuilderForTargetClass .addMethod(MethodSpec.methodBuilder("with" + typeElement.getSimpleName()) .addModifiers(Modifier.PUBLIC) .addParameter(targetTypeName, DELEGATOR_FIELD_NAME, Modifier.FINAL) .addCode(CodeBlock.builder() .addStatement("this." + DELEGATOR_FIELD_NAME + " = " + DELEGATOR_FIELD_NAME) .addStatement("return this").build()) .returns(ClassName.get(pkgName(typeElement), targetClassNameSimple(typeElement))) .build()); } @Override protected CodeBlock defineMethodImplementation(final ExecutableElement methodElement, final String methodName2Delegate) { final TypeMirror returnType = methodElement.getReturnType(); final Builder codeBlockBuilder = CodeBlock.builder(); if (returnType.getKind() == TypeKind.VOID) { codeBlockBuilder .addStatement("final long start = System.nanoTime()") .addStatement(DELEGATOR_FIELD_NAME + "." + delegatorMethodCall(methodElement, methodName2Delegate)) .addStatement("final long stop = System.nanoTime()") .addStatement("final $T methodCalls = metrics.histogram(" + CLASS_NAME + " + \".\" + \"" + methodElement.getSimpleName() + "\")", Histogram.class) .addStatement("methodCalls.update(stop - start)"); } else { codeBlockBuilder .addStatement("final long start = System.nanoTime()") .addStatement("$T result = " + DELEGATOR_FIELD_NAME + "." + delegatorMethodCall(methodElement, methodName2Delegate), returnType) .addStatement("final long stop = System.nanoTime()") .addStatement("final $T methodCalls = metrics.histogram(" + CLASS_NAME + " + \".\" + \"" + methodElement.getSimpleName() + "\")", Histogram.class) .addStatement("methodCalls.update(stop - start)") .addStatement("return result"); } return codeBlockBuilder.build(); } protected FieldSpec defineMetricsField() { final ClassName metricsClassname = ClassName.get(MetricRegistry.class); return FieldSpec .builder(metricsClassname, "metrics") .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .initializer("$T.getInstance().getMetrics()", RapidPMMetricsRegistry.class) .build(); } }
PB-11 Changed the setDelegator Methodname
modules/static/generated/processors/src/main/java/org/rapidpm/proxybuilder/staticgenerated/processors/StaticMetricsProxyAnnotationProcessor.java
PB-11 Changed the setDelegator Methodname
Java
apache-2.0
4e868f24f92d3090a8427f9511001b1e43034e30
0
pubudu538/stratos,Thanu/stratos,apache/stratos,Thanu/stratos,ravihansa3000/stratos,apache/stratos,apache/stratos,pubudu538/stratos,ravihansa3000/stratos,ravihansa3000/stratos,pubudu538/stratos,ravihansa3000/stratos,pubudu538/stratos,pubudu538/stratos,apache/stratos,Thanu/stratos,ravihansa3000/stratos,apache/stratos,ravihansa3000/stratos,apache/stratos,Thanu/stratos,pubudu538/stratos,pubudu538/stratos,apache/stratos,Thanu/stratos,ravihansa3000/stratos,Thanu/stratos,Thanu/stratos
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.integration.tests.server; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.stratos.common.beans.application.ApplicationBean; import org.apache.stratos.common.beans.policy.deployment.ApplicationPolicyBean; import org.apache.stratos.integration.common.RestConstants; import org.apache.stratos.integration.common.TopologyHandler; import org.apache.stratos.integration.common.extensions.StratosServerExtension; import org.apache.stratos.integration.tests.StratosIntegrationTest; import org.apache.stratos.messaging.domain.application.ApplicationStatus; import org.apache.stratos.messaging.domain.topology.Member; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.AssertJUnit.assertTrue; /** * Deploy a sample application on mock IaaS and assert whether application instance, cluster instance, member instances * are getting activated. Restart the Stratos and check all again. */ public class StratosServerRestartTestCase extends StratosIntegrationTest { private static final Log log = LogFactory.getLog(StratosServerRestartTestCase.class); private static final String RESOURCES_PATH = "/stratos-server-restart-test"; private static final String autoscalingPolicyId = "autoscaling-policy-stratos-server-restart-test"; private static final String cartridgeId = "c1-stratos-server-restart-test"; private static final String networkPartitionId = "network-partition-stratos-server-restart-test"; private static final String deploymentPolicyId = "deployment-policy-stratos-server-restart-test"; private static final String applicationId = "stratos-server-restart-test"; private static final String applicationPolicyId = "application-policy-stratos-server-restart-test"; @Test(timeOut = APPLICATION_TEST_TIMEOUT, groups = { "stratos.server.restart"}, dependsOnGroups = { "stratos.application.deployment","stratos.cartridge.iaas", "stratos.policy.management","adc","all","smoke","metadata"}) public void stratosServerRestartTest() throws Exception { TopologyHandler topologyHandler = TopologyHandler.getInstance(); log.info("Adding autoscaling policy [autoscale policy id] " + autoscalingPolicyId); boolean addedScalingPolicy = restClient.addEntity( RESOURCES_PATH + RestConstants.AUTOSCALING_POLICIES_PATH + "/" + autoscalingPolicyId + ".json", RestConstants.AUTOSCALING_POLICIES, RestConstants.AUTOSCALING_POLICIES_NAME); assertTrue(addedScalingPolicy); log.info(String.format("Adding cartridge [cartridge type] %s", cartridgeId)); boolean addedC1 = restClient.addEntity( RESOURCES_PATH + RestConstants.CARTRIDGES_PATH + "/" + cartridgeId + ".json", RestConstants.CARTRIDGES, RestConstants.CARTRIDGES_NAME); assertTrue(addedC1); log.info(String.format("Adding network partition [network partition id] %s", networkPartitionId)); boolean addedN1 = restClient.addEntity(RESOURCES_PATH + RestConstants.NETWORK_PARTITIONS_PATH + "/" + networkPartitionId + ".json", RestConstants.NETWORK_PARTITIONS, RestConstants.NETWORK_PARTITIONS_NAME); assertTrue(addedN1); log.info(String.format("Adding deployment policy [deployment policy id] %s", deploymentPolicyId)); boolean addedDep = restClient.addEntity(RESOURCES_PATH + RestConstants.DEPLOYMENT_POLICIES_PATH + "/" + deploymentPolicyId + ".json", RestConstants.DEPLOYMENT_POLICIES, RestConstants.DEPLOYMENT_POLICIES_NAME); assertTrue(addedDep); log.info(String.format("Adding application [application id] %s", applicationId)); boolean addedApp = restClient.addEntity(RESOURCES_PATH + RestConstants.APPLICATIONS_PATH + "/" + applicationId + ".json", RestConstants.APPLICATIONS, RestConstants.APPLICATIONS_NAME); assertEquals(addedApp, true); ApplicationBean bean = (ApplicationBean) restClient .getEntity(RestConstants.APPLICATIONS, applicationId, ApplicationBean.class, RestConstants.APPLICATIONS_NAME); assertEquals(bean.getApplicationId(), applicationId); log.info(String.format("Adding application policy [application policy id] %s", applicationPolicyId)); boolean addAppPolicy = restClient.addEntity(RESOURCES_PATH + RestConstants.APPLICATION_POLICIES_PATH + "/" + applicationPolicyId + ".json", RestConstants.APPLICATION_POLICIES, RestConstants.APPLICATION_POLICIES_NAME); assertTrue(addAppPolicy); ApplicationPolicyBean policyBean = (ApplicationPolicyBean) restClient .getEntity(RestConstants.APPLICATION_POLICIES, applicationPolicyId, ApplicationPolicyBean.class, RestConstants.APPLICATION_POLICIES_NAME); assertEquals(policyBean.getId(), applicationPolicyId); log.info(String.format("Deploying application [application id] %s using [application policy id] %s", applicationId, applicationPolicyId)); String resourcePath = RestConstants.APPLICATIONS + "/" + applicationId + RestConstants.APPLICATIONS_DEPLOY + "/" + applicationPolicyId; boolean deployed = restClient.deployEntity(resourcePath, RestConstants.APPLICATIONS_NAME); assertTrue(deployed); log.info("Waiting for application status to become ACTIVE..."); topologyHandler.assertApplicationStatus(applicationId, ApplicationStatus.Active); log.info("Waiting for cluster status to become ACTIVE..."); topologyHandler.assertClusterActivation(applicationId); List<Member> memberList = topologyHandler.getMembersForApplication(applicationId); Assert.assertTrue(memberList.size() == 1, String.format("Active member list for application %s is empty", applicationId)); log.info("Terminating members in [cluster id] c1-stratos-server-restart-test in mock IaaS directly to " + "simulate faulty members..."); Map<String, Member> memberMap = TopologyHandler.getInstance() .getMembersForCluster("c1-stratos-server-restart-test", bean.getApplicationId()); for (Map.Entry<String, Member> entry : memberMap.entrySet()) { String memberId = entry.getValue().getMemberId(); TopologyHandler.getInstance().terminateMemberInMockIaas(memberId, mockIaasApiClient); TopologyHandler.getInstance().assertMemberTermination(memberId); } // application status should be marked as inactive since some members are faulty log.info("Waiting for application status to become INACTIVE"); topologyHandler.assertApplicationStatus(bean.getApplicationId(), ApplicationStatus.Inactive); // application should recover itself and become active after spinning more instances log.info("Waiting for application status to become ACTIVE..."); topologyHandler.assertApplicationStatus(bean.getApplicationId(), ApplicationStatus.Active); log.info("Waiting for cluster status to become ACTIVE..."); topologyHandler.assertClusterActivation(bean.getApplicationId()); // restart stratos server StratosServerExtension.restartStratosServer(); log.info("Waiting for application status to become ACTIVE..."); topologyHandler.assertApplicationStatus(bean.getApplicationId(), ApplicationStatus.Active); log.info("Waiting for cluster status to become ACTIVE..."); topologyHandler.assertClusterActivation(bean.getApplicationId()); memberList = topologyHandler.getMembersForApplication(bean.getApplicationId()); Assert.assertTrue(memberList.size() == 1, String.format("Active member list for application %s is empty", bean.getApplicationId())); log.info(String.format("Un-deploying the application [application id] %s", applicationId)); String resourcePathUndeploy = RestConstants.APPLICATIONS + "/" + applicationId+ RestConstants.APPLICATIONS_UNDEPLOY; boolean unDeployed = restClient.undeployEntity(resourcePathUndeploy, RestConstants.APPLICATIONS_NAME); assertTrue(unDeployed); boolean undeploy = topologyHandler.assertApplicationUndeploy(applicationId); if (!undeploy) { //Need to forcefully undeploy the application log.info(String.format("Force undeployment is going to start for the [application] %s", applicationId)); restClient.undeployEntity(RestConstants.APPLICATIONS + "/" + applicationId+ RestConstants.APPLICATIONS_UNDEPLOY + "?force=true", RestConstants.APPLICATIONS); boolean forceUndeployed = topologyHandler.assertApplicationUndeploy(applicationId); assertTrue(String.format("Forceful undeployment failed for the application %s", applicationId), forceUndeployed); } log.info(String.format("Removing the application [application id] %s", applicationId)); boolean removedApp = restClient.removeEntity(RestConstants.APPLICATIONS, applicationId, RestConstants.APPLICATIONS_NAME); assertTrue(removedApp); ApplicationBean beanRemoved = (ApplicationBean) restClient .getEntity(RestConstants.APPLICATIONS, applicationId, ApplicationBean.class, RestConstants.APPLICATIONS_NAME); assertNull(beanRemoved); log.info(String.format("Removing the application policy [application policy id] %s", applicationPolicyId)); boolean removeAppPolicy = restClient .removeEntity(RestConstants.APPLICATION_POLICIES, applicationPolicyId, RestConstants.APPLICATION_POLICIES_NAME); assertTrue(removeAppPolicy); log.info(String.format("Removing the cartridge [cartridge type] %s", cartridgeId)); boolean removedC1 = restClient.removeEntity(RestConstants.CARTRIDGES, cartridgeId, RestConstants.CARTRIDGES_NAME); assertTrue(removedC1); log.info(String.format("Removing the autoscaling policy [autoscaling policy id] %s", autoscalingPolicyId)); boolean removedAuto = restClient.removeEntity(RestConstants.AUTOSCALING_POLICIES, autoscalingPolicyId, RestConstants.AUTOSCALING_POLICIES_NAME); assertTrue(removedAuto); log.info(String.format("Removing the deployment policy [deployment policy id] %s", deploymentPolicyId)); boolean removedDep = restClient .removeEntity(RestConstants.DEPLOYMENT_POLICIES, deploymentPolicyId, RestConstants.DEPLOYMENT_POLICIES_NAME); assertTrue(removedDep); log.info(String.format("Removing the network partition [network partition id] %s", networkPartitionId)); boolean removedNet = restClient .removeEntity(RestConstants.NETWORK_PARTITIONS, networkPartitionId, RestConstants.NETWORK_PARTITIONS_NAME); assertTrue(removedNet); } }
products/stratos/modules/integration/test-integration/src/test/java/org/apache/stratos/integration/tests/server/StratosServerRestartTestCase.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.integration.tests.server; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.stratos.common.beans.application.ApplicationBean; import org.apache.stratos.common.beans.policy.deployment.ApplicationPolicyBean; import org.apache.stratos.integration.common.RestConstants; import org.apache.stratos.integration.common.TopologyHandler; import org.apache.stratos.integration.common.extensions.StratosServerExtension; import org.apache.stratos.integration.tests.StratosIntegrationTest; import org.apache.stratos.messaging.domain.application.ApplicationStatus; import org.apache.stratos.messaging.domain.topology.Member; import org.apache.stratos.metadata.client.beans.PropertyBean; import org.apache.stratos.mock.iaas.domain.MockInstanceMetadata; import org.testng.Assert; import org.testng.annotations.Test; import java.util.*; import static org.testng.Assert.*; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; /** * Deploy a sample application on mock IaaS and assert whether application instance, cluster instance, member instances * are getting activated. Restart the Stratos and check all again. */ public class StratosServerRestartTestCase extends StratosIntegrationTest { private static final Log log = LogFactory.getLog(StratosServerRestartTestCase.class); private static final String RESOURCES_PATH = "/stratos-server-restart-test"; private static final String autoscalingPolicyId = "autoscaling-policy-stratos-server-restart-test"; private static final String cartridgeId = "c1-stratos-server-restart-test"; private static final String networkPartitionId = "network-partition-stratos-server-restart-test"; private static final String deploymentPolicyId = "deployment-policy-stratos-server-restart-test"; private static final String applicationId = "stratos-server-restart-test"; private static final String applicationPolicyId = "application-policy-stratos-server-restart-test"; @Test(timeOut = APPLICATION_TEST_TIMEOUT, groups = { "stratos.server.restart"}, dependsOnGroups = { "stratos.application.deployment" }) public void stratosServerRestartTest() throws Exception { TopologyHandler topologyHandler = TopologyHandler.getInstance(); log.info("Adding autoscaling policy [autoscale policy id] " + autoscalingPolicyId); boolean addedScalingPolicy = restClient.addEntity( RESOURCES_PATH + RestConstants.AUTOSCALING_POLICIES_PATH + "/" + autoscalingPolicyId + ".json", RestConstants.AUTOSCALING_POLICIES, RestConstants.AUTOSCALING_POLICIES_NAME); assertTrue(addedScalingPolicy); log.info(String.format("Adding cartridge [cartridge type] %s", cartridgeId)); boolean addedC1 = restClient.addEntity( RESOURCES_PATH + RestConstants.CARTRIDGES_PATH + "/" + cartridgeId + ".json", RestConstants.CARTRIDGES, RestConstants.CARTRIDGES_NAME); assertTrue(addedC1); log.info(String.format("Adding network partition [network partition id] %s", networkPartitionId)); boolean addedN1 = restClient.addEntity(RESOURCES_PATH + RestConstants.NETWORK_PARTITIONS_PATH + "/" + networkPartitionId + ".json", RestConstants.NETWORK_PARTITIONS, RestConstants.NETWORK_PARTITIONS_NAME); assertTrue(addedN1); log.info(String.format("Adding deployment policy [deployment policy id] %s", deploymentPolicyId)); boolean addedDep = restClient.addEntity(RESOURCES_PATH + RestConstants.DEPLOYMENT_POLICIES_PATH + "/" + deploymentPolicyId + ".json", RestConstants.DEPLOYMENT_POLICIES, RestConstants.DEPLOYMENT_POLICIES_NAME); assertTrue(addedDep); log.info(String.format("Adding application [application id] %s", applicationId)); boolean addedApp = restClient.addEntity(RESOURCES_PATH + RestConstants.APPLICATIONS_PATH + "/" + applicationId + ".json", RestConstants.APPLICATIONS, RestConstants.APPLICATIONS_NAME); assertEquals(addedApp, true); ApplicationBean bean = (ApplicationBean) restClient .getEntity(RestConstants.APPLICATIONS, applicationId, ApplicationBean.class, RestConstants.APPLICATIONS_NAME); assertEquals(bean.getApplicationId(), applicationId); log.info(String.format("Adding application policy [application policy id] %s", applicationPolicyId)); boolean addAppPolicy = restClient.addEntity(RESOURCES_PATH + RestConstants.APPLICATION_POLICIES_PATH + "/" + applicationPolicyId + ".json", RestConstants.APPLICATION_POLICIES, RestConstants.APPLICATION_POLICIES_NAME); assertTrue(addAppPolicy); ApplicationPolicyBean policyBean = (ApplicationPolicyBean) restClient .getEntity(RestConstants.APPLICATION_POLICIES, applicationPolicyId, ApplicationPolicyBean.class, RestConstants.APPLICATION_POLICIES_NAME); assertEquals(policyBean.getId(), applicationPolicyId); log.info(String.format("Deploying application [application id] %s using [application policy id] %s", applicationId, applicationPolicyId)); String resourcePath = RestConstants.APPLICATIONS + "/" + applicationId + RestConstants.APPLICATIONS_DEPLOY + "/" + applicationPolicyId; boolean deployed = restClient.deployEntity(resourcePath, RestConstants.APPLICATIONS_NAME); assertTrue(deployed); log.info("Waiting for application status to become ACTIVE..."); topologyHandler.assertApplicationStatus(applicationId, ApplicationStatus.Active); log.info("Waiting for cluster status to become ACTIVE..."); topologyHandler.assertClusterActivation(applicationId); List<Member> memberList = topologyHandler.getMembersForApplication(applicationId); Assert.assertTrue(memberList.size() == 1, String.format("Active member list for application %s is empty", applicationId)); log.info("Terminating members in [cluster id] c1-stratos-server-restart-test in mock IaaS directly to " + "simulate faulty members..."); Map<String, Member> memberMap = TopologyHandler.getInstance() .getMembersForCluster("c1-stratos-server-restart-test", bean.getApplicationId()); for (Map.Entry<String, Member> entry : memberMap.entrySet()) { String memberId = entry.getValue().getMemberId(); TopologyHandler.getInstance().terminateMemberInMockIaas(memberId, mockIaasApiClient); TopologyHandler.getInstance().assertMemberTermination(memberId); } // application status should be marked as inactive since some members are faulty log.info("Waiting for application status to become INACTIVE"); topologyHandler.assertApplicationStatus(bean.getApplicationId(), ApplicationStatus.Inactive); // application should recover itself and become active after spinning more instances log.info("Waiting for application status to become ACTIVE..."); topologyHandler.assertApplicationStatus(bean.getApplicationId(), ApplicationStatus.Active); log.info("Waiting for cluster status to become ACTIVE..."); topologyHandler.assertClusterActivation(bean.getApplicationId()); // restart stratos server StratosServerExtension.restartStratosServer(); log.info("Waiting for application status to become ACTIVE..."); topologyHandler.assertApplicationStatus(bean.getApplicationId(), ApplicationStatus.Active); log.info("Waiting for cluster status to become ACTIVE..."); topologyHandler.assertClusterActivation(bean.getApplicationId()); memberList = topologyHandler.getMembersForApplication(bean.getApplicationId()); Assert.assertTrue(memberList.size() == 1, String.format("Active member list for application %s is empty", bean.getApplicationId())); log.info(String.format("Un-deploying the application [application id] %s", applicationId)); String resourcePathUndeploy = RestConstants.APPLICATIONS + "/" + applicationId+ RestConstants.APPLICATIONS_UNDEPLOY; boolean unDeployed = restClient.undeployEntity(resourcePathUndeploy, RestConstants.APPLICATIONS_NAME); assertTrue(unDeployed); boolean undeploy = topologyHandler.assertApplicationUndeploy(applicationId); if (!undeploy) { //Need to forcefully undeploy the application log.info(String.format("Force undeployment is going to start for the [application] %s", applicationId)); restClient.undeployEntity(RestConstants.APPLICATIONS + "/" + applicationId+ RestConstants.APPLICATIONS_UNDEPLOY + "?force=true", RestConstants.APPLICATIONS); boolean forceUndeployed = topologyHandler.assertApplicationUndeploy(applicationId); assertTrue(String.format("Forceful undeployment failed for the application %s", applicationId), forceUndeployed); } log.info(String.format("Removing the application [application id] %s", applicationId)); boolean removedApp = restClient.removeEntity(RestConstants.APPLICATIONS, applicationId, RestConstants.APPLICATIONS_NAME); assertTrue(removedApp); ApplicationBean beanRemoved = (ApplicationBean) restClient .getEntity(RestConstants.APPLICATIONS, applicationId, ApplicationBean.class, RestConstants.APPLICATIONS_NAME); assertNull(beanRemoved); log.info(String.format("Removing the application policy [application policy id] %s", applicationPolicyId)); boolean removeAppPolicy = restClient .removeEntity(RestConstants.APPLICATION_POLICIES, applicationPolicyId, RestConstants.APPLICATION_POLICIES_NAME); assertTrue(removeAppPolicy); log.info(String.format("Removing the cartridge [cartridge type] %s", cartridgeId)); boolean removedC1 = restClient.removeEntity(RestConstants.CARTRIDGES, cartridgeId, RestConstants.CARTRIDGES_NAME); assertTrue(removedC1); log.info(String.format("Removing the autoscaling policy [autoscaling policy id] %s", autoscalingPolicyId)); boolean removedAuto = restClient.removeEntity(RestConstants.AUTOSCALING_POLICIES, autoscalingPolicyId, RestConstants.AUTOSCALING_POLICIES_NAME); assertTrue(removedAuto); log.info(String.format("Removing the deployment policy [deployment policy id] %s", deploymentPolicyId)); boolean removedDep = restClient .removeEntity(RestConstants.DEPLOYMENT_POLICIES, deploymentPolicyId, RestConstants.DEPLOYMENT_POLICIES_NAME); assertTrue(removedDep); log.info(String.format("Removing the network partition [network partition id] %s", networkPartitionId)); boolean removedNet = restClient .removeEntity(RestConstants.NETWORK_PARTITIONS, networkPartitionId, RestConstants.NETWORK_PARTITIONS_NAME); assertTrue(removedNet); } }
Adding depends on groups for server restart test
products/stratos/modules/integration/test-integration/src/test/java/org/apache/stratos/integration/tests/server/StratosServerRestartTestCase.java
Adding depends on groups for server restart test
Java
apache-2.0
026b39ad9d9336b1efdd8e2ffb9a508cb0db6259
0
soumabrata-chakraborty/hadoop,ronny-macmaster/hadoop,legend-hua/hadoop,ChetnaChaudhari/hadoop,szegedim/hadoop,soumabrata-chakraborty/hadoop,apurtell/hadoop,plusplusjiajia/hadoop,nandakumar131/hadoop,wenxinhe/hadoop,JingchengDu/hadoop,lukmajercak/hadoop,bitmybytes/hadoop,littlezhou/hadoop,huafengw/hadoop,legend-hua/hadoop,lukmajercak/hadoop,bitmybytes/hadoop,steveloughran/hadoop,xiao-chen/hadoop,lukmajercak/hadoop,GeLiXin/hadoop,979969786/hadoop,xiao-chen/hadoop,ChetnaChaudhari/hadoop,ctrezzo/hadoop,soumabrata-chakraborty/hadoop,dierobotsdie/hadoop,ChetnaChaudhari/hadoop,dennishuo/hadoop,JingchengDu/hadoop,szegedim/hadoop,littlezhou/hadoop,littlezhou/hadoop,dierobotsdie/hadoop,wenxinhe/hadoop,nandakumar131/hadoop,steveloughran/hadoop,JingchengDu/hadoop,dierobotsdie/hadoop,dennishuo/hadoop,ronny-macmaster/hadoop,wenxinhe/hadoop,GeLiXin/hadoop,apurtell/hadoop,dierobotsdie/hadoop,979969786/hadoop,ucare-uchicago/hadoop,steveloughran/hadoop,JingchengDu/hadoop,ucare-uchicago/hadoop,apurtell/hadoop,979969786/hadoop,wwjiang007/hadoop,dierobotsdie/hadoop,littlezhou/hadoop,steveloughran/hadoop,GeLiXin/hadoop,Ethanlm/hadoop,Ethanlm/hadoop,nandakumar131/hadoop,wenxinhe/hadoop,legend-hua/hadoop,plusplusjiajia/hadoop,mapr/hadoop-common,dennishuo/hadoop,xiao-chen/hadoop,soumabrata-chakraborty/hadoop,huafengw/hadoop,littlezhou/hadoop,ctrezzo/hadoop,apurtell/hadoop,dierobotsdie/hadoop,steveloughran/hadoop,Ethanlm/hadoop,apache/hadoop,apache/hadoop,ucare-uchicago/hadoop,mapr/hadoop-common,nandakumar131/hadoop,JingchengDu/hadoop,nandakumar131/hadoop,979969786/hadoop,littlezhou/hadoop,xiao-chen/hadoop,ctrezzo/hadoop,dennishuo/hadoop,979969786/hadoop,legend-hua/hadoop,ctrezzo/hadoop,wwjiang007/hadoop,plusplusjiajia/hadoop,ronny-macmaster/hadoop,GeLiXin/hadoop,lukmajercak/hadoop,WIgor/hadoop,ChetnaChaudhari/hadoop,huafengw/hadoop,Ethanlm/hadoop,soumabrata-chakraborty/hadoop,plusplusjiajia/hadoop,mapr/hadoop-common,WIgor/hadoop,Ethanlm/hadoop,bitmybytes/hadoop,wwjiang007/hadoop,wenxinhe/hadoop,xiao-chen/hadoop,mapr/hadoop-common,xiao-chen/hadoop,ctrezzo/hadoop,mapr/hadoop-common,GeLiXin/hadoop,legend-hua/hadoop,WIgor/hadoop,mapr/hadoop-common,JingchengDu/hadoop,JingchengDu/hadoop,979969786/hadoop,wwjiang007/hadoop,ronny-macmaster/hadoop,szegedim/hadoop,ChetnaChaudhari/hadoop,apache/hadoop,szegedim/hadoop,soumabrata-chakraborty/hadoop,dennishuo/hadoop,soumabrata-chakraborty/hadoop,szegedim/hadoop,szegedim/hadoop,WIgor/hadoop,steveloughran/hadoop,ucare-uchicago/hadoop,ChetnaChaudhari/hadoop,GeLiXin/hadoop,WIgor/hadoop,wenxinhe/hadoop,WIgor/hadoop,xiao-chen/hadoop,bitmybytes/hadoop,ronny-macmaster/hadoop,wwjiang007/hadoop,steveloughran/hadoop,apache/hadoop,ctrezzo/hadoop,plusplusjiajia/hadoop,lukmajercak/hadoop,apurtell/hadoop,ChetnaChaudhari/hadoop,legend-hua/hadoop,ronny-macmaster/hadoop,apache/hadoop,wenxinhe/hadoop,szegedim/hadoop,plusplusjiajia/hadoop,lukmajercak/hadoop,wwjiang007/hadoop,legend-hua/hadoop,wwjiang007/hadoop,dennishuo/hadoop,WIgor/hadoop,huafengw/hadoop,dennishuo/hadoop,mapr/hadoop-common,bitmybytes/hadoop,979969786/hadoop,apache/hadoop,Ethanlm/hadoop,apache/hadoop,huafengw/hadoop,apurtell/hadoop,lukmajercak/hadoop,nandakumar131/hadoop,Ethanlm/hadoop,ucare-uchicago/hadoop,dierobotsdie/hadoop,plusplusjiajia/hadoop,apurtell/hadoop,ucare-uchicago/hadoop,nandakumar131/hadoop,huafengw/hadoop,littlezhou/hadoop,huafengw/hadoop,bitmybytes/hadoop,ctrezzo/hadoop,GeLiXin/hadoop,ronny-macmaster/hadoop,bitmybytes/hadoop,ucare-uchicago/hadoop
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapreduce.v2.hs.webapp; import static org.apache.hadoop.mapreduce.v2.app.webapp.AMParams.TASK_TYPE; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.ACCORDION; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_ID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_SELECTOR; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initSelector; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.postInitID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.tableInit; import org.apache.hadoop.mapreduce.v2.api.records.TaskType; import org.apache.hadoop.mapreduce.v2.util.MRApps; import org.apache.hadoop.yarn.webapp.SubView; /** * A page showing the tasks for a given application. */ public class HsTasksPage extends HsView { /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.v2.hs.webapp.HsView#preHead(org.apache.hadoop.yarn.webapp.hamlet.Hamlet.HTML) */ @Override protected void preHead(Page.HTML<_> html) { commonPreHead(html); set(DATATABLES_ID, "tasks"); set(DATATABLES_SELECTOR, ".dt-tasks" ); set(initSelector(DATATABLES), tasksTableInit()); set(initID(ACCORDION, "nav"), "{autoHeight:false, active:1}"); set(initID(DATATABLES, "tasks"), tasksTableInit()); set(postInitID(DATATABLES, "tasks"), jobsPostTableInit()); setTableStyles(html, "tasks"); } /** * The content of this page is the TasksBlock * @return HsTasksBlock.class */ @Override protected Class<? extends SubView> content() { return HsTasksBlock.class; } /** * @return the end of the JS map that is the jquery datatable configuration * for the tasks table. */ private String tasksTableInit() { TaskType type = null; String symbol = $(TASK_TYPE); if (!symbol.isEmpty()) { type = MRApps.taskType(symbol); } StringBuilder b = tableInit(). append(", 'aaData': tasksTableData") .append(", bDeferRender: true") .append(", bProcessing: true") .append("\n, aoColumnDefs: [\n") .append("{'sType':'natural', 'aTargets': [ 0 ]") .append(", 'mRender': parseHadoopID }") .append(", {'sType':'numeric', 'aTargets': [ 4") .append(type == TaskType.REDUCE ? ", 9, 10, 11, 12" : ", 7") .append(" ], 'mRender': renderHadoopElapsedTime }") .append("\n, {'sType':'numeric', 'aTargets': [ 2, 3, 5") .append(type == TaskType.REDUCE ? ", 6, 7, 8" : ", 6") .append(" ], 'mRender': renderHadoopDate }]") // Sort by id upon page load .append("\n, aaSorting: [[0, 'asc']]") .append("}"); return b.toString(); } private String jobsPostTableInit() { return "var asInitVals = new Array();\n" + "$('tfoot input').keyup( function () \n{"+ " $('.dt-tasks').dataTable().fnFilter("+ " this.value, $('tfoot input').index(this) );\n"+ "} );\n"+ "$('tfoot input').each( function (i) {\n"+ " asInitVals[i] = this.value;\n"+ "} );\n"+ "$('tfoot input').focus( function () {\n"+ " if ( this.className == 'search_init' )\n"+ " {\n"+ " this.className = '';\n"+ " this.value = '';\n"+ " }\n"+ "} );\n"+ "$('tfoot input').blur( function (i) {\n"+ " if ( this.value == '' )\n"+ " {\n"+ " this.className = 'search_init';\n"+ " this.value = asInitVals[$('tfoot input').index(this)];\n"+ " }\n"+ "} );\n"; } }
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/HsTasksPage.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapreduce.v2.hs.webapp; import static org.apache.hadoop.mapreduce.v2.app.webapp.AMParams.TASK_TYPE; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.ACCORDION; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_ID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_SELECTOR; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initSelector; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.postInitID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.tableInit; import org.apache.hadoop.mapreduce.v2.api.records.TaskType; import org.apache.hadoop.mapreduce.v2.util.MRApps; import org.apache.hadoop.yarn.webapp.SubView; /** * A page showing the tasks for a given application. */ public class HsTasksPage extends HsView { /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.v2.hs.webapp.HsView#preHead(org.apache.hadoop.yarn.webapp.hamlet.Hamlet.HTML) */ @Override protected void preHead(Page.HTML<_> html) { commonPreHead(html); set(DATATABLES_ID, "tasks"); set(DATATABLES_SELECTOR, ".dt-tasks" ); set(initSelector(DATATABLES), tasksTableInit()); set(initID(ACCORDION, "nav"), "{autoHeight:false, active:1}"); set(initID(DATATABLES, "tasks"), tasksTableInit()); set(postInitID(DATATABLES, "tasks"), jobsPostTableInit()); setTableStyles(html, "tasks"); } /** * The content of this page is the TasksBlock * @return HsTasksBlock.class */ @Override protected Class<? extends SubView> content() { return HsTasksBlock.class; } /** * @return the end of the JS map that is the jquery datatable configuration * for the tasks table. */ private String tasksTableInit() { TaskType type = null; String symbol = $(TASK_TYPE); if (!symbol.isEmpty()) { type = MRApps.taskType(symbol); } StringBuilder b = tableInit(). append(", 'aaData': tasksTableData") .append(", bDeferRender: true") .append(", bProcessing: true") .append("\n, aoColumnDefs: [\n") .append("{'sType':'natural', 'aTargets': [ 0 ]") .append(", 'mRender': parseHadoopID }") .append(", {'sType':'numeric', 'aTargets': [ 4") .append(type == TaskType.REDUCE ? ", 9, 10, 11, 12" : ", 7") .append(" ], 'mRender': renderHadoopElapsedTime }") .append("\n, {'sType':'numeric', 'aTargets': [ 2, 3, 5") .append(type == TaskType.REDUCE ? ", 6, 7, 8" : ", 6") .append(" ], 'mRender': renderHadoopDate }]") // Sort by id upon page load .append("\n, aaSorting: [[0, 'asc']]") .append("}"); return b.toString(); } private String jobsPostTableInit() { return "var asInitVals = new Array();\n" + "$('tfoot input').keyup( function () \n{"+ " tasksDataTable.fnFilter( this.value, $('tfoot input').index(this) );\n"+ "} );\n"+ "$('tfoot input').each( function (i) {\n"+ " asInitVals[i] = this.value;\n"+ "} );\n"+ "$('tfoot input').focus( function () {\n"+ " if ( this.className == 'search_init' )\n"+ " {\n"+ " this.className = '';\n"+ " this.value = '';\n"+ " }\n"+ "} );\n"+ "$('tfoot input').blur( function (i) {\n"+ " if ( this.value == '' )\n"+ " {\n"+ " this.className = 'search_init';\n"+ " this.value = asInitVals[$('tfoot input').index(this)];\n"+ " }\n"+ "} );\n"; } }
MAPREDUCE-6782. JHS task page search based on each individual column not working (Ajith S via Varun Saxena)
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/HsTasksPage.java
MAPREDUCE-6782. JHS task page search based on each individual column not working (Ajith S via Varun Saxena)
Java
apache-2.0
455ccceac4cad11593a22d9e46b1c90497856ba2
0
pkocandr/indy,pkocandr/indy,ligangty/indy,jdcasey/indy,Commonjava/indy,Commonjava/indy,yma88/indy,ruhan1/indy,yma88/indy,jdcasey/indy,yma88/indy,ruhan1/indy,Commonjava/indy,jdcasey/indy,ruhan1/indy,pkocandr/indy,jdcasey/indy,ligangty/indy,ligangty/indy,Commonjava/indy,Commonjava/indy,ligangty/indy,ruhan1/indy,ruhan1/indy,yma88/indy,ligangty/indy,Commonjava/indy,yma88/indy,yma88/indy,jdcasey/indy,pkocandr/indy,jdcasey/indy,ligangty/indy,pkocandr/indy,pkocandr/indy,ruhan1/indy
/** * Copyright (C) 2011-2017 Red Hat, Inc. (https://github.com/Commonjava/indy) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.commonjava.indy.core.expire; import com.fasterxml.jackson.core.JsonProcessingException; import org.commonjava.indy.action.BootupAction; import org.commonjava.indy.action.IndyLifecycleException; import org.commonjava.indy.action.ShutdownAction; import org.commonjava.indy.conf.IndyConfiguration; import org.commonjava.indy.core.conf.IndySchedulerConfig; import org.commonjava.indy.core.expire.cache.ScheduleCache; import org.commonjava.indy.data.IndyDataException; import org.commonjava.indy.data.StoreDataManager; import org.commonjava.indy.model.core.ArtifactStore; import org.commonjava.indy.model.core.Group; import org.commonjava.indy.model.core.HostedRepository; import org.commonjava.indy.model.core.RemoteRepository; import org.commonjava.indy.model.core.StoreKey; import org.commonjava.indy.model.core.StoreType; import org.commonjava.indy.model.core.io.IndyObjectMapper; import org.commonjava.indy.spi.pkg.ContentAdvisor; import org.commonjava.indy.spi.pkg.ContentQuality; import org.commonjava.indy.subsys.infinispan.CacheHandle; import org.commonjava.indy.subsys.infinispan.CacheKeyMatcher; import org.commonjava.indy.util.LocationUtils; import org.commonjava.maven.galley.model.ConcreteResource; import org.commonjava.maven.galley.model.SpecialPathInfo; import org.commonjava.maven.galley.spi.io.SpecialPathManager; import org.infinispan.container.entries.CacheEntry; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Event; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport; import static org.commonjava.indy.core.change.StoreEnablementManager.DISABLE_TIMEOUT; import static org.commonjava.indy.core.change.StoreEnablementManager.TIMEOUT_USE_DEFAULT; /** * A ScheduleManager is used to do the schedule time out jobs for the {@link ArtifactStore} to do some time-related jobs, like * removing useless artifacts. It used ISPN cache timeout mechanism to implement this type of function. * This class is also acted as a cache listener to handle the cache expiration job event to distribute the expiration * info through CDI event for the real actor to do the expiration work. */ @ApplicationScoped @Listener public class ScheduleManager implements BootupAction, ShutdownAction { private final Logger logger = LoggerFactory.getLogger( getClass() ); public static final String PAYLOAD = "payload"; public static final String ANY = "__ANY__"; public static final String CONTENT_JOB_TYPE = "CONTENT"; public static final String JOB_TYPE = "JOB_TYPE"; public static final String SCHEDULE_TIME = "SCHEDULE_TIME"; @Inject private StoreDataManager dataManager; @Inject private IndyConfiguration config; @Inject private IndyObjectMapper objectMapper; @Inject private IndySchedulerConfig schedulerConfig; @Inject private SpecialPathManager specialPathManager; @Inject @ScheduleCache private CacheHandle<ScheduleKey, Map> scheduleCache; @Inject @Any private Instance<ContentAdvisor> contentAdvisor; @Inject private Event<SchedulerEvent> eventDispatcher; @Override public void init() throws IndyLifecycleException { if ( !schedulerConfig.isEnabled() ) { logger.info( "Scheduler disabled. Skipping initialization" ); return; } // register this producer as schedule cache listener scheduleCache.execute( cache -> { cache.addListener( ScheduleManager.this ); return null; } ); } public synchronized void rescheduleSnapshotTimeouts( final HostedRepository deploy ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } int timeout = -1; if ( deploy.isAllowSnapshots() && deploy.getSnapshotTimeoutSeconds() > 0 ) { timeout = deploy.getSnapshotTimeoutSeconds(); } if ( timeout > 0 ) { final Set<ScheduleKey> canceled = cancelAllBefore( new StoreKeyMatcher( deploy.getKey(), CONTENT_JOB_TYPE ), timeout ); for ( final ScheduleKey key : canceled ) { final String path = key.getName(); final StoreKey sk = storeKeyFrom( key.groupName() ); scheduleContentExpiration( sk, path, timeout ); } } } public synchronized void rescheduleProxyTimeouts( final RemoteRepository repo ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } int timeout = -1; if ( !repo.isPassthrough() && repo.getCacheTimeoutSeconds() > 0 ) { timeout = repo.getCacheTimeoutSeconds(); } else if ( repo.isPassthrough() ) { timeout = config.getPassthroughTimeoutSeconds(); } if ( timeout > 0 ) { final Set<ScheduleKey> canceled = cancelAllBefore( new StoreKeyMatcher( repo.getKey(), CONTENT_JOB_TYPE ), timeout ); for ( final ScheduleKey key : canceled ) { final String path = key.getName(); final StoreKey sk = storeKeyFrom( key.groupName() ); scheduleContentExpiration( sk, path, timeout ); } } } public synchronized void setProxyTimeouts( final StoreKey key, final String path ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } RemoteRepository repo = null; try { repo = (RemoteRepository) dataManager.getArtifactStore( key ); } catch ( final IndyDataException e ) { logger.error( String.format( "Failed to retrieve store for: %s. Reason: %s", key, e.getMessage() ), e ); } if ( repo == null ) { return; } int timeout = config.getPassthroughTimeoutSeconds(); final ConcreteResource resource = new ConcreteResource( LocationUtils.toLocation( repo ), path ); final SpecialPathInfo info = specialPathManager.getSpecialPathInfo( resource ); if ( !repo.isPassthrough() ) { if ( ( info != null && info.isMetadata() ) && repo.getMetadataTimeoutSeconds() > 0 ) { logger.debug( "Using metadata timeout for: {}", resource ); timeout = repo.getMetadataTimeoutSeconds(); } else { if ( info == null ) { logger.debug( "No special path info for: {}", resource ); } else { logger.debug( "{} is a special path, but not metadata.", resource ); } timeout = repo.getCacheTimeoutSeconds(); } } if ( timeout > 0 ) { // logger.info( "[PROXY TIMEOUT SET] {}/{}; {}", repo.getKey(), path, new Date( System.currentTimeMillis() // + timeout ) ); cancel( new StoreKeyMatcher( key, CONTENT_JOB_TYPE ), path ); scheduleContentExpiration( key, path, timeout ); } } public synchronized void scheduleForStore( final StoreKey key, final String jobType, final String jobName, final Object payload, final int startSeconds ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } final Map<String, Object> dataMap = new HashMap<>( 3 ); dataMap.put( JOB_TYPE, jobType ); try { dataMap.put( PAYLOAD, objectMapper.writeValueAsString( payload ) ); } catch ( final JsonProcessingException e ) { throw new IndySchedulerException( "Failed to serialize JSON payload: " + payload, e ); } dataMap.put( SCHEDULE_TIME, System.currentTimeMillis() ); final ScheduleKey cacheKey = new ScheduleKey( key, jobType, jobName ); scheduleCache.execute( cache -> cache.put( cacheKey, dataMap, startSeconds, TimeUnit.SECONDS ) ); logger.debug( "Scheduled for the key {} with timeout: {} seconds", cacheKey, startSeconds ); } public synchronized void scheduleContentExpiration( final StoreKey key, final String path, final int timeoutSeconds ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } logger.info( "Scheduling timeout for: {} in: {} in: {} seconds (at: {}).", path, key, timeoutSeconds, new Date( System.currentTimeMillis() + ( timeoutSeconds * 1000 ) ) ); scheduleForStore( key, CONTENT_JOB_TYPE, path, new ContentExpiration( key, path ), timeoutSeconds ); } public synchronized void setSnapshotTimeouts( final StoreKey key, final String path ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } HostedRepository deploy = null; try { final ArtifactStore store = dataManager.getArtifactStore( key ); if ( store == null ) { return; } if ( store instanceof HostedRepository ) { deploy = (HostedRepository) store; } else if ( store instanceof Group ) { final Group group = (Group) store; deploy = findDeployPoint( group ); } } catch ( final IndyDataException e ) { logger.error( String.format( "Failed to retrieve deploy point for: %s. Reason: %s", key, e.getMessage() ), e ); } if ( deploy == null ) { return; } final ContentAdvisor advisor = StreamSupport.stream( Spliterators.spliteratorUnknownSize( contentAdvisor.iterator(), Spliterator.ORDERED ), false ) .filter( Objects::nonNull ) .findFirst() .orElse( null ); final ContentQuality quality = advisor == null ? null : advisor.getContentQuality( path ); if ( quality == null ) { return; } if ( ContentQuality.SNAPSHOT == quality && deploy.getSnapshotTimeoutSeconds() > 0 ) { final int timeout = deploy.getSnapshotTimeoutSeconds(); // // logger.info( "[SNAPSHOT TIMEOUT SET] {}/{}; {}", deploy.getKey(), path, new Date( timeout ) ); // cancel( new StoreKeyMatcher( key, CONTENT_JOB_TYPE ), path ); scheduleContentExpiration( key, path, timeout ); } } public synchronized void rescheduleDisableTimeout( final StoreKey key ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } ArtifactStore store = null; try { store = dataManager.getArtifactStore( key ); } catch ( final IndyDataException e ) { logger.error( String.format( "Failed to retrieve store for: %s. Reason: %s", key, e.getMessage() ), e ); } if ( store == null ) { return; } int timeout = store.getDisableTimeout(); if ( timeout == TIMEOUT_USE_DEFAULT ) { // case TIMEOUT_USE_DEFAULT: will use default timeout configuration timeout = config.getStoreDisableTimeoutSeconds(); } // No need to cancel as the job will be cancelled immediately after the re-enable in StoreEnablementManager // final Set<ScheduleKey> canceled = // cancelAllBefore( new StoreKeyMatcher( store.getKey(), DISABLE_TIMEOUT ), // timeout ); // logger.info( "Cancel disable timeout for stores:{}", canceled ); if ( timeout > TIMEOUT_USE_DEFAULT && store.isDisabled() ) { final StoreKey sk = store.getKey(); logger.debug( "Set/Reschedule disable timeout for store:{}", sk ); scheduleForStore( sk, DISABLE_TIMEOUT, DISABLE_TIMEOUT, sk, timeout ); } // Will never consider the TIMEOUT_NEVER_DISABLE case here, will consider this in the calling object(StoreEnablementManager) } private HostedRepository findDeployPoint( final Group group ) throws IndyDataException { for ( final StoreKey key : group.getConstituents() ) { if ( StoreType.hosted == key.getType() ) { return (HostedRepository) dataManager.getArtifactStore( key ); } else if ( StoreType.group == key.getType() ) { final Group grp = (Group) dataManager.getArtifactStore( key ); final HostedRepository dp = findDeployPoint( grp ); if ( dp != null ) { return dp; } } } return null; } public synchronized Set<ScheduleKey> cancelAllBefore( final CacheKeyMatcher<ScheduleKey> matcher, final long timeout ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return Collections.emptySet(); } final Set<ScheduleKey> canceled = new HashSet<>(); final Date to = new Date( System.currentTimeMillis() + ( timeout * 1000 ) ); matcher.matches( scheduleCache ).forEach( key -> { final Date nextFire = getNextExpireTime( key ); if ( nextFire == null || !nextFire.after( to ) ) { // former impl uses quartz and here use the unscheduleJob method, but ISPN does not have similar // op, so directly did a remove here. removeCache( key ); logger.debug( "Removed cache job for key: {}, before {}", key, to ); canceled.add( key ); } } ); return canceled; } public synchronized Set<ScheduleKey> cancelAll( final CacheKeyMatcher<ScheduleKey> matcher ) throws IndySchedulerException { return cancel( matcher, ANY ); } public synchronized Set<ScheduleKey> cancel( final CacheKeyMatcher<ScheduleKey> matcher, final String name ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return Collections.emptySet(); } Set<ScheduleKey> canceled = new HashSet<>(); final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); if ( keys != null && !keys.isEmpty() ) { Set<ScheduleKey> unscheduled = null; if ( name == ANY ) { for ( final ScheduleKey k : keys ) { removeCache( k ); } unscheduled = keys; } else { for ( final ScheduleKey k : keys ) { if ( k.getName().equals( name ) ) { removeCache( k ); unscheduled = Collections.singleton( k ); break; } } } if ( unscheduled != null ) { canceled = unscheduled; } } return canceled; } public synchronized Expiration findSingleExpiration( final StoreKeyMatcher matcher ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return null; } final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); if ( keys != null && !keys.isEmpty() ) { ScheduleKey triggerKey = keys.iterator().next(); return toExpiration( triggerKey ); } return null; } public synchronized ExpirationSet findMatchingExpirations( final CacheKeyMatcher<ScheduleKey> matcher ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return null; } final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); Set<Expiration> expirations = new HashSet<>( keys.size() ); if ( keys != null && !keys.isEmpty() ) { for ( ScheduleKey key : keys ) { expirations.add( toExpiration( key ) ); } } return new ExpirationSet( expirations ); } private Expiration toExpiration( final ScheduleKey cacheKey ) { return new Expiration( cacheKey.groupName(), cacheKey.getName(), getNextExpireTime( cacheKey ) ); } private Date getNextExpireTime( final ScheduleKey cacheKey ) { return scheduleCache.execute( cache -> { final CacheEntry entry = cache.getAdvancedCache().getCacheEntry( cacheKey ); if ( entry != null ) { final Metadata metadata = entry.getMetadata(); long expire = metadata.lifespan(); final long startTimeInMillis = (Long)scheduleCache.get( cacheKey ).get( SCHEDULE_TIME ); return calculateNextExpireTime( expire, startTimeInMillis ); } return null; } ); } static Date calculateNextExpireTime( final long expire, final long start ) { if ( expire > 1 ) { final long duration = System.currentTimeMillis() - start; if ( duration < expire ) { final long nextTimeInMillis = expire - duration + System.currentTimeMillis(); final LocalDateTime time = Instant.ofEpochMilli( nextTimeInMillis ).atZone( ZoneId.systemDefault() ).toLocalDateTime(); return Date.from( time.atZone( ZoneId.systemDefault() ).toInstant() ); } } return null; } public synchronized ScheduleKey findFirstMatchingTrigger( final CacheKeyMatcher<ScheduleKey> matcher ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return null; } final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); if ( keys != null && !keys.isEmpty() ) { return keys.iterator().next(); } return null; } public static String groupName( final StoreKey key, final String jobType ) { return key.toString() + groupNameSuffix( jobType ); } public static String groupNameSuffix( final String jobType ) { return "#" + jobType; } public static StoreKey storeKeyFrom( final String group ) { final String[] parts = group.split( "#" ); if ( parts.length > 1 ) { final StoreType type = StoreType.get( parts[0] ); if ( type != null ) { return new StoreKey( type, parts[1] ); } } return null; } public synchronized boolean deleteJob( final String group, final String name ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return false; } // We're responding to a cache expiration...the following isn't necessary, because it already expired. // In fact, this leads to circularity if the notification is processed synchronously. // final ScheduleKey cacheKey = ScheduleKey.fromGroupWithName( group, name ); // if ( scheduleCache.containsKey( cacheKey ) ) // { // removeCache( cacheKey ); // return true; // } // // return false; return true; } @Override public String getId() { return "Indy Scheduler"; } @Override public int getBootPriority() { return 80; } @Override public int getShutdownPriority() { return 95; } @Override public void stop() throws IndyLifecycleException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } scheduleCache.stop(); } private synchronized void removeCache( final ScheduleKey cacheKey ) { if ( scheduleCache.containsKey( cacheKey ) ) { scheduleCache.remove( cacheKey ); } } @CacheEntryCreated public void scheduled( final CacheEntryCreatedEvent<ScheduleKey, Map> e ) { if ( e == null ) { throw new IllegalArgumentException( "[FATAL]The infinispan cache created event for indy schedule manager is null." ); } if ( !e.isPre() ) { final ScheduleKey expiredKey = e.getKey(); final Map expiredContent = e.getValue(); if ( expiredKey != null && expiredContent != null ) { logger.debug( "Expiration Created: {}", expiredKey ); final String type = (String) expiredContent.get( ScheduleManager.JOB_TYPE ); final String data = (String) expiredContent.get( ScheduleManager.PAYLOAD ); eventDispatcher.fire( new SchedulerScheduleEvent( type, data ) ); } } } @CacheEntryExpired public void expired( CacheEntryExpiredEvent<ScheduleKey, Map> e ) { if ( e == null ) { throw new IllegalArgumentException( "[FATAL]The infinispan cache expired event for indy schedule manager is null." ); } if ( !e.isPre() ) { final ScheduleKey expiredKey = e.getKey(); final Map expiredContent = e.getValue(); if ( expiredKey != null && expiredContent != null ) { logger.debug( "EXPIRED: {}", expiredKey ); final String type = (String) expiredContent.get( ScheduleManager.JOB_TYPE ); final String data = (String) expiredContent.get( ScheduleManager.PAYLOAD ); eventDispatcher.fire( new SchedulerTriggerEvent( type, data ) ); } } } @CacheEntryRemoved public void cancelled( CacheEntryRemovedEvent<ScheduleKey, Map> e ) { if ( e == null ) { throw new IllegalArgumentException( "[FATAL]The infinispan cache removed event for indy schedule manager is null." ); } logger.info( "Cache removed to cancel scheduling, Key is {}, Value is {}", e.getKey(), e.getValue() ); } }
core/src/main/java/org/commonjava/indy/core/expire/ScheduleManager.java
/** * Copyright (C) 2011-2017 Red Hat, Inc. (https://github.com/Commonjava/indy) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.commonjava.indy.core.expire; import com.fasterxml.jackson.core.JsonProcessingException; import org.commonjava.indy.action.BootupAction; import org.commonjava.indy.action.IndyLifecycleException; import org.commonjava.indy.action.ShutdownAction; import org.commonjava.indy.conf.IndyConfiguration; import org.commonjava.indy.core.conf.IndySchedulerConfig; import org.commonjava.indy.core.expire.cache.ScheduleCache; import org.commonjava.indy.data.IndyDataException; import org.commonjava.indy.data.StoreDataManager; import org.commonjava.indy.model.core.ArtifactStore; import org.commonjava.indy.model.core.Group; import org.commonjava.indy.model.core.HostedRepository; import org.commonjava.indy.model.core.RemoteRepository; import org.commonjava.indy.model.core.StoreKey; import org.commonjava.indy.model.core.StoreType; import org.commonjava.indy.model.core.io.IndyObjectMapper; import org.commonjava.indy.spi.pkg.ContentAdvisor; import org.commonjava.indy.spi.pkg.ContentQuality; import org.commonjava.indy.subsys.infinispan.CacheHandle; import org.commonjava.indy.subsys.infinispan.CacheKeyMatcher; import org.commonjava.indy.util.LocationUtils; import org.commonjava.maven.galley.model.ConcreteResource; import org.commonjava.maven.galley.model.SpecialPathInfo; import org.commonjava.maven.galley.spi.io.SpecialPathManager; import org.infinispan.container.entries.CacheEntry; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Event; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport; import static org.commonjava.indy.core.change.StoreEnablementManager.DISABLE_TIMEOUT; import static org.commonjava.indy.core.change.StoreEnablementManager.TIMEOUT_USE_DEFAULT; /** * A ScheduleManager is used to do the schedule time out jobs for the {@link ArtifactStore} to do some time-related jobs, like * removing useless artifacts. It used ISPN cache timeout mechanism to implement this type of function. * This class is also acted as a cache listener to handle the cache expiration job event to distribute the expiration * info through CDI event for the real actor to do the expiration work. */ @ApplicationScoped @Listener public class ScheduleManager implements BootupAction, ShutdownAction { private final Logger logger = LoggerFactory.getLogger( getClass() ); public static final String PAYLOAD = "payload"; public static final String ANY = "__ANY__"; public static final String CONTENT_JOB_TYPE = "CONTENT"; public static final String JOB_TYPE = "JOB_TYPE"; public static final String SCHEDULE_TIME = "SCHEDULE_TIME"; @Inject private StoreDataManager dataManager; @Inject private IndyConfiguration config; @Inject private IndyObjectMapper objectMapper; @Inject private IndySchedulerConfig schedulerConfig; @Inject private SpecialPathManager specialPathManager; @Inject @ScheduleCache private CacheHandle<ScheduleKey, Map> scheduleCache; @Inject @Any private Instance<ContentAdvisor> contentAdvisor; @Inject private Event<SchedulerEvent> eventDispatcher; @Override public void init() throws IndyLifecycleException { if ( !schedulerConfig.isEnabled() ) { logger.info( "Scheduler disabled. Skipping initialization" ); return; } // register this producer as schedule cache listener scheduleCache.execute( cache -> { cache.addListener( ScheduleManager.this ); return null; } ); } public synchronized void rescheduleSnapshotTimeouts( final HostedRepository deploy ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } int timeout = -1; if ( deploy.isAllowSnapshots() && deploy.getSnapshotTimeoutSeconds() > 0 ) { timeout = deploy.getSnapshotTimeoutSeconds(); } if ( timeout > 0 ) { final Set<ScheduleKey> canceled = cancelAllBefore( new StoreKeyMatcher( deploy.getKey(), CONTENT_JOB_TYPE ), timeout ); for ( final ScheduleKey key : canceled ) { final String path = key.getName(); final StoreKey sk = storeKeyFrom( key.groupName() ); scheduleContentExpiration( sk, path, timeout ); } } } public synchronized void rescheduleProxyTimeouts( final RemoteRepository repo ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } int timeout = -1; if ( !repo.isPassthrough() && repo.getCacheTimeoutSeconds() > 0 ) { timeout = repo.getCacheTimeoutSeconds(); } else if ( repo.isPassthrough() ) { timeout = config.getPassthroughTimeoutSeconds(); } if ( timeout > 0 ) { final Set<ScheduleKey> canceled = cancelAllBefore( new StoreKeyMatcher( repo.getKey(), CONTENT_JOB_TYPE ), timeout ); for ( final ScheduleKey key : canceled ) { final String path = key.getName(); final StoreKey sk = storeKeyFrom( key.groupName() ); scheduleContentExpiration( sk, path, timeout ); } } } public synchronized void setProxyTimeouts( final StoreKey key, final String path ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } RemoteRepository repo = null; try { repo = (RemoteRepository) dataManager.getArtifactStore( key ); } catch ( final IndyDataException e ) { logger.error( String.format( "Failed to retrieve store for: %s. Reason: %s", key, e.getMessage() ), e ); } if ( repo == null ) { return; } int timeout = config.getPassthroughTimeoutSeconds(); final ConcreteResource resource = new ConcreteResource( LocationUtils.toLocation( repo ), path ); final SpecialPathInfo info = specialPathManager.getSpecialPathInfo( resource ); if ( !repo.isPassthrough() ) { if ( ( info != null && info.isMetadata() ) && repo.getMetadataTimeoutSeconds() > 0 ) { logger.debug( "Using metadata timeout for: {}", resource ); timeout = repo.getMetadataTimeoutSeconds(); } else { if ( info == null ) { logger.debug( "No special path info for: {}", resource ); } else { logger.debug( "{} is a special path, but not metadata.", resource ); } timeout = repo.getCacheTimeoutSeconds(); } } if ( timeout > 0 ) { // logger.info( "[PROXY TIMEOUT SET] {}/{}; {}", repo.getKey(), path, new Date( System.currentTimeMillis() // + timeout ) ); cancel( new StoreKeyMatcher( key, CONTENT_JOB_TYPE ), path ); scheduleContentExpiration( key, path, timeout ); } } public synchronized void scheduleForStore( final StoreKey key, final String jobType, final String jobName, final Object payload, final int startSeconds ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } final Map<String, Object> dataMap = new HashMap<>( 3 ); dataMap.put( JOB_TYPE, jobType ); try { dataMap.put( PAYLOAD, objectMapper.writeValueAsString( payload ) ); } catch ( final JsonProcessingException e ) { throw new IndySchedulerException( "Failed to serialize JSON payload: " + payload, e ); } dataMap.put( SCHEDULE_TIME, System.currentTimeMillis() ); final ScheduleKey cacheKey = new ScheduleKey( key, jobType, jobName ); scheduleCache.execute( cache -> cache.put( cacheKey, dataMap, startSeconds, TimeUnit.SECONDS ) ); logger.debug( "Scheduled for the key {} with timeout: {} seconds", cacheKey, startSeconds ); } public synchronized void scheduleContentExpiration( final StoreKey key, final String path, final int timeoutSeconds ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } logger.info( "Scheduling timeout for: {} in: {} in: {} seconds (at: {}).", path, key, timeoutSeconds, new Date( System.currentTimeMillis() + ( timeoutSeconds * 1000 ) ) ); scheduleForStore( key, CONTENT_JOB_TYPE, path, new ContentExpiration( key, path ), timeoutSeconds ); } public synchronized void setSnapshotTimeouts( final StoreKey key, final String path ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } HostedRepository deploy = null; try { final ArtifactStore store = dataManager.getArtifactStore( key ); if ( store == null ) { return; } if ( store instanceof HostedRepository ) { deploy = (HostedRepository) store; } else if ( store instanceof Group ) { final Group group = (Group) store; deploy = findDeployPoint( group ); } } catch ( final IndyDataException e ) { logger.error( String.format( "Failed to retrieve deploy point for: %s. Reason: %s", key, e.getMessage() ), e ); } if ( deploy == null ) { return; } final ContentAdvisor advisor = StreamSupport.stream( Spliterators.spliteratorUnknownSize( contentAdvisor.iterator(), Spliterator.ORDERED ), false ) .filter( Objects::nonNull ) .findFirst() .orElse( null ); final ContentQuality quality = advisor == null ? null : advisor.getContentQuality( path ); if ( quality == null ) { return; } if ( ContentQuality.SNAPSHOT == quality && deploy.getSnapshotTimeoutSeconds() > 0 ) { final int timeout = deploy.getSnapshotTimeoutSeconds(); // // logger.info( "[SNAPSHOT TIMEOUT SET] {}/{}; {}", deploy.getKey(), path, new Date( timeout ) ); // cancel( new StoreKeyMatcher( key, CONTENT_JOB_TYPE ), path ); scheduleContentExpiration( key, path, timeout ); } } public synchronized void rescheduleDisableTimeout( final StoreKey key ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } ArtifactStore store = null; try { store = dataManager.getArtifactStore( key ); } catch ( final IndyDataException e ) { logger.error( String.format( "Failed to retrieve store for: %s. Reason: %s", key, e.getMessage() ), e ); } if ( store == null ) { return; } int timeout = store.getDisableTimeout(); if ( timeout == TIMEOUT_USE_DEFAULT ) { // case TIMEOUT_USE_DEFAULT: will use default timeout configuration timeout = config.getStoreDisableTimeoutSeconds(); } // No need to cancel as the job will be cancelled immediately after the re-enable in StoreEnablementManager // final Set<ScheduleKey> canceled = // cancelAllBefore( new StoreKeyMatcher( store.getKey(), DISABLE_TIMEOUT ), // timeout ); // logger.info( "Cancel disable timeout for stores:{}", canceled ); if ( timeout > TIMEOUT_USE_DEFAULT && store.isDisabled() ) { final StoreKey sk = store.getKey(); logger.debug( "Set/Reschedule disable timeout for store:{}", sk ); scheduleForStore( sk, DISABLE_TIMEOUT, DISABLE_TIMEOUT, sk, timeout ); } // Will never consider the TIMEOUT_NEVER_DISABLE case here, will consider this in the calling object(StoreEnablementManager) } private HostedRepository findDeployPoint( final Group group ) throws IndyDataException { for ( final StoreKey key : group.getConstituents() ) { if ( StoreType.hosted == key.getType() ) { return (HostedRepository) dataManager.getArtifactStore( key ); } else if ( StoreType.group == key.getType() ) { final Group grp = (Group) dataManager.getArtifactStore( key ); final HostedRepository dp = findDeployPoint( grp ); if ( dp != null ) { return dp; } } } return null; } public synchronized Set<ScheduleKey> cancelAllBefore( final CacheKeyMatcher<ScheduleKey> matcher, final long timeout ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return Collections.emptySet(); } final Set<ScheduleKey> canceled = new HashSet<>(); final Date to = new Date( System.currentTimeMillis() + ( timeout * 1000 ) ); matcher.matches( scheduleCache ).forEach( key -> { final Date nextFire = getNextExpireTime( key ); if ( nextFire == null || !nextFire.after( to ) ) { // former impl uses quartz and here use the unscheduleJob method, but ISPN does not have similar // op, so directly did a remove here. removeCache( key ); logger.debug( "Removed cache job for key: {}, before {}", key, to ); canceled.add( key ); } } ); return canceled; } public synchronized Set<ScheduleKey> cancelAll( final CacheKeyMatcher<ScheduleKey> matcher ) throws IndySchedulerException { return cancel( matcher, ANY ); } public synchronized Set<ScheduleKey> cancel( final CacheKeyMatcher<ScheduleKey> matcher, final String name ) throws IndySchedulerException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return Collections.emptySet(); } Set<ScheduleKey> canceled = new HashSet<>(); final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); if ( keys != null && !keys.isEmpty() ) { Set<ScheduleKey> unscheduled = null; if ( name == ANY ) { for ( final ScheduleKey k : keys ) { removeCache( k ); } unscheduled = keys; } else { for ( final ScheduleKey k : keys ) { if ( k.getName().equals( name ) ) { removeCache( k ); unscheduled = Collections.singleton( k ); break; } } } if ( unscheduled != null ) { canceled = unscheduled; } } return canceled; } public synchronized Expiration findSingleExpiration( final StoreKeyMatcher matcher ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return null; } final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); if ( keys != null && !keys.isEmpty() ) { ScheduleKey triggerKey = keys.iterator().next(); return toExpiration( triggerKey ); } return null; } public synchronized ExpirationSet findMatchingExpirations( final CacheKeyMatcher<ScheduleKey> matcher ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return null; } final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); Set<Expiration> expirations = new HashSet<>( keys.size() ); if ( keys != null && !keys.isEmpty() ) { for ( ScheduleKey key : keys ) { expirations.add( toExpiration( key ) ); } } return new ExpirationSet( expirations ); } private Expiration toExpiration( final ScheduleKey cacheKey ) { return new Expiration( cacheKey.groupName(), cacheKey.getName(), getNextExpireTime( cacheKey ) ); } private Date getNextExpireTime( final ScheduleKey cacheKey ) { return scheduleCache.execute( cache -> { final CacheEntry entry = cache.getAdvancedCache().getCacheEntry( cacheKey ); if ( entry != null ) { final Metadata metadata = entry.getMetadata(); long expire = metadata.lifespan(); final long startTimeInMillis = (Long)scheduleCache.get( cacheKey ).get( SCHEDULE_TIME ); return calculateNextExpireTime( expire, startTimeInMillis ); } return null; } ); } static Date calculateNextExpireTime( final long expire, final long start ) { if ( expire > 1 ) { final long duration = System.currentTimeMillis() - start; if ( duration < expire ) { final long nextTimeInMillis = expire - duration + System.currentTimeMillis(); final LocalDateTime time = Instant.ofEpochMilli( nextTimeInMillis ).atZone( ZoneId.systemDefault() ).toLocalDateTime(); return Date.from( time.atZone( ZoneId.systemDefault() ).toInstant() ); } } return null; } public synchronized ScheduleKey findFirstMatchingTrigger( final CacheKeyMatcher<ScheduleKey> matcher ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return null; } final Set<ScheduleKey> keys = matcher.matches( scheduleCache ); if ( keys != null && !keys.isEmpty() ) { return keys.iterator().next(); } return null; } public static String groupName( final StoreKey key, final String jobType ) { return key.toString() + groupNameSuffix( jobType ); } public static String groupNameSuffix( final String jobType ) { return "#" + jobType; } public static StoreKey storeKeyFrom( final String group ) { final String[] parts = group.split( "#" ); if ( parts.length > 1 ) { final StoreType type = StoreType.get( parts[0] ); if ( type != null ) { return new StoreKey( type, parts[1] ); } } return null; } public synchronized boolean deleteJob( final String group, final String name ) { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return false; } // We're responding to a cache expiration...the following isn't necessary, because it already expired. // In fact, this leads to circularity if the notification is processed synchronously. // final ScheduleKey cacheKey = ScheduleKey.fromGroupWithName( group, name ); // if ( scheduleCache.containsKey( cacheKey ) ) // { // removeCache( cacheKey ); // return true; // } // // return false; return true; } @Override public String getId() { return "Indy Scheduler"; } @Override public int getBootPriority() { return 80; } @Override public int getShutdownPriority() { return 95; } @Override public void stop() throws IndyLifecycleException { if ( !schedulerConfig.isEnabled() ) { logger.debug( "Scheduler disabled." ); return; } scheduleCache.stop(); } private synchronized void removeCache( final ScheduleKey cacheKey ) { if ( scheduleCache.containsKey( cacheKey ) ) { scheduleCache.remove( cacheKey ); } } @CacheEntryCreated public void scheduled( final CacheEntryCreatedEvent<ScheduleKey, Map> e ) { final ScheduleKey expiredKey = e.getKey(); final Map expiredContent = e.getValue(); if ( expiredKey != null && expiredContent != null ) { logger.debug( "Expiration Created: {}", expiredKey ); final String type = (String) expiredContent.get( ScheduleManager.JOB_TYPE ); final String data = (String) expiredContent.get( ScheduleManager.PAYLOAD ); eventDispatcher.fire( new SchedulerScheduleEvent( type, data ) ); } } @CacheEntryExpired public void expired( CacheEntryExpiredEvent<ScheduleKey, Map> e ) { final ScheduleKey expiredKey = e.getKey(); final Map expiredContent = e.getValue(); if ( expiredKey != null && expiredContent != null ) { logger.debug( "EXPIRED: {}", expiredKey ); final String type = (String) expiredContent.get( ScheduleManager.JOB_TYPE ); final String data = (String) expiredContent.get( ScheduleManager.PAYLOAD ); eventDispatcher.fire( new SchedulerTriggerEvent( type, data ) ); } } @CacheEntryRemoved public void cancelled( CacheEntryRemovedEvent<ScheduleKey, Map> e ) { logger.info( "Cache removed to cancel scheduling, Key is {}, Value is {}", e.getKey(), e.getValue() ); } }
Add some potential NPE checking in ScheduleManager PNC devel env found that there were NPE happening in ScheduleManager.expired of the infinispan cache timeout working, so added some code to check potential NPE and rethrow IllegalArgumentException to make sure the NPE location. And also added the event.isPre to make sure the event instance is passed in after the real event happening
core/src/main/java/org/commonjava/indy/core/expire/ScheduleManager.java
Add some potential NPE checking in ScheduleManager
Java
apache-2.0
b90b8cf32d4a36543b0de7185d08ffe20f51cdba
0
nicolargo/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,caot/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,adedayo/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ibinti/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,da1z/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,holmes/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,semonte/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,blademainer/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,da1z/intellij-community,FHannes/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,adedayo/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,blademainer/intellij-community,hurricup/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,kdwink/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,asedunov/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,fitermay/intellij-community,robovm/robovm-studio,jagguli/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,xfournet/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,blademainer/intellij-community,ryano144/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,petteyg/intellij-community,supersven/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,caot/intellij-community,diorcety/intellij-community,fnouama/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,signed/intellij-community,orekyuu/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,petteyg/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,holmes/intellij-community,vladmm/intellij-community,fnouama/intellij-community,fitermay/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,amith01994/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,samthor/intellij-community,xfournet/intellij-community,diorcety/intellij-community,semonte/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,holmes/intellij-community,caot/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,clumsy/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,allotria/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,fnouama/intellij-community,diorcety/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,semonte/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,signed/intellij-community,amith01994/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,signed/intellij-community,dslomov/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,apixandru/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,signed/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,amith01994/intellij-community,hurricup/intellij-community,samthor/intellij-community,izonder/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,caot/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,da1z/intellij-community,holmes/intellij-community,orekyuu/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,signed/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,izonder/intellij-community,robovm/robovm-studio,samthor/intellij-community,fnouama/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,ryano144/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,hurricup/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,hurricup/intellij-community,signed/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,semonte/intellij-community,supersven/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,semonte/intellij-community,Lekanich/intellij-community,semonte/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,semonte/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,izonder/intellij-community,amith01994/intellij-community,fitermay/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,slisson/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,allotria/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,kool79/intellij-community,allotria/intellij-community,fitermay/intellij-community,signed/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,izonder/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,jagguli/intellij-community,allotria/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,izonder/intellij-community,suncycheng/intellij-community,supersven/intellij-community,asedunov/intellij-community,vladmm/intellij-community,caot/intellij-community,gnuhub/intellij-community,caot/intellij-community,clumsy/intellij-community,apixandru/intellij-community,izonder/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,slisson/intellij-community,ibinti/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,asedunov/intellij-community,allotria/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ibinti/intellij-community,kdwink/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,ibinti/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,blademainer/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,petteyg/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,fnouama/intellij-community,slisson/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,holmes/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,amith01994/intellij-community,petteyg/intellij-community,kool79/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,ryano144/intellij-community,FHannes/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,supersven/intellij-community,supersven/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,retomerz/intellij-community,allotria/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,jagguli/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,hurricup/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,holmes/intellij-community,supersven/intellij-community,jagguli/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ryano144/intellij-community,apixandru/intellij-community,caot/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,caot/intellij-community,kool79/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,supersven/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,blademainer/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,vladmm/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,diorcety/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,ibinti/intellij-community,semonte/intellij-community,ryano144/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,holmes/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,clumsy/intellij-community,izonder/intellij-community,apixandru/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,caot/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,clumsy/intellij-community,hurricup/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,caot/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,nicolargo/intellij-community,slisson/intellij-community,izonder/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,slisson/intellij-community,youdonghai/intellij-community,holmes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,caot/intellij-community,SerCeMan/intellij-community,signed/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community
/* * User: anna * Date: 11-Mar-2008 */ package com.jetbrains.python.validation; import com.intellij.codeInsight.daemon.ReferenceImporter; import com.intellij.codeInsight.daemon.impl.CollectHighlightsUtil; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.jetbrains.python.psi.PyReferenceExpression; import com.jetbrains.python.psi.PyFile; import com.jetbrains.python.actions.AddImportAction; import org.jetbrains.annotations.NotNull; import java.util.List; public class PythonReferenceImporter implements ReferenceImporter { public boolean autoImportReferenceAtCursor(@NotNull final Editor editor, @NotNull final PsiFile file) { if (!(file instanceof PyFile)) return false; int caretOffset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); int lineNumber = document.getLineNumber(caretOffset); int startOffset = document.getLineStartOffset(lineNumber); int endOffset = document.getLineEndOffset(lineNumber); List<PsiElement> elements = CollectHighlightsUtil.getElementsInRange(file, startOffset, endOffset); for (PsiElement element : elements) { if (element instanceof PyReferenceExpression) { if (((PyReferenceExpression)element).resolve() == null) { new AddImportAction((PsiReference)element).execute(); return true; } } } return false; } }
python/src/com/jetbrains/python/validation/PythonReferenceImporter.java
/* * User: anna * Date: 11-Mar-2008 */ package com.jetbrains.python.validation; import com.intellij.codeInsight.daemon.ReferenceImporter; import com.intellij.codeInsight.daemon.impl.CollectHighlightsUtil; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.jetbrains.python.psi.PyReferenceExpression; import com.jetbrains.python.actions.AddImportAction; import org.jetbrains.annotations.NotNull; import java.util.List; public class PythonReferenceImporter implements ReferenceImporter { public PythonReferenceImporter() { // nothing } public boolean autoImportReferenceAtCursor(@NotNull final Editor editor, @NotNull final PsiFile file) { int caretOffset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); int lineNumber = document.getLineNumber(caretOffset); int startOffset = document.getLineStartOffset(lineNumber); int endOffset = document.getLineEndOffset(lineNumber); List<PsiElement> elements = CollectHighlightsUtil.getElementsInRange(file, startOffset, endOffset); for (PsiElement element : elements) { if (element instanceof PyReferenceExpression) { if (((PyReferenceExpression)element).resolve() == null) { new AddImportAction((PsiReference)element).execute(); return true; } } } return false; } }
performance
python/src/com/jetbrains/python/validation/PythonReferenceImporter.java
performance
Java
apache-2.0
4f58e437327e0c21aeb569d6b06e342ca71c350e
0
ganshane/lichen,ganshane/lichen,ganshane/lichen
// Copyright 2013 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * This software is distributed under the terms of the FSF * Gnu Lesser General Public License (see lgpl.txt). * * This program is distributed WITHOUT ANY WARRANTY. See the * GNU General Public License for more details. */ package lichen.core.services; import java.util.*; /** * 针对英文单词的复数转换. * 此文件来自 http://www.scooterframework.com. * <p/> * <p>Conversion between singular and plural form of a noun word.</p> * * @author (Fei) John Chen */ public final class WordUtil { public static final Map<String, String> SINGLE_2PLURALS = new HashMap<String, String>(); public static final List<String> PLURALS = new ArrayList<String>(); public static final Map<String, String> PLURAL_2SINGLES = new HashMap<String, String>(); public static final List<String> SINGLES = new ArrayList<String>(); static { //Irregular plurals: SINGLE_2PLURALS.put("child", "children"); SINGLE_2PLURALS.put("corpus", "corpora"); SINGLE_2PLURALS.put("foot", "feet"); SINGLE_2PLURALS.put("goose", "geese"); SINGLE_2PLURALS.put("louse", "lice"); SINGLE_2PLURALS.put("man", "men"); SINGLE_2PLURALS.put("mouse", "mice"); SINGLE_2PLURALS.put("ox", "oxen"); SINGLE_2PLURALS.put("person", "people"); SINGLE_2PLURALS.put("tooth", "teeth"); SINGLE_2PLURALS.put("woman", "women"); //Some nouns do not change at all: SINGLE_2PLURALS.put("cod", "cod"); SINGLE_2PLURALS.put("deer", "deer"); SINGLE_2PLURALS.put("fish", "fish"); SINGLE_2PLURALS.put("offspring", "offspring"); SINGLE_2PLURALS.put("perch", "perch"); SINGLE_2PLURALS.put("sheep", "sheep"); SINGLE_2PLURALS.put("trout", "trout"); SINGLE_2PLURALS.put("species", "species"); SINGLE_2PLURALS.put("series", "series"); //Other nouns that do not change: SINGLE_2PLURALS.put("data", "data"); SINGLE_2PLURALS.put("dice", "dice"); SINGLE_2PLURALS.put("media", "media"); //Singular ends in -us, plural ends in // -i: alumnus/alumni, focus/foci, nucleus/nuclei, //octopus/octopi, radius/radii, stimulus/stimuli, virus/viri //Exceptions to the above SINGLE_2PLURALS.put("bus", "buses"); //Singular ends in -ex, // plural ends in -ices: appendix/appendices, index/indices SINGLE_2PLURALS.put("index", "indices"); SINGLE_2PLURALS.put("vertex", "vertices"); //These include nouns that are traditionally plural, // but are also used for singular forms: SINGLE_2PLURALS.put("barracks", "barracks"); SINGLE_2PLURALS.put("crossroads", "crossroads"); SINGLE_2PLURALS.put("die", "dice"); SINGLE_2PLURALS.put("gallows", "gallows"); SINGLE_2PLURALS.put("headquarters", "headquarters"); SINGLE_2PLURALS.put("means", "means"); SINGLE_2PLURALS.put("series", "series"); SINGLE_2PLURALS.put("species", "species"); //Exception to Rule 6: Some nouns ending in f or fe are made plural //by changing f or fe to ves. with the following exceptions: SINGLE_2PLURALS.put("chief", "chiefs"); SINGLE_2PLURALS.put("chef", "chefs"); SINGLE_2PLURALS.put("dwarf", "dwarfs"); SINGLE_2PLURALS.put("hoof", "hoofs"); SINGLE_2PLURALS.put("kerchief", "kerchiefs"); SINGLE_2PLURALS.put("fife", "fifes"); SINGLE_2PLURALS.put("proof", "proofs"); //m-w.com SINGLE_2PLURALS.put("roof", "roofs"); SINGLE_2PLURALS.put("safe", "safes"); SINGLE_2PLURALS.put("mischief", "mischiefs"); SINGLE_2PLURALS.put("grief", "griefs"); //Rule 7b: All musical terms // ending in -o have plurals ending in just -s. SINGLE_2PLURALS.put("cello", "cellos"); SINGLE_2PLURALS.put("photo", "photos"); SINGLE_2PLURALS.put("solo", "solos"); SINGLE_2PLURALS.put("soprano", "sopranos"); SINGLE_2PLURALS.put("studio", "studios"); //Exception to Rule 7: Most nouns ending in o preceded by a consonant //is formed into a plural by adding es with the following exceptions: SINGLE_2PLURALS.put("canto", "cantos"); SINGLE_2PLURALS.put("lasso", "lassos"); SINGLE_2PLURALS.put("halo", "halos"); SINGLE_2PLURALS.put("memento", "mementos"); SINGLE_2PLURALS.put("photo", "photos"); SINGLE_2PLURALS.put("sirocco", "siroccos"); //Rule 7c: Plural forms of words ending in -o (-os): SINGLE_2PLURALS.put("albino", "albinos"); SINGLE_2PLURALS.put("armadillo", "armadillos"); SINGLE_2PLURALS.put("auto", "autos"); SINGLE_2PLURALS.put("bravo", "bravos"); SINGLE_2PLURALS.put("bronco", "broncos"); SINGLE_2PLURALS.put("canto", "cantos"); SINGLE_2PLURALS.put("casino", "casinos"); SINGLE_2PLURALS.put("combo", "combos"); SINGLE_2PLURALS.put("gazebo", "gazebos"); SINGLE_2PLURALS.put("inferno", "infernos"); SINGLE_2PLURALS.put("kangaroo", "kangaroos"); SINGLE_2PLURALS.put("kilo", "kilos"); SINGLE_2PLURALS.put("kimono", "kimonos"); SINGLE_2PLURALS.put("logo", "logos"); SINGLE_2PLURALS.put("maraschino", "maraschinos"); SINGLE_2PLURALS.put("memo", "memos"); SINGLE_2PLURALS.put("photo", "photos"); SINGLE_2PLURALS.put("pimento", "pimentos"); SINGLE_2PLURALS.put("poncho", "ponchos"); SINGLE_2PLURALS.put("pro", "pros"); SINGLE_2PLURALS.put("sombrero", "sombreros"); SINGLE_2PLURALS.put("taco", "tacos"); SINGLE_2PLURALS.put("tattoo", "tattoos"); SINGLE_2PLURALS.put("torso", "torsos"); SINGLE_2PLURALS.put("tobacco", "tobaccos"); SINGLE_2PLURALS.put("typo", "typos"); //Rule 7c: Plural forms of words ending in -o (-oes): SINGLE_2PLURALS.put("echo", "echoes"); SINGLE_2PLURALS.put("embargo", "embargoes"); SINGLE_2PLURALS.put("hero", "heroes"); SINGLE_2PLURALS.put("potato", "potatoes"); SINGLE_2PLURALS.put("tomato", "tomatoes"); SINGLE_2PLURALS.put("torpedo", "torpedoes"); SINGLE_2PLURALS.put("veto", "vetoes"); //Rule 7c: Plural forms of words ending in -o (-os or -oes): SINGLE_2PLURALS.put("avocado", "avocados"); SINGLE_2PLURALS.put("buffalo", "buffaloes"); SINGLE_2PLURALS.put("cargo", "cargoes"); SINGLE_2PLURALS.put("desperado", "desperadoes"); SINGLE_2PLURALS.put("dodo", "dodoes"); SINGLE_2PLURALS.put("domino", "dominoes"); SINGLE_2PLURALS.put("ghetto", "ghettos"); SINGLE_2PLURALS.put("grotto", "grottoes"); SINGLE_2PLURALS.put("hobo", "hoboes"); SINGLE_2PLURALS.put("innuendo", "innuendoes"); SINGLE_2PLURALS.put("lasso", "lassos"); SINGLE_2PLURALS.put("mango", "mangoes"); SINGLE_2PLURALS.put("mosquito", "mosquitoes"); SINGLE_2PLURALS.put("motto", "mottoes"); SINGLE_2PLURALS.put("mulatto", "mulattos"); SINGLE_2PLURALS.put("no", "noes"); SINGLE_2PLURALS.put("peccadillo", "peccadilloes"); SINGLE_2PLURALS.put("tornado", "tornadoes"); SINGLE_2PLURALS.put("volcano", "volcanoes"); SINGLE_2PLURALS.put("zero", "zeros"); //others SINGLE_2PLURALS.put("forum", "forums"); //Things that come in pairs PLURALS.add("binoculars"); PLURALS.add("forceps"); PLURALS.add("jeans"); PLURALS.add("glasses"); PLURALS.add("pajamas"); PLURALS.add("pants"); PLURALS.add("scissors"); PLURALS.add("shorts"); PLURALS.add("tongs"); PLURALS.add("trousers"); PLURALS.add("tweezers"); //Nouns that end in -s but have no singular (aggregate nouns) PLURALS.add("accommodations"); PLURALS.add("amends"); PLURALS.add("archives"); PLURALS.add("arms"); PLURALS.add("bellows"); PLURALS.add("bowels"); PLURALS.add("brains"); PLURALS.add("clothes"); PLURALS.add("communications"); PLURALS.add("congratulations"); PLURALS.add("contents"); PLURALS.add("dregs"); PLURALS.add("goods"); PLURALS.add("measles"); PLURALS.add("mumps"); PLURALS.add("oats"); PLURALS.add("pinchers"); PLURALS.add("shears"); PLURALS.add("snuffers"); PLURALS.add("stairs"); PLURALS.add("thanks"); PLURALS.add("vespers"); PLURALS.add("victuals"); //Nouns that are plural but do not end in -s PLURALS.add("children"); PLURALS.add("cattle"); PLURALS.add("corpora"); PLURALS.add("data"); PLURALS.add("men"); PLURALS.add("people"); PLURALS.add("police"); PLURALS.add("women"); //Nouns that are always singular -- uncountable SINGLES.add("cooper"); SINGLES.add("corn"); SINGLES.add("cotton"); SINGLES.add("gold"); SINGLES.add("information"); SINGLES.add("money"); SINGLES.add("news"); SINGLES.add("rice"); SINGLES.add("silver"); SINGLES.add("sugar"); SINGLES.add("wheat"); //PLURAL_2SINGLES.put("data", "data"); //PLURAL_2SINGLES.put("media", "media"); PLURAL_2SINGLES.put("dice", "dice"); PLURAL_2SINGLES.put("indices", "index"); PLURAL_2SINGLES.put("vertices", "vertex"); PLURAL_2SINGLES.put("movies", "movie"); PLURAL_2SINGLES.put("viri", "virus"); PLURAL_2SINGLES.put("axes", "axis"); PLURAL_2SINGLES.put("crises", "crisis"); PLURAL_2SINGLES.put("analyses", "analysis"); PLURAL_2SINGLES.put("diagnoses", "diagnosis"); PLURAL_2SINGLES.put("synopses", "synopsis"); PLURAL_2SINGLES.put("theses", "thesis"); PLURAL_2SINGLES.put("moves", "move"); PLURAL_2SINGLES.put("caves", "cave"); PLURAL_2SINGLES.put("toes", "toe"); //merge PLURAL_2SINGLES with SINGLE_2PLURALS for (Map.Entry<String, String> entry : SINGLE_2PLURALS.entrySet()) { String sk = entry.getKey(); String sv = entry.getValue(); String pv = PLURAL_2SINGLES.get(sv); if (pv == null) { PLURAL_2SINGLES.put(sv, sk); } } //merge SINGLE_2PLURALS with PLURAL_2SINGLES for (Map.Entry<String, String> entry : PLURAL_2SINGLES.entrySet()) { String pk = entry.getKey(); String pv = entry.getValue(); String sv = SINGLE_2PLURALS.get(pv); if (sv == null) { SINGLE_2PLURALS.put(pv, pk); } } } //单数到复数的映射 private static final Map<String, String> RESOLVED_SINGLE_2_PLURALS = new HashMap<String, String>(); //已经处理过的复数 private static final List<String> RESOLVED_PLURALS = new ArrayList<String>(); //复数到单数的映射 private static final Map<String, String> RESOLVED_PLURAL_2_SINGLES = new HashMap<String, String>(); private static final List<String> RESOLVED_SINGLES = new ArrayList<String>(); private static String A2Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static String a2z = "abcdefghijklmnopqrstuvwxyz"; /** * 把给定的单词转换为复数. * * @param word 待转换的单词 * @return 复数字符串 */ public static String pluralize(String word) { if (word == null || "".equals(word)) { return word; } //先判断是否处理过了 String plform = RESOLVED_SINGLE_2_PLURALS.get(word); if (plform == null && (RESOLVED_PLURALS.contains(word) || RESOLVED_PLURAL_2_SINGLES.containsKey(word))) { plform = word; } if (plform != null) return plform; String tmp = word.toLowerCase(); plform = SINGLE_2PLURALS.get(tmp); if (plform == null && (PLURALS.contains(tmp) || SINGLES.contains(tmp) || PLURAL_2SINGLES.containsKey(tmp))) { plform = tmp; } if (plform != null) { //映射里面已经得到 ; } else if (tmp.endsWith("is")) { //Rule #5: For words that end in -is, change the -is to -es to make the plural form plform = replaceLast(tmp, "is", "es"); } else if (tmp.endsWith("ix")) { //Singular ends in -ix, plural ends in -ices: appendix/appendices, index/indices plform = replaceLast(tmp, "ix", "ices"); } else if (tmp.endsWith("us")) { //Singular ends in -us, plural ends in -i: alumnus/alumni, focus/foci, nucleus/nuclei, //octopus/octopi, radius/radii, stimulus/stimuli, virus/viri plform = replaceLast(tmp, "us", "i"); } else if (!tmp.endsWith("es") && (tmp.endsWith("z") || tmp.endsWith("x") || tmp.endsWith("ch") || tmp.endsWith("sh"))) { //Rule #2: For words that end in a "hissing" sound (-s, -z, -x, -ch, -sh), add an -es to form the plural. //Note: I removed tmp.endsWith("s") || as this cause "posts"->"postses". plform = tmp + "es"; } else if (tmp.endsWith("y")) { //Rule #3: If the word ends in a vowel plus -y (-ay, -ey, -iy, -oy, -uy), add an -s to the word. if (tmp.endsWith("ay") || tmp.endsWith("ey") || tmp.endsWith("iy") || tmp.endsWith("oy") || tmp.endsWith("uy")) { plform = word + "s"; } else { //Rule #4: If the word ends in a consonant plus -y, change the -y into -ie and add an -s to form the plural. plform = replaceLast(tmp, "y", "ies"); } } //Rule #6: Some words that end in -f or -fe have plurals that end in -ves. else if (tmp.endsWith("f")) { plform = replaceLast(tmp, "f", "ves"); } else if (tmp.endsWith("fe")) { plform = replaceLast(tmp, "fe", "ves"); } //Rule #7: The plurals of words ending in -o are formed by either adding -s or by adding -es else if (tmp.endsWith("o")) { //All words that end in a vowel plus -o (-ao, -eo, -io, -oo, -uo) // have plurals that end in just -s: if (tmp.endsWith("ao") || tmp.endsWith("eo") || tmp.endsWith("io") || tmp.endsWith("oo") || tmp.endsWith("uo")) { plform = word + "s"; } else { //All musical terms ending in -o have plurals ending in just -s. //Most others by adding -es with exceptions plform = word + "es"; } } else if (tmp.endsWith("um")) { //Singular ends in -um, plural ends in -a: datum/data, curriculum/curricula plform = replaceLast(tmp, "um", "a"); } else if (tmp.endsWith("on") && !tmp.endsWith("ation")) { //Singular ends in -on, plural ends in -a: criterion/criteria, phenomenon/phenomena plform = replaceLast(tmp, "on", "a"); } else if (tmp.endsWith("a")) { //Singular ends in -a, plural ends in -ae: alumna/alumnae, formula/formulae, antenna/antennae plform = replaceLast(tmp, "a", "ae"); } else if (tmp.endsWith("eau")) { //Singular ends in -eau, plural ends in -eaux: bureau/bureaux, beau/beaux plform = replaceLast(tmp, "eau", "eaux"); } else if (tmp.endsWith("man")) { //special plform = replaceLast(tmp, "man", "men"); } else if (!tmp.endsWith("s")) { //Rule #1: Add an -s to form the plural of most words. plform = word + "s"; } else if (word.toUpperCase().equals(word)) { //Rule #8: The plurals of single capital letters, acronyms, and Arabic numerals //(1,2,3,...) take an -s WITHOUT an apostrophe: plform = word + "s"; } else { RESOLVED_PLURALS.add(word); return word; } //check cases boolean caseChanged = false; int wl = word.length(); int pl = plform.length(); char[] pChars = plform.toCharArray(); int length = wl < pl ? wl : pl; for (int i = 0; i < length; i++) { char wChar = word.charAt(i); char pChar = plform.charAt(i); if (((int) wChar - (int) pChar) == -32) { pChars[i] = wChar; caseChanged = true; } } if (caseChanged) plform = new String(pChars); if (!plform.equalsIgnoreCase(word)) { RESOLVED_SINGLE_2_PLURALS.put(word, plform); RESOLVED_PLURAL_2_SINGLES.put(plform, word); } return plform; } /** * 从复数变换为单数 * * @param word 复数形式的单词 * @return singularized string */ public static String singularize(String word) { if (word == null || "".equals(word)) return word; String sgform = RESOLVED_PLURAL_2_SINGLES.get(word); if (sgform == null && (RESOLVED_SINGLES.contains(word) || RESOLVED_SINGLE_2_PLURALS.containsKey(word))) { sgform = word; } if (sgform != null) return sgform; String tmp = word.toLowerCase(); sgform = PLURAL_2SINGLES.get(tmp); if (sgform == null && (PLURALS.contains(tmp) || SINGLES.contains(tmp) || SINGLE_2PLURALS.containsKey(tmp))) { sgform = tmp; } if (sgform != null) { ; } else if (tmp.endsWith("ices")) { sgform = replaceLast(tmp, "ices", "ix"); } else if (tmp.endsWith("i")) { sgform = replaceLast(tmp, "i", "us"); } else if (tmp.endsWith("ses") && !tmp.endsWith("bases") || tmp.endsWith("zes") || tmp.endsWith("xes") || tmp.endsWith("ches") || tmp.endsWith("shes")) { sgform = replaceLast(tmp, "es", ""); } else if (tmp.endsWith("ays") || tmp.endsWith("eys") || tmp.endsWith("iys") || tmp.endsWith("oys") || tmp.endsWith("uys")) { sgform = replaceLast(tmp, "ys", "y"); } else if (tmp.endsWith("ies")) { sgform = replaceLast(tmp, "ies", "y"); } //Rule #7 else if (tmp.endsWith("aos") || tmp.endsWith("eos") || tmp.endsWith("ios") || tmp.endsWith("oos") || tmp.endsWith("uos")) { sgform = replaceLast(tmp, "os", "o"); } //Rule #7 else if (tmp.endsWith("oes")) { sgform = replaceLast(tmp, "oes", "o"); } else if (tmp.endsWith("ives")) { sgform = replaceLast(tmp, "ves", "fe"); } else if (tmp.endsWith("lves") || tmp.endsWith("rves") || tmp.endsWith("aves")) { sgform = replaceLast(tmp, "ves", "f"); } else if (tmp.endsWith("ae")) { sgform = replaceLast(tmp, "ae", "a"); } else if (tmp.endsWith("eaux")) { sgform = replaceLast(tmp, "eaux", "eau"); } else if (tmp.endsWith("men")) { sgform = replaceLast(tmp, "men", "man"); } else if (tmp.endsWith("s")) { sgform = replaceLast(tmp, "s", ""); } else { sgform = tmp; RESOLVED_SINGLES.add(word); return word; } //check cases boolean caseChanged = false; int wl = word.length(); int pl = sgform.length(); char[] sChars = sgform.toCharArray(); int length = wl < pl ? wl : pl; for (int i = 0; i < length; i++) { char wChar = word.charAt(i); char pChar = sgform.charAt(i); if ((int) wChar - (int) pChar == -32) { sChars[i] = wChar; caseChanged = true; } } if (caseChanged) sgform = new String(sChars); if (!sgform.equalsIgnoreCase(word)) { RESOLVED_PLURAL_2_SINGLES.put(word, sgform); RESOLVED_SINGLE_2_PLURALS.put(sgform, word); } return sgform; } /** * Replaces the last occurance of an old symbol with a new symbol. * * @param data the original string * @param oldSymbol the old symbols to be replaced * @param newSymbol the corresponding new symbol * @return a new string */ public static String replaceLast(String data, String oldSymbol, String newSymbol) { if (data == null || data.indexOf(oldSymbol) == -1) return data; int lastIndex = data.lastIndexOf(oldSymbol); int oldLength = oldSymbol.length(); String result = data.substring(0, lastIndex) + newSymbol + data.substring(lastIndex + oldLength); return result; } /** * Adds more pairs of single and plural words. * * @param single singular form of the word * @param plural plural form of the word */ public static void addPlural(String single, String plural) { RESOLVED_SINGLE_2_PLURALS.put(single, plural); RESOLVED_PLURAL_2_SINGLES.put(plural, single); } /** * Converts string to Camel case. * * @param word the word to be converted to camelized form * @return a camelized string */ public static String camelize(String word) { return camelize(word, false); } /** * Converts string to Camel case. If <tt>firstLetterInLowerCase</tt> * is true, then the first letter of the result string is in lower case. * <p/> * <pre> * Examples: * camelize("hello") ==> "Hello" * camelize("hello world") ==> "Hello world" * camelize("active_record") ==> "ActiveRecord" * camelize("active_record", true) ==> "activeRecord" * </pre> * * @param word the word to be converted to camelized form * @param firstLetterInLowerCase true if the first character should be in lower case * @return a camelized string */ public static String camelize(String word, boolean firstLetterInLowerCase) { if (word == null || "".equals(word)) return word; String result = ""; if (word.indexOf('_') != -1) { StringBuilder sb = new StringBuilder(); int count = 0; StringTokenizer st = new StringTokenizer(word, "_"); while (st.hasMoreTokens()) { String token = st.nextToken(); count++; if (count == 1) { sb.append(camelizeOneWord(token, firstLetterInLowerCase)); } else { sb.append(camelizeOneWord(token, false)); } } result = sb.toString(); } else { result = camelizeOneWord(word, firstLetterInLowerCase); } return result; } private static String camelizeOneWord(String word, boolean firstLetterInLowerCase) { if (word == null || "".equals(word)) return word; String firstChar = word.substring(0, 1); String result = firstLetterInLowerCase ? firstChar.toLowerCase() : firstChar.toUpperCase(); if (word.length() > 1) { result += word.substring(1); } return result; } /** * <tt>underscore</tt> is the reverse of <tt>camelize</tt> method. * <p/> * <pre> * Examples: * underscore("Hello world") ==> "hello world" * underscore("ActiveRecord") ==> "active_record" * underscore("The RedCross") ==> "the red_cross" * underscore("ABCD") ==> "abcd" * </pre> * * @param phase the original string * @return an underscored string */ public static String underscore(String phase) { if (phase == null || "".equals(phase)) return phase; phase = phase.replace('-', '_'); StringBuilder sb = new StringBuilder(); int total = phase.length(); for (int i = 0; i < total; i++) { char c = phase.charAt(i); if (i == 0) { if (isInA2Z(c)) { sb.append(String.valueOf(c).toLowerCase()); } else { sb.append(c); } } else { if (isInA2Z(c)) { if (isIna2z(phase.charAt(i - 1))) { sb.append("_").append(String.valueOf(c).toLowerCase()); } else { sb.append(String.valueOf(c).toLowerCase()); } } else { sb.append(c); } } } return sb.toString(); } private static boolean isInA2Z(char c) { return (A2Z.indexOf(c) != -1) ? true : false; } private static boolean isIna2z(char c) { return (a2z.indexOf(c) != -1) ? true : false; } /** * Replaces all dashes and underscores by spaces and capitalizes all the words. * <p/> * <pre> * Examples: * titleize("ch 1: Java-ActiveRecordIsFun") ==> "Ch 1: Java Active Record Is Fun" * </pre> * * @param phase the original string * @return a titleized string */ public static String titleize(String phase) { if (phase == null || "".equals(phase)) return phase; phase = humanize(phase); StringBuilder sb = new StringBuilder(); int total = phase.length(); for (int i = 0; i < total; i++) { char c = phase.charAt(i); if (i == 0) { if (isIna2z(c)) { sb.append(String.valueOf(c).toUpperCase()); } else { sb.append(c); } } else { if (isIna2z(c) && ' ' == phase.charAt(i - 1)) { sb.append(String.valueOf(c).toUpperCase()); } else { sb.append(c); } } } return sb.toString(); } /** * Replaces all dashes and underscores by spaces and capitalizes the first * word. Also removes * <p/> * <pre> * Examples: * humanize("active_record") ==> "Active record" * humanize("post_id") ==> "Post" * </pre> * * @param phase the original string * @return a humanized string */ public static String humanize(String phase) { if (phase == null || "".equals(phase)) return phase; phase = underscore(phase); if (phase.endsWith("_id")) phase += " "; return camelize(phase.replaceAll("_id ", " ").replace('_', ' ').trim()); } /** * Returns a database table name corresponding to the input model class * name. * <p/> * <pre> * Examples: * tableize("Person") ==> "people" * tableize("LineItem") ==> "line_items" * </pre> * * @param modelClassName * @return the table name of the java model class name */ public static String tableize(String modelClassName) { return pluralize(underscore(modelClassName)); } /** * Returns a model class name corresponding to the input database * table name. * <p/> * <pre> * Examples: * classify("people") ==> "Person" * classify("line_items") ==> "LineItem" * </pre> * * @param tableName java class name of the model * @return a java model class name */ public static String classify(String tableName) { return camelize(singularize(tableName)); } /** * Returns an ordinalized string. * <p/> * <pre> * Examples: * ordinalize(100) ==> "100th" * ordinalize(1003) ==> "1003rd" * </pre> * * @param number the number * @return an ordinalized string for the number */ public static String ordinalize(int number) { String result = "" + number; if (result.endsWith("1")) result = result + "st"; else if (result.endsWith("2")) result = result + "nd"; else if (result.endsWith("3")) result = result + "rd"; else result = result + "th"; return result; } }
lichen-core/src/main/java/lichen/core/services/WordUtil.java
// Copyright 2013 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * This software is distributed under the terms of the FSF * Gnu Lesser General Public License (see lgpl.txt). * * This program is distributed WITHOUT ANY WARRANTY. See the * GNU General Public License for more details. */ package lichen.core.services; import java.util.*; /** * 针对英文单词的复数转换. * 此文件来自 http://www.scooterframework.com. * <p/> * <p>Conversion between singular and plural form of a noun word.</p> * * @author (Fei) John Chen */ public final class WordUtil { public static final Map<String, String> SINGLE_2PLURALS = new HashMap<String, String>(); public static final List<String> PLURALS = new ArrayList<String>(); public static final Map<String, String> PLURAL_2SINGLES = new HashMap<String, String>(); public static final List<String> SINGLES = new ArrayList<String>(); static { //Irregular plurals: SINGLE_2PLURALS.put("child", "children"); SINGLE_2PLURALS.put("corpus", "corpora"); SINGLE_2PLURALS.put("foot", "feet"); SINGLE_2PLURALS.put("goose", "geese"); SINGLE_2PLURALS.put("louse", "lice"); SINGLE_2PLURALS.put("man", "men"); SINGLE_2PLURALS.put("mouse", "mice"); SINGLE_2PLURALS.put("ox", "oxen"); SINGLE_2PLURALS.put("person", "people"); SINGLE_2PLURALS.put("tooth", "teeth"); SINGLE_2PLURALS.put("woman", "women"); //Some nouns do not change at all: SINGLE_2PLURALS.put("cod", "cod"); SINGLE_2PLURALS.put("deer", "deer"); SINGLE_2PLURALS.put("fish", "fish"); SINGLE_2PLURALS.put("offspring", "offspring"); SINGLE_2PLURALS.put("perch", "perch"); SINGLE_2PLURALS.put("sheep", "sheep"); SINGLE_2PLURALS.put("trout", "trout"); SINGLE_2PLURALS.put("species", "species"); SINGLE_2PLURALS.put("series", "series"); //Other nouns that do not change: SINGLE_2PLURALS.put("data", "data"); SINGLE_2PLURALS.put("dice", "dice"); SINGLE_2PLURALS.put("media", "media"); //Singular ends in -us, plural ends in // -i: alumnus/alumni, focus/foci, nucleus/nuclei, //octopus/octopi, radius/radii, stimulus/stimuli, virus/viri //Exceptions to the above SINGLE_2PLURALS.put("bus", "buses"); //Singular ends in -ex, // plural ends in -ices: appendix/appendices, index/indices SINGLE_2PLURALS.put("index", "indices"); SINGLE_2PLURALS.put("vertex", "vertices"); //These include nouns that are traditionally plural, // but are also used for singular forms: SINGLE_2PLURALS.put("barracks", "barracks"); SINGLE_2PLURALS.put("crossroads", "crossroads"); SINGLE_2PLURALS.put("die", "dice"); SINGLE_2PLURALS.put("gallows", "gallows"); SINGLE_2PLURALS.put("headquarters", "headquarters"); SINGLE_2PLURALS.put("means", "means"); SINGLE_2PLURALS.put("series", "series"); SINGLE_2PLURALS.put("species", "species"); //Exception to Rule 6: Some nouns ending in f or fe are made plural //by changing f or fe to ves. with the following exceptions: SINGLE_2PLURALS.put("chief", "chiefs"); SINGLE_2PLURALS.put("chef", "chefs"); SINGLE_2PLURALS.put("dwarf", "dwarfs"); SINGLE_2PLURALS.put("hoof", "hoofs"); SINGLE_2PLURALS.put("kerchief", "kerchiefs"); SINGLE_2PLURALS.put("fife", "fifes"); SINGLE_2PLURALS.put("proof", "proofs"); //m-w.com SINGLE_2PLURALS.put("roof", "roofs"); SINGLE_2PLURALS.put("safe", "safes"); SINGLE_2PLURALS.put("mischief", "mischiefs"); SINGLE_2PLURALS.put("grief", "griefs"); //Rule 7b: All musical terms // ending in -o have plurals ending in just -s. SINGLE_2PLURALS.put("cello", "cellos"); SINGLE_2PLURALS.put("photo", "photos"); SINGLE_2PLURALS.put("solo", "solos"); SINGLE_2PLURALS.put("soprano", "sopranos"); SINGLE_2PLURALS.put("studio", "studios"); //Exception to Rule 7: Most nouns ending in o preceded by a consonant //is formed into a plural by adding es with the following exceptions: SINGLE_2PLURALS.put("canto", "cantos"); SINGLE_2PLURALS.put("lasso", "lassos"); SINGLE_2PLURALS.put("halo", "halos"); SINGLE_2PLURALS.put("memento", "mementos"); SINGLE_2PLURALS.put("photo", "photos"); SINGLE_2PLURALS.put("sirocco", "siroccos"); //Rule 7c: Plural forms of words ending in -o (-os): SINGLE_2PLURALS.put("albino", "albinos"); SINGLE_2PLURALS.put("armadillo", "armadillos"); SINGLE_2PLURALS.put("auto", "autos"); SINGLE_2PLURALS.put("bravo", "bravos"); SINGLE_2PLURALS.put("bronco", "broncos"); SINGLE_2PLURALS.put("canto", "cantos"); SINGLE_2PLURALS.put("casino", "casinos"); SINGLE_2PLURALS.put("combo", "combos"); SINGLE_2PLURALS.put("gazebo", "gazebos"); SINGLE_2PLURALS.put("inferno", "infernos"); SINGLE_2PLURALS.put("kangaroo", "kangaroos"); SINGLE_2PLURALS.put("kilo", "kilos"); SINGLE_2PLURALS.put("kimono", "kimonos"); SINGLE_2PLURALS.put("logo", "logos"); SINGLE_2PLURALS.put("maraschino", "maraschinos"); SINGLE_2PLURALS.put("memo", "memos"); SINGLE_2PLURALS.put("photo", "photos"); SINGLE_2PLURALS.put("pimento", "pimentos"); SINGLE_2PLURALS.put("poncho", "ponchos"); SINGLE_2PLURALS.put("pro", "pros"); SINGLE_2PLURALS.put("sombrero", "sombreros"); SINGLE_2PLURALS.put("taco", "tacos"); SINGLE_2PLURALS.put("tattoo", "tattoos"); SINGLE_2PLURALS.put("torso", "torsos"); SINGLE_2PLURALS.put("tobacco", "tobaccos"); SINGLE_2PLURALS.put("typo", "typos"); //Rule 7c: Plural forms of words ending in -o (-oes): SINGLE_2PLURALS.put("echo", "echoes"); SINGLE_2PLURALS.put("embargo", "embargoes"); SINGLE_2PLURALS.put("hero", "heroes"); SINGLE_2PLURALS.put("potato", "potatoes"); SINGLE_2PLURALS.put("tomato", "tomatoes"); SINGLE_2PLURALS.put("torpedo", "torpedoes"); SINGLE_2PLURALS.put("veto", "vetoes"); //Rule 7c: Plural forms of words ending in -o (-os or -oes): SINGLE_2PLURALS.put("avocado", "avocados"); SINGLE_2PLURALS.put("buffalo", "buffaloes"); SINGLE_2PLURALS.put("cargo", "cargoes"); SINGLE_2PLURALS.put("desperado", "desperadoes"); SINGLE_2PLURALS.put("dodo", "dodoes"); SINGLE_2PLURALS.put("domino", "dominoes"); SINGLE_2PLURALS.put("ghetto", "ghettos"); SINGLE_2PLURALS.put("grotto", "grottoes"); SINGLE_2PLURALS.put("hobo", "hoboes"); SINGLE_2PLURALS.put("innuendo", "innuendoes"); SINGLE_2PLURALS.put("lasso", "lassos"); SINGLE_2PLURALS.put("mango", "mangoes"); SINGLE_2PLURALS.put("mosquito", "mosquitoes"); SINGLE_2PLURALS.put("motto", "mottoes"); SINGLE_2PLURALS.put("mulatto", "mulattos"); SINGLE_2PLURALS.put("no", "noes"); SINGLE_2PLURALS.put("peccadillo", "peccadilloes"); SINGLE_2PLURALS.put("tornado", "tornadoes"); SINGLE_2PLURALS.put("volcano", "volcanoes"); SINGLE_2PLURALS.put("zero", "zeros"); //others SINGLE_2PLURALS.put("forum", "forums"); //Things that come in pairs PLURALS.add("binoculars"); PLURALS.add("forceps"); PLURALS.add("jeans"); PLURALS.add("glasses"); PLURALS.add("pajamas"); PLURALS.add("pants"); PLURALS.add("scissors"); PLURALS.add("shorts"); PLURALS.add("tongs"); PLURALS.add("trousers"); PLURALS.add("tweezers"); //Nouns that end in -s but have no singular (aggregate nouns) PLURALS.add("accommodations"); PLURALS.add("amends"); PLURALS.add("archives"); PLURALS.add("arms"); PLURALS.add("bellows"); PLURALS.add("bowels"); PLURALS.add("brains"); PLURALS.add("clothes"); PLURALS.add("communications"); PLURALS.add("congratulations"); PLURALS.add("contents"); PLURALS.add("dregs"); PLURALS.add("goods"); PLURALS.add("measles"); PLURALS.add("mumps"); PLURALS.add("oats"); PLURALS.add("pinchers"); PLURALS.add("shears"); PLURALS.add("snuffers"); PLURALS.add("stairs"); PLURALS.add("thanks"); PLURALS.add("vespers"); PLURALS.add("victuals"); //Nouns that are plural but do not end in -s PLURALS.add("children"); PLURALS.add("cattle"); PLURALS.add("corpora"); PLURALS.add("data"); PLURALS.add("men"); PLURALS.add("people"); PLURALS.add("police"); PLURALS.add("women"); //Nouns that are always singular -- uncountable SINGLES.add("cooper"); SINGLES.add("corn"); SINGLES.add("cotton"); SINGLES.add("gold"); SINGLES.add("information"); SINGLES.add("money"); SINGLES.add("news"); SINGLES.add("rice"); SINGLES.add("silver"); SINGLES.add("sugar"); SINGLES.add("wheat"); //PLURAL_2SINGLES.put("data", "data"); //PLURAL_2SINGLES.put("media", "media"); PLURAL_2SINGLES.put("dice", "dice"); PLURAL_2SINGLES.put("indices", "index"); PLURAL_2SINGLES.put("vertices", "vertex"); PLURAL_2SINGLES.put("movies", "movie"); PLURAL_2SINGLES.put("viri", "virus"); PLURAL_2SINGLES.put("axes", "axis"); PLURAL_2SINGLES.put("crises", "crisis"); PLURAL_2SINGLES.put("analyses", "analysis"); PLURAL_2SINGLES.put("diagnoses", "diagnosis"); PLURAL_2SINGLES.put("synopses", "synopsis"); PLURAL_2SINGLES.put("theses", "thesis"); PLURAL_2SINGLES.put("moves", "move"); PLURAL_2SINGLES.put("caves", "cave"); PLURAL_2SINGLES.put("toes", "toe"); //merge PLURAL_2SINGLES with SINGLE_2PLURALS for (Map.Entry<String, String> entry : SINGLE_2PLURALS.entrySet()) { String sk = entry.getKey(); String sv = entry.getValue(); String pv = PLURAL_2SINGLES.get(sv); if (pv == null) { PLURAL_2SINGLES.put(sv, sk); } } //merge SINGLE_2PLURALS with PLURAL_2SINGLES for (Map.Entry<String, String> entry : PLURAL_2SINGLES.entrySet()) { String pk = entry.getKey(); String pv = entry.getValue(); String sv = SINGLE_2PLURALS.get(pv); if (sv == null) { SINGLE_2PLURALS.put(pv, pk); } } } //单数到复数的映射 private static final Map<String, String> RESOLVED_SINGLE_2_PLURALS = new HashMap<String, String>(); //已经处理过的复数 private static final List<String> RESOLVED_PLURALS = new ArrayList<String>(); //复数到单数的映射 private static final Map<String, String> RESOLVED_PLURAL_2_SINGLES = new HashMap<String, String>(); private static final List<String> RESOLVED_SINGLES = new ArrayList<String>(); private static String A2Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static String a2z = "abcdefghijklmnopqrstuvwxyz"; /** * 把给定的单词转换为复数. * * @param word 待转换的单词 * @return 复数字符串 */ public static String pluralize(String word) { if (word == null || "".equals(word)) { return word; } //先判断是否处理过了 String plform = RESOLVED_SINGLE_2_PLURALS.get(word); if (plform == null && (RESOLVED_PLURALS.contains(word) || RESOLVED_PLURAL_2_SINGLES.containsKey(word))) { plform = word; } if (plform != null) return plform; String tmp = word.toLowerCase(); plform = SINGLE_2PLURALS.get(tmp); if (plform == null && (PLURALS.contains(tmp) || SINGLES.contains(tmp) || PLURAL_2SINGLES.containsKey(tmp))) { plform = tmp; } if (plform != null) { //映射里面已经得到 System.out.println(plform); } else if (tmp.endsWith("is")) { //Rule #5: For words that end in -is, change the -is to -es to make the plural form plform = replaceLast(tmp, "is", "es"); } else if (tmp.endsWith("ix")) { //Singular ends in -ix, plural ends in -ices: appendix/appendices, index/indices plform = replaceLast(tmp, "ix", "ices"); } else if (tmp.endsWith("us")) { //Singular ends in -us, plural ends in -i: alumnus/alumni, focus/foci, nucleus/nuclei, //octopus/octopi, radius/radii, stimulus/stimuli, virus/viri plform = replaceLast(tmp, "us", "i"); } else if (!tmp.endsWith("es") && (tmp.endsWith("z") || tmp.endsWith("x") || tmp.endsWith("ch") || tmp.endsWith("sh"))) { //Rule #2: For words that end in a "hissing" sound (-s, -z, -x, -ch, -sh), add an -es to form the plural. //Note: I removed tmp.endsWith("s") || as this cause "posts"->"postses". plform = tmp + "es"; } else if (tmp.endsWith("y")) { //Rule #3: If the word ends in a vowel plus -y (-ay, -ey, -iy, -oy, -uy), add an -s to the word. if (tmp.endsWith("ay") || tmp.endsWith("ey") || tmp.endsWith("iy") || tmp.endsWith("oy") || tmp.endsWith("uy")) { plform = word + "s"; } else { //Rule #4: If the word ends in a consonant plus -y, change the -y into -ie and add an -s to form the plural. plform = replaceLast(tmp, "y", "ies"); } } //Rule #6: Some words that end in -f or -fe have plurals that end in -ves. else if (tmp.endsWith("f")) { plform = replaceLast(tmp, "f", "ves"); } else if (tmp.endsWith("fe")) { plform = replaceLast(tmp, "fe", "ves"); } //Rule #7: The plurals of words ending in -o are formed by either adding -s or by adding -es else if (tmp.endsWith("o")) { //All words that end in a vowel plus -o (-ao, -eo, -io, -oo, -uo) // have plurals that end in just -s: if (tmp.endsWith("ao") || tmp.endsWith("eo") || tmp.endsWith("io") || tmp.endsWith("oo") || tmp.endsWith("uo")) { plform = word + "s"; } else { //All musical terms ending in -o have plurals ending in just -s. //Most others by adding -es with exceptions plform = word + "es"; } } else if (tmp.endsWith("um")) { //Singular ends in -um, plural ends in -a: datum/data, curriculum/curricula plform = replaceLast(tmp, "um", "a"); } else if (tmp.endsWith("on") && !tmp.endsWith("ation")) { //Singular ends in -on, plural ends in -a: criterion/criteria, phenomenon/phenomena plform = replaceLast(tmp, "on", "a"); } else if (tmp.endsWith("a")) { //Singular ends in -a, plural ends in -ae: alumna/alumnae, formula/formulae, antenna/antennae plform = replaceLast(tmp, "a", "ae"); } else if (tmp.endsWith("eau")) { //Singular ends in -eau, plural ends in -eaux: bureau/bureaux, beau/beaux plform = replaceLast(tmp, "eau", "eaux"); } else if (tmp.endsWith("man")) { //special plform = replaceLast(tmp, "man", "men"); } else if (!tmp.endsWith("s")) { //Rule #1: Add an -s to form the plural of most words. plform = word + "s"; } else if (word.toUpperCase().equals(word)) { //Rule #8: The plurals of single capital letters, acronyms, and Arabic numerals //(1,2,3,...) take an -s WITHOUT an apostrophe: plform = word + "s"; } else { RESOLVED_PLURALS.add(word); return word; } //check cases boolean caseChanged = false; int wl = word.length(); int pl = plform.length(); char[] pChars = plform.toCharArray(); int length = wl < pl ? wl : pl; for (int i = 0; i < length; i++) { char wChar = word.charAt(i); char pChar = plform.charAt(i); if (((int) wChar - (int) pChar) == -32) { pChars[i] = wChar; caseChanged = true; } } if (caseChanged) plform = new String(pChars); if (!plform.equalsIgnoreCase(word)) { RESOLVED_SINGLE_2_PLURALS.put(word, plform); RESOLVED_PLURAL_2_SINGLES.put(plform, word); } return plform; } /** * 从复数变换为单数 * * @param word 复数形式的单词 * @return singularized string */ public static String singularize(String word) { if (word == null || "".equals(word)) return word; String sgform = RESOLVED_PLURAL_2_SINGLES.get(word); if (sgform == null && (RESOLVED_SINGLES.contains(word) || RESOLVED_SINGLE_2_PLURALS.containsKey(word))) { sgform = word; } if (sgform != null) return sgform; String tmp = word.toLowerCase(); sgform = PLURAL_2SINGLES.get(tmp); if (sgform == null && (PLURALS.contains(tmp) || SINGLES.contains(tmp) || SINGLE_2PLURALS.containsKey(tmp))) { sgform = tmp; } if (sgform != null) { } else if (tmp.endsWith("ices")) { sgform = replaceLast(tmp, "ices", "ix"); } else if (tmp.endsWith("i")) { sgform = replaceLast(tmp, "i", "us"); } else if (tmp.endsWith("ses") && !tmp.endsWith("bases") || tmp.endsWith("zes") || tmp.endsWith("xes") || tmp.endsWith("ches") || tmp.endsWith("shes")) { sgform = replaceLast(tmp, "es", ""); } else if (tmp.endsWith("ays") || tmp.endsWith("eys") || tmp.endsWith("iys") || tmp.endsWith("oys") || tmp.endsWith("uys")) { sgform = replaceLast(tmp, "ys", "y"); } else if (tmp.endsWith("ies")) { sgform = replaceLast(tmp, "ies", "y"); } //Rule #7 else if (tmp.endsWith("aos") || tmp.endsWith("eos") || tmp.endsWith("ios") || tmp.endsWith("oos") || tmp.endsWith("uos")) { sgform = replaceLast(tmp, "os", "o"); } //Rule #7 else if (tmp.endsWith("oes")) { sgform = replaceLast(tmp, "oes", "o"); } else if (tmp.endsWith("ives")) { sgform = replaceLast(tmp, "ves", "fe"); } else if (tmp.endsWith("lves") || tmp.endsWith("rves") || tmp.endsWith("aves")) { sgform = replaceLast(tmp, "ves", "f"); } else if (tmp.endsWith("ae")) { sgform = replaceLast(tmp, "ae", "a"); } else if (tmp.endsWith("eaux")) { sgform = replaceLast(tmp, "eaux", "eau"); } else if (tmp.endsWith("men")) { sgform = replaceLast(tmp, "men", "man"); } else if (tmp.endsWith("s")) { sgform = replaceLast(tmp, "s", ""); } else { sgform = tmp; RESOLVED_SINGLES.add(word); return word; } //check cases boolean caseChanged = false; int wl = word.length(); int pl = sgform.length(); char[] sChars = sgform.toCharArray(); int length = wl < pl ? wl : pl; for (int i = 0; i < length; i++) { char wChar = word.charAt(i); char pChar = sgform.charAt(i); if ((int) wChar - (int) pChar == -32) { sChars[i] = wChar; caseChanged = true; } } if (caseChanged) sgform = new String(sChars); if (!sgform.equalsIgnoreCase(word)) { RESOLVED_PLURAL_2_SINGLES.put(word, sgform); RESOLVED_SINGLE_2_PLURALS.put(sgform, word); } return sgform; } /** * Replaces the last occurance of an old symbol with a new symbol. * * @param data the original string * @param oldSymbol the old symbols to be replaced * @param newSymbol the corresponding new symbol * @return a new string */ public static String replaceLast(String data, String oldSymbol, String newSymbol) { if (data == null || data.indexOf(oldSymbol) == -1) return data; int lastIndex = data.lastIndexOf(oldSymbol); int oldLength = oldSymbol.length(); String result = data.substring(0, lastIndex) + newSymbol + data.substring(lastIndex + oldLength); return result; } /** * Adds more pairs of single and plural words. * * @param single singular form of the word * @param plural plural form of the word */ public static void addPlural(String single, String plural) { RESOLVED_SINGLE_2_PLURALS.put(single, plural); RESOLVED_PLURAL_2_SINGLES.put(plural, single); } /** * Converts string to Camel case. * * @param word the word to be converted to camelized form * @return a camelized string */ public static String camelize(String word) { return camelize(word, false); } /** * Converts string to Camel case. If <tt>firstLetterInLowerCase</tt> * is true, then the first letter of the result string is in lower case. * <p/> * <pre> * Examples: * camelize("hello") ==> "Hello" * camelize("hello world") ==> "Hello world" * camelize("active_record") ==> "ActiveRecord" * camelize("active_record", true) ==> "activeRecord" * </pre> * * @param word the word to be converted to camelized form * @param firstLetterInLowerCase true if the first character should be in lower case * @return a camelized string */ public static String camelize(String word, boolean firstLetterInLowerCase) { if (word == null || "".equals(word)) return word; String result = ""; if (word.indexOf('_') != -1) { StringBuilder sb = new StringBuilder(); int count = 0; StringTokenizer st = new StringTokenizer(word, "_"); while (st.hasMoreTokens()) { String token = st.nextToken(); count++; if (count == 1) { sb.append(camelizeOneWord(token, firstLetterInLowerCase)); } else { sb.append(camelizeOneWord(token, false)); } } result = sb.toString(); } else { result = camelizeOneWord(word, firstLetterInLowerCase); } return result; } private static String camelizeOneWord(String word, boolean firstLetterInLowerCase) { if (word == null || "".equals(word)) return word; String firstChar = word.substring(0, 1); String result = firstLetterInLowerCase ? firstChar.toLowerCase() : firstChar.toUpperCase(); if (word.length() > 1) { result += word.substring(1); } return result; } /** * <tt>underscore</tt> is the reverse of <tt>camelize</tt> method. * <p/> * <pre> * Examples: * underscore("Hello world") ==> "hello world" * underscore("ActiveRecord") ==> "active_record" * underscore("The RedCross") ==> "the red_cross" * underscore("ABCD") ==> "abcd" * </pre> * * @param phase the original string * @return an underscored string */ public static String underscore(String phase) { if (phase == null || "".equals(phase)) return phase; phase = phase.replace('-', '_'); StringBuilder sb = new StringBuilder(); int total = phase.length(); for (int i = 0; i < total; i++) { char c = phase.charAt(i); if (i == 0) { if (isInA2Z(c)) { sb.append(String.valueOf(c).toLowerCase()); } else { sb.append(c); } } else { if (isInA2Z(c)) { if (isIna2z(phase.charAt(i - 1))) { sb.append("_").append(String.valueOf(c).toLowerCase()); } else { sb.append(String.valueOf(c).toLowerCase()); } } else { sb.append(c); } } } return sb.toString(); } private static boolean isInA2Z(char c) { return (A2Z.indexOf(c) != -1) ? true : false; } private static boolean isIna2z(char c) { return (a2z.indexOf(c) != -1) ? true : false; } /** * Replaces all dashes and underscores by spaces and capitalizes all the words. * <p/> * <pre> * Examples: * titleize("ch 1: Java-ActiveRecordIsFun") ==> "Ch 1: Java Active Record Is Fun" * </pre> * * @param phase the original string * @return a titleized string */ public static String titleize(String phase) { if (phase == null || "".equals(phase)) return phase; phase = humanize(phase); StringBuilder sb = new StringBuilder(); int total = phase.length(); for (int i = 0; i < total; i++) { char c = phase.charAt(i); if (i == 0) { if (isIna2z(c)) { sb.append(String.valueOf(c).toUpperCase()); } else { sb.append(c); } } else { if (isIna2z(c) && ' ' == phase.charAt(i - 1)) { sb.append(String.valueOf(c).toUpperCase()); } else { sb.append(c); } } } return sb.toString(); } /** * Replaces all dashes and underscores by spaces and capitalizes the first * word. Also removes * <p/> * <pre> * Examples: * humanize("active_record") ==> "Active record" * humanize("post_id") ==> "Post" * </pre> * * @param phase the original string * @return a humanized string */ public static String humanize(String phase) { if (phase == null || "".equals(phase)) return phase; phase = underscore(phase); if (phase.endsWith("_id")) phase += " "; return camelize(phase.replaceAll("_id ", " ").replace('_', ' ').trim()); } /** * Returns a database table name corresponding to the input model class * name. * <p/> * <pre> * Examples: * tableize("Person") ==> "people" * tableize("LineItem") ==> "line_items" * </pre> * * @param modelClassName * @return the table name of the java model class name */ public static String tableize(String modelClassName) { return pluralize(underscore(modelClassName)); } /** * Returns a model class name corresponding to the input database * table name. * <p/> * <pre> * Examples: * classify("people") ==> "Person" * classify("line_items") ==> "LineItem" * </pre> * * @param tableName java class name of the model * @return a java model class name */ public static String classify(String tableName) { return camelize(singularize(tableName)); } /** * Returns an ordinalized string. * <p/> * <pre> * Examples: * ordinalize(100) ==> "100th" * ordinalize(1003) ==> "1003rd" * </pre> * * @param number the number * @return an ordinalized string for the number */ public static String ordinalize(int number) { String result = "" + number; if (result.endsWith("1")) result = result + "st"; else if (result.endsWith("2")) result = result + "nd"; else if (result.endsWith("3")) result = result + "rd"; else result = result + "th"; return result; } }
FIXES #1 增加分号,避免编译器编译的过程中导致语句失败
lichen-core/src/main/java/lichen/core/services/WordUtil.java
FIXES #1 增加分号,避免编译器编译的过程中导致语句失败
Java
bsd-2-clause
5dc4fdb587b9add073e5361cb71e882870cc3296
0
balcirakpeter/perun,martin-kuba/perun,Holdo/perun,tauceti2/perun,jirmauritz/perun,zoraseb/perun,Laliska/perun,zlamalp/perun,D3jph/perun,tauceti2/perun,ondrocks/perun,martin-kuba/perun,licehammer/perun,ondrocks/perun,CESNET/perun,ondrocks/perun,Simcsa/perun,zlamalp/perun,licehammer/perun,dsarman/perun,Holdo/perun,tauceti2/perun,CESNET/perun,zoraseb/perun,zoraseb/perun,tauceti2/perun,ondrejvelisek/perun,stavamichal/perun,stavamichal/perun,stavamichal/perun,zwejra/perun,Natrezim/perun,zlamalp/perun,CESNET/perun,licehammer/perun,mvocu/perun,dsarman/perun,balcirakpeter/perun,mvocu/perun,Laliska/perun,Simcsa/perun,martin-kuba/perun,zlamalp/perun,stavamichal/perun,martin-kuba/perun,zwejra/perun,tauceti2/perun,Natrezim/perun,Simcsa/perun,ondrejvelisek/perun,D3jph/perun,jirmauritz/perun,Holdo/perun,zlamalp/perun,Simcsa/perun,balcirakpeter/perun,dsarman/perun,zlamalp/perun,Holdo/perun,ondrocks/perun,D3jph/perun,D3jph/perun,stavamichal/perun,jirmauritz/perun,Natrezim/perun,mvocu/perun,jirmauritz/perun,balcirakpeter/perun,D3jph/perun,dsarman/perun,CESNET/perun,jirmauritz/perun,D3jph/perun,licehammer/perun,dsarman/perun,ondrejvelisek/perun,Natrezim/perun,martin-kuba/perun,zwejra/perun,zwejra/perun,dsarman/perun,martin-kuba/perun,tauceti2/perun,Laliska/perun,Holdo/perun,balcirakpeter/perun,mvocu/perun,stavamichal/perun,licehammer/perun,stavamichal/perun,martin-kuba/perun,Holdo/perun,ondrocks/perun,CESNET/perun,mvocu/perun,zoraseb/perun,mvocu/perun,Laliska/perun,zoraseb/perun,mvocu/perun,ondrocks/perun,balcirakpeter/perun,Laliska/perun,ondrejvelisek/perun,Simcsa/perun,zwejra/perun,balcirakpeter/perun,licehammer/perun,zoraseb/perun,zlamalp/perun,ondrejvelisek/perun,Natrezim/perun,ondrejvelisek/perun,Laliska/perun,jirmauritz/perun,CESNET/perun,Natrezim/perun,zwejra/perun,CESNET/perun,Simcsa/perun
package cz.metacentrum.perun.webgui.client.applicationresources.pages; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.http.client.UrlBuilder; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.ui.*; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import cz.metacentrum.perun.webgui.client.ApplicationFormGui; import cz.metacentrum.perun.webgui.client.PerunWebSession; import cz.metacentrum.perun.webgui.client.applicationresources.SendsApplicationForm; import cz.metacentrum.perun.webgui.client.localization.ApplicationMessages; import cz.metacentrum.perun.webgui.client.resources.*; import cz.metacentrum.perun.webgui.json.JsonCallbackEvents; import cz.metacentrum.perun.webgui.json.JsonPostClient; import cz.metacentrum.perun.webgui.json.JsonUtils; import cz.metacentrum.perun.webgui.json.attributesManager.GetLogins; import cz.metacentrum.perun.webgui.json.registrarManager.CreateApplication; import cz.metacentrum.perun.webgui.json.registrarManager.GetApplicationForm; import cz.metacentrum.perun.webgui.json.registrarManager.GetFormItemsWithPrefilledValues; import cz.metacentrum.perun.webgui.json.usersManager.FindCompleteRichUsers; import cz.metacentrum.perun.webgui.json.usersManager.FindUsersByName; import cz.metacentrum.perun.webgui.model.*; import cz.metacentrum.perun.webgui.widgets.Confirm; import cz.metacentrum.perun.webgui.widgets.CustomButton; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Page with VO application form * * @author Vaclav Mach <374430@mail.muni.cz> */ public class ApplicationFormPage extends ApplicationPage { /** * Main body contents */ private SimplePanel bodyContents = new SimplePanel(); private VerticalPanel formContent = new VerticalPanel(); /** * Data */ private ArrayList<ApplicationFormItemData> data; /** * VO */ private VirtualOrganization vo; /** * Group */ private Group group; /** * session */ private PerunWebSession session = PerunWebSession.getInstance(); /** * Form type */ private String type = "INITIAL"; private ApplicationForm form; /** * Switch languages button */ private PushButton languageButtonCzech; private PushButton languageButtonEnglish; private boolean submittedOrError = false; /** * Creates a new page with application form * * @param vo * @param type INITIAL or EXTENSION */ public ApplicationFormPage(VirtualOrganization vo, Group group, String type) { this.initWidget(bodyContents); this.vo = vo; this.group = group; this.type = type; bodyContents.setSize("100%", "100%"); bodyContents.setStyleName("formContent"); } /** * Prepares the buttons for local languages */ private void prepareToggleLanguageButton() { languageButtonCzech = new PushButton(new Image(SmallIcons.INSTANCE.flagCzechRepublicIcon())); languageButtonCzech.setTitle(ApplicationMessages.INSTANCE.changeLanguageToCzech()); languageButtonCzech.setStyleName("gwt-Button"); languageButtonCzech.setPixelSize(17, 17); languageButtonEnglish = new PushButton(new Image(SmallIcons.INSTANCE.flagGreatBritainIcon())); languageButtonEnglish.setTitle(ApplicationMessages.INSTANCE.changeLanguageToEnglish()); languageButtonEnglish.setStyleName("gwt-Button"); languageButtonEnglish.setPixelSize(17, 17); languageButtonCzech.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Confirm conf = new Confirm(languageButtonCzech.getTitle(), new HTML(ApplicationMessages.INSTANCE.changeLanguageText()), new ClickHandler(){ public void onClick(ClickEvent event) { // on OK UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", "cs"); Window.Location.replace(builder.buildString()); }}, new ClickHandler(){ public void onClick(ClickEvent event) { // on CANCEL } }, true); conf.setNonScrollable(true); conf.show(); } }); languageButtonEnglish.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Confirm conf = new Confirm(languageButtonEnglish.getTitle(), new HTML(ApplicationMessages.INSTANCE.changeLanguageText()), new ClickHandler(){ public void onClick(ClickEvent event) { // on OK UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", "en"); Window.Location.replace(builder.buildString()); }}, new ClickHandler(){ public void onClick(ClickEvent event) { // on CANCEL } }, true); conf.setNonScrollable(true); conf.show(); } }); } /** * Prepares a VO form */ protected void prepareVoForm() { bodyContents.setWidget(formContent); formContent.setStyleName("formContentTable"); submittedOrError = false; // try to get user for VOs initial application (only for authz origin) if (session.getUser() == null && !session.getPerunPrincipal().getExtSource().equalsIgnoreCase("LOCAL")) { tryToFindUserByName(null); } FlexTable header = new FlexTable(); header.setWidth("100%"); header.setCellPadding(5); int row = 0; // display VO logo if present in attribute for (int i=0; i<vo.getAttributes().length(); i++) { if (vo.getAttributes().get(i).getFriendlyName().equalsIgnoreCase("voLogoURL")) { header.setWidget(row, 0, new Image(vo.getAttributes().get(i).getValue())); row++; } } /* String headerString = ""; // display application header if (type.equalsIgnoreCase("INITIAL")) { if (group != null) { headerString = ApplicationMessages.INSTANCE.applicationFormForGroup(group.getName()); } else { headerString = ApplicationMessages.INSTANCE.applicationFormForVo(vo.getName()); } } else if (type.equalsIgnoreCase("EXTENSION")) { if (group != null) { headerString = ApplicationMessages.INSTANCE.membershipExtensionForGroup(group.getName()); } else { headerString = ApplicationMessages.INSTANCE.membershipExtensionForVo(vo.getName()); } } header.setHTML(row, 0, "<h1>" + headerString + "</h1>"); */ // language button prepareToggleLanguageButton(); FlexTable lang = new FlexTable(); lang.setWidget(0, 1, languageButtonCzech); lang.setWidget(0, 2, languageButtonEnglish); header.setWidget(0, 1, lang); header.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); formContent.add(header); JsonCallbackEvents jqueryEvent = new JsonCallbackEvents(){ @Override public void onFinished(JavaScriptObject jso) { Scheduler.get().scheduleDeferred(new Command() { @Override public void execute() { positionLinker(); } }); } }; final GetFormItemsWithPrefilledValues fitems; if (group != null) { fitems = new GetFormItemsWithPrefilledValues(PerunEntity.GROUP, group.getId(), jqueryEvent); } else { fitems = new GetFormItemsWithPrefilledValues(PerunEntity.VIRTUAL_ORGANIZATION, vo.getId(), jqueryEvent); } // pass valid app type in URL or use default if (Location.getParameter("type") != null && (Location.getParameter("type").equalsIgnoreCase("INITIAL") || Location.getParameter("type").equalsIgnoreCase("EXTENSION"))) { fitems.setType(Location.getParameter("type").toUpperCase()); } else { fitems.setType(type); } fitems.setHidden(true); fitems.setSendFormHandler(new SendsApplicationForm() { public void sendApplicationForm(CustomButton button) { data = fitems.getValues(); sendForm(button); } }); fitems.retrieveData(); formContent.add(fitems.getContents()); formContent.add(new HTML("<br /><br /><br />")); JsonCallbackEvents formEvent = new JsonCallbackEvents(){ @Override public void onFinished(JavaScriptObject jso) { form = jso.cast(); } }; GetApplicationForm formRequest; if (group != null) { formRequest = new GetApplicationForm(PerunEntity.GROUP, group.getId(), formEvent); } else { formRequest = new GetApplicationForm(PerunEntity.VIRTUAL_ORGANIZATION, vo.getId(), formEvent); } formRequest.retrieveData(); } /** * Send form */ protected void sendForm(final CustomButton button) { PerunPrincipal pp = session.getPerunPrincipal(); // fed info String fedInfo = ""; fedInfo += "{"; fedInfo += " displayName=\"" + pp.getAdditionInformations("displayName")+"\""; fedInfo += " commonName=\"" + pp.getAdditionInformations("cn")+"\""; fedInfo += " givenName=\"" + pp.getAdditionInformations("givenName")+"\""; fedInfo += " sureName=\"" + pp.getAdditionInformations("sn")+"\""; fedInfo += " loa=\"" + pp.getAdditionInformations("loa")+"\""; fedInfo += " mail=\"" + pp.getAdditionInformations("mail")+"\""; fedInfo += " organization=\"" + pp.getAdditionInformations("o")+"\""; fedInfo += " }"; Application app = Application.construct(vo, group, type, fedInfo, pp.getActor(), pp.getExtSource(), pp.getExtSourceType(), pp.getExtSourceLoa()); if (session.getUser() != null) { // set user association if known from perun app.setUser(session.getUser()); } // loading final PopupPanel loadingBox = session.getUiElements().perunLoadingBox(ApplicationMessages.INSTANCE.processing()); // Create application request CreateApplication ca = new CreateApplication(JsonCallbackEvents.disableButtonEvents(button, new JsonCallbackEvents() { @Override public void onLoadingStart() { // show loading box loadingBox.show(); } @Override public void onFinished(JavaScriptObject jso) { loadingBox.hide(); formOk(jso); } @Override public void onError(PerunError err) { loadingBox.hide(); formError(err); } })); // Send the request ca.createApplication(app, data); } /** * Form OK */ protected void formOk(JavaScriptObject jso) { ApplicationFormGui.redrawGuiWithMenu(); submittedOrError = true; if (session.getUser() == null && !session.getPerunPrincipal().getExtSource().equalsIgnoreCase("LOCAL")) { // if not yet user of perun, retry search for similar users after app submit // only for VO initial applications tryToFindUserByName(jso); } Boolean autoApproval = false; if (form != null) { if (type.equalsIgnoreCase("INITIAL")) { autoApproval = form.getAutomaticApproval(); } else if (type.equalsIgnoreCase("EXTENSION")) { autoApproval = form.getAutomaticApprovalExtension(); } } String approveText = ""; if (autoApproval) { approveText = ApplicationMessages.INSTANCE.autoApprovalApplicationText(); } else { approveText = ApplicationMessages.INSTANCE.nonAutoApprovalApplicationText(); } approveText = "<p><strong>" + approveText + "</strong></p>"; // conditional sending of validation email String validationText = ""; ArrayList<ApplicationFormItemData> data = JsonUtils.jsoAsList(jso); for (ApplicationFormItemData item : data) { if ("VALIDATED_EMAIL".equalsIgnoreCase(item.getFormItem().getType())) { // if not verified, email was sent if (!"1".equalsIgnoreCase(item.getAssuranceLevel())) { validationText = "<p>" + ApplicationMessages.INSTANCE.ifEmailProvidedCheckInbox() + "</p>"; } } } if (type.equalsIgnoreCase("INITIAL")) { FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); String succSendText = ApplicationMessages.INSTANCE.applicationSuccessfullySent(vo.getName()); if (group != null) { succSendText = ApplicationMessages.INSTANCE.applicationSuccessfullySent(group.getName()); } ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.acceptIcon())+"<h2>"+ succSendText +"</h2>" + validationText + approveText); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); bodyContents.setWidget(ft); if (Location.getParameter("targetnew") != null) { Location.replace(Location.getParameter("targetnew")); } } else if (type.equalsIgnoreCase("EXTENSION")) { FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.acceptIcon())+"<h2>" + ApplicationMessages.INSTANCE.membershipExtensionSuccessfullySent(vo.getName()) + "</h2>" + approveText); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); bodyContents.setWidget(ft); if (autoApproval) { // automatically extended if (Location.getParameter("targetextended") != null) { Location.replace(Location.getParameter("targetextended")); } } else { // TODO - only when user have valid account if (Location.getParameter("targetexisting") != null) { Location.replace(Location.getParameter("targetexisting")); } } } } /** * Form error */ protected void formError(PerunError error) { if (error != null ) { submittedOrError = true; FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); bodyContents.setWidget(ft); if (error.getName().equalsIgnoreCase("ApplicationNotCreatedException")) { // application WAS NOT SAVED ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon())+"<h2>" + ApplicationMessages.INSTANCE.errorWhileCreatingApplication() + "</h2>" + "<p><strong>" + ApplicationMessages.INSTANCE.errorWhileCreatingApplicationMessage() + "</strong></p>"); // back to form button to prevent user from losing data final CustomButton back = new CustomButton("Back", "Back to application form", SmallIcons.INSTANCE.arrowLeftIcon()); ft.setWidget(1, 0, back); ft.getFlexCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_MIDDLE); back.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { submittedOrError = false; bodyContents.setWidget(formContent); } }); } else { // some minor error - application WAS SAVED ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon())+"<h2>" + ApplicationMessages.INSTANCE.errorWhileCreatingApplication() + "</h2>" + "<p><strong>" + ApplicationMessages.INSTANCE.voAdministratorWasNotified() + "</strong>"+ "<p>" + ApplicationMessages.INSTANCE.ifEmailProvidedCheckInbox() + "</p>"); } ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); } } @Override public void menuClick() { // load application only once and also when submitted or on error if (formContent.getWidgetCount() == 0 || submittedOrError) { prepareVoForm(); } else { // do nothing } } /** * Try to find user by name * * If user found, message box shown * * @param jso returned data */ private void tryToFindUserByName(JavaScriptObject jso) { // try to find JsonPostClient jspc = new JsonPostClient(new JsonCallbackEvents(){ @Override public void onFinished(JavaScriptObject jso) { ArrayList<User> users = JsonUtils.<User>jsoAsList(jso); if (users != null && !users.isEmpty()) similarUsersFound(JsonUtils.<User>jsoAsList(jso)); } }); JSONObject query = new JSONObject(); if (jso == null) { // before app submission jspc.sendData("registrarManager/checkForSimilarUsers", query); } else { // after app submission query.put("voId", new JSONNumber(vo.getId())); if (group != null) { query.put("groupId", new JSONNumber(group.getId())); } else { query.put("groupId", new JSONNumber(0)); } query.put("type", new JSONString(type)); jspc.sendData("registrarManager/checkForSimilarUsers", query); } } /** * When similar users found, display a message * * @param users */ protected void similarUsersFound(ArrayList<User> users) { FlexTable ft = new FlexTable(); ft.setWidth("600px"); FlexCellFormatter ftf = ft.getFlexCellFormatter(); ft.setHTML(0, 0, ApplicationMessages.INSTANCE.similarUsersFoundIsItYou() + "<br /><br />"); ftf.setColSpan(0, 0, 3); ft.setHTML(1, 0, "<strong>" + ApplicationMessages.INSTANCE.name() + "</strong>"); ft.setHTML(1, 1, "<strong>" + ApplicationMessages.INSTANCE.email() +"</strong>"); ft.setHTML(1, 2, "<strong>" + ApplicationMessages.INSTANCE.organization() +"</strong>"); int i = 2; for (User user : users) { // skip service users if (!user.isServiceUser()) { ft.setHTML(i, 0, user.getFullNameWithTitles()); if (user.getAttribute("urn:perun:user:attribute-def:def:preferredMail").getValue() == null || user.getAttribute("urn:perun:user:attribute-def:def:preferredMail").getValue().isEmpty()) { ft.setHTML(i, 1, "N/A"); } else { ft.setHTML(i, 1, user.getAttribute("urn:perun:user:attribute-def:def:preferredMail").getValue()); } if (user.getAttribute("urn:perun:user:attribute-def:def:organization").getValue() == null || user.getAttribute("urn:perun:user:attribute-def:def:organization").getValue().isEmpty()) { ft.setHTML(i, 2, "N/A"); } else { ft.setHTML(i, 2, user.getAttribute("urn:perun:user:attribute-def:def:organization").getValue()); } i++; } } // confirm element final Confirm confirm = new Confirm(ApplicationMessages.INSTANCE.similarUsersFound(), ft, new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { Window.Location.replace(Utils.getIdentityConsolidatorLink(true)); } }, true); confirm.setOkButtonText(ApplicationMessages.INSTANCE.joinIdentity()); confirm.setOkIcon(SmallIcons.INSTANCE.userGreenIcon()); confirm.setCancelButtonText(ApplicationMessages.INSTANCE.notJoinIdentity()); confirm.show(); } private final native void positionLinker() /*-{ var linker = $wnd.jQuery("#cesnet_linker_placeholder"); if (!$('#cesnet_linker_placeholder').is(':empty')){ $wnd.jQuery("#cesnet_linker_placeholder").remove(); $wnd.jQuery("body").append(linker); $wnd.jQuery("#appFormGUI").parent().parent().css({"position":"absolute" , "left":"0px" , "top":"40px" , "right":"0px" , "bottom":"0px"}); //$wnd.jQuery("#appFormGUI").css({"position":"absolute" , "left":"0px" , "top":"40px" , "right":"0px" , "bottom":"0px"}); $wnd.jQuery("body").append("<script src=\"https://linker.cesnet.cz/linker.js\" async type=\"text/javascript\">"); } }-*/; }
perun-web-gui/src/main/java/cz/metacentrum/perun/webgui/client/applicationresources/pages/ApplicationFormPage.java
package cz.metacentrum.perun.webgui.client.applicationresources.pages; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.http.client.UrlBuilder; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.ui.*; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import cz.metacentrum.perun.webgui.client.ApplicationFormGui; import cz.metacentrum.perun.webgui.client.PerunWebSession; import cz.metacentrum.perun.webgui.client.applicationresources.SendsApplicationForm; import cz.metacentrum.perun.webgui.client.localization.ApplicationMessages; import cz.metacentrum.perun.webgui.client.resources.*; import cz.metacentrum.perun.webgui.json.JsonCallbackEvents; import cz.metacentrum.perun.webgui.json.JsonPostClient; import cz.metacentrum.perun.webgui.json.JsonUtils; import cz.metacentrum.perun.webgui.json.attributesManager.GetLogins; import cz.metacentrum.perun.webgui.json.registrarManager.CreateApplication; import cz.metacentrum.perun.webgui.json.registrarManager.GetApplicationForm; import cz.metacentrum.perun.webgui.json.registrarManager.GetFormItemsWithPrefilledValues; import cz.metacentrum.perun.webgui.json.usersManager.FindCompleteRichUsers; import cz.metacentrum.perun.webgui.json.usersManager.FindUsersByName; import cz.metacentrum.perun.webgui.model.*; import cz.metacentrum.perun.webgui.widgets.Confirm; import cz.metacentrum.perun.webgui.widgets.CustomButton; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Page with VO application form * * @author Vaclav Mach <374430@mail.muni.cz> */ public class ApplicationFormPage extends ApplicationPage { /** * Main body contents */ private SimplePanel bodyContents = new SimplePanel(); private VerticalPanel formContent = new VerticalPanel(); /** * Data */ private ArrayList<ApplicationFormItemData> data; /** * VO */ private VirtualOrganization vo; /** * Group */ private Group group; /** * session */ private PerunWebSession session = PerunWebSession.getInstance(); /** * Form type */ private String type = "INITIAL"; private ApplicationForm form; /** * Switch languages button */ private PushButton languageButtonCzech; private PushButton languageButtonEnglish; private boolean submittedOrError = false; /** * Creates a new page with application form * * @param vo * @param type INITIAL or EXTENSION */ public ApplicationFormPage(VirtualOrganization vo, Group group, String type) { this.initWidget(bodyContents); this.vo = vo; this.group = group; this.type = type; bodyContents.setSize("100%", "100%"); bodyContents.setStyleName("formContent"); } /** * Prepares the buttons for local languages */ private void prepareToggleLanguageButton() { languageButtonCzech = new PushButton(new Image(SmallIcons.INSTANCE.flagCzechRepublicIcon())); languageButtonCzech.setTitle(ApplicationMessages.INSTANCE.changeLanguageToCzech()); languageButtonCzech.setStyleName("gwt-Button"); languageButtonCzech.setPixelSize(17, 17); languageButtonEnglish = new PushButton(new Image(SmallIcons.INSTANCE.flagGreatBritainIcon())); languageButtonEnglish.setTitle(ApplicationMessages.INSTANCE.changeLanguageToEnglish()); languageButtonEnglish.setStyleName("gwt-Button"); languageButtonEnglish.setPixelSize(17, 17); languageButtonCzech.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Confirm conf = new Confirm(languageButtonCzech.getTitle(), new HTML(ApplicationMessages.INSTANCE.changeLanguageText()), new ClickHandler(){ public void onClick(ClickEvent event) { // on OK UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", "cs"); Window.Location.replace(builder.buildString()); }}, new ClickHandler(){ public void onClick(ClickEvent event) { // on CANCEL } }, true); conf.setNonScrollable(true); conf.show(); } }); languageButtonEnglish.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Confirm conf = new Confirm(languageButtonEnglish.getTitle(), new HTML(ApplicationMessages.INSTANCE.changeLanguageText()), new ClickHandler(){ public void onClick(ClickEvent event) { // on OK UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", "en"); Window.Location.replace(builder.buildString()); }}, new ClickHandler(){ public void onClick(ClickEvent event) { // on CANCEL } }, true); conf.setNonScrollable(true); conf.show(); } }); } /** * Prepares a VO form */ protected void prepareVoForm() { bodyContents.setWidget(formContent); formContent.setStyleName("formContentTable"); submittedOrError = false; // try to get user for VOs initial application (only for authz origin) if (session.getUser() == null && !session.getPerunPrincipal().getExtSource().equalsIgnoreCase("LOCAL")) { tryToFindUserByName(null); } FlexTable header = new FlexTable(); header.setWidth("100%"); header.setCellPadding(5); int row = 0; // display VO logo if present in attribute for (int i=0; i<vo.getAttributes().length(); i++) { if (vo.getAttributes().get(i).getFriendlyName().equalsIgnoreCase("voLogoURL")) { header.setWidget(row, 0, new Image(vo.getAttributes().get(i).getValue())); row++; } } String headerString = ""; // display application header if (type.equalsIgnoreCase("INITIAL")) { if (group != null) { headerString = ApplicationMessages.INSTANCE.applicationFormForGroup(group.getName()); } else { headerString = ApplicationMessages.INSTANCE.applicationFormForVo(vo.getName()); } } else if (type.equalsIgnoreCase("EXTENSION")) { if (group != null) { headerString = ApplicationMessages.INSTANCE.membershipExtensionForGroup(group.getName()); } else { headerString = ApplicationMessages.INSTANCE.membershipExtensionForVo(vo.getName()); } } header.setHTML(row, 0, "<h1>" + headerString + "</h1>"); // language button prepareToggleLanguageButton(); FlexTable lang = new FlexTable(); lang.setWidget(0, 1, languageButtonCzech); lang.setWidget(0, 2, languageButtonEnglish); header.setWidget(0, 1, lang); header.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); formContent.add(header); JsonCallbackEvents jqueryEvent = new JsonCallbackEvents(){ @Override public void onFinished(JavaScriptObject jso) { Scheduler.get().scheduleDeferred(new Command() { @Override public void execute() { positionLinker(); } }); } }; final GetFormItemsWithPrefilledValues fitems; if (group != null) { fitems = new GetFormItemsWithPrefilledValues(PerunEntity.GROUP, group.getId(), jqueryEvent); } else { fitems = new GetFormItemsWithPrefilledValues(PerunEntity.VIRTUAL_ORGANIZATION, vo.getId(), jqueryEvent); } // pass valid app type in URL or use default if (Location.getParameter("type") != null && (Location.getParameter("type").equalsIgnoreCase("INITIAL") || Location.getParameter("type").equalsIgnoreCase("EXTENSION"))) { fitems.setType(Location.getParameter("type").toUpperCase()); } else { fitems.setType(type); } fitems.setHidden(true); fitems.setSendFormHandler(new SendsApplicationForm() { public void sendApplicationForm(CustomButton button) { data = fitems.getValues(); sendForm(button); } }); fitems.retrieveData(); formContent.add(fitems.getContents()); formContent.add(new HTML("<br /><br /><br />")); JsonCallbackEvents formEvent = new JsonCallbackEvents(){ @Override public void onFinished(JavaScriptObject jso) { form = jso.cast(); } }; GetApplicationForm formRequest; if (group != null) { formRequest = new GetApplicationForm(PerunEntity.GROUP, group.getId(), formEvent); } else { formRequest = new GetApplicationForm(PerunEntity.VIRTUAL_ORGANIZATION, vo.getId(), formEvent); } formRequest.retrieveData(); } /** * Send form */ protected void sendForm(final CustomButton button) { PerunPrincipal pp = session.getPerunPrincipal(); // fed info String fedInfo = ""; fedInfo += "{"; fedInfo += " displayName=\"" + pp.getAdditionInformations("displayName")+"\""; fedInfo += " commonName=\"" + pp.getAdditionInformations("cn")+"\""; fedInfo += " givenName=\"" + pp.getAdditionInformations("givenName")+"\""; fedInfo += " sureName=\"" + pp.getAdditionInformations("sn")+"\""; fedInfo += " loa=\"" + pp.getAdditionInformations("loa")+"\""; fedInfo += " mail=\"" + pp.getAdditionInformations("mail")+"\""; fedInfo += " organization=\"" + pp.getAdditionInformations("o")+"\""; fedInfo += " }"; Application app = Application.construct(vo, group, type, fedInfo, pp.getActor(), pp.getExtSource(), pp.getExtSourceType(), pp.getExtSourceLoa()); if (session.getUser() != null) { // set user association if known from perun app.setUser(session.getUser()); } // loading final PopupPanel loadingBox = session.getUiElements().perunLoadingBox(ApplicationMessages.INSTANCE.processing()); // Create application request CreateApplication ca = new CreateApplication(JsonCallbackEvents.disableButtonEvents(button, new JsonCallbackEvents() { @Override public void onLoadingStart() { // show loading box loadingBox.show(); } @Override public void onFinished(JavaScriptObject jso) { loadingBox.hide(); formOk(jso); } @Override public void onError(PerunError err) { loadingBox.hide(); formError(err); } })); // Send the request ca.createApplication(app, data); } /** * Form OK */ protected void formOk(JavaScriptObject jso) { ApplicationFormGui.redrawGuiWithMenu(); submittedOrError = true; if (session.getUser() == null && !session.getPerunPrincipal().getExtSource().equalsIgnoreCase("LOCAL")) { // if not yet user of perun, retry search for similar users after app submit // only for VO initial applications tryToFindUserByName(jso); } Boolean autoApproval = false; if (form != null) { if (type.equalsIgnoreCase("INITIAL")) { autoApproval = form.getAutomaticApproval(); } else if (type.equalsIgnoreCase("EXTENSION")) { autoApproval = form.getAutomaticApprovalExtension(); } } String approveText = ""; if (autoApproval) { approveText = ApplicationMessages.INSTANCE.autoApprovalApplicationText(); } else { approveText = ApplicationMessages.INSTANCE.nonAutoApprovalApplicationText(); } approveText = "<p><strong>" + approveText + "</strong></p>"; // conditional sending of validation email String validationText = ""; ArrayList<ApplicationFormItemData> data = JsonUtils.jsoAsList(jso); for (ApplicationFormItemData item : data) { if ("VALIDATED_EMAIL".equalsIgnoreCase(item.getFormItem().getType())) { // if not verified, email was sent if (!"1".equalsIgnoreCase(item.getAssuranceLevel())) { validationText = "<p>" + ApplicationMessages.INSTANCE.ifEmailProvidedCheckInbox() + "</p>"; } } } if (type.equalsIgnoreCase("INITIAL")) { FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); String succSendText = ApplicationMessages.INSTANCE.applicationSuccessfullySent(vo.getName()); if (group != null) { succSendText = ApplicationMessages.INSTANCE.applicationSuccessfullySent(group.getName()); } ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.acceptIcon())+"<h2>"+ succSendText +"</h2>" + validationText + approveText); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); bodyContents.setWidget(ft); if (Location.getParameter("targetnew") != null) { Location.replace(Location.getParameter("targetnew")); } } else if (type.equalsIgnoreCase("EXTENSION")) { FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.acceptIcon())+"<h2>" + ApplicationMessages.INSTANCE.membershipExtensionSuccessfullySent(vo.getName()) + "</h2>" + approveText); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); bodyContents.setWidget(ft); if (autoApproval) { // automatically extended if (Location.getParameter("targetextended") != null) { Location.replace(Location.getParameter("targetextended")); } } else { // TODO - only when user have valid account if (Location.getParameter("targetexisting") != null) { Location.replace(Location.getParameter("targetexisting")); } } } } /** * Form error */ protected void formError(PerunError error) { if (error != null ) { submittedOrError = true; FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); bodyContents.setWidget(ft); if (error.getName().equalsIgnoreCase("ApplicationNotCreatedException")) { // application WAS NOT SAVED ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon())+"<h2>" + ApplicationMessages.INSTANCE.errorWhileCreatingApplication() + "</h2>" + "<p><strong>" + ApplicationMessages.INSTANCE.errorWhileCreatingApplicationMessage() + "</strong></p>"); // back to form button to prevent user from losing data final CustomButton back = new CustomButton("Back", "Back to application form", SmallIcons.INSTANCE.arrowLeftIcon()); ft.setWidget(1, 0, back); ft.getFlexCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_MIDDLE); back.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { submittedOrError = false; bodyContents.setWidget(formContent); } }); } else { // some minor error - application WAS SAVED ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon())+"<h2>" + ApplicationMessages.INSTANCE.errorWhileCreatingApplication() + "</h2>" + "<p><strong>" + ApplicationMessages.INSTANCE.voAdministratorWasNotified() + "</strong>"+ "<p>" + ApplicationMessages.INSTANCE.ifEmailProvidedCheckInbox() + "</p>"); } ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); } } @Override public void menuClick() { // load application only once and also when submitted or on error if (formContent.getWidgetCount() == 0 || submittedOrError) { prepareVoForm(); } else { // do nothing } } /** * Try to find user by name * * If user found, message box shown * * @param jso returned data */ private void tryToFindUserByName(JavaScriptObject jso) { // try to find JsonPostClient jspc = new JsonPostClient(new JsonCallbackEvents(){ @Override public void onFinished(JavaScriptObject jso) { ArrayList<User> users = JsonUtils.<User>jsoAsList(jso); if (users != null && !users.isEmpty()) similarUsersFound(JsonUtils.<User>jsoAsList(jso)); } }); JSONObject query = new JSONObject(); if (jso == null) { // before app submission jspc.sendData("registrarManager/checkForSimilarUsers", query); } else { // after app submission query.put("voId", new JSONNumber(vo.getId())); if (group != null) { query.put("groupId", new JSONNumber(group.getId())); } else { query.put("groupId", new JSONNumber(0)); } query.put("type", new JSONString(type)); jspc.sendData("registrarManager/checkForSimilarUsers", query); } } /** * When similar users found, display a message * * @param users */ protected void similarUsersFound(ArrayList<User> users) { FlexTable ft = new FlexTable(); ft.setWidth("600px"); FlexCellFormatter ftf = ft.getFlexCellFormatter(); ft.setHTML(0, 0, ApplicationMessages.INSTANCE.similarUsersFoundIsItYou() + "<br /><br />"); ftf.setColSpan(0, 0, 3); ft.setHTML(1, 0, "<strong>" + ApplicationMessages.INSTANCE.name() + "</strong>"); ft.setHTML(1, 1, "<strong>" + ApplicationMessages.INSTANCE.email() +"</strong>"); ft.setHTML(1, 2, "<strong>" + ApplicationMessages.INSTANCE.organization() +"</strong>"); int i = 2; for (User user : users) { // skip service users if (!user.isServiceUser()) { ft.setHTML(i, 0, user.getFullNameWithTitles()); if (user.getAttribute("urn:perun:user:attribute-def:def:preferredMail").getValue() == null || user.getAttribute("urn:perun:user:attribute-def:def:preferredMail").getValue().isEmpty()) { ft.setHTML(i, 1, "N/A"); } else { ft.setHTML(i, 1, user.getAttribute("urn:perun:user:attribute-def:def:preferredMail").getValue()); } if (user.getAttribute("urn:perun:user:attribute-def:def:organization").getValue() == null || user.getAttribute("urn:perun:user:attribute-def:def:organization").getValue().isEmpty()) { ft.setHTML(i, 2, "N/A"); } else { ft.setHTML(i, 2, user.getAttribute("urn:perun:user:attribute-def:def:organization").getValue()); } i++; } } // confirm element final Confirm confirm = new Confirm(ApplicationMessages.INSTANCE.similarUsersFound(), ft, new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { Window.Location.replace(Utils.getIdentityConsolidatorLink(true)); } }, true); confirm.setOkButtonText(ApplicationMessages.INSTANCE.joinIdentity()); confirm.setOkIcon(SmallIcons.INSTANCE.userGreenIcon()); confirm.setCancelButtonText(ApplicationMessages.INSTANCE.notJoinIdentity()); confirm.show(); } private final native void positionLinker() /*-{ var linker = $wnd.jQuery("#cesnet_linker_placeholder"); if (!$('#cesnet_linker_placeholder').is(':empty')){ $wnd.jQuery("#cesnet_linker_placeholder").remove(); $wnd.jQuery("body").append(linker); $wnd.jQuery("#appFormGUI").parent().parent().css({"position":"absolute" , "left":"0px" , "top":"40px" , "right":"0px" , "bottom":"0px"}); //$wnd.jQuery("#appFormGUI").css({"position":"absolute" , "left":"0px" , "top":"40px" , "right":"0px" , "bottom":"0px"}); $wnd.jQuery("body").append("<script src=\"https://linker.cesnet.cz/linker.js\" async type=\"text/javascript\">"); } }-*/; }
GUI: Remove common application form header (kept in menu).
perun-web-gui/src/main/java/cz/metacentrum/perun/webgui/client/applicationresources/pages/ApplicationFormPage.java
GUI: Remove common application form header (kept in menu).
Java
bsd-3-clause
997fcc840301c2133018cec408f6c36fd6911f21
0
NCIP/catissue-core,NCIP/catissue-core,krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen,NCIP/catissue-core,asamgir/openspecimen,krishagni/openspecimen,krishagni/openspecimen
package edu.wustl.catissuecore.actionForm; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.util.global.Validator; /** * orderSpecimenForm for placing an order * * @author deepti_phadnis * */ public class OrderSpecimenForm extends AbstractActionForm { /** * String containing the type of specimen whether existing or derived */ private String typeOfSpecimen = "existingSpecimen"; /** * Map containing the key-value pairs */ private Map values = new HashMap(); /** * String containing the class of specimen */ private String specimenClassName; /** * String containing the type of specimen */ private String specimenType; /** * String array containing the selected items */ private String[] selectedItems = null; /** * String array containing the items to be removed */ private String[] itemsToRemove = null; /** * String containing the unit */ private String unit; /** * OrderForm object */ private OrderForm orderForm; /** * String containing the concentration */ private String concentration; /** * String containing the distrbution Protocol */ private String distrbutionProtocol; /** * String containing the name of array to which to add the specimen */ private String addToArray = ""; /** * List containing Define Array objects */ private List defineArrayObj; /** * @return List of defineArrayObj */ public List getDefineArrayObj() { return defineArrayObj; } /** * @param defineArrayObj List containing Define Array objects */ public void setDefineArrayObj(List defineArrayObj) { this.defineArrayObj = defineArrayObj; } /** * * @return String containing whether speicmens got to be added to list or * array */ public String getAddToArray() { return addToArray; } /** * @param addToArray String containing the name of array to which to add the specimen */ public void setAddToArray(String addToArray) { this.addToArray = addToArray; } // For 'ADD' operation in CommonAddEditAction. /** * @return boolean true */ public boolean isAddOperation() { return true; } /** * @return concentration */ public String getConcentration() { return concentration; } /** * @param concentration String containing the concentration */ public void setConcentration(String concentration) { this.concentration = concentration; } /** * @return unit of requested quantity */ public String getUnit() { return unit; } /** * @param unit String containing the unit */ public void setUnit(String unit) { this.unit = unit; } /** * @return string of specimen selected */ public String[] getSelectedItems() { return this.selectedItems; } /** * @param selectedItems String array containing the selected items */ public void setSelectedItems(String[] selectedItems) { this.selectedItems = selectedItems; } /** * @return typeOfSpecimen i.e.derived or existing */ public String getTypeOfSpecimen() { return typeOfSpecimen; } /** * @param typeOfSpecimen String containing the type of specimen whether existing or derived */ public void setTypeOfSpecimen(String typeOfSpecimen) { this.typeOfSpecimen = typeOfSpecimen; } /** * @param abstractDomain AbstractDomainObject */ public void setAllValues(AbstractDomainObject abstractDomain) { } /** * @return Constants.ORDER_FORM_ID i.e. the FormId */ public int getFormId() { return Constants.ORDER_FORM_ID; } /** * function for resetting */ protected void reset() { this.typeOfSpecimen = null; this.selectedItems = null; } /** ** for map *** */ /** * @param mapping ActionMapping * @param request HttpServletRequest */ public void reset(ActionMapping mapping, HttpServletRequest request) { } /** * @param key String * @param value Object */ public void setValue(String key, Object value) { if (isMutable()) { values.put(key, value); } } /** * @param mapping ActionMapping * @param request HttpServletRequest * @return errors ActionErrors */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); if (selectedItems != null) { boolean isNumber = true; HttpSession session = request.getSession(); List defineArrayFormList = (List) session.getAttribute("DefineArrayFormObjects"); Map dataMap = (Map) session.getAttribute(Constants.REQUESTED_BIOSPECIMENS); DefineArrayForm defineArrayFormObj = null; int capacity = 0; if (defineArrayFormList != null) { defineArrayFormObj = (DefineArrayForm) searchDefineArrayList(defineArrayFormList, addToArray); capacity = Integer.parseInt(defineArrayFormObj.getDimenmsionX()) * Integer.parseInt(defineArrayFormObj.getDimenmsionY()); } if (!addToArray.equalsIgnoreCase("None")) { if (dataMap == null) { if (selectedItems.length > capacity) { errors.add("addToArray", new ActionError("errors.order.capacityless")); values.clear(); } } else { if (dataMap.containsKey(addToArray)) { List orderItems = (List) dataMap.get(addToArray); if (orderItems.size() + selectedItems.length > capacity) { errors.add("addToArray", new ActionError("errors.order.capacityless")); values.clear(); } } else { if (selectedItems.length > capacity) { errors.add("addToArray", new ActionError("errors.order.capacityless")); values.clear(); } } } } if (typeOfSpecimen.equals("true")) { if (specimenClassName.equals("-1") || specimenClassName.equals("-- Select --")) { errors.add("className", new ActionError("errors.specimenClass.required")); values.clear(); } if (specimenType.equals("-1") || specimenType.equals("-- Select --")) { errors.add("type", new ActionError("errors.specimenType.required")); values.clear(); } if (!addToArray.equalsIgnoreCase("None") && defineArrayFormObj != null && !defineArrayFormObj.getArrayClass().equals(specimenClassName)) { errors.add("addToArray", new ActionError("errors.order.properclass")); values.clear(); } } if (values != null && values.size() != 0) { String cnt = null; String key = null; String keyClass = null; int reqQntyError = 0; for (int i = 0; i < selectedItems.length; i++) { cnt = selectedItems[i]; key = "OrderSpecimenBean:" + cnt + "_requestedQuantity"; if ((values.get(key)) == null || (values.get(key)).equals("")) { errors.add("values", new ActionError("errors.requestedQuantity.required")); values.clear(); break; } else { isNumber = isNumeric(values.get(key).toString()); if (!(isNumber)) { errors.add("values", new ActionError( "errors.requestedQuantityBeNumeric.required")); values.clear(); break; } else { Double reqQnty = new Double(values.get(key).toString()); if (reqQnty < 0.0 || reqQnty == 0.0) { errors.add("values", new ActionError( "errors.requestedQuantity.required")); values.clear(); break; } } } keyClass = "OrderSpecimenBean:" + cnt + "_specimenClass"; if (typeOfSpecimen.equals("false") && !addToArray.equalsIgnoreCase("None") && defineArrayFormObj != null && !defineArrayFormObj.getArrayClass().equalsIgnoreCase( values.get(keyClass).toString())) { errors.add("addToArray", new ActionError("errors.order.properclass")); values.clear(); break; } } } } return errors; } /** * @param sText String containing the text to be checked * @return boolean isNumber -true if given String is in proper number * format or else returns false */ private boolean isNumeric(String sText) { String validChars = "0123456789."; boolean isNumber = true; Character charTemp; for (int i = 0; i < sText.length() && isNumber; i++) { charTemp = sText.charAt(i); if (validChars.indexOf(charTemp) == -1) { isNumber = false; } } return isNumber; } /** * @param defineArrayFormList List containing DefineArrayForm objects * @param arrayName String containing name of array * @return defineArrayFormObj */ private DefineArrayForm searchDefineArrayList(List defineArrayFormList, String arrayName) { Iterator iter = defineArrayFormList.iterator(); DefineArrayForm defineArrayFormObj = null; while (iter.hasNext()) { defineArrayFormObj = (DefineArrayForm) iter.next(); if (defineArrayFormObj.getArrayName().equalsIgnoreCase(arrayName)) { break; } } return defineArrayFormObj; } /** * @param key String * @return Object */ public Object getValue(String key) { return values.get(key); } /** * @return values in map */ public Collection getAllValues() { return values.values(); } /** * @param values Map containing key-value pairs */ public void setValues(Map values) { this.values = values; } /** * @return Map */ public Map getValues() { return this.values; } /** * @return specimens to be removed */ public String[] getItemsToRemove() { return itemsToRemove; } /** * @param itemsToRemove String array containing the items to be removed */ public void setItemsToRemove(String[] itemsToRemove) { this.itemsToRemove = itemsToRemove; } /** * @return OrderForm */ public OrderForm getOrderForm() { return orderForm; } /** * @param orderForm OrderForm object */ public void setOrderForm(OrderForm orderForm) { this.orderForm = orderForm; } /** * @return name of distribution protocol */ public String getDistrbutionProtocol() { return distrbutionProtocol; } /** * @param distrbutionProtocol String containing the distrbution Protocol */ public void setDistrbutionProtocol(String distrbutionProtocol) { this.distrbutionProtocol = distrbutionProtocol; } /** * @return specimenClassName */ public String getSpecimenClassName() { return specimenClassName; } /** * @param specimenClassName String containing the class of specimen */ public void setSpecimenClassName(String specimenClassName) { this.specimenClassName = specimenClassName; } /** * @return specimenType */ public String getSpecimenType() { return specimenType; } /** * @param specimenType String containing the type of specimen */ public void setSpecimenType(String specimenType) { this.specimenType = specimenType; } }
WEB-INF/src/edu/wustl/catissuecore/actionForm/OrderSpecimenForm.java
package edu.wustl.catissuecore.actionForm; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.util.global.Validator; import edu.wustl.catissuecore.actionForm.DefineArrayForm; /** * orderSpecimenForm for placing an order * * @author deepti_phadnis * */ public class OrderSpecimenForm extends AbstractActionForm { /** * String containing the type of specimen whether existing or derived */ private String typeOfSpecimen = "existingSpecimen"; /** * Map containing the key-value pairs */ private Map values = new HashMap(); /** * String containing the class of specimen */ private String specimenClassName; /** * String containing the type of specimen */ private String specimenType; /** * String array containing the selected items */ private String[] selectedItems = null; /** * String array containing the items to be removed */ private String[] itemsToRemove = null; /** * String containing the unit */ private String unit; /** * OrderForm object */ private OrderForm orderForm; /** * String containing the concentration */ private String concentration; /** * String containing the distrbution Protocol */ private String distrbutionProtocol; /** * String containing the name of array to which to add the specimen */ private String addToArray = ""; /** * List containing Define Array objects */ private List defineArrayObj; /** * @return List of defineArrayObj */ public List getDefineArrayObj() { return defineArrayObj; } /** * @param defineArrayObj List containing Define Array objects */ public void setDefineArrayObj(List defineArrayObj) { this.defineArrayObj = defineArrayObj; } /** * * @return String containing whether speicmens got to be added to list or * array */ public String getAddToArray() { return addToArray; } /** * @param addToArray String containing the name of array to which to add the specimen */ public void setAddToArray(String addToArray) { this.addToArray = addToArray; } // For 'ADD' operation in CommonAddEditAction. /** * @return boolean true */ public boolean isAddOperation() { return true; } /** * @return concentration */ public String getConcentration() { return concentration; } /** * @param concentration String containing the concentration */ public void setConcentration(String concentration) { this.concentration = concentration; } /** * @return unit of requested quantity */ public String getUnit() { return unit; } /** * @param unit String containing the unit */ public void setUnit(String unit) { this.unit = unit; } /** * @return string of specimen selected */ public String[] getSelectedItems() { return this.selectedItems; } /** * @param selectedItems String array containing the selected items */ public void setSelectedItems(String[] selectedItems) { this.selectedItems = selectedItems; } /** * @return typeOfSpecimen i.e.derived or existing */ public String getTypeOfSpecimen() { return typeOfSpecimen; } /** * @param typeOfSpecimen String containing the type of specimen whether existing or derived */ public void setTypeOfSpecimen(String typeOfSpecimen) { this.typeOfSpecimen = typeOfSpecimen; } /** * @param abstractDomain AbstractDomainObject */ public void setAllValues(AbstractDomainObject abstractDomain) { } /** * @return Constants.ORDER_FORM_ID i.e. the FormId */ public int getFormId() { return Constants.ORDER_FORM_ID; } /** * function for resetting */ protected void reset() { this.typeOfSpecimen = null; this.selectedItems = null; } /** ** for map *** */ /** * @param mapping ActionMapping * @param request HttpServletRequest */ public void reset(ActionMapping mapping, HttpServletRequest request) { } /** * @param key String * @param value Object */ public void setValue(String key, Object value) { if (isMutable()) { values.put(key, value); } } /** * @param mapping ActionMapping * @param request HttpServletRequest * @return errors ActionErrors */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); if (selectedItems != null) { boolean isNumber = true; HttpSession session = request.getSession(); List defineArrayFormList = (List) session.getAttribute("DefineArrayFormObjects"); Map dataMap = (Map) session.getAttribute(Constants.REQUESTED_BIOSPECIMENS); DefineArrayForm defineArrayFormObj = null; int capacity = 0; if (defineArrayFormList != null) { defineArrayFormObj = (DefineArrayForm) searchDefineArrayList(defineArrayFormList, addToArray); capacity = Integer.parseInt(defineArrayFormObj.getDimenmsionX()) * Integer.parseInt(defineArrayFormObj.getDimenmsionY()); } if (!addToArray.equalsIgnoreCase("None")) { if (dataMap == null) { if (selectedItems.length > capacity) { errors.add("addToArray", new ActionError("errors.order.capacityless")); values.clear(); } } else { if (dataMap.containsKey(addToArray)) { List orderItems = (List) dataMap.get(addToArray); if (orderItems.size() + selectedItems.length > capacity) { errors.add("addToArray", new ActionError("errors.order.capacityless")); values.clear(); } } else { if (selectedItems.length > capacity) { errors.add("addToArray", new ActionError("errors.order.capacityless")); values.clear(); } } } } if (typeOfSpecimen.equals("true")) { if (specimenClassName.equals("-1") || specimenClassName.equals("-- Select --")) { errors.add("className", new ActionError("errors.specimenClass.required")); values.clear(); } if (specimenType.equals("-1") || specimenType.equals("-- Select --")) { errors.add("type", new ActionError("errors.specimenType.required")); values.clear(); } if (!addToArray.equalsIgnoreCase("None") && defineArrayFormObj != null && !defineArrayFormObj.getArrayClass().equals(specimenClassName)) { errors.add("addToArray", new ActionError("errors.order.properclass")); values.clear(); } } if (values != null && values.size() != 0) { String cnt = null; String key = null; String keyClass = null; int reqQntyError = 0; for (int i = 0; i < selectedItems.length; i++) { cnt = selectedItems[i]; key = "OrderSpecimenBean:" + cnt + "_requestedQuantity"; if ((values.get(key)) == null || (values.get(key)).equals("")) { errors.add("values", new ActionError("errors.requestedQuantity.required")); values.clear(); break; } else { isNumber = isNumeric(values.get(key).toString()); if (!(isNumber)) { errors.add("values", new ActionError( "errors.requestedQuantityBeNumeric.required")); values.clear(); break; } else { Double reqQnty = new Double(values.get(key).toString()); if (reqQnty < 0.0 || reqQnty == 0.0) { errors.add("values", new ActionError( "errors.requestedQuantity.required")); values.clear(); break; } } } keyClass = "OrderSpecimenBean:" + cnt + "_specimenClass"; if (typeOfSpecimen.equals("false") && !addToArray.equalsIgnoreCase("None") && defineArrayFormObj != null && !defineArrayFormObj.getArrayClass().equalsIgnoreCase( values.get(keyClass).toString())) { errors.add("addToArray", new ActionError("errors.order.properclass")); values.clear(); break; } } } } return errors; } /** * @param sText String containing the text to be checked * @return boolean isNumber -true if given String is in proper number * format or else returns false */ private boolean isNumeric(String sText) { String validChars = "0123456789."; boolean isNumber = true; Character charTemp; for (int i = 0; i < sText.length() && isNumber; i++) { charTemp = sText.charAt(i); if (validChars.indexOf(charTemp) == -1) { isNumber = false; } } return isNumber; } /** * @param defineArrayFormList List containing DefineArrayForm objects * @param arrayName String containing name of array * @return defineArrayFormObj */ private DefineArrayForm searchDefineArrayList(List defineArrayFormList, String arrayName) { Iterator iter = defineArrayFormList.iterator(); DefineArrayForm defineArrayFormObj = null; while (iter.hasNext()) { defineArrayFormObj = (DefineArrayForm) iter.next(); if (defineArrayFormObj.getArrayName().equalsIgnoreCase(arrayName)) { break; } } return defineArrayFormObj; } /** * @param key String * @return Object */ public Object getValue(String key) { return values.get(key); } /** * @return values in map */ public Collection getAllValues() { return values.values(); } /** * @param values Map containing key-value pairs */ public void setValues(Map values) { this.values = values; } /** * @return Map */ public Map getValues() { return this.values; } /** * @return specimens to be removed */ public String[] getItemsToRemove() { return itemsToRemove; } /** * @param itemsToRemove String array containing the items to be removed */ public void setItemsToRemove(String[] itemsToRemove) { this.itemsToRemove = itemsToRemove; } /** * @return OrderForm */ public OrderForm getOrderForm() { return orderForm; } /** * @param orderForm OrderForm object */ public void setOrderForm(OrderForm orderForm) { this.orderForm = orderForm; } /** * @return name of distribution protocol */ public String getDistrbutionProtocol() { return distrbutionProtocol; } /** * @param distrbutionProtocol String containing the distrbution Protocol */ public void setDistrbutionProtocol(String distrbutionProtocol) { this.distrbutionProtocol = distrbutionProtocol; } /** * @return specimenClassName */ public String getSpecimenClassName() { return specimenClassName; } /** * @param specimenClassName String containing the class of specimen */ public void setSpecimenClassName(String specimenClassName) { this.specimenClassName = specimenClassName; } /** * @return specimenType */ public String getSpecimenType() { return specimenType; } /** * @param specimenType String containing the type of specimen */ public void setSpecimenType(String specimenType) { this.specimenType = specimenType; } }
checkstyle changes SVN-Revision: 6899
WEB-INF/src/edu/wustl/catissuecore/actionForm/OrderSpecimenForm.java
checkstyle changes
Java
bsd-3-clause
62e2877cf5b824a30abc794abbe97d02463214e5
0
lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon
/* * $Id: PluginManager.java,v 1.80 2004-04-27 19:38:02 tlipkis Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin; import java.util.*; import java.io.IOException; import org.lockss.daemon.*; import org.lockss.daemon.status.*; import org.lockss.poller.*; import org.lockss.util.*; import org.lockss.app.BaseLockssManager; import org.lockss.plugin.definable.DefinablePlugin; /** * Plugin global functionality * * @author TAL * @version 0.0 */ public class PluginManager extends BaseLockssManager { public static final String PARAM_AU_TREE = Configuration.PREFIX + "au"; private static String PARAM_PLUGIN_LOCATION = Configuration.PREFIX + "platform.pluginDir"; static String PARAM_PLUGIN_REGISTRY = Configuration.PREFIX + "plugin.registry"; static String PARAM_PLUGIN_XML_PLUGINS = Configuration.PREFIX + "plugin.xmlPlugins"; static String PARAM_REMOVE_STOPPED_AUS = Configuration.PREFIX + "plugin.removeStoppedAus"; static boolean DEFAULT_REMOVE_STOPPED_AUS = true; static final String PARAM_TITLE_DB = ConfigManager.PARAM_TITLE_DB; static final String AU_PARAM_WRAPPER = "reserved.wrapper"; public static final String AU_PARAM_DISABLED = "reserved.disabled"; public static final String AU_PARAM_DISPLAY_NAME = "reserved.displayName"; static final String CONFIGURABLE_PLUGIN_NAME = DefinablePlugin.class.getName(); private static Logger log = Logger.getLogger("PluginMgr"); private ConfigManager configMgr; private StatusService statusSvc; private String pluginDir = null; private AuOrderComparator auComparator = new AuOrderComparator(); // maps plugin key(not id) to plugin private Map pluginMap = Collections.synchronizedMap(new HashMap()); private Map auMap = Collections.synchronizedMap(new HashMap()); private Set auSet = Collections.synchronizedSet(new TreeSet(auComparator)); private Set inactiveAuIds = Collections.synchronizedSet(new HashSet()); private List xmlPlugins = Collections.EMPTY_LIST; public PluginManager() { } /* ------- LockssManager implementation ------------------ */ /** * start the plugin manager. * @see org.lockss.app.LockssManager#startService() */ public void startService() { super.startService(); configMgr = getDaemon().getConfigManager(); statusSvc = getDaemon().getStatusService(); // statusSvc.registerStatusAccessor("AUS", new Status()); resetConfig(); // causes setConfig to think previous config was empty } /** * stop the plugin manager * @see org.lockss.app.LockssManager#stopService() */ public void stopService() { // tk - checkpoint if nec. for (Iterator iter = pluginMap.values().iterator(); iter.hasNext(); ) { Plugin plugin = (Plugin)iter.next(); plugin.stopPlugin(); } super.stopService(); } Configuration currentAllPlugs = ConfigManager.EMPTY_CONFIGURATION; protected void setConfig(Configuration config, Configuration oldConfig, Set changedKeys) { pluginDir = config.get(PARAM_PLUGIN_LOCATION); // Must load the xml plugin list *before* the plugin registry if (changedKeys.contains(PARAM_PLUGIN_XML_PLUGINS)) { xmlPlugins = StringUtil.breakAt(config.get(PARAM_PLUGIN_XML_PLUGINS), ';', 0, true); } // Don't load or start plugins until the daemon is running. if (isDaemonInited()) { // Process the plugin registry. if (changedKeys.contains(PARAM_PLUGIN_REGISTRY)) { initPluginRegistry(config.get(PARAM_PLUGIN_REGISTRY)); } Configuration allPlugs = config.getConfigTree(PARAM_AU_TREE); if (!allPlugs.equals(currentAllPlugs)) { for (Iterator iter = allPlugs.nodeIterator(); iter.hasNext(); ) { String pluginKey = (String)iter.next(); log.debug("Configuring plugin key: " + pluginKey); Configuration pluginConf = allPlugs.getConfigTree(pluginKey); Configuration prevPluginConf = currentAllPlugs.getConfigTree(pluginKey); configurePlugin(pluginKey, pluginConf, prevPluginConf); } currentAllPlugs = allPlugs; } } } /** * Convert plugin property key to plugin class name. * @param key the key * @return the plugin name */ public static String pluginNameFromKey(String key) { return StringUtil.replaceString(key, "|", "."); } /** * Convert plugin class name to key suitable for property file. * @param className the class name * @return the plugin key */ public static String pluginKeyFromName(String className) { return StringUtil.replaceString(className, ".", "|"); } /** * Convert plugin id to key suitable for property file. Plugin id is * currently the same as plugin class name, but that may change. * @param id the plugin id * @return String the plugin key */ public static String pluginKeyFromId(String id) { // tk - needs to do real mapping from IDs obtained from all available // plugins. return StringUtil.replaceString(id, ".", "|"); } /** * Return a unique identifier for an au based on its plugin id and defining * properties. * @param pluginId plugin id (with . not escaped) * @param auDefProps Properties with values for all definitional AU params * @return a unique identifier for an au based on its plugin id and defining * properties. */ public static String generateAuId(String pluginId, Properties auDefProps) { return generateAuId(pluginId, PropUtil.propsToCanonicalEncodedString(auDefProps)); } public static String generateAuId(Plugin plugin, Configuration auConfig) { Properties props = new Properties(); for (Iterator iter = plugin.getAuConfigDescrs().iterator(); iter.hasNext();) { ConfigParamDescr descr = (ConfigParamDescr)iter.next(); if (descr.isDefinitional()) { String key = descr.getKey(); props.setProperty(key, auConfig.get(key)); } } return generateAuId(plugin.getPluginId(), props); } static String generateAuId(String pluginId, String auKey) { return pluginKeyFromId(pluginId)+"&"+auKey; } public static String auKeyFromAuId(String auid) { int pos = auid.indexOf("&"); if (pos < 0) { throw new IllegalArgumentException("Illegal AuId: " + auid); } return auid.substring(pos + 1); } public static String pluginIdFromAuId(String auid) { int pos = auid.indexOf("&"); if (pos < 0) { throw new IllegalArgumentException("Illegal AuId: " + auid); } return auid.substring(0, pos); } public static String pluginNameFromAuId(String auid) { return pluginNameFromKey(pluginIdFromAuId(auid)); } public static String configKeyFromAuId(String auid) { return StringUtil.replaceFirst(auid, "&", "."); } /** * Return the plugin with the given key. * @param pluginKey the plugin key * @return the plugin or null */ public Plugin getPlugin(String pluginKey) { return (Plugin)pluginMap.get(pluginKey); } /** * Returns true if the reserved.wrapper key is true * @param auConf the Configuration * @return true if wrapped */ private boolean isAuWrapped(Configuration auConf) { return WrapperState.isUsingWrapping() && auConf.getBoolean(AU_PARAM_WRAPPER, false); } private Configuration removeWrapper(Configuration auConf) { Configuration copy = auConf.copy(); if (copy.containsKey(AU_PARAM_WRAPPER)) { copy.remove(AU_PARAM_WRAPPER); } return copy; } private void configurePlugin(String pluginKey, Configuration pluginConf, Configuration oldPluginConf) { for (Iterator iter = pluginConf.nodeIterator(); iter.hasNext(); ) { String auKey = (String)iter.next(); String auId = generateAuId(pluginKey, auKey); try { Configuration auConf = pluginConf.getConfigTree(auKey); Configuration oldAuConf = oldPluginConf.getConfigTree(auKey); if (auConf.getBoolean(AU_PARAM_DISABLED, false)) { // tk should actually remove AU? log.debug("Not configuring disabled AU id: " + auKey); if (auMap.get(auId) == null) { // don't add to inactive if it's still running inactiveAuIds.add(auId); } } else if (!auConf.equals(oldAuConf)) { log.debug("Configuring AU id: " + auKey); if (!isAuWrapped(auConf)) { boolean pluginOk = ensurePluginLoaded(pluginKey); if (pluginOk) { Plugin plugin = getPlugin(pluginKey); if (WrapperState.isWrappedPlugin(plugin)) { throw new ArchivalUnit.ConfigurationException("An attempt was made to have load unwrapped " + auKey + " from plugin " + pluginKey + " which is already wrapped."); } configureAu(plugin, auConf, auId); } else { log.warning("Not configuring AU " + auKey); } } else { log.debug("Wrapping " + auKey); if ((pluginMap.containsKey(pluginKey)) && (!WrapperState.isWrappedPlugin(pluginMap.get(pluginKey)))) { throw new ArchivalUnit.ConfigurationException("An attempt was made to wrap AU " + auKey + " from plugin " + pluginKey + " which is already loaded."); } Plugin wrappedPlugin = WrapperState.retrieveWrappedPlugin(pluginKey, theDaemon); if (wrappedPlugin==null) { log.warning("Not configuring AU " + auKey); log.error("Error instantiating " + WrapperState.WRAPPED_PLUGIN_NAME); } else { setPlugin(pluginKey,wrappedPlugin); Configuration wrappedAuConf = removeWrapper(auConf); configureAu(wrappedPlugin, wrappedAuConf, auId); } } inactiveAuIds.remove(generateAuId(pluginKey, auKey)); } else { log.debug("AU already configured, not reconfiguring: " + auKey); } } catch (ArchivalUnit.ConfigurationException e) { log.error("Failed to configure AU " + auKey, e); } catch (Exception e) { log.error("Unexpected exception configuring AU " + auKey, e); } } } void configureAu(Plugin plugin, Configuration auConf, String auId) throws ArchivalUnit.ConfigurationException { try { ArchivalUnit au = plugin.configureAu(auConf, (ArchivalUnit)auMap.get(auId)); log.debug("Configured AU " + au); try { getDaemon().startOrReconfigureAuManagers(au, auConf); } catch (Exception e) { throw new ArchivalUnit.ConfigurationException("Couldn't configure AU managers", e); } log.debug("putAuMap(" + au.getAuId() +", " + au); if (!auId.equals(au.getAuId())) { throw new ArchivalUnit.ConfigurationException("Configured AU has " +"unexpected AUId, " +"is: "+au.getAuId() +" expected: "+auId); } putAuInMap(au); } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error configuring AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } ArchivalUnit createAu(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException { String auid = null; ArchivalUnit oldAu = null; try { auid = generateAuId(plugin, auConf); oldAu = getAuFromId(auid); } catch (Exception e) { // no action. Bad/missing config value might cause getAuFromId() to // throw. It will be caught soon when creating the AU; for now we // can assume it means the AU doesn't already exist. } if (oldAu != null) { inactiveAuIds.remove(oldAu.getAuId()); throw new ArchivalUnit.ConfigurationException("Cannot create that AU because it already exists"); } try { ArchivalUnit au = plugin.createAu(auConf); inactiveAuIds.remove(au.getAuId()); log.debug("Created AU " + au); try { getDaemon().startOrReconfigureAuManagers(au, auConf); } catch (Exception e) { log.error("Couldn't start AU processes", e); throw new ArchivalUnit.ConfigurationException("Couldn't start AU processes", e); } log.debug("putAuMap(" + au.getAuId() +", " + au); putAuInMap(au); return au; } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error creating AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } /** Stop the AU's activity and remove it, as though it had never been * configured. Does not affect the AU's current repository contents. * @return true if the AU was removed, false if it didn't exist or is * stale. */ public boolean stopAu(ArchivalUnit au) { String auid = au.getAuId(); ArchivalUnit mapAu = (ArchivalUnit)auMap.get(auid); if (mapAu == null) { log.warning("stopAu(" + au.getName() + "), wasn't in map"); return false; } if (mapAu != au) { log.warning("stopAu(" + au.getName() + "), but map contains " + mapAu); return false; } log.debug("Deactivating AU: " + au.getName()); // remove from map first, so no new activity can start (poll messages, // RemoteAPI, etc.) auMap.remove(auid); auSet.remove(au); theDaemon.getPollManager().cancelAuPolls(au); theDaemon.getCrawlManager().cancelAuCrawls(au); try { // Plugin plugin = au.getPlugin(); // plugin.removeAu(au); theDaemon.stopAuManagers(au); } catch (Exception e) { // Shouldn't happen, as stopAuManagers() catches errors in // stopService(). Not clear what to do anyway, if some of the // managers don't stop cleanly. } return true; } protected void putAuInMap(ArchivalUnit au) { auMap.put(au.getAuId(), au); auSet.add(au); } public ArchivalUnit getAuFromId(String auId) { ArchivalUnit au = (ArchivalUnit)auMap.get(auId); log.debug3("getAu(" + auId + ") = " + au); return au; } // These don't belong here /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAuConfiguration(ArchivalUnit au, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { setAndSaveAuConfiguration(au, ConfigManager.fromProperties(auProps)); } /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAuConfiguration(ArchivalUnit au, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Reconfiguring AU " + au); au.setConfiguration(auConf); updateAuConfigFile(au, auConf); } private void updateAuConfigFile(ArchivalUnit au, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { String auid = au.getAuId(); String prefix = PARAM_AU_TREE + "." + configKeyFromAuId(auid); Configuration fqConfig = auConf.addPrefix(prefix); configMgr.updateAuConfigFile(fqConfig, prefix); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAuConfiguration(Plugin plugin, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { return createAndSaveAuConfiguration(plugin, ConfigManager.fromProperties(auProps)); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAuConfiguration(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { ArchivalUnit au = createAu(plugin, auConf); updateAuConfigFile(au, auConf); return au; } /** * Delete AU configuration from the local config file. Need to find a * better place for this. * @param au the ArchivalUnit to be unconfigured * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deleteAuConfiguration(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Deleting AU config: " + au); updateAuConfigFile(au, ConfigManager.EMPTY_CONFIGURATION); } /** * Deactivate an AU in the config file. Does not actually stop the AU. * @param au the ArchivalUnit to be deactivated * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deactivateAuConfiguration(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Deactivating AU: " + au); Configuration config = getStoredAuConfiguration(au); config.put(AU_PARAM_DISABLED, "true"); config.put(AU_PARAM_DISPLAY_NAME, au.getName()); updateAuConfigFile(au, config); } /** * Delete an AU * @param au the ArchivalUnit to be deleted * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deleteAu(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { deleteAuConfiguration(au); if (isRemoveStoppedAus()) { stopAu(au); } } /** * Deactivate an AU * @param au the ArchivalUnit to be deactivated * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deactivateAu(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { deactivateAuConfiguration(au); if (isRemoveStoppedAus()) { String auid = au.getAuId(); stopAu(au); inactiveAuIds.add(auid); } } public boolean isRemoveStoppedAus() { return configMgr.getBooleanParam(PARAM_REMOVE_STOPPED_AUS, DEFAULT_REMOVE_STOPPED_AUS); } /** * Return the stored config info for an AU (from config file, not from * AU instance). * @param au the ArchivalUnit * @return the AU's Configuration, with unprefixed keys. */ public Configuration getStoredAuConfiguration(ArchivalUnit au) { return getStoredAuConfiguration(au.getAuId()); } /** * Return the config tree for an AU id (from the local au config file, * not the au itself). * @param auid the AU's id. * @return the AU's Configuration, with unprefixed keys. */ public Configuration getStoredAuConfiguration(String auid) { String aukey = configKeyFromAuId(auid); Configuration config = configMgr.readAuConfigFile(); String prefix = PARAM_AU_TREE + "." + aukey; return config.getConfigTree(prefix); } Plugin retrievePlugin(String pluginKey) throws Exception { if (pluginMap.containsKey(pluginKey)) { return (Plugin)pluginMap.get(pluginKey); } String pluginName = pluginNameFromKey(pluginKey); String confFile = null; if (xmlPlugins.contains(pluginName)) { confFile = pluginName; pluginName = getConfigurablePluginName(); } Class pluginClass; try { pluginClass = Class.forName(pluginName); } catch (ClassNotFoundException e) { log.debug(pluginName + " not on classpath"); // not on classpath try { // tk - search plugin dir for signed jar, try loading again throw e; // for now, simulate failure of that process } catch (ClassNotFoundException e1) { // plugin is really not available log.error(pluginName + " not found"); return null; } } catch (Exception e) { // any other exception while loading class if not recoverable log.error("Error loading " + pluginName, e); return null; } Plugin plugin = (Plugin) pluginClass.newInstance(); if (confFile != null && plugin instanceof DefinablePlugin) { log.debug("Instantiating Configurable plugin from " + confFile); ((DefinablePlugin)plugin).initPlugin(theDaemon, confFile); } else { log.debug("Instantiating " + pluginClass); plugin.initPlugin(theDaemon); } return plugin; } /** * Load a plugin with the given class name from somewhere in our classpath * @param pluginKey the key for this plugin * @return true if loaded */ public boolean ensurePluginLoaded(String pluginKey) { if (pluginMap.containsKey(pluginKey)) { return true; } String pluginName = ""; try { pluginName = pluginNameFromKey(pluginKey); Plugin plugin = retrievePlugin(pluginKey); if (plugin != null) { setPlugin(pluginKey, plugin); return true; } else { return false; } } catch (Exception e) { log.error("Error instantiating " + pluginName, e); return false; } } // separate method so can be called by test code protected void setPlugin(String pluginKey, Plugin plugin) { if (log.isDebug3()) { log.debug3("PluginManager.setPlugin(" + pluginKey + ", " + plugin.getPluginName() + ")"); } pluginMap.put(pluginKey, plugin); resetTitles(); } protected String getConfigurablePluginName() { return CONFIGURABLE_PLUGIN_NAME; } /** * Find the CachedUrlSet from a PollSpec. * @param spec the PollSpec (from an incoming message) * @return a CachedUrlSet for the plugin, au and URL in the spec, or * null if au not present on this cache */ public CachedUrlSet findCachedUrlSet(PollSpec spec) { if (log.isDebug3()) log.debug3(this +".findCachedUrlSet2("+spec+")"); String auId = spec.getAuId(); ArchivalUnit au = getAuFromId(auId); if (log.isDebug3()) log.debug3("au: " + au); if (au == null) return null; Plugin plugin = au.getPlugin(); String url = spec.getUrl(); CachedUrlSet cus; if (AuUrl.isAuUrl(url)) { cus = au.getAuCachedUrlSet(); } else if ((spec.getLwrBound()!=null) && (spec.getLwrBound().equals(PollSpec.SINGLE_NODE_LWRBOUND))) { cus = plugin.makeCachedUrlSet(au, new SingleNodeCachedUrlSetSpec(url)); } else { RangeCachedUrlSetSpec rcuss = new RangeCachedUrlSetSpec(url, spec.getLwrBound(), spec.getUprBound()); cus = plugin.makeCachedUrlSet(au, rcuss); } if (log.isDebug3()) log.debug3("ret cus: " + cus); return cus; } /** * Searches all ArchivalUnits to find the most recent CachedUrl for the URL. * @param url The URL to search for. * @return a CachedUrl, or null if URL not present in any AU */ public CachedUrl findMostRecentCachedUrl(String url) { CachedUrl best = null; for (Iterator iter = getAllAus().iterator(); iter.hasNext();) { ArchivalUnit au = (ArchivalUnit)iter.next(); Plugin plugin = au.getPlugin(); if (au.shouldBeCached(url)) { CachedUrl cu = plugin.makeCachedUrl(au.getAuCachedUrlSet(), url); if (cu != null && cu.hasContent() && cuNewerThan(cu, best)) { best = cu; } } } return best; } // return true if cu1 is newer than cu2, or cu2 is null // tk - no date available for comparison yet, return arbitrary order private boolean cuNewerThan(CachedUrl cu1, CachedUrl cu2) { if (cu2 == null) return true; CIProperties p1 = cu1.getProperties(); CIProperties p2 = cu2.getProperties(); // tk - this should use the crawl-date prop taht the crawler will add // Long.parseLong(p1.getProperty(HttpFields.__LastModified, "-1")); return true; } /** * Return a list of all configured ArchivalUnits. * @return the List of aus */ public List getAllAus() { return new ArrayList(auSet); } public Collection getInactiveAuIds() { return inactiveAuIds; } /** Return all the known titles from the title db, sorted by title */ public List findAllTitles() { if (allTitles == null) { allTitles = new ArrayList(getTitleMap().keySet()); Collections.sort(allTitles, auComparator.coc); } return allTitles; } /** Find all the plugins that support the given title */ public Collection getTitlePlugins(String title) { return (Collection)getTitleMap().get(title); } private Map titleMap = null; private List allTitles = null; public void resetTitles() { titleMap = null; allTitles = null; } public Map getTitleMap() { if (titleMap == null) { titleMap = buildTitleMap(); } return titleMap; } Map buildTitleMap() { Map map = new org.apache.commons.collections.MultiHashMap(); synchronized (pluginMap) { for (Iterator iter = getRegisteredPlugins().iterator(); iter.hasNext();) { Plugin p = (Plugin)iter.next(); Collection titles = p.getSupportedTitles(); for (Iterator iter2 = titles.iterator(); iter2.hasNext();) { String title = (String)iter2.next(); if (title != null) { map.put(title, p); } } } } return map; } /** Return a SortedMap mapping (human readable) plugin name to plugin * instance */ public SortedMap getPluginNameMap() { SortedMap pMap = new TreeMap(); synchronized (pluginMap) { for (Iterator iter = getRegisteredPlugins().iterator(); iter.hasNext(); ) { Plugin p = (Plugin)iter.next(); pMap.put(p.getPluginName(), p); } } return pMap; } /** @return All plugins that have been registered. <i>Ie</i>, that are * either listed in org.lockss.plugin.registry, or were loaded by a * configured AU */ public Collection getRegisteredPlugins() { return pluginMap.values(); } /** @return list of xml plugin names. For testing only. */ List getXmlPlugins() { return xmlPlugins; } // Synch the plugin registry with the plugins listed in names void initPluginRegistry(String names) { Collection newKeys = new HashSet(); List nameList = StringUtil.breakAt(names, ';', 0, true); for (Iterator iter = nameList.iterator(); iter.hasNext(); ) { String name = (String)iter.next(); String key = pluginKeyFromName(name); ensurePluginLoaded(key); newKeys.add(key); } // remove plugins that are no longer listed, unless they have one or // more configured AUs synchronized (pluginMap) { for (Iterator iter = pluginMap.keySet().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); String key = pluginKeyFromName(name); if (!newKeys.contains(key)) { Configuration tree = currentAllPlugs.getConfigTree(key); if (tree == null || tree.isEmpty()) { iter.remove(); } } } } } /** Comparator for sorting Aus alphabetically by title. This is used in a * TreeSet, so must return 0 only for identical objects. */ class AuOrderComparator implements Comparator { CatalogueOrderComparator coc = new CatalogueOrderComparator(); public int compare(Object o1, Object o2) { if (o1 == o2) { return 0; } if (!((o1 instanceof ArchivalUnit) && (o2 instanceof ArchivalUnit))) { throw new IllegalArgumentException("AuOrderComparator(" + o1.getClass() + "," + o2.getClass() + ")"); } ArchivalUnit a1 = (ArchivalUnit)o1; ArchivalUnit a2 = (ArchivalUnit)o2; int res = coc.compare(a1.getName(), a2.getName()); if (res == 0) { res = coc.compare(a1.getAuId(), a2.getAuId()); } if (res == 0) { // this can happen during testing. Don't care about order, but // mustn't be equal. res = 1; } return res; } } private class Status implements StatusAccessor { private final List sortRules = ListUtil.list(new StatusTable.SortRule("au", true)); private final List colDescs = ListUtil.list( new ColumnDescriptor("au", "Journal Volume", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("poll", "Poll Status", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("crawl", "Crawl Status", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("auid", "AUID", ColumnDescriptor.TYPE_STRING) ); Status() { } public String getDisplayName() { return "Archival Units"; } public List getColumnDescriptors(String key) { return colDescs; } public List getRows(String key) { List table = new ArrayList(); for (Iterator iter = getAllAus().iterator(); iter.hasNext();) { Map row = new HashMap(); ArchivalUnit au = (ArchivalUnit)iter.next(); row.put("au", au.getName()); row.put("auid", au.getAuId()); row.put("poll", statusSvc.getReference(PollerStatus.MANAGER_STATUS_TABLE_NAME, au)); table.add(row); } return table; } public List getDefaultSortRules(String key) { return sortRules; } public boolean requiresKey() { return false; } public void populateTable(StatusTable table) { String key = table.getKey(); table.setColumnDescriptors(getColumnDescriptors(key)); table.setDefaultSortRules(getDefaultSortRules(key)); table.setRows(getRows(key)); } } // protected void initPlugins() { // /* grab our 3rd party plugins and load them using security manager */ // String[] files = new java.io.File(pluginDir).list(); // for(int i= 0; i < files.length; i++) { // if(files[i].endsWith(".jar")) { // loadPlugin(files[i].substring(0,files[i].lastIndexOf(".jar"))); // } // else { // loadPlugin(files[i]); // } // } // } }
src/org/lockss/plugin/PluginManager.java
/* * $Id: PluginManager.java,v 1.79 2004-04-09 06:53:00 tlipkis Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin; import java.util.*; import java.io.IOException; import org.lockss.daemon.*; import org.lockss.daemon.status.*; import org.lockss.poller.*; import org.lockss.util.*; import org.lockss.app.BaseLockssManager; import org.lockss.plugin.definable.DefinablePlugin; /** * Plugin global functionality * * @author TAL * @version 0.0 */ public class PluginManager extends BaseLockssManager { public static final String PARAM_AU_TREE = Configuration.PREFIX + "au"; private static String PARAM_PLUGIN_LOCATION = Configuration.PREFIX + "platform.pluginDir"; static String PARAM_PLUGIN_REGISTRY = Configuration.PREFIX + "plugin.registry"; static String PARAM_PLUGIN_XML_PLUGINS = Configuration.PREFIX + "plugin.xmlPlugins"; static String PARAM_REMOVE_STOPPED_AUS = Configuration.PREFIX + "plugin.removeStoppedAus"; static boolean DEFAULT_REMOVE_STOPPED_AUS = true; static final String PARAM_TITLE_DB = ConfigManager.PARAM_TITLE_DB; static final String AU_PARAM_WRAPPER = "reserved.wrapper"; public static final String AU_PARAM_DISABLED = "reserved.disabled"; public static final String AU_PARAM_DISPLAY_NAME = "reserved.displayName"; static final String CONFIGURABLE_PLUGIN_NAME = DefinablePlugin.class.getName(); private static Logger log = Logger.getLogger("PluginMgr"); private ConfigManager configMgr; private StatusService statusSvc; private String pluginDir = null; // maps plugin key(not id) to plugin private Map pluginMap = Collections.synchronizedMap(new HashMap()); private Map auMap = Collections.synchronizedMap(new HashMap()); private Set inactiveAuIds = Collections.synchronizedSet(new HashSet()); private List xmlPlugins = Collections.EMPTY_LIST; public PluginManager() { } /* ------- LockssManager implementation ------------------ */ /** * start the plugin manager. * @see org.lockss.app.LockssManager#startService() */ public void startService() { super.startService(); configMgr = getDaemon().getConfigManager(); statusSvc = getDaemon().getStatusService(); // statusSvc.registerStatusAccessor("AUS", new Status()); resetConfig(); // causes setConfig to think previous config was empty } /** * stop the plugin manager * @see org.lockss.app.LockssManager#stopService() */ public void stopService() { // tk - checkpoint if nec. for (Iterator iter = pluginMap.values().iterator(); iter.hasNext(); ) { Plugin plugin = (Plugin)iter.next(); plugin.stopPlugin(); } super.stopService(); } Configuration currentAllPlugs = ConfigManager.EMPTY_CONFIGURATION; protected void setConfig(Configuration config, Configuration oldConfig, Set changedKeys) { pluginDir = config.get(PARAM_PLUGIN_LOCATION); // Must load the xml plugin list *before* the plugin registry if (changedKeys.contains(PARAM_PLUGIN_XML_PLUGINS)) { xmlPlugins = StringUtil.breakAt(config.get(PARAM_PLUGIN_XML_PLUGINS), ';', 0, true); } // Don't load or start plugins until the daemon is running. if (isDaemonInited()) { // Process the plugin registry. if (changedKeys.contains(PARAM_PLUGIN_REGISTRY)) { initPluginRegistry(config.get(PARAM_PLUGIN_REGISTRY)); } Configuration allPlugs = config.getConfigTree(PARAM_AU_TREE); if (!allPlugs.equals(currentAllPlugs)) { for (Iterator iter = allPlugs.nodeIterator(); iter.hasNext(); ) { String pluginKey = (String)iter.next(); log.debug("Configuring plugin key: " + pluginKey); Configuration pluginConf = allPlugs.getConfigTree(pluginKey); Configuration prevPluginConf = currentAllPlugs.getConfigTree(pluginKey); configurePlugin(pluginKey, pluginConf, prevPluginConf); } currentAllPlugs = allPlugs; } } } /** * Convert plugin property key to plugin class name. * @param key the key * @return the plugin name */ public static String pluginNameFromKey(String key) { return StringUtil.replaceString(key, "|", "."); } /** * Convert plugin class name to key suitable for property file. * @param className the class name * @return the plugin key */ public static String pluginKeyFromName(String className) { return StringUtil.replaceString(className, ".", "|"); } /** * Convert plugin id to key suitable for property file. Plugin id is * currently the same as plugin class name, but that may change. * @param id the plugin id * @return String the plugin key */ public static String pluginKeyFromId(String id) { // tk - needs to do real mapping from IDs obtained from all available // plugins. return StringUtil.replaceString(id, ".", "|"); } /** * Return a unique identifier for an au based on its plugin id and defining * properties. * @param pluginId plugin id (with . not escaped) * @param auDefProps Properties with values for all definitional AU params * @return a unique identifier for an au based on its plugin id and defining * properties. */ public static String generateAuId(String pluginId, Properties auDefProps) { return generateAuId(pluginId, PropUtil.propsToCanonicalEncodedString(auDefProps)); } public static String generateAuId(Plugin plugin, Configuration auConfig) { Properties props = new Properties(); for (Iterator iter = plugin.getAuConfigDescrs().iterator(); iter.hasNext();) { ConfigParamDescr descr = (ConfigParamDescr)iter.next(); if (descr.isDefinitional()) { String key = descr.getKey(); props.setProperty(key, auConfig.get(key)); } } return generateAuId(plugin.getPluginId(), props); } static String generateAuId(String pluginId, String auKey) { return pluginKeyFromId(pluginId)+"&"+auKey; } public static String auKeyFromAuId(String auid) { int pos = auid.indexOf("&"); if (pos < 0) { throw new IllegalArgumentException("Illegal AuId: " + auid); } return auid.substring(pos + 1); } public static String pluginIdFromAuId(String auid) { int pos = auid.indexOf("&"); if (pos < 0) { throw new IllegalArgumentException("Illegal AuId: " + auid); } return auid.substring(0, pos); } public static String pluginNameFromAuId(String auid) { return pluginNameFromKey(pluginIdFromAuId(auid)); } public static String configKeyFromAuId(String auid) { return StringUtil.replaceFirst(auid, "&", "."); } /** * Return the plugin with the given key. * @param pluginKey the plugin key * @return the plugin or null */ public Plugin getPlugin(String pluginKey) { return (Plugin)pluginMap.get(pluginKey); } /** * Returns true if the reserved.wrapper key is true * @param auConf the Configuration * @return true if wrapped */ private boolean isAuWrapped(Configuration auConf) { return WrapperState.isUsingWrapping() && auConf.getBoolean(AU_PARAM_WRAPPER, false); } private Configuration removeWrapper(Configuration auConf) { Configuration copy = auConf.copy(); if (copy.containsKey(AU_PARAM_WRAPPER)) { copy.remove(AU_PARAM_WRAPPER); } return copy; } private void configurePlugin(String pluginKey, Configuration pluginConf, Configuration oldPluginConf) { for (Iterator iter = pluginConf.nodeIterator(); iter.hasNext(); ) { String auKey = (String)iter.next(); String auId = generateAuId(pluginKey, auKey); try { Configuration auConf = pluginConf.getConfigTree(auKey); Configuration oldAuConf = oldPluginConf.getConfigTree(auKey); if (auConf.getBoolean(AU_PARAM_DISABLED, false)) { // tk should actually remove AU? log.debug("Not configuring disabled AU id: " + auKey); if (auMap.get(auId) == null) { // don't add to inactive if it's still running inactiveAuIds.add(auId); } } else if (!auConf.equals(oldAuConf)) { log.debug("Configuring AU id: " + auKey); if (!isAuWrapped(auConf)) { boolean pluginOk = ensurePluginLoaded(pluginKey); if (pluginOk) { Plugin plugin = getPlugin(pluginKey); if (WrapperState.isWrappedPlugin(plugin)) { throw new ArchivalUnit.ConfigurationException("An attempt was made to have load unwrapped " + auKey + " from plugin " + pluginKey + " which is already wrapped."); } configureAu(plugin, auConf, auId); } else { log.warning("Not configuring AU " + auKey); } } else { log.debug("Wrapping " + auKey); if ((pluginMap.containsKey(pluginKey)) && (!WrapperState.isWrappedPlugin(pluginMap.get(pluginKey)))) { throw new ArchivalUnit.ConfigurationException("An attempt was made to wrap AU " + auKey + " from plugin " + pluginKey + " which is already loaded."); } Plugin wrappedPlugin = WrapperState.retrieveWrappedPlugin(pluginKey, theDaemon); if (wrappedPlugin==null) { log.warning("Not configuring AU " + auKey); log.error("Error instantiating " + WrapperState.WRAPPED_PLUGIN_NAME); } else { setPlugin(pluginKey,wrappedPlugin); Configuration wrappedAuConf = removeWrapper(auConf); configureAu(wrappedPlugin, wrappedAuConf, auId); } } inactiveAuIds.remove(generateAuId(pluginKey, auKey)); } else { log.debug("AU already configured, not reconfiguring: " + auKey); } } catch (ArchivalUnit.ConfigurationException e) { log.error("Failed to configure AU " + auKey, e); } catch (Exception e) { log.error("Unexpected exception configuring AU " + auKey, e); } } } void configureAu(Plugin plugin, Configuration auConf, String auId) throws ArchivalUnit.ConfigurationException { try { ArchivalUnit au = plugin.configureAu(auConf, (ArchivalUnit)auMap.get(auId)); log.debug("Configured AU " + au); try { getDaemon().startOrReconfigureAuManagers(au, auConf); } catch (Exception e) { throw new ArchivalUnit.ConfigurationException("Couldn't configure AU managers", e); } log.debug("putAuMap(" + au.getAuId() +", " + au); if (!auId.equals(au.getAuId())) { throw new ArchivalUnit.ConfigurationException("Configured AU has " +"unexpected AUId, " +"is: "+au.getAuId() +" expected: "+auId); } putAuInMap(au); } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error configuring AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } ArchivalUnit createAu(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException { String auid = null; ArchivalUnit oldAu = null; try { auid = generateAuId(plugin, auConf); oldAu = getAuFromId(auid); } catch (Exception e) { // no action. Bad/missing config value might cause getAuFromId() to // throw. It will be caught soon when creating the AU; for now we // can assume it means the AU doesn't already exist. } if (oldAu != null) { inactiveAuIds.remove(oldAu.getAuId()); throw new ArchivalUnit.ConfigurationException("Cannot create that AU because it already exists"); } try { ArchivalUnit au = plugin.createAu(auConf); inactiveAuIds.remove(au.getAuId()); log.debug("Created AU " + au); try { getDaemon().startOrReconfigureAuManagers(au, auConf); } catch (Exception e) { log.error("Couldn't start AU processes", e); throw new ArchivalUnit.ConfigurationException("Couldn't start AU processes", e); } log.debug("putAuMap(" + au.getAuId() +", " + au); putAuInMap(au); return au; } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error creating AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } /** Stop the AU's activity and remove it, as though it had never been * configured. Does not affect the AU's current repository contents. * @return true if the AU was removed, false if it didn't exist or is * stale. */ public boolean stopAu(ArchivalUnit au) { String auid = au.getAuId(); ArchivalUnit mapAu = (ArchivalUnit)auMap.get(auid); if (mapAu == null) { log.warning("stopAu(" + au.getName() + "), wasn't in map"); return false; } if (mapAu != au) { log.warning("stopAu(" + au.getName() + "), but map contains " + mapAu); return false; } log.debug("Deactivating AU: " + au.getName()); // remove from map first, so no new activity can start (poll messages, // RemoteAPI, etc.) auMap.remove(auid); theDaemon.getPollManager().cancelAuPolls(au); theDaemon.getCrawlManager().cancelAuCrawls(au); try { // Plugin plugin = au.getPlugin(); // plugin.removeAu(au); theDaemon.stopAuManagers(au); } catch (Exception e) { // Shouldn't happen, as stopAuManagers() catches errors in // stopService(). Not clear what to do anyway, if some of the // managers don't stop cleanly. } return true; } protected void putAuInMap(ArchivalUnit au) { auMap.put(au.getAuId(), au); } public ArchivalUnit getAuFromId(String auId) { ArchivalUnit au = (ArchivalUnit)auMap.get(auId); log.debug3("getAu(" + auId + ") = " + au); return au; } // These don't belong here /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAuConfiguration(ArchivalUnit au, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { setAndSaveAuConfiguration(au, ConfigManager.fromProperties(auProps)); } /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAuConfiguration(ArchivalUnit au, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Reconfiguring AU " + au); au.setConfiguration(auConf); updateAuConfigFile(au, auConf); } private void updateAuConfigFile(ArchivalUnit au, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { String auid = au.getAuId(); String prefix = PARAM_AU_TREE + "." + configKeyFromAuId(auid); Configuration fqConfig = auConf.addPrefix(prefix); configMgr.updateAuConfigFile(fqConfig, prefix); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAuConfiguration(Plugin plugin, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { return createAndSaveAuConfiguration(plugin, ConfigManager.fromProperties(auProps)); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAuConfiguration(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { ArchivalUnit au = createAu(plugin, auConf); updateAuConfigFile(au, auConf); return au; } /** * Delete AU configuration from the local config file. Need to find a * better place for this. * @param au the ArchivalUnit to be unconfigured * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deleteAuConfiguration(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Deleting AU config: " + au); updateAuConfigFile(au, ConfigManager.EMPTY_CONFIGURATION); } /** * Deactivate an AU in the config file. Does not actually stop the AU. * @param au the ArchivalUnit to be deactivated * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deactivateAuConfiguration(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Deactivating AU: " + au); Configuration config = getStoredAuConfiguration(au); config.put(AU_PARAM_DISABLED, "true"); config.put(AU_PARAM_DISPLAY_NAME, au.getName()); updateAuConfigFile(au, config); } /** * Delete an AU * @param au the ArchivalUnit to be deleted * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deleteAu(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { deleteAuConfiguration(au); if (isRemoveStoppedAus()) { stopAu(au); } } /** * Deactivate an AU * @param au the ArchivalUnit to be deactivated * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deactivateAu(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { deactivateAuConfiguration(au); if (isRemoveStoppedAus()) { String auid = au.getAuId(); stopAu(au); inactiveAuIds.add(auid); } } public boolean isRemoveStoppedAus() { return configMgr.getBooleanParam(PARAM_REMOVE_STOPPED_AUS, DEFAULT_REMOVE_STOPPED_AUS); } /** * Return the stored config info for an AU (from config file, not from * AU instance). * @param au the ArchivalUnit * @return the AU's Configuration, with unprefixed keys. */ public Configuration getStoredAuConfiguration(ArchivalUnit au) { return getStoredAuConfiguration(au.getAuId()); } /** * Return the config tree for an AU id (from the local au config file, * not the au itself). * @param auid the AU's id. * @return the AU's Configuration, with unprefixed keys. */ public Configuration getStoredAuConfiguration(String auid) { String aukey = configKeyFromAuId(auid); Configuration config = configMgr.readAuConfigFile(); String prefix = PARAM_AU_TREE + "." + aukey; return config.getConfigTree(prefix); } Plugin retrievePlugin(String pluginKey) throws Exception { if (pluginMap.containsKey(pluginKey)) { return (Plugin)pluginMap.get(pluginKey); } String pluginName = pluginNameFromKey(pluginKey); String confFile = null; if (xmlPlugins.contains(pluginName)) { confFile = pluginName; pluginName = getConfigurablePluginName(); } Class pluginClass; try { pluginClass = Class.forName(pluginName); } catch (ClassNotFoundException e) { log.debug(pluginName + " not on classpath"); // not on classpath try { // tk - search plugin dir for signed jar, try loading again throw e; // for now, simulate failure of that process } catch (ClassNotFoundException e1) { // plugin is really not available log.error(pluginName + " not found"); return null; } } catch (Exception e) { // any other exception while loading class if not recoverable log.error("Error loading " + pluginName, e); return null; } Plugin plugin = (Plugin) pluginClass.newInstance(); if (confFile != null && plugin instanceof DefinablePlugin) { log.debug("Instantiating Configurable plugin from " + confFile); ((DefinablePlugin)plugin).initPlugin(theDaemon, confFile); } else { log.debug("Instantiating " + pluginClass); plugin.initPlugin(theDaemon); } return plugin; } /** * Load a plugin with the given class name from somewhere in our classpath * @param pluginKey the key for this plugin * @return true if loaded */ public boolean ensurePluginLoaded(String pluginKey) { if (pluginMap.containsKey(pluginKey)) { return true; } String pluginName = ""; try { pluginName = pluginNameFromKey(pluginKey); Plugin plugin = retrievePlugin(pluginKey); if (plugin != null) { setPlugin(pluginKey, plugin); return true; } else { return false; } } catch (Exception e) { log.error("Error instantiating " + pluginName, e); return false; } } // separate method so can be called by test code protected void setPlugin(String pluginKey, Plugin plugin) { if (log.isDebug3()) { log.debug3("PluginManager.setPlugin(" + pluginKey + ", " + plugin.getPluginName() + ")"); } pluginMap.put(pluginKey, plugin); titleMap = null; } protected String getConfigurablePluginName() { return CONFIGURABLE_PLUGIN_NAME; } /** * Find the CachedUrlSet from a PollSpec. * @param spec the PollSpec (from an incoming message) * @return a CachedUrlSet for the plugin, au and URL in the spec, or * null if au not present on this cache */ public CachedUrlSet findCachedUrlSet(PollSpec spec) { if (log.isDebug3()) log.debug3(this +".findCachedUrlSet2("+spec+")"); String auId = spec.getAuId(); ArchivalUnit au = getAuFromId(auId); if (log.isDebug3()) log.debug3("au: " + au); if (au == null) return null; Plugin plugin = au.getPlugin(); String url = spec.getUrl(); CachedUrlSet cus; if (AuUrl.isAuUrl(url)) { cus = au.getAuCachedUrlSet(); } else if ((spec.getLwrBound()!=null) && (spec.getLwrBound().equals(PollSpec.SINGLE_NODE_LWRBOUND))) { cus = plugin.makeCachedUrlSet(au, new SingleNodeCachedUrlSetSpec(url)); } else { RangeCachedUrlSetSpec rcuss = new RangeCachedUrlSetSpec(url, spec.getLwrBound(), spec.getUprBound()); cus = plugin.makeCachedUrlSet(au, rcuss); } if (log.isDebug3()) log.debug3("ret cus: " + cus); return cus; } /** * Searches all ArchivalUnits to find the most recent CachedUrl for the URL. * @param url The URL to search for. * @return a CachedUrl, or null if URL not present in any AU */ public CachedUrl findMostRecentCachedUrl(String url) { CachedUrl best = null; for (Iterator iter = getAllAus().iterator(); iter.hasNext();) { ArchivalUnit au = (ArchivalUnit)iter.next(); Plugin plugin = au.getPlugin(); if (au.shouldBeCached(url)) { CachedUrl cu = plugin.makeCachedUrl(au.getAuCachedUrlSet(), url); if (cu != null && cu.hasContent() && cuNewerThan(cu, best)) { best = cu; } } } return best; } // return true if cu1 is newer than cu2, or cu2 is null // tk - no date available for comparison yet, return arbitrary order private boolean cuNewerThan(CachedUrl cu1, CachedUrl cu2) { if (cu2 == null) return true; CIProperties p1 = cu1.getProperties(); CIProperties p2 = cu2.getProperties(); // tk - this should use the crawl-date prop taht the crawler will add // Long.parseLong(p1.getProperty(HttpFields.__LastModified, "-1")); return true; } /** * Return a list of all configured ArchivalUnits. * @return the List of aus */ public List getAllAus() { return new ArrayList(auMap.values()); } public Collection getInactiveAuIds() { return inactiveAuIds; } /** Return all the known titles from the title db */ public Collection findAllTitles() { return getTitleMap().keySet(); } /** Find all the plugins that support the given title */ public Collection getTitlePlugins(String title) { return (Collection)getTitleMap().get(title); } private Map titleMap = null; public void resetTitles() { titleMap = null; } public Map getTitleMap() { if (titleMap == null) { titleMap = buildTitleMap(); } return titleMap; } Map buildTitleMap() { Map map = new org.apache.commons.collections.MultiHashMap(); synchronized (pluginMap) { for (Iterator iter = getRegisteredPlugins().iterator(); iter.hasNext();) { Plugin p = (Plugin)iter.next(); Collection titles = p.getSupportedTitles(); for (Iterator iter2 = titles.iterator(); iter2.hasNext();) { String title = (String)iter2.next(); if (title != null) { map.put(title, p); } } } } return map; } /** Return a SortedMap mapping (human readable) plugin name to plugin * instance */ public SortedMap getPluginNameMap() { SortedMap pMap = new TreeMap(); synchronized (pluginMap) { for (Iterator iter = getRegisteredPlugins().iterator(); iter.hasNext(); ) { Plugin p = (Plugin)iter.next(); pMap.put(p.getPluginName(), p); } } return pMap; } /** @return All plugins that have been registered. <i>Ie</i>, that are * either listed in org.lockss.plugin.registry, or were loaded by a * configured AU */ public Collection getRegisteredPlugins() { return pluginMap.values(); } /** @return list of xml plugin names. For testing only. */ List getXmlPlugins() { return xmlPlugins; } // Synch the plugin registry with the plugins listed in names void initPluginRegistry(String names) { Collection newKeys = new HashSet(); List nameList = StringUtil.breakAt(names, ';', 0, true); for (Iterator iter = nameList.iterator(); iter.hasNext(); ) { String name = (String)iter.next(); String key = pluginKeyFromName(name); ensurePluginLoaded(key); newKeys.add(key); } // remove plugins that are no longer listed, unless they have one or // more configured AUs synchronized (pluginMap) { for (Iterator iter = pluginMap.keySet().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); String key = pluginKeyFromName(name); if (!newKeys.contains(key)) { Configuration tree = currentAllPlugs.getConfigTree(key); if (tree == null || tree.isEmpty()) { iter.remove(); } } } } } private class Status implements StatusAccessor { private final List sortRules = ListUtil.list(new StatusTable.SortRule("au", true)); private final List colDescs = ListUtil.list( new ColumnDescriptor("au", "Journal Volume", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("poll", "Poll Status", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("crawl", "Crawl Status", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("auid", "AUID", ColumnDescriptor.TYPE_STRING) ); Status() { } public String getDisplayName() { return "Archival Units"; } public List getColumnDescriptors(String key) { return colDescs; } public List getRows(String key) { List table = new ArrayList(); for (Iterator iter = getAllAus().iterator(); iter.hasNext();) { Map row = new HashMap(); ArchivalUnit au = (ArchivalUnit)iter.next(); row.put("au", au.getName()); row.put("auid", au.getAuId()); row.put("poll", statusSvc.getReference(PollerStatus.MANAGER_STATUS_TABLE_NAME, au)); table.add(row); } return table; } public List getDefaultSortRules(String key) { return sortRules; } public boolean requiresKey() { return false; } public void populateTable(StatusTable table) { String key = table.getKey(); table.setColumnDescriptors(getColumnDescriptors(key)); table.setDefaultSortRules(getDefaultSortRules(key)); table.setRows(getRows(key)); } } // protected void initPlugins() { // /* grab our 3rd party plugins and load them using security manager */ // String[] files = new java.io.File(pluginDir).list(); // for(int i= 0; i < files.length; i++) { // if(files[i].endsWith(".jar")) { // loadPlugin(files[i].substring(0,files[i].lastIndexOf(".jar"))); // } // else { // loadPlugin(files[i]); // } // } // } }
getAllAus() and findAllTitles() now sorted by title. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@2843 4f837ed2-42f5-46e7-a7a5-fa17313484d4
src/org/lockss/plugin/PluginManager.java
getAllAus() and findAllTitles() now sorted by title.
Java
mit
e4a9c368cd3e2775443a5aa2ca213192574c7b84
0
nking/shared,nking/shared
package algorithms.statistics; import algorithms.matrix.MatrixUtil; import algorithms.misc.MiscMath0; import java.security.SecureRandom; import junit.framework.TestCase; /** * * @author nichole */ public class StandardizationTest extends TestCase { public StandardizationTest(String testName) { super(testName); } public void testStandardUnitNormalization() { double[] data; int nDimensions; double[] outputMean, expectedMean; double[] outputStDev, expectdStDev; double[] mean2; double[][] stDev2; double[] st, expectedSt, dSt; double tol = 0.001; int nc0, nc1, nc; //(1, 1), (3, 3) --> (2,2) nDimensions = 2; data = new double[]{1, 1, 3, 3}; // -1, 1 expectedMean = new double[]{2, 2}; expectdStDev = new double[]{1.414, 1.414}; expectedSt = new double[]{-0.707, -0.707, 0.707, 0.707}; outputMean = new double[nDimensions]; outputStDev = new double[nDimensions]; st = Standardization.standardUnitNormalization(data, nDimensions, outputMean, outputStDev); assertEquals(st.length, expectedSt.length); nc0 = 0; nc1=0; for (int i = 0; i < outputMean.length; ++i) { if (Math.abs(outputMean[i] - expectedMean[i]) < tol) { nc0++; } if (Math.abs(outputStDev[i] - expectdStDev[i]) < tol) { nc1++; } } assertEquals(expectedMean.length, nc0); assertEquals(expectdStDev.length, nc1); nc = 0; for (int i = 0; i < expectedSt.length; ++i) { if (Math.abs(st[i] - expectedSt[i]) < tol) { nc++; } } assertEquals(st.length, nc); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1=0; nc = 0; for (int i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputMean, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (int i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); //------------------------------------------ //(0, 0), (0, 0), (0, 12) nDimensions = 2; data = new double[]{0, 0, 0, 0, 0, 12}; expectedMean = new double[]{0, 4}; expectdStDev = new double[]{0, 6.928}; expectedSt = new double[]{0, -0.5774, 0, -0.577, 0, 1.1547}; outputMean = new double[nDimensions]; outputStDev = new double[nDimensions]; st = Standardization.standardUnitNormalization(data, nDimensions, outputMean, outputStDev); assertEquals(st.length, expectedSt.length); nc0 = 0; nc1=0; for (int i = 0; i < outputMean.length; ++i) { if (Math.abs(outputMean[i] - expectedMean[i]) < tol) { nc0++; } if (Math.abs(outputStDev[i] - expectdStDev[i]) < tol) { nc1++; } } assertEquals(expectedMean.length, nc0); assertEquals(expectdStDev.length, nc1); nc = 0; for (int i = 0; i < expectedSt.length; ++i) { if (Math.abs(st[i] - expectedSt[i]) < tol) { nc++; } } assertEquals(st.length, nc); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1=0; nc = 0; for (int i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputMean, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (int i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); // ------------ //(-20, 48), (-20, -48), (20, 0), (59, 0) nDimensions = 2; data = new double[]{-20, 48, -20, -48, 20, 0, 59, 0}; expectedMean = new double[]{9.75, 0}; expectdStDev = new double[]{37.863, 39.192}; expectedSt = new double[]{-0.7857, 1.225, -0.786, -1.225, 0.271, 0, 1.301, 0}; outputMean = new double[nDimensions]; outputStDev = new double[nDimensions]; st = Standardization.standardUnitNormalization(data, nDimensions, outputMean, outputStDev); assertEquals(st.length, expectedSt.length); nc0 = 0; nc1=0; for (int i = 0; i < outputMean.length; ++i) { if (Math.abs(outputMean[i] - expectedMean[i]) < tol) { nc0++; } if (Math.abs(outputStDev[i] - expectdStDev[i]) < tol) { nc1++; } } assertEquals(expectedMean.length, nc0); assertEquals(expectdStDev.length, nc1); nc = 0; for (int i = 0; i < expectedSt.length; ++i) { if (Math.abs(st[i] - expectedSt[i]) < tol) { nc++; } } assertEquals(st.length, nc); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1=0; nc = 0; for (int i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputMean, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (int i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); } public void test2() { SecureRandom sr = new SecureRandom(); long seed = System.nanoTime(); System.out.println("test2: seed=" + seed); sr.setSeed(seed); int nIter = 10; double tol = 0.001; int nData, nDimensions; double[] data, st, outputM, outputStDev, dSt; double[] mean2; double[][] stDev2; int i, it, nc0, nc1, nc; for (it = 0; it < nIter; ++it) { nData = sr.nextInt(1023) + 5; nDimensions = sr.nextInt(nData / 4) + 1; data = new double[nData * nDimensions]; outputM = new double[nDimensions]; outputStDev = new double[nDimensions]; for (i = 0; i < data.length; ++i) { data[i] = sr.nextDouble(); if (sr.nextBoolean()) { data[i] *= -1.; } data[i] *= sr.nextInt(); } st = Standardization.standardUnitNormalization(data, nDimensions, outputM, outputStDev); assertEquals(st.length, data.length); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1 = 0; nc = 0; for (i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputM, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); } } public void test3() { SecureRandom sr = new SecureRandom(); long seed = System.nanoTime(); System.out.println("test3: seed=" + seed); sr.setSeed(seed); int nIter = 10; double tol = 0.001; int nData, nDimensions; double[] outputM, outputStDev, dSt; double[] mean2, stDev2; double[][] data, st; int i, j, it, nc0, nc1, nc; for (it = 0; it < nIter; ++it) { nData = sr.nextInt(1023) + 5; nDimensions = sr.nextInt(nData / 4) + 1; data = new double[nData][nDimensions]; outputM = new double[nDimensions]; outputStDev = new double[nDimensions]; for (i = 0; i < data.length; ++i) { data[i] = new double[nDimensions]; for (j = 0; j < data[i].length; ++j) { data[i][j] = sr.nextDouble(); if (sr.nextBoolean()) { data[i][j] *= -1.; } data[i][j] *= sr.nextInt(); } } st = Standardization.standardUnitNormalization(data, outputM, outputStDev); assertEquals(st.length, data.length); mean2 = MatrixUtil.mean(st); stDev2 = MatrixUtil.standardDeviation(st); assertEquals(nDimensions, mean2.length); assertEquals(nDimensions, stDev2.length); nc0 = 0; nc = 0; for (i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if ((Math.abs(stDev2[i] - 1.) < tol) || (Math.abs(stDev2[i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc); /* dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputM, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); */ } } }
src/test/java/algorithms/statistics/StandardizationTest.java
package algorithms.statistics; import algorithms.matrix.MatrixUtil; import algorithms.misc.MiscMath0; import java.security.SecureRandom; import junit.framework.TestCase; /** * * @author nichole */ public class StandardizationTest extends TestCase { public StandardizationTest(String testName) { super(testName); } public void testStandardUnitNormalization() { double[] data; int nDimensions; double[] outputMean, expectedMean; double[] outputStDev, expectdStDev; double[] mean2; double[][] stDev2; double[] st, expectedSt, dSt; double tol = 0.001; int nc0, nc1, nc; //(1, 1), (3, 3) --> (2,2) nDimensions = 2; data = new double[]{1, 1, 3, 3}; // -1, 1 expectedMean = new double[]{2, 2}; expectdStDev = new double[]{1.414, 1.414}; expectedSt = new double[]{-0.707, -0.707, 0.707, 0.707}; outputMean = new double[nDimensions]; outputStDev = new double[nDimensions]; st = Standardization.standardUnitNormalization(data, nDimensions, outputMean, outputStDev); assertEquals(st.length, expectedSt.length); nc0 = 0; nc1=0; for (int i = 0; i < outputMean.length; ++i) { if (Math.abs(outputMean[i] - expectedMean[i]) < tol) { nc0++; } if (Math.abs(outputStDev[i] - expectdStDev[i]) < tol) { nc1++; } } assertEquals(expectedMean.length, nc0); assertEquals(expectdStDev.length, nc1); nc = 0; for (int i = 0; i < expectedSt.length; ++i) { if (Math.abs(st[i] - expectedSt[i]) < tol) { nc++; } } assertEquals(st.length, nc); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1=0; nc = 0; for (int i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputMean, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (int i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); //------------------------------------------ //(0, 0), (0, 0), (0, 12) nDimensions = 2; data = new double[]{0, 0, 0, 0, 0, 12}; expectedMean = new double[]{0, 4}; expectdStDev = new double[]{0, 6.928}; expectedSt = new double[]{0, -0.5774, 0, -0.577, 0, 1.1547}; outputMean = new double[nDimensions]; outputStDev = new double[nDimensions]; st = Standardization.standardUnitNormalization(data, nDimensions, outputMean, outputStDev); assertEquals(st.length, expectedSt.length); nc0 = 0; nc1=0; for (int i = 0; i < outputMean.length; ++i) { if (Math.abs(outputMean[i] - expectedMean[i]) < tol) { nc0++; } if (Math.abs(outputStDev[i] - expectdStDev[i]) < tol) { nc1++; } } assertEquals(expectedMean.length, nc0); assertEquals(expectdStDev.length, nc1); nc = 0; for (int i = 0; i < expectedSt.length; ++i) { if (Math.abs(st[i] - expectedSt[i]) < tol) { nc++; } } assertEquals(st.length, nc); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1=0; nc = 0; for (int i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputMean, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (int i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); // ------------ //(-20, 48), (-20, -48), (20, 0), (59, 0) nDimensions = 2; data = new double[]{-20, 48, -20, -48, 20, 0, 59, 0}; expectedMean = new double[]{9.75, 0}; expectdStDev = new double[]{37.863, 39.192}; expectedSt = new double[]{-0.7857, 1.225, -0.786, -1.225, 0.271, 0, 1.301, 0}; outputMean = new double[nDimensions]; outputStDev = new double[nDimensions]; st = Standardization.standardUnitNormalization(data, nDimensions, outputMean, outputStDev); assertEquals(st.length, expectedSt.length); nc0 = 0; nc1=0; for (int i = 0; i < outputMean.length; ++i) { if (Math.abs(outputMean[i] - expectedMean[i]) < tol) { nc0++; } if (Math.abs(outputStDev[i] - expectdStDev[i]) < tol) { nc1++; } } assertEquals(expectedMean.length, nc0); assertEquals(expectdStDev.length, nc1); nc = 0; for (int i = 0; i < expectedSt.length; ++i) { if (Math.abs(st[i] - expectedSt[i]) < tol) { nc++; } } assertEquals(st.length, nc); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1=0; nc = 0; for (int i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputMean, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (int i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); } public void test2() { SecureRandom sr = new SecureRandom(); long seed = System.nanoTime(); System.out.println("test2: seed=" + seed); sr.setSeed(seed); int nIter = 10; double tol = 0.001; int nData, nDimensions; double[] data, st, outputM, outputStDev, dSt; double[] mean2; double[][] stDev2; int i, it, nc0, nc1, nc; for (it = 0; it < nIter; ++it) { nData = sr.nextInt(1023) + 1; nDimensions = sr.nextInt(nData / 4) + 1; data = new double[nData * nDimensions]; outputM = new double[nDimensions]; outputStDev = new double[nDimensions]; for (i = 0; i < data.length; ++i) { data[i] = sr.nextDouble(); if (sr.nextBoolean()) { data[i] *= -1.; } data[i] *= sr.nextInt(); } st = Standardization.standardUnitNormalization(data, nDimensions, outputM, outputStDev); assertEquals(st.length, data.length); mean2 = MiscMath0.mean(st, nDimensions); stDev2 = MiscMath0.standardDeviation(st, nDimensions); assertEquals(nDimensions, mean2.length); assertEquals(2, stDev2.length); assertEquals(nDimensions, stDev2[0].length); assertEquals(nDimensions, stDev2[1].length); nc0 = 0; nc1 = 0; nc = 0; for (i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if (Math.abs(stDev2[0][i] - 0) < tol) { nc1++; } if ((Math.abs(stDev2[1][i] - 1.) < tol) || (Math.abs(stDev2[1][i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc1); assertEquals(nDimensions, nc); dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputM, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); } } public void test3() { SecureRandom sr = new SecureRandom(); long seed = System.nanoTime(); System.out.println("test3: seed=" + seed); sr.setSeed(seed); int nIter = 10; double tol = 0.001; int nData, nDimensions; double[] outputM, outputStDev, dSt; double[] mean2, stDev2; double[][] data, st; int i, j, it, nc0, nc1, nc; for (it = 0; it < nIter; ++it) { nData = sr.nextInt(1023) + 1; nDimensions = sr.nextInt(nData / 4) + 1; data = new double[nData][nDimensions]; outputM = new double[nDimensions]; outputStDev = new double[nDimensions]; for (i = 0; i < data.length; ++i) { data[i] = new double[nDimensions]; for (j = 0; j < data[i].length; ++j) { data[i][j] = sr.nextDouble(); if (sr.nextBoolean()) { data[i][j] *= -1.; } data[i][j] *= sr.nextInt(); } } st = Standardization.standardUnitNormalization(data, outputM, outputStDev); assertEquals(st.length, data.length); mean2 = MatrixUtil.mean(st); stDev2 = MatrixUtil.standardDeviation(st); assertEquals(nDimensions, mean2.length); assertEquals(nDimensions, stDev2.length); nc0 = 0; nc = 0; for (i = 0; i < nDimensions; ++i) { if (Math.abs(mean2[i] - 0.) < tol) { nc0++; } if ((Math.abs(stDev2[i] - 1.) < tol) || (Math.abs(stDev2[i] - 0.) < tol)) { nc++; } } assertEquals(nDimensions, nc0); assertEquals(nDimensions, nc); /* dSt = Standardization.standardUnitDenormalization(st, nDimensions, outputM, outputStDev); assertEquals(data.length, dSt.length); nc = 0; for (i = 0; i < data.length; ++i) { if ((Math.abs(dSt[i] - data[i]) < tol)) { nc++; } } assertEquals(data.length, nc); */ } } }
fixed a potential bug in a unit test, duplicated
src/test/java/algorithms/statistics/StandardizationTest.java
fixed a potential bug in a unit test, duplicated
Java
mit
f2ecc9ce0624dfbabb51bcb9afd57ee97f98cfe4
0
CS2103JAN2017-W15-B4/main,CS2103JAN2017-W15-B4/main
package seedu.geekeep; import java.util.function.Supplier; import javafx.stage.Screen; import javafx.stage.Stage; import seedu.geekeep.commons.core.Config; import seedu.geekeep.commons.core.GuiSettings; import seedu.geekeep.model.ReadOnlyTaskManager; import seedu.geekeep.model.UserPrefs; import seedu.geekeep.storage.XmlSerializableTaskManager; import seedu.geekeep.testutil.TestUtil; /** * This class is meant to override some properties of MainApp so that it will be suited for * testing */ public class TestApp extends MainApp { public static final String SAVE_LOCATION_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("sampleData.xml"); protected static final String DEFAULT_PREF_FILE_LOCATION_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("pref_testing.json"); public static final String APP_TITLE = "Test App"; protected static final String TASK_MANAGER_NAME = "Test"; protected Supplier<ReadOnlyTaskManager> initialDataSupplier = () -> null; protected String saveFileLocation = SAVE_LOCATION_FOR_TESTING; public TestApp() { } public TestApp(Supplier<ReadOnlyTaskManager> initialDataSupplier, String saveFileLocation) { super(); this.initialDataSupplier = initialDataSupplier; this.saveFileLocation = saveFileLocation; // If some initial local data has been provided, write those to the file if (initialDataSupplier.get() != null) { TestUtil.createDataFileWithData( new XmlSerializableTaskManager(this.initialDataSupplier.get()), this.saveFileLocation); } } @Override protected Config initConfig(String configFilePath) { Config config = super.initConfig(configFilePath); config.setAppTitle(APP_TITLE); config.setGeeKeepFilePath(saveFileLocation); config.setUserPrefsFilePath(DEFAULT_PREF_FILE_LOCATION_FOR_TESTING); config.setGeeKeepName(TASK_MANAGER_NAME); return config; } @Override protected UserPrefs initPrefs(Config config) { UserPrefs userPrefs = super.initPrefs(config); double x = Screen.getPrimary().getVisualBounds().getMinX(); double y = Screen.getPrimary().getVisualBounds().getMinY(); userPrefs.updateLastUsedGuiSetting(new GuiSettings(600.0, 600.0, (int) x, (int) y)); return userPrefs; } @Override public void start(Stage primaryStage) { ui.start(primaryStage); } public static void main(String[] args) { launch(args); } }
src/test/java/seedu/geekeep/TestApp.java
package seedu.geekeep; import java.util.function.Supplier; import javafx.stage.Screen; import javafx.stage.Stage; import seedu.geekeep.commons.core.Config; import seedu.geekeep.commons.core.GuiSettings; import seedu.geekeep.model.ReadOnlyTaskManager; import seedu.geekeep.model.UserPrefs; import seedu.geekeep.storage.XmlSerializableTaskManager; import seedu.geekeep.testutil.TestUtil; /** * This class is meant to override some properties of MainApp so that it will be suited for * testing */ public class TestApp extends MainApp { public static final String SAVE_LOCATION_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("sampleData.xml"); protected static final String DEFAULT_PREF_FILE_LOCATION_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("pref_testing.json"); public static final String APP_TITLE = "Test App"; protected static final String ADDRESS_BOOK_NAME = "Test"; protected Supplier<ReadOnlyTaskManager> initialDataSupplier = () -> null; protected String saveFileLocation = SAVE_LOCATION_FOR_TESTING; public TestApp() { } public TestApp(Supplier<ReadOnlyTaskManager> initialDataSupplier, String saveFileLocation) { super(); this.initialDataSupplier = initialDataSupplier; this.saveFileLocation = saveFileLocation; // If some initial local data has been provided, write those to the file if (initialDataSupplier.get() != null) { TestUtil.createDataFileWithData( new XmlSerializableTaskManager(this.initialDataSupplier.get()), this.saveFileLocation); } } @Override protected Config initConfig(String configFilePath) { Config config = super.initConfig(configFilePath); config.setAppTitle(APP_TITLE); config.setGeeKeepFilePath(saveFileLocation); config.setUserPrefsFilePath(DEFAULT_PREF_FILE_LOCATION_FOR_TESTING); config.setGeeKeepName(ADDRESS_BOOK_NAME); return config; } @Override protected UserPrefs initPrefs(Config config) { UserPrefs userPrefs = super.initPrefs(config); double x = Screen.getPrimary().getVisualBounds().getMinX(); double y = Screen.getPrimary().getVisualBounds().getMinY(); userPrefs.updateLastUsedGuiSetting(new GuiSettings(600.0, 600.0, (int) x, (int) y)); return userPrefs; } @Override public void start(Stage primaryStage) { ui.start(primaryStage); } public static void main(String[] args) { launch(args); } }
Rename ADDRESS_BOOK_NAME
src/test/java/seedu/geekeep/TestApp.java
Rename ADDRESS_BOOK_NAME
Java
mit
11fb559bb88e4c3adbee835fd214a75e3cbbb3b3
0
valencik/battlecode
package team353; import battlecode.common.*; import java.util.*; public class RobotPlayer { public static class smuConstants { public static int roundToLaunchAttack = 1600; public static int roundToDefendTowers = 500; public static int roundToFormSupplyConvoy = 400; // roundToBuildSOLDIERS; public static int RADIUS_FOR_SUPPLY_CONVOY = 2; public static int numTowersRemainingToAttackHQ = 1; public static double weightExponentMagic = 0.3; public static double weightScaleMagic = 0.8; public static int currentOreGoal = 100; public static double percentBeaversToGoToSecondBase = 0.4; // Defence public static int NUM_TOWER_PROTECTORS = 4; public static int NUM_HOLE_PROTECTORS = 3; public static int PROTECT_OTHERS_RANGE = 15; public static int DISTANCE_TO_START_PROTECTING_SQUARED = 200; // Idle States public static MapLocation defenseRallyPoint; public static int PROTECT_HOLE = 1; public static int PROTECT_TOWER = 2; // Supply public static int NUM_ROUNDS_TO_KEEP_SUPPLIED = 20; // Contain public static int CLOCKWISE = 0; public static int COUNTERCLOCKWISE = 1; public static int CURRENTLY_BEING_CONTAINED = 1; public static int NOT_CURRENTLY_BEING_CONTAINED = 2; // Strategies /* * NOTE: If changing these values, alter smuTeamMemoryIndices accordingly */ public static int STRATEGY_DRONE_CONTAIN = 1; public static int STRATEGY_TANKS_AND_SOLDIERS = 2; public static int STRATEGY_DRONE_SWARM = 3; public static int STRATEGY_TANKS_AND_LAUNCHERS = 4; public static int STRATEGY_LAUNCHERS = 5; public static int STRATEGY_TANK_SWARM =6; } public static class smuIndices { public static int RALLY_POINT_X = 0; public static int RALLY_POINT_Y = 1; //Economy public static int freqQueue = 11; public static int STRATEGY = 19; public static int HQ_BEING_CONTAINED = 20; public static int HQ_BEING_CONTAINED_BY = 21; //Strategy broadcasts use frequencies 1000 through 3200! //TODO public static final int channelAEROSPACELAB = 1100; public static final int channelBARRACKS = 1200; public static final int channelBASHER = 1300; public static final int channelBEAVER = 1400; public static final int channelCOMMANDER = 1500; public static final int channelCOMPUTER = 1600; public static final int channelDRONE = 1700; public static final int channelHANDWASHSTATION = 1800; public static final int channelHELIPAD = 1900; public static final int channelHQ = 2000; public static final int channelLAUNCHER = 2100; public static final int channelMINER = 2200; public static final int channelMINERFACTORY = 2300; public static final int channelMISSILE = 2400; public static final int channelSOLDIER = 2500; public static final int channelSUPPLYDEPOT = 2600; public static final int channelTANK = 2700; public static final int channelTANKFACTORY = 2800; public static final int channelTECHNOLOGYINSTITUTE = 2900; public static final int channelTOWER = 3000; public static final int channelTRAININGFIELD = 3100; public static final int[] channel = new int[] {0, channelAEROSPACELAB, channelBARRACKS, channelBASHER, channelBEAVER, channelCOMMANDER, channelCOMPUTER, channelDRONE, channelHANDWASHSTATION, channelHELIPAD, channelHQ, channelLAUNCHER, channelMINER, channelMINERFACTORY, channelMISSILE, channelSOLDIER, channelSUPPLYDEPOT, channelTANK, channelTANKFACTORY, channelTECHNOLOGYINSTITUTE, channelTOWER, channelTRAININGFIELD}; public static int TOWER_HOLES_BEGIN = 4000; } public static class smuTeamMemoryIndices { public static int PREV_MAP_TOWER_THREAT = 0; public static int PREV_MAP_VOID_TYPE_PERCENT = 1; public static int NUM_ROUNDS_USING_STRATEGY_BASE = 1; // Strategies from smuConstants take values 2-7 public static int ROUND_OUR_HQ_ATTACKED = 8; // Round their HQ attacked? public static int ROUND_OUR_TOWER_DESTROYED_BASE = 10; // Base will expand to values 10-16 public static int ROUND_THEIR_TOWER_DESTROYED_BASE = 17; // Base will expand to values 17-23 // public static int ROUND_STARTED_USING_STRATEGY_BASE = 23; // // Base will expand to values 23-29 } public static void run(RobotController rc) throws GameActionException { BaseBot myself; if (rc.getType() == RobotType.HQ) { myself = new HQ(rc); } else if (rc.getType() == RobotType.MINER) { myself = new Miner(rc); } else if (rc.getType() == RobotType.MINERFACTORY) { myself = new Minerfactory(rc); } else if (rc.getType() == RobotType.BEAVER) { myself = new Beaver(rc); } else if (rc.getType() == RobotType.BARRACKS) { myself = new Barracks(rc); } else if (rc.getType() == RobotType.SOLDIER) { myself = new Soldier(rc); } else if (rc.getType() == RobotType.BASHER) { myself = new Basher(rc); } else if (rc.getType() == RobotType.HELIPAD) { myself = new Helipad(rc); } else if (rc.getType() == RobotType.DRONE) { myself = new Drone(rc); } else if (rc.getType() == RobotType.TOWER) { myself = new Tower(rc); } else if (rc.getType() == RobotType.SUPPLYDEPOT) { myself = new Supplydepot(rc); } else if (rc.getType() == RobotType.HANDWASHSTATION) { myself = new Handwashstation(rc); } else if (rc.getType() == RobotType.TANKFACTORY) { myself = new Tankfactory(rc); } else if (rc.getType() == RobotType.TANK) { myself = new Tank(rc); } else if (rc.getType() == RobotType.AEROSPACELAB) { myself = new Aerospacelab(rc); } else if (rc.getType() == RobotType.LAUNCHER) { myself = new Launcher(rc); } else if (rc.getType() == RobotType.MISSILE) { myself = new Missile(rc); } else { myself = new BaseBot(rc); } while (true) { try { myself.go(); } catch (Exception e) { e.printStackTrace(); } } } public static class BaseBot { protected RobotController rc; protected MapLocation myHQ, theirHQ; protected Team myTeam, theirTeam; protected int myRange; protected RobotType myType; static Random rand; public BaseBot(RobotController rc) { this.rc = rc; this.myHQ = rc.senseHQLocation(); this.theirHQ = rc.senseEnemyHQLocation(); this.myTeam = rc.getTeam(); this.theirTeam = this.myTeam.opponent(); this.myType = rc.getType(); this.myRange = myType.attackRadiusSquared; rand = new Random(rc.getID()); } public int getDistanceSquared(MapLocation A, MapLocation B){ return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); } public int getDistanceSquared(MapLocation A){ MapLocation B = rc.getLocation(); return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); } public Direction[] getDirectionsToward(MapLocation dest) { Direction toDest = rc.getLocation().directionTo(dest); Direction[] dirs = new Direction[5]; dirs[0] = toDest; if (rand.nextDouble() < 0.5){ dirs[1] = toDest.rotateLeft(); dirs[2] = toDest.rotateRight(); } else { dirs[2] = toDest.rotateLeft(); dirs[1] = toDest.rotateRight(); } if (rand.nextDouble() < 0.5){ dirs[3] = toDest.rotateLeft().rotateLeft(); dirs[4] = toDest.rotateRight().rotateRight(); } else { dirs[4] = toDest.rotateLeft().rotateLeft(); dirs[3] = toDest.rotateRight().rotateRight(); } return dirs; } public Direction[] getDirectionsAway(MapLocation dest) { Direction toDest = rc.getLocation().directionTo(dest).opposite(); Direction[] dirs = new Direction[5]; dirs[0] = toDest; if (rand.nextDouble() < 0.5){ dirs[1] = toDest.rotateLeft(); dirs[2] = toDest.rotateRight(); } else { dirs[2] = toDest.rotateLeft(); dirs[1] = toDest.rotateRight(); } if (rand.nextDouble() < 0.5){ dirs[3] = toDest.rotateLeft().rotateLeft(); dirs[4] = toDest.rotateRight().rotateRight(); } else { dirs[4] = toDest.rotateLeft().rotateLeft(); dirs[3] = toDest.rotateRight().rotateRight(); } return dirs; } public Direction getMoveDir(MapLocation dest) { Direction[] dirs = getDirectionsToward(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirAway(MapLocation dest) { Direction[] dirs = getDirectionsAway(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirRand(MapLocation dest) { //TODO return a random direction Direction[] dirs = getDirectionsToward(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirAwayRand(MapLocation dest) { //TODO return a random direction Direction[] dirs = getDirectionsAway(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } //Will return a single direction for spawning. (Uses getDirectionsToward()) public Direction getSpawnDir(RobotType type) { Direction[] dirs = getDirectionsToward(this.theirHQ); for (Direction d : dirs) { if (rc.canSpawn(d, type)) { return d; } } dirs = getDirectionsToward(this.myHQ); for (Direction d : dirs) { if (rc.canSpawn(d, type)) { return d; } else { // //System.out.println("Could not find valid spawn location!"); } } return null; } //Will return a single direction for building. (Uses getDirectionsToward()) public Direction getBuildDir(RobotType type) { Direction[] dirs = getDirectionsToward(this.theirHQ); for (Direction d : dirs) { if (rc.canBuild(d, type)) { return d; } } dirs = getDirectionsToward(this.myHQ); for (Direction d : dirs) { if (rc.canBuild(d, type)) { return d; } else { // //System.out.println("Could not find valid build location!"); } } return null; } public RobotInfo[] getAllies() { RobotInfo[] allies = rc.senseNearbyRobots(Integer.MAX_VALUE, myTeam); return allies; } public RobotInfo[] getEnemiesInAttackingRange() { RobotInfo[] enemies = rc.senseNearbyRobots(myRange, theirTeam); return enemies; } public Direction getDirOfLauncherTarget() { int startingByteCode = Clock.getBytecodeNum(); MapLocation myLocation = rc.getLocation(); Direction[] targetDirections = getDirectionsToward(theirHQ); MapLocation[] targets = new MapLocation[5]; for (int i=0; i<targetDirections.length; i++){ targets[i] = myLocation.add(targetDirections[i], 3); } for (int j = 0; j < targets.length; j++) { if (Clock.getBytecodesLeft() > 500) { int teammates = 0; MapLocation targetCenter = targets[j]; RobotInfo[] allRobotsInTargetArea = rc.senseNearbyRobots( targetCenter, 15, null); for (RobotInfo robot : allRobotsInTargetArea) { if (robot.team == myTeam) teammates++; } if (allRobotsInTargetArea.length >= 2 * teammates) { // //System.out.println("getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode)); return myLocation.directionTo(targetCenter); } } } // System.out.println("FAILED getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode)); return null; } public void attackLeastHealthEnemy(RobotInfo[] enemies) throws GameActionException { if (enemies.length == 0) { return; } double minEnergon = Double.MAX_VALUE; MapLocation toAttack = null; for (RobotInfo info : enemies) { if (info.health < minEnergon) { toAttack = info.location; minEnergon = info.health; } } if (toAttack != null) { rc.attackLocation(toAttack); } } public void attackLeastHealthEnemyInRange() throws GameActionException { RobotInfo[] enemies = getEnemiesInAttackingRange(); if (enemies.length > 0) { if (rc.isWeaponReady()) { attackLeastHealthEnemy(enemies); } } } public void moveToRallyPoint() throws GameActionException { if (rc.isCoreReady()) { int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X); int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y); MapLocation rallyPoint = new MapLocation(rallyX, rallyY); if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack && rc.getLocation().distanceSquaredTo(rallyPoint) > 8 + Clock.getRoundNum() / 100) { moveOptimally(getDirectionsToward(rallyPoint)); } else { Direction newDir = getMoveDir(rallyPoint); if (newDir != null && rc.canMove(newDir)) { rc.move(newDir); } } } } //Returns the current rally point MapLocation public MapLocation getRallyPoint() throws GameActionException { int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X); int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y); MapLocation rallyPoint = new MapLocation(rallyX, rallyY); return rallyPoint; } //Moves a random safe direction from input array public void moveOptimally(Direction[] optimalDirections) throws GameActionException { //TODO check safety if (optimalDirections != null) { boolean lookingForDirection = true; int attemptForDirection = 0; while(lookingForDirection){ MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); Direction currentDirection = optimalDirections[attemptForDirection]; //Direction currentDirection = optimalDirections[(int) (rand.nextDouble()*optimalDirections.length)]; MapLocation tileInFront = rc.getLocation().add(currentDirection); //check that the direction in front is not a tile that can be attacked by the enemy towers boolean tileInFrontSafe = true; for(MapLocation m: enemyTowers){ if(m.distanceSquaredTo(tileInFront)<=RobotType.TOWER.attackRadiusSquared+1){ tileInFrontSafe = false; break; } } //check that we are not facing off the edge of the map TerrainTile terrainTileInFront = rc.senseTerrainTile(tileInFront); if(!tileInFrontSafe || !rc.isPathable(myType, tileInFront) || terrainTileInFront == TerrainTile.OFF_MAP || (myType != RobotType.DRONE && terrainTileInFront!=TerrainTile.NORMAL)){ //currentDirection = currentDirection.rotateLeft(); attemptForDirection++; if (attemptForDirection == optimalDirections.length) { // //System.out.println("No suitable direction found!"); return; } }else{ //try to move in the currentDirection direction if(currentDirection != null && rc.isCoreReady() && rc.canMove(currentDirection)){ rc.move(currentDirection); lookingForDirection = false; return; } } } } } //Gets optimal directions and then calls moveOptimally() with those directions. public void moveOptimally() throws GameActionException { Direction[] optimalDirections = getOptimalDirections(); if (optimalDirections != null) { moveOptimally(optimalDirections); } } //TODO Finish public Direction[] getOptimalDirections() throws GameActionException { // The switch statement should result in an array of directions that make sense //for the RobotType. Safety is considered in moveOptimally() RobotType currentRobotType = rc.getType(); Direction[] optimalDirections = null; switch(currentRobotType){ case BASHER: optimalDirections = getDirectionsToward(this.theirHQ); break; case BEAVER: if (getDistanceSquared(this.myHQ) < 50){ optimalDirections = getDirectionsAway(this.myHQ); } optimalDirections = Direction.values(); break; case COMMANDER: break; case COMPUTER: break; case DRONE: optimalDirections = getDirectionsToward(this.theirHQ); break; case LAUNCHER: optimalDirections = getDirectionsToward(this.theirHQ); break; case MINER: if (getDistanceSquared(this.myHQ) < 50){ optimalDirections = getDirectionsToward(this.myHQ); } optimalDirections = Direction.values(); break; case MISSILE: break; case SOLDIER: optimalDirections = getDirectionsToward(this.theirHQ); break; case TANK: optimalDirections = getDirectionsToward(this.theirHQ); break; default: } //Done RobotType specific actions. return optimalDirections; } //Spawns or Queues the unit if it is needed public boolean tryToSpawn(RobotType spawnType) throws GameActionException{ int round = Clock.getRoundNum(); double ore = rc.getTeamOre(); int spawnTypeInt = RobotTypeToInt(spawnType); int spawnQueue = rc.readBroadcast(smuIndices.freqQueue); int currentAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+0); int desiredAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+1); int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+2); //Check if we actually need anymore spawnType units if (round > roundToBeginSpawning && currentAmount < desiredAmount){ if(ore > myType.oreCost){ if (spawnUnit(spawnType)) return true; } else { //Add spawnType to queue if (spawnQueue == 0){ rc.broadcast(smuIndices.freqQueue, spawnTypeInt); } return false; } } return false; } //Spawns unit based on calling type. Performs all checks. public boolean spawnOptimally() throws GameActionException { if (rc.isCoreReady()){ int spawnQueue = rc.readBroadcast(smuIndices.freqQueue); switch(myType){ case BARRACKS: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.SOLDIER)){ if (tryToSpawn(RobotType.SOLDIER)) return true; } if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BASHER)){ if (tryToSpawn(RobotType.BASHER)) return true; } break; case HQ: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BEAVER)){ if (tryToSpawn(RobotType.BEAVER)) return true; } break; case HELIPAD: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.DRONE)){ if (tryToSpawn(RobotType.DRONE)) return true; } break; case AEROSPACELAB: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.LAUNCHER)){ if (tryToSpawn(RobotType.LAUNCHER)) return true; } break; case MINERFACTORY: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.MINER)){ if (tryToSpawn(RobotType.MINER)) return true; } break; case TANKFACTORY: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.TANK)){ if (tryToSpawn(RobotType.TANK)) return true; } break; case TECHNOLOGYINSTITUTE: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMPUTER)){ if (tryToSpawn(RobotType.COMPUTER)) return true; } break; case TRAININGFIELD: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMMANDER)){ if (tryToSpawn(RobotType.COMMANDER)) return true; } break; default: // System.out.println("ERROR: No building type match found in spawnOptimally()!"); return false; } }//isCoreReady return false; } //Gets direction, checks delays, and spawns unit public boolean spawnUnit(RobotType spawnType) { //Get a direction and then actually spawn the unit. Direction randomDir = getSpawnDir(spawnType); if(rc.isCoreReady() && randomDir != null){ try { if (rc.canSpawn(randomDir, spawnType)) { rc.spawn(randomDir, spawnType); if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == spawnType) { rc.broadcast(smuIndices.freqQueue, 0); } incrementCount(spawnType); return true; } } catch (GameActionException e) { e.printStackTrace(); } } return false; } //Spawns unit based on calling type. Performs all checks. public void buildOptimally() throws GameActionException { int round = Clock.getRoundNum(); double ore = rc.getTeamOre(); boolean buildingsOutrankUnits = true; int queue = rc.readBroadcast(smuIndices.freqQueue); RobotType[] arrayOfStructures = new RobotType[] {RobotType.AEROSPACELAB, RobotType.BARRACKS, RobotType.HANDWASHSTATION, RobotType.HELIPAD, RobotType.HQ, RobotType.MINERFACTORY, RobotType.SUPPLYDEPOT, RobotType.TANKFACTORY, RobotType.TECHNOLOGYINSTITUTE, RobotType.TOWER, RobotType.TRAININGFIELD}; //If there is something in the queue and we can not replace it, then return if (queue != 0 && !buildingsOutrankUnits){ System.out.println("Queue full, can't outrank"); return; } //Check if there is a building in queue if (Arrays.asList(arrayOfStructures).contains(IntToRobotType(queue))) { //Build it if we can afford it if (ore > IntToRobotType(queue).oreCost) { System.out.println("INFO: Satisfying queue. ("+IntToRobotType(queue).name()+")"); buildUnit(IntToRobotType(queue)); } //Return either way, we can't replace buildings in the queue return; } //Loop over structures and build or queue any needed ones for (RobotType structure : arrayOfStructures) { int intStructure = RobotTypeToInt(structure); double weightOfStructure = getWeightOfRobotType(IntToRobotType(intStructure)); if (weightOfStructure == 1.0){ if (ore > IntToRobotType(intStructure).oreCost){ buildUnit(IntToRobotType(intStructure)); System.out.println("Tried to build "+ IntToRobotType(intStructure)); } else { rc.broadcast(smuIndices.freqQueue, intStructure); System.out.println("Scheduled a " + IntToRobotType(intStructure).name() + ". Need " + (IntToRobotType(intStructure).oreCost-ore) + " more ore."); } return; } }//end loop of structures } //Gets direction, checks delays, and builds unit public boolean buildUnit(RobotType buildType) { //Get a direction and then actually build the unit. Direction randomDir = getBuildDir(buildType); if(rc.isCoreReady() && randomDir != null){ try { if (rc.canBuild(randomDir, buildType)) { rc.build(randomDir, buildType); if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == buildType) { rc.broadcast(smuIndices.freqQueue, 0); } incrementCount(buildType); return true; } } catch (GameActionException e) { e.printStackTrace(); } } return false; } //Increment the currentAmount of a RobotType public void incrementCount(RobotType type) throws GameActionException { int intType = RobotTypeToInt(type); int currentAmount = rc.readBroadcast(smuIndices.channel[intType]+0); rc.broadcast(smuIndices.channel[intType+0], currentAmount+1); } public void transferSupplies() throws GameActionException { double lowestSupply = rc.getSupplyLevel(); if (lowestSupply == 0) { return; } int roundStart = Clock.getRoundNum(); final MapLocation myLocation = rc.getLocation(); RobotInfo[] nearbyAllies = rc.senseNearbyRobots(myLocation,GameConstants.SUPPLY_TRANSFER_RADIUS_SQUARED,rc.getTeam()); double transferAmount = 0; MapLocation suppliesToThisLocation = null; for(RobotInfo ri:nearbyAllies){ if (!ri.type.isBuilding && ri.supplyLevel < lowestSupply) { lowestSupply = ri.supplyLevel; transferAmount = (rc.getSupplyLevel()-ri.supplyLevel)/2; suppliesToThisLocation = ri.location; } } if(suppliesToThisLocation!=null){ if (roundStart == Clock.getRoundNum() && transferAmount > 0 && Clock.getBytecodesLeft() > 550) { try { rc.transferSupplies((int)transferAmount, suppliesToThisLocation); } catch(GameActionException gax) { gax.printStackTrace(); } } } } // true, I'm in the convoy or going to be // false, no place in the convoy for me public boolean formSupplyConvoy() { try { if (rc.readBroadcast(smuIndices.STRATEGY) == smuConstants.STRATEGY_DRONE_CONTAIN) { return false; } } catch (GameActionException e1) { e1.printStackTrace(); } Direction directionForChain = getSupplyConvoyDirection(myHQ); RobotInfo minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, myHQ, directionForChain); if (minerAtEdge == null){ goToLocation(myHQ.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY)); return true; } else if (minerAtEdge.ID == rc.getID()) { return true; } RobotInfo previousMiner = null; try { while ((minerAtEdge != null || !minerAtEdge.type.isBuilding) && minerAtEdge.location.distanceSquaredTo(getRallyPoint()) > 4) { directionForChain = getSupplyConvoyDirection(minerAtEdge.location); previousMiner = minerAtEdge; minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, minerAtEdge.location, directionForChain); if (minerAtEdge == null) { goToLocation(previousMiner.location.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY)); return true; } else if (minerAtEdge.ID == rc.getID()) { return true; } } } catch (GameActionException e) { e.printStackTrace(); } return false; } public Direction getSupplyConvoyDirection(MapLocation startLocation) { Direction directionForChain = myHQ.directionTo(theirHQ); MapLocation locationToGo = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL && rc.canSenseLocation(locationToGo)) { RobotInfo robotInDirection; try { robotInDirection = rc.senseRobotAtLocation(locationToGo); if (robotInDirection == null || !robotInDirection.type.isBuilding) { return directionForChain; } } catch (GameActionException e) { e.printStackTrace(); } } Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST, Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST}; for (int i = 0; i < directions.length; i++) { locationToGo = startLocation.add(directions[i], smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (directions[i] != directionForChain && directions[i] != Direction.OMNI && directions[i] != Direction.NONE && rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) { RobotInfo robotInDirection; try { robotInDirection = rc.senseRobotAtLocation(locationToGo); if (robotInDirection == null || !robotInDirection.type.isBuilding) { return directions[i]; } } catch (GameActionException e) { e.printStackTrace(); } } } return Direction.NONE; } public RobotInfo getUnitAtEdgeOfSupplyRangeOf(RobotType unitType, MapLocation startLocation, Direction directionForChain) { MapLocation locationInChain = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (rc.canSenseLocation(locationInChain)) { try { return rc.senseRobotAtLocation(locationInChain); } catch (GameActionException e) { e.printStackTrace(); } } return null; } public MapLocation getSecondBaseLocation() { Direction directionToTheirHQ = myHQ.directionTo(theirHQ); MapLocation secondBase = null; if (directionToTheirHQ == Direction.EAST || directionToTheirHQ == Direction.WEST) { secondBase = getSecondBaseLocationInDirections(Direction.NORTH, Direction.SOUTH); } else if (directionToTheirHQ == Direction.NORTH || directionToTheirHQ == Direction.SOUTH) { secondBase = getSecondBaseLocationInDirections(Direction.EAST, Direction.WEST); } else { Direction[] directions = breakdownDirection(directionToTheirHQ); secondBase = getSecondBaseLocationInDirections(directions[0], directions[1]); } if (secondBase != null) { secondBase = secondBase.add(myHQ.directionTo(secondBase), 4); } return secondBase; } public MapLocation getSecondBaseLocationInDirections(Direction dir1, Direction dir2) { MapLocation towers[] = rc.senseTowerLocations(); int maxDistance = Integer.MIN_VALUE; int maxDistanceIndex = -1; Direction dirToEnemy = myHQ.directionTo(theirHQ); Direction dir1left = dir1.rotateLeft(); Direction dir1right = dir1.rotateRight(); Direction dir2left = dir2.rotateLeft(); Direction dir2right = dir2.rotateRight(); for (int i = 0; i<towers.length; i++) { Direction dirToTower = myHQ.directionTo(towers[i]); if (dirToTower == dir1 || dirToTower == dir2 || (dir1left != dirToEnemy && dirToTower == dir1left) || (dir1right != dirToEnemy && dirToTower == dir1right) || (dir2left != dirToEnemy && dirToTower == dir2left) || (dir2right != dirToEnemy && dirToTower == dir2right)) { int distanceToTower = myHQ.distanceSquaredTo(towers[i]); if (distanceToTower > maxDistance) { maxDistance = distanceToTower; maxDistanceIndex = i; } } } if (maxDistanceIndex != -1) { return towers[maxDistanceIndex]; } return null; } public void beginningOfTurn() { if (rc.senseEnemyHQLocation() != null) { this.theirHQ = rc.senseEnemyHQLocation(); } } public void endOfTurn() { } public void go() throws GameActionException { beginningOfTurn(); execute(); endOfTurn(); } public void execute() throws GameActionException { rc.yield(); } public void supplyAndYield() throws GameActionException { transferSupplies(); rc.yield(); } public int myContainDirection = smuConstants.CLOCKWISE; public MapLocation myContainPreviousLocation; public void contain() { MapLocation enemyHQ = rc.senseEnemyHQLocation(); MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); MapLocation myLocation = rc.getLocation(); int radiusFromHQ = 24; if (enemyTowers.length >= 2) { radiusFromHQ = 35; } MapLocation toBeContained = null; RobotInfo[] enemies = rc.senseNearbyRobots(myType.sensorRadiusSquared, theirTeam); for (RobotInfo enemy : enemies) { if (myLocation.directionTo(enemy.location) != myLocation.directionTo(enemyHQ)) { toBeContained = enemy.location; break; } } boolean attackingEnemy = false; if (toBeContained != null) { Direction directionToGo = myLocation.directionTo(toBeContained); if (isLocationSafe(myLocation.add(directionToGo))) { attackingEnemy = true; goToLocation(myLocation.add(directionToGo)); } } if (!attackingEnemy && myLocation.distanceSquaredTo(enemyHQ) > radiusFromHQ + 3) { // move towards the HQ try { RobotInfo[] nearbyTeammates = rc.senseNearbyRobots(4, myTeam); int numAttackers = 0; for (RobotInfo teammate : nearbyTeammates) { if (!teammate.type.isBuilding && teammate.type != RobotType.MINER && teammate.type != RobotType.BEAVER) numAttackers++; } if (numAttackers >= getNumAttackersToContain()) { moveOptimally(); } } catch (GameActionException e) { e.printStackTrace(); } } else { MapLocation locationToGo = null; Direction directionToGo = null; if (myContainDirection == smuConstants.CLOCKWISE) { directionToGo = getClockwiseDirection(myLocation, enemyHQ); } else { directionToGo = getCounterClockwiseDirection(myLocation, enemyHQ); } locationToGo = myLocation.add(directionToGo); if (rc.isPathable(myType, locationToGo)) { if (isLocationSafe(locationToGo)) { goToLocation(locationToGo); } else { Direction[] directions = breakdownDirection(directionToGo); for (int i = 0; i < directions.length; i++) { locationToGo = myLocation.add(directions[i]); if (isLocationSafe(locationToGo)) { goToLocation(locationToGo); myContainPreviousLocation = myLocation; return; } } } } else if (myContainPreviousLocation.equals(myLocation)){ if (myContainDirection == smuConstants.CLOCKWISE) { myContainDirection = smuConstants.COUNTERCLOCKWISE; } else { myContainDirection = smuConstants.CLOCKWISE; } } } myContainPreviousLocation = myLocation; } public int getNumAttackersToContain() { if (myType == RobotType.SOLDIER) { return 2; } else if (myType == RobotType.TANK) { return 1; } else if (myType == RobotType.DRONE) { return 1; } else { return 2; } } public boolean isLocationSafe(MapLocation location) { int hqAttackRadius = RobotType.HQ.attackRadiusSquared; if (rc.senseEnemyTowerLocations().length >= 2) hqAttackRadius = 35; if (location.distanceSquaredTo(theirHQ) > hqAttackRadius) { for (MapLocation tower : rc.senseEnemyTowerLocations()) { if (location.distanceSquaredTo(tower) <= RobotType.TOWER.attackRadiusSquared) { return false; } } return true; } return false; } public Direction[] breakdownDirection(Direction direction) { Direction[] breakdown = new Direction[2]; switch(direction) { case NORTH_EAST: breakdown[0] = Direction.NORTH; breakdown[1] = Direction.EAST; break; case SOUTH_EAST: breakdown[0] = Direction.SOUTH; breakdown[1] = Direction.EAST; break; case NORTH_WEST: breakdown[0] = Direction.NORTH; breakdown[1] = Direction.WEST; break; case SOUTH_WEST: breakdown[0] = Direction.SOUTH; breakdown[1] = Direction.WEST; break; default: break; } return breakdown; } public Direction getClockwiseDirection(MapLocation myLocation, MapLocation anchor) { Direction directionToAnchor = myLocation.directionTo(anchor); if (directionToAnchor.equals(Direction.EAST) || directionToAnchor.equals(Direction.SOUTH_EAST)) { return Direction.NORTH_EAST; } else if (directionToAnchor.equals(Direction.SOUTH) || directionToAnchor.equals(Direction.SOUTH_WEST)) { return Direction.SOUTH_EAST; } else if (directionToAnchor.equals(Direction.WEST) || directionToAnchor.equals(Direction.NORTH_WEST)) { return Direction.SOUTH_WEST; } else if (directionToAnchor.equals(Direction.NORTH) || directionToAnchor.equals(Direction.NORTH_EAST)) { return Direction.NORTH_WEST; } return Direction.NONE; } public Direction getCounterClockwiseDirection(MapLocation myLocation, MapLocation anchor) { Direction oppositeDirection = getClockwiseDirection(myLocation, anchor); if (oppositeDirection.equals(Direction.NORTH_EAST)) { return Direction.SOUTH_WEST; } else if (oppositeDirection.equals(Direction.SOUTH_EAST)) { return Direction.NORTH_WEST; } else if (oppositeDirection.equals(Direction.SOUTH_WEST)) { return Direction.NORTH_EAST; } else if (oppositeDirection.equals(Direction.NORTH_WEST)) { return Direction.SOUTH_WEST; } return Direction.NONE; } // Defend public boolean defendSelf() { RobotInfo[] nearbyEnemies = getEnemiesInAttackRange(); if(nearbyEnemies != null && nearbyEnemies.length > 0) { try { if (rc.isWeaponReady()) { attackLeastHealthEnemyInRange(); } } catch (GameActionException e) { e.printStackTrace(); } return true; } return false; } public boolean defendTeammates() { RobotInfo[] engagedRobots = getRobotsEngagedInAttack(); if(engagedRobots != null && engagedRobots.length>0) { // Check broadcasts for enemies that are being attacked // TODO: Calculate which enemy is attacking/within range/closest to teammate // For now, just picking the first enemy // Once our unit is in range of the other unit, A1 will takeover for (RobotInfo robot : engagedRobots) { if (robot.team == theirTeam) { goToLocation(robot.location); } } return true; } return false; } public boolean defend() { // A1, Protect Self boolean isProtectingSelf = defendSelf(); if (isProtectingSelf) { return true; } // A2, Protect Nearby boolean isProtectingTeammates = defendTeammates(); if (isProtectingTeammates) { return true; } return false; } public int RobotTypeToInt(RobotType type){ switch(type) { case AEROSPACELAB: return 1; case BARRACKS: return 2; case BASHER: return 3; case BEAVER: return 4; case COMMANDER: return 5; case COMPUTER: return 6; case DRONE: return 7; case HANDWASHSTATION: return 8; case HELIPAD: return 9; case HQ: return 10; case LAUNCHER: return 11; case MINER: return 12; case MINERFACTORY: return 13; case MISSILE: return 14; case SOLDIER: return 15; case SUPPLYDEPOT: return 16; case TANK: return 17; case TANKFACTORY: return 18; case TECHNOLOGYINSTITUTE: return 19; case TOWER: return 20; case TRAININGFIELD: return 21; default: return -1; } } public RobotType IntToRobotType(int type){ switch(type) { case 1: return RobotType.AEROSPACELAB; case 2: return RobotType.BARRACKS; case 3: return RobotType.BASHER; case 4: return RobotType.BEAVER; case 5: return RobotType.COMMANDER; case 6: return RobotType.COMPUTER; case 7: return RobotType.DRONE; case 8: return RobotType.HANDWASHSTATION; case 9: return RobotType.HELIPAD; case 10: return RobotType.HQ; case 11: return RobotType.LAUNCHER; case 12: return RobotType.MINER; case 13: return RobotType.MINERFACTORY; case 14: return RobotType.MISSILE; case 15: return RobotType.SOLDIER; case 16: return RobotType.SUPPLYDEPOT; case 17: return RobotType.TANK; case 18: return RobotType.TANKFACTORY; case 19: return RobotType.TECHNOLOGYINSTITUTE; case 20: return RobotType.TOWER; case 21: return RobotType.TRAININGFIELD; default: return null; } } // //Returns a weight representing the 'need' for the RobotType // public double getWeightOfRobotType(RobotType type) throws GameActionException { // int typeInt = RobotTypeToInt(type); // if (rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) == 0) return 0; // double weight = rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt) + // (rc.readBroadcast(smuIndices.freqRoundToFinish + typeInt) - rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt)) / // rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) * rc.readBroadcast(smuIndices.freqNum[typeInt]); // return weight; // } //Returns a weight representing the 'need' for the RobotType public double getWeightOfRobotType(RobotType type) throws GameActionException { int typeInt = RobotTypeToInt(type); int round = Clock.getRoundNum(); double weight = 0; if (!type.isBuilding) { int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0); int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1); int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+2); int roundToFinishSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+3); //Return zero if unit is not desired. (Divide by zero protection) if (desiredAmount == 0) { //System.out.println("Error: No desired "+IntToRobotType(typeInt)); return 0; } if (roundToBeginSpawning >= roundToFinishSpawning) { //System.out.println("Error: build > finish for: "+IntToRobotType(typeInt)); return 0; } if (round < roundToBeginSpawning) { //System.out.println("Error: Too early for "+IntToRobotType(typeInt)); return 0; } //The weight is equal to a point on the surface drawn by z = x^(m*y) where double x = (double) (round - roundToBeginSpawning) / (double) (roundToFinishSpawning - roundToBeginSpawning); double y = (double) currentAmount / (double) desiredAmount; weight = smuConstants.weightScaleMagic * Math.pow(x, (smuConstants.weightExponentMagic + y)); //System.out.println("type: "+IntToRobotType(typeInt)+" x: " + x + " y: " + y + " weight: " + weight); return weight; } //end units if (type.isBuilding){ int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0); int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1); int nextRoundToBuild = rc.readBroadcast(smuIndices.channel[typeInt]+2+currentAmount); int intQueuedType = rc.readBroadcast(smuIndices.freqQueue); if (currentAmount < desiredAmount && nextRoundToBuild != 0) { if (round > nextRoundToBuild && typeInt != intQueuedType) { //TODO We need to check if we are currently building it... System.out.println("Warning: round > nextRoundToBuild && not queued >> " + type.name()); return 1.0; } if (round == nextRoundToBuild) { return 1.0; } if (round < nextRoundToBuild) { return 0.0; } System.out.println("ERROR: Unexpected return path in getWeightOfRobotType " + type.name()); return weight; } else { return 0; } } //end structures System.out.println("ERROR: Unexpected return path in getWeightOfRobotType"); return weight; } public RobotInfo[] getEnemiesInAttackRange() { return rc.senseNearbyRobots(myRange, theirTeam); } //TODO Use optimally instead? public void goToLocation(MapLocation location) { try { if (rc.canSenseLocation(location) && rc.senseRobotAtLocation(location) != null && rc.getLocation().distanceSquaredTo(location)<3) { // 3 squares return; } Direction direction = getMoveDir(location); RobotInfo[] nearbyEnemies = rc.senseNearbyRobots(rc.getLocation().add(direction), RobotType.TOWER.attackRadiusSquared, theirTeam); boolean towersNearby = false; for (RobotInfo enemy : nearbyEnemies) { if (enemy.type == RobotType.TOWER || enemy.type == RobotType.HQ) { towersNearby = true; break; } } if (!towersNearby || Clock.getRoundNum() > smuConstants.roundToLaunchAttack) { if (direction != null && rc.isCoreReady() && rc.canMove(direction) && Clock.getBytecodesLeft() > 55) { rc.move(direction); } } } catch (GameActionException e1) { e1.printStackTrace(); } } public RobotInfo[] getRobotsEngagedInAttack() { RobotInfo[] nearbyRobots = rc.senseNearbyRobots(smuConstants.PROTECT_OTHERS_RANGE); boolean hasEnemy = false; boolean hasFriendly = false; for (RobotInfo robot : nearbyRobots) { if(robot.team == theirTeam && robot.type != RobotType.TOWER) { hasEnemy = true; if (hasFriendly) { return nearbyRobots; } } else { hasFriendly = true; if (hasEnemy) { return nearbyRobots; } } } return null; } public RobotInfo[] getTeammatesInAttackRange() { return rc.senseNearbyRobots(myRange, myTeam); } public RobotInfo[] getTeammatesNearTower(MapLocation towerLocation) { return rc.senseNearbyRobots(towerLocation, RobotType.TOWER.attackRadiusSquared, myTeam); } // Find out if there are any holes between a teams tower and their HQ public MapLocation[] computeHoles() { MapLocation[] towerLocations = rc.senseTowerLocations(); MapLocation[][] towerRadii = new MapLocation[towerLocations.length][]; for(int i = 0; i < towerLocations.length; i++) { // Get all map locations that a tower can attack MapLocation[] locations = MapLocation.getAllMapLocationsWithinRadiusSq(towerLocations[i], RobotType.TOWER.attackRadiusSquared); Arrays.sort(locations); towerRadii[i] = locations; } if(towerRadii.length == 0 || towerRadii[0] == null) { return null; } // Naively say, if overlapping by two towers, there is no path int[] overlapped = new int[towerRadii.length]; int holesBroadcastIndex = smuIndices.TOWER_HOLES_BEGIN; for(int i = 0; i<towerRadii.length; i++) { MapLocation[] locations = towerRadii[i]; boolean coveredLeft = false; boolean coveredRight = false; boolean coveredTop = false; boolean coveredBottom = false; for (int j = 0; j < towerRadii.length; j++) { if (j != i) { MapLocation[] otherLocations = towerRadii[j]; if (locations[0].x <= otherLocations[otherLocations.length-1].x && otherLocations[0].x <= locations[locations.length-1].x && locations[0].y <= otherLocations[otherLocations.length-1].y && otherLocations[0].y <= locations[locations.length-1].y) { overlapped[i]++; Direction otherTowerDir = towerLocations[i].directionTo(towerLocations[j]); if (otherTowerDir.equals(Direction.EAST) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.SOUTH_EAST)) { coveredLeft = true; } if (otherTowerDir.equals(Direction.WEST) || otherTowerDir.equals(Direction.NORTH_WEST) || otherTowerDir.equals(Direction.SOUTH_WEST)) { coveredRight = true; } if (otherTowerDir.equals(Direction.NORTH) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.NORTH_WEST)) { coveredTop = true; } if (otherTowerDir.equals(Direction.SOUTH) || otherTowerDir.equals(Direction.SOUTH_EAST) || otherTowerDir.equals(Direction.SOUTH_WEST)) { coveredBottom = true; } } } } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x - 1, locations[0].y))) { overlapped[i]++; coveredLeft = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[locations.length-1].x + 1, locations[0].y))) { overlapped[i]++; coveredRight = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[0].y - 1))) { overlapped[i]++; coveredTop = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[locations.length-1].y + 1))) { overlapped[i]++; coveredBottom = true; } // //System.out.println("Tower " + i + " overlapped " + overlapped[i] + " " + towerLocations[i]); if (overlapped[i] < 2) { try { int towerAttackRadius = (int) Math.sqrt(RobotType.TOWER.attackRadiusSquared) + 1; if (!coveredLeft) { // //System.out.println("Tower " + towerLocations[i] + " Not covered left"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x - towerAttackRadius); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y); holesBroadcastIndex+=2; } if (!coveredRight) { // //System.out.println("Tower " + towerLocations[i] + " Not covered right"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x + towerAttackRadius); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y); holesBroadcastIndex+=2; } if (!coveredTop) { // //System.out.println("Tower " + towerLocations[i] + " Not covered top"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y - towerAttackRadius); holesBroadcastIndex+=2; } if (!coveredBottom) { // //System.out.println("Tower " + towerLocations[i] + " Not covered bottom"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y + towerAttackRadius); holesBroadcastIndex+=2; } } catch (GameActionException e) { e.printStackTrace(); } } } // Signify end of holes try { rc.broadcast(holesBroadcastIndex, -1); } catch (GameActionException e) { e.printStackTrace(); } // //System.out.println("BYTEEND on " + Clock.getRoundNum() + ": " + Clock.getBytecodeNum()); return null; } } //----- Per RoboType code below ----- //HQ public static class HQ extends BaseBot { public int xMin, xMax, yMin, yMax; public int xpos, ypos; public int totalNormal, totalVoid, totalProcessed; public int towerThreat; public static double ratio; public boolean isFinishedAnalyzing = false; public boolean analyzedTowers = false; public int defaultStrategy = smuConstants.STRATEGY_TANKS_AND_SOLDIERS; public boolean hasChosenStrategyPrior = false; public int strategy = defaultStrategy; public int prevStrategy = 0; public int numTowers; public int numEnemyTowers; public boolean dronesFailed = false; public boolean analyzedPrevMatch = false; public HQ(RobotController rc) { super(rc); numTowers = rc.senseTowerLocations().length; numEnemyTowers = rc.senseEnemyTowerLocations().length; xMin = Math.min(this.myHQ.x, this.theirHQ.x); xMax = Math.max(this.myHQ.x, this.theirHQ.x); yMin = Math.min(this.myHQ.y, this.theirHQ.y); yMax = Math.max(this.myHQ.y, this.theirHQ.y); xpos = xMin; ypos = yMin; totalNormal = totalVoid = totalProcessed = 0; towerThreat = 0; isFinishedAnalyzing = false; try { computeStrategy(); } catch (GameActionException e) { e.printStackTrace(); } computeHoles(); } public void analyzePreviousMatch() { long[] prevGameTeamMemory = rc.getTeamMemory(); boolean hasData = false; for (long memory : prevGameTeamMemory) { if (memory != 0) { hasData = true; break; } } if (hasData) { double prevRatio = ((double) prevGameTeamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT])/100.0; int mostUsed = 0; int mostUsedIndex = -1; int secondMostUsed = 0; int secondMostUsedIndex = -1; for(int i = 0; i < 6; i++) { // 6 is number of different strategies int numRoundsUsed = (int) prevGameTeamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + i]; if (numRoundsUsed > mostUsed) { secondMostUsed = mostUsed; secondMostUsedIndex = mostUsedIndex; mostUsed = numRoundsUsed; mostUsedIndex = i; } else if (numRoundsUsed > secondMostUsed) { secondMostUsed = numRoundsUsed; secondMostUsedIndex = i; } } if (mostUsed == smuConstants.STRATEGY_DRONE_CONTAIN || mostUsed == smuConstants.STRATEGY_DRONE_SWARM) { dronesFailed = true; // System.out.println(Clock.getRoundNum() + " Drones failed."); } else { if (ratio > 0.85 && prevRatio > 0.85) { // Both Traversables int i = 0; while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + i] != 0) { i++; } int ourTowersDestroyed = i; int j = 0; while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + j] != 0) { j++; } int theirTowersDestroyed = j; if (ourTowersDestroyed < theirTowersDestroyed) { defaultStrategy = mostUsedIndex + 1; } else { if (secondMostUsedIndex != -1) { defaultStrategy = secondMostUsedIndex + 1; } } } } for (int i = 0; i < GameConstants.TEAM_MEMORY_LENGTH; i++) { rc.setTeamMemory(i, 0); } } analyzedPrevMatch = true; } public void analyzeMap() { while (ypos < yMax + 1) { TerrainTile t = rc.senseTerrainTile(new MapLocation(xpos, ypos)); if (t == TerrainTile.NORMAL) { totalNormal++; totalProcessed++; } else if (t == TerrainTile.VOID) { totalVoid++; totalProcessed++; } xpos++; if (xpos == xMax + 1) { xpos = xMin; ypos++; } if (Clock.getBytecodesLeft() < 50) { return; } } ratio = (double) totalNormal / totalProcessed; isFinishedAnalyzing = true; } public void analyzeTowers() { MapLocation[] towers = rc.senseEnemyTowerLocations(); towerThreat = 0; for (int i=0; i<towers.length; ++i) { MapLocation towerLoc = towers[i]; if ((xMin <= towerLoc.x && towerLoc.x <= xMax && yMin <= towerLoc.y && towerLoc.y <= yMax) || towerLoc.distanceSquaredTo(this.theirHQ) <= 50) { for (int j=0; j<towers.length; ++j) { if (towers[j].distanceSquaredTo(towerLoc) <= 50) { towerThreat++; } } } } analyzedTowers = true; } public void chooseStrategy() throws GameActionException { if (hasChosenStrategyPrior && Clock.getRoundNum() % 250 != 0) { return; } if (rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) == smuConstants.NOT_CURRENTLY_BEING_CONTAINED) { // Test for Swarms MapLocation[] ourTowers = rc.senseTowerLocations(); RobotType swarmingType = null; if (ourTowers != null && ourTowers.length > 0) { int closestTower = -1; int closestDistanceToEnemyHQ = Integer.MAX_VALUE; for (int i = 0; i < ourTowers.length; i++) { int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ); if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) { closestDistanceToEnemyHQ = currDistanceToEnemyHQ; closestTower = i; } } RobotInfo[] enemiesSwarming = rc.senseNearbyRobots(ourTowers[closestTower], 100, theirTeam); if (enemiesSwarming != null && enemiesSwarming.length > 0) { swarmingType = IntToRobotType(getMajorityRobotType(enemiesSwarming)); } } if (ratio <= 0.85) { // Void heavy map if (towerThreat >= 10) { // Defensive Map strategy = smuConstants.STRATEGY_DRONE_SWARM; } else { // Offensive Map strategy = smuConstants.STRATEGY_DRONE_CONTAIN; } } else { // Traversable Map if (swarmingType == RobotType.SOLDIER) { strategy = smuConstants.STRATEGY_TANKS_AND_LAUNCHERS; } else if (swarmingType == RobotType.DRONE) { strategy = smuConstants.STRATEGY_LAUNCHERS; } else if (swarmingType == RobotType.TANK) { strategy = smuConstants.STRATEGY_TANK_SWARM; } else { strategy = defaultStrategy; } } } else { RobotType containingType = IntToRobotType(rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED_BY)); if (containingType == RobotType.DRONE) { strategy = smuConstants.STRATEGY_LAUNCHERS; } else if (containingType == RobotType.TANK) { strategy = smuConstants.STRATEGY_LAUNCHERS; } } //STRATEGY_DRONE_CONTAIN = 1; //STRATEGY_TANKS_AND_SOLDIERS = 2; //STRATEGY_DRONE_SWARM = 3; //STRATEGY_TANKS_AND_LAUNCHERS = 4; //STRATEGY_LAUNCHERS = 5; //STRATEGY_TANK_SWARM = 6; rc.broadcast(smuIndices.STRATEGY, strategy); hasChosenStrategyPrior = true; } public void computeStrategy() throws GameActionException{ if (prevStrategy == strategy) { return; } // [desiredNumOf, roundToBuild, roundToFinish] int[] strategyAEROSPACELAB = new int[3]; int[] strategyBARRACKS = new int[3]; int[] strategyBASHER = new int[3]; int[] strategyBEAVER = new int[3]; int[] strategyCOMMANDER = new int[3]; int[] strategyCOMPUTER = new int[3]; int[] strategyDRONE = new int[3]; int[] strategyHANDWASHSTATION = new int[3]; int[] strategyHELIPAD = new int[3]; int[] strategyHQ = new int[3]; int[] strategyLAUNCHER = new int[3]; int[] strategyMINER = new int[3]; int[] strategyMINERFACTORY = new int[3]; int[] strategyMISSILE = new int[3]; int[] strategySOLDIER = new int[3]; int[] strategySUPPLYDEPOT = new int[3]; int[] strategyTANK = new int[3]; int[] strategyTANKFACTORY = new int[3]; int[] strategyTECHNOLOGYINSTITUTE = new int[3]; int[] strategyTOWER = new int[3]; int[] strategyTRAININGFIELD = new int[3]; if (strategy == smuConstants.STRATEGY_TANKS_AND_SOLDIERS) { System.out.println("COMPUTE STRATEGY: Tanks and Soldiers"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {100, 300, 650, 800}; strategyBASHER = new int[] {50, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 0, 0}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {0}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 0, 0}; strategyMINER = new int[] {50, 1, 500}; strategyMINERFACTORY = new int[] {1, 200}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {120, 200, 1200}; // strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategySUPPLYDEPOT = new int[] {1000, 1400, 1500}; strategyTANK = new int[] {20, 1100, 1800}; strategyTANKFACTORY = new int[] {1000, 1200}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_LAUNCHERS){ System.out.println("COMPUTE STRATEGY: Launchers"); strategyAEROSPACELAB = new int[] {800, 1000}; strategyBARRACKS = new int[] {4, 500, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 0, 0}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {20, 1100, 1700}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {120, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {0, 1100, 1800}; strategyTANKFACTORY = new int[] {0}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_DRONE_CONTAIN) { System.out.println("COMPUTE STRATEGY: Drone Contain"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {0}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 100}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {100, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1, 300}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 1100, 1700}; strategyMINER = new int[] {20, 100, 500}; strategyMINERFACTORY = new int[] {100, 500}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {0, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {0, 1100, 1800}; strategyTANKFACTORY = new int[] {0}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_DRONE_SWARM) { System.out.println("COMPUTE STRATEGY: Drone Swarm"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {2, 500, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {120, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1, 400}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 1100, 1700}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {25, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {0, 0, 0}; strategyTANKFACTORY = new int[] {0}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_TANK_SWARM) { System.out.println("COMPUTE STRATEGY: Tank Swarm"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {2, 100, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {00}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 0, 0}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {60, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {100, 300, 1800}; strategyTANKFACTORY = new int[] {200, 400, 600, 800, 1000}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_TANKS_AND_LAUNCHERS) { System.out.println("COMPUTE STRATEGY: Tanks and Launchers"); strategyAEROSPACELAB = new int[] {1000, 1200}; strategyBARRACKS = new int[] {0, 100, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1, 500, 1000}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {30, 1100, 1700}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {0, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {100, 800, 1800}; strategyTANKFACTORY = new int[] {5, 500, 1400}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } //BE CAREFUL!!! //TODO int[][] strategyUnitArray = new int[][] {strategyBASHER, strategyBEAVER, strategyCOMMANDER, strategyCOMPUTER, strategyDRONE, strategyLAUNCHER, strategyMINER, strategyMISSILE, strategySOLDIER, strategyTANK}; int[] channelUnitArray = new int[] {smuIndices.channelBASHER, smuIndices.channelBEAVER, smuIndices.channelCOMMANDER, smuIndices.channelCOMPUTER, smuIndices.channelDRONE, smuIndices.channelLAUNCHER, smuIndices.channelMINER, smuIndices.channelMISSILE, smuIndices.channelSOLDIER, smuIndices.channelTANK}; int[][] strategyStructureArray = new int[][] {strategyAEROSPACELAB, strategyBARRACKS, strategyHANDWASHSTATION, strategyHELIPAD, strategyHQ, strategyMINERFACTORY, strategySUPPLYDEPOT, strategyTANKFACTORY, strategyTECHNOLOGYINSTITUTE, strategyTOWER, strategyTRAININGFIELD}; int[] channelStructureArray = new int[] {smuIndices.channelAEROSPACELAB, smuIndices.channelBARRACKS, smuIndices.channelHANDWASHSTATION, smuIndices.channelHELIPAD, smuIndices.channelHQ, smuIndices.channelMINERFACTORY, smuIndices.channelSUPPLYDEPOT, smuIndices.channelTANKFACTORY, smuIndices.channelTECHNOLOGYINSTITUTE, smuIndices.channelTOWER, smuIndices.channelTRAININGFIELD}; //Broadcast unit strategies for (int i = 1; i < strategyUnitArray.length; i++) { rc.broadcast(channelUnitArray[i] + 0, 0); rc.broadcast(channelUnitArray[i] + 1, strategyUnitArray[i][0]); rc.broadcast(channelUnitArray[i] + 2, strategyUnitArray[i][1]); rc.broadcast(channelUnitArray[i] + 3, strategyUnitArray[i][2]); } //Broadcast structure strategies for (int i = 1; i < strategyStructureArray.length; i++) { rc.broadcast(channelStructureArray[i] + 0, 0); if (strategyStructureArray[i].length > 1) { rc.broadcast(channelStructureArray[i] + 1, strategyStructureArray[i].length); for (int j = 0; j < strategyStructureArray[i].length; j++) { rc.broadcast(channelStructureArray[i] + j + 2, strategyStructureArray[i][j]); } } else { rc.broadcast(channelStructureArray[i] + 1, 0); rc.broadcast(channelStructureArray[i] + 2, 0); } } prevStrategy = strategy; } public void saveTeamMemory() { long[] teamMemory = rc.getTeamMemory();; int currRound = Clock.getRoundNum(); if (analyzedTowers && teamMemory[smuTeamMemoryIndices.PREV_MAP_TOWER_THREAT] == 0) { rc.setTeamMemory(smuTeamMemoryIndices.PREV_MAP_TOWER_THREAT, towerThreat);; } if (isFinishedAnalyzing && teamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT] == 0) { rc.setTeamMemory(smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT, (long) (ratio * 100)); } rc.setTeamMemory(smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy, teamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy] + 1); if (teamMemory[smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED] == 0) { if (rc.getHealth() < RobotType.HQ.maxHealth) { rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED, currRound); } } int currNumTowers = rc.senseTowerLocations().length; if (currNumTowers < numTowers) { int towersIndex = 0; while (teamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex] != 0) { towersIndex++; } for (int i = 0; i < numTowers - currNumTowers; i++) { rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex + i, currRound); } numTowers = currNumTowers; } int currNumEnemyTowers = rc.senseEnemyTowerLocations().length; if (currNumEnemyTowers < numEnemyTowers) { int towersIndex = 0; while (teamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex] != 0) { towersIndex++; } for (int i = 0; i < numEnemyTowers - currNumEnemyTowers; i++) { rc.setTeamMemory(smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex + i, currRound); } numEnemyTowers = currNumEnemyTowers; } } public RobotType checkContainment() throws GameActionException { RobotInfo[] enemyRobotsContaining = rc.senseNearbyRobots(50, theirTeam); if (enemyRobotsContaining.length > 4) { rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.CURRENTLY_BEING_CONTAINED); int robotTypeContaining = getMajorityRobotType(enemyRobotsContaining); rc.broadcast(smuIndices.HQ_BEING_CONTAINED_BY, robotTypeContaining); return IntToRobotType(robotTypeContaining); } else { rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.NOT_CURRENTLY_BEING_CONTAINED); return null; } } public int getMajorityRobotType(RobotInfo[] enemyRobots) { int[] enemyRobotTypes = new int[22]; //Max RobotType -> int value + 1 int highestValue = 0; int highestValueIndex = -1; for (int i = 0; i < enemyRobots.length; i++) { int robotType = RobotTypeToInt(enemyRobots[i].type); enemyRobotTypes[robotType] = enemyRobotTypes[robotType] + 1; if (enemyRobotTypes[robotType] > highestValue) { highestValue = enemyRobotTypes[robotType]; highestValueIndex = i; } } return highestValueIndex; } public void setRallyPoint() throws GameActionException { MapLocation rallyPoint = null; RobotType beingContained = checkContainment(); if (beingContained == null) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { MapLocation[] ourTowers = rc.senseTowerLocations(); if (ourTowers != null && ourTowers.length > 0) { int closestTower = -1; int closestDistanceToEnemyHQ = Integer.MAX_VALUE; for (int i = 0; i < ourTowers.length; i++) { int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ); if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) { closestDistanceToEnemyHQ = currDistanceToEnemyHQ; closestTower = i; } } rallyPoint = ourTowers[closestTower].add(ourTowers[closestTower].directionTo(theirHQ), 2); } } else { MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); if (enemyTowers == null || enemyTowers.length <= smuConstants.numTowersRemainingToAttackHQ) { rallyPoint = rc.senseEnemyHQLocation(); } else { rallyPoint = enemyTowers[0]; } } } else { rallyPoint = getSecondBaseLocation(); if (rallyPoint != null) { rallyPoint = rallyPoint.add(rallyPoint.directionTo(theirHQ), 8); } } if (rallyPoint != null) { rc.broadcast(smuIndices.RALLY_POINT_X, rallyPoint.x); rc.broadcast(smuIndices.RALLY_POINT_Y, rallyPoint.y); } } public void execute() throws GameActionException { spawnOptimally(); setRallyPoint(); attackLeastHealthEnemyInRange(); transferSupplies(); if (!isFinishedAnalyzing) { analyzeMap(); if (!analyzedTowers) { analyzeTowers(); } } else { if (!analyzedPrevMatch) analyzePreviousMatch(); chooseStrategy(); try { computeStrategy(); } catch (GameActionException e) { e.printStackTrace(); } } if (analyzedPrevMatch) saveTeamMemory(); rc.yield(); } } //BEAVER public static class Beaver extends BaseBot { public MapLocation secondBase; public Beaver(RobotController rc) { super(rc); Random rand = new Random(rc.getID()); if (rand.nextDouble() < smuConstants.percentBeaversToGoToSecondBase) { secondBase = getSecondBaseLocation(); } } public void execute() throws GameActionException { if (secondBase != null && rc.getLocation().distanceSquaredTo(secondBase) > 6) { goToLocation(secondBase); } buildOptimally(); transferSupplies(); if (Clock.getRoundNum() > 400) defend(); if (rc.isCoreReady()) { //mine if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } else { moveOptimally(); } } rc.yield(); } } //MINERFACTORY public static class Minerfactory extends BaseBot { public Minerfactory(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //MINER public static class Miner extends BaseBot { public Miner(RobotController rc) { super(rc); } public void execute() throws GameActionException { boolean inConvoy = false; if (Clock.getRoundNum()>smuConstants.roundToFormSupplyConvoy && rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) != smuConstants.CURRENTLY_BEING_CONTAINED) { inConvoy = formSupplyConvoy(); } if (!inConvoy) { if (!defend()) { if (rc.isCoreReady()) { //mine if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } else { moveOptimally(); } } } } else if(!defendSelf()) { if (rc.isCoreReady()) { if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } } } transferSupplies(); rc.yield(); } } //BARRACKS public static class Barracks extends BaseBot { public Barracks(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //SOLDIER public static class Soldier extends BaseBot { public Soldier(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defend()) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } } transferSupplies(); rc.yield(); } } //BASHER public static class Basher extends BaseBot { public Basher(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } transferSupplies(); rc.yield(); } } //TANK public static class Tank extends BaseBot { public Tank(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defend()) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } } transferSupplies(); rc.yield(); } } //DRONE public static class Drone extends BaseBot { public Drone(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defendSelf()) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } } transferSupplies(); rc.yield(); } } //TOWER public static class Tower extends BaseBot { public Tower(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); attackLeastHealthEnemyInRange(); rc.yield(); } } //SUPPLYDEPOT public static class Supplydepot extends BaseBot { public Supplydepot(RobotController rc) { super(rc); } public void execute() throws GameActionException { rc.yield(); } } //HANDWASHSTATION public static class Handwashstation extends BaseBot { public Handwashstation(RobotController rc) { super(rc); } public void execute() throws GameActionException { rc.yield(); } } //TANKFACTORY public static class Tankfactory extends BaseBot { public Tankfactory(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //HELIPAD public static class Helipad extends BaseBot { public Helipad(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //AEROSPACELAB public static class Aerospacelab extends BaseBot { public Aerospacelab(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //LAUNCHER public static class Launcher extends BaseBot { public Launcher(RobotController rc) { super(rc); } public void execute() throws GameActionException { boolean launched = false; if (rc.getMissileCount() > 0) { Direction targetDir = getDirOfLauncherTarget(); if (targetDir != null && rc.isWeaponReady()){ if (rc.canLaunch(targetDir)){ rc.launchMissile(targetDir); launched = true; } } } if (!launched) { contain(); } rc.yield(); } } //MISSILE public static class Missile extends BaseBot { public Direction dirToTarget = null; public Missile(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (dirToTarget == null) { RobotInfo[] nearbyRobots = rc.senseNearbyRobots(2, myTeam); for (RobotInfo robot : nearbyRobots) { if (robot.type == RobotType.LAUNCHER) { dirToTarget = rc.getLocation().directionTo(robot.location).opposite(); } } // //System.out.println("dirToTarget: "+dirToTarget.name()); } if (rc.isCoreReady() && rc.canMove(dirToTarget)){ rc.move(dirToTarget); } // if (getTeammatesInAttackRange().length <= 1 && getTeammatesInAttackRange().length > 4){ // rc.explode(); // } rc.yield(); } } }
teams/team353/RobotPlayer.java
package team353; import battlecode.common.*; import java.util.*; public class RobotPlayer { public static class smuConstants { public static int roundToLaunchAttack = 1600; public static int roundToDefendTowers = 500; public static int roundToFormSupplyConvoy = 400; // roundToBuildSOLDIERS; public static int RADIUS_FOR_SUPPLY_CONVOY = 2; public static int numTowersRemainingToAttackHQ = 1; public static double weightExponentMagic = 0.3; public static double weightScaleMagic = 0.8; public static int currentOreGoal = 100; public static double percentBeaversToGoToSecondBase = 0.4; // Defence public static int NUM_TOWER_PROTECTORS = 4; public static int NUM_HOLE_PROTECTORS = 3; public static int PROTECT_OTHERS_RANGE = 15; public static int DISTANCE_TO_START_PROTECTING_SQUARED = 200; // Idle States public static MapLocation defenseRallyPoint; public static int PROTECT_HOLE = 1; public static int PROTECT_TOWER = 2; // Supply public static int NUM_ROUNDS_TO_KEEP_SUPPLIED = 20; // Contain public static int CLOCKWISE = 0; public static int COUNTERCLOCKWISE = 1; public static int CURRENTLY_BEING_CONTAINED = 1; public static int NOT_CURRENTLY_BEING_CONTAINED = 2; // Strategies /* * NOTE: If changing these values, alter smuTeamMemoryIndices accordingly */ public static int STRATEGY_DRONE_CONTAIN = 1; public static int STRATEGY_TANKS_AND_SOLDIERS = 2; public static int STRATEGY_DRONE_SWARM = 3; public static int STRATEGY_TANKS_AND_LAUNCHERS = 4; public static int STRATEGY_LAUNCHERS = 5; public static int STRATEGY_TANK_SWARM =6; } public static class smuIndices { public static int RALLY_POINT_X = 0; public static int RALLY_POINT_Y = 1; //Economy public static int freqQueue = 11; public static int STRATEGY = 19; public static int HQ_BEING_CONTAINED = 20; public static int HQ_BEING_CONTAINED_BY = 21; //Strategy broadcasts use frequencies 1000 through 3200! //TODO public static final int channelAEROSPACELAB = 1100; public static final int channelBARRACKS = 1200; public static final int channelBASHER = 1300; public static final int channelBEAVER = 1400; public static final int channelCOMMANDER = 1500; public static final int channelCOMPUTER = 1600; public static final int channelDRONE = 1700; public static final int channelHANDWASHSTATION = 1800; public static final int channelHELIPAD = 1900; public static final int channelHQ = 2000; public static final int channelLAUNCHER = 2100; public static final int channelMINER = 2200; public static final int channelMINERFACTORY = 2300; public static final int channelMISSILE = 2400; public static final int channelSOLDIER = 2500; public static final int channelSUPPLYDEPOT = 2600; public static final int channelTANK = 2700; public static final int channelTANKFACTORY = 2800; public static final int channelTECHNOLOGYINSTITUTE = 2900; public static final int channelTOWER = 3000; public static final int channelTRAININGFIELD = 3100; public static final int[] channel = new int[] {0, channelAEROSPACELAB, channelBARRACKS, channelBASHER, channelBEAVER, channelCOMMANDER, channelCOMPUTER, channelDRONE, channelHANDWASHSTATION, channelHELIPAD, channelHQ, channelLAUNCHER, channelMINER, channelMINERFACTORY, channelMISSILE, channelSOLDIER, channelSUPPLYDEPOT, channelTANK, channelTANKFACTORY, channelTECHNOLOGYINSTITUTE, channelTOWER, channelTRAININGFIELD}; public static int TOWER_HOLES_BEGIN = 4000; } public static class smuTeamMemoryIndices { public static int PREV_MAP_TOWER_THREAT = 0; public static int PREV_MAP_VOID_TYPE_PERCENT = 1; public static int NUM_ROUNDS_USING_STRATEGY_BASE = 1; // Strategies from smuConstants take values 2-7 public static int ROUND_OUR_HQ_ATTACKED = 8; // Round their HQ attacked? public static int ROUND_OUR_TOWER_DESTROYED_BASE = 10; // Base will expand to values 10-16 public static int ROUND_THEIR_TOWER_DESTROYED_BASE = 17; // Base will expand to values 17-23 // public static int ROUND_STARTED_USING_STRATEGY_BASE = 23; // // Base will expand to values 23-29 } public static void run(RobotController rc) throws GameActionException { BaseBot myself; if (rc.getType() == RobotType.HQ) { myself = new HQ(rc); } else if (rc.getType() == RobotType.MINER) { myself = new Miner(rc); } else if (rc.getType() == RobotType.MINERFACTORY) { myself = new Minerfactory(rc); } else if (rc.getType() == RobotType.BEAVER) { myself = new Beaver(rc); } else if (rc.getType() == RobotType.BARRACKS) { myself = new Barracks(rc); } else if (rc.getType() == RobotType.SOLDIER) { myself = new Soldier(rc); } else if (rc.getType() == RobotType.BASHER) { myself = new Basher(rc); } else if (rc.getType() == RobotType.HELIPAD) { myself = new Helipad(rc); } else if (rc.getType() == RobotType.DRONE) { myself = new Drone(rc); } else if (rc.getType() == RobotType.TOWER) { myself = new Tower(rc); } else if (rc.getType() == RobotType.SUPPLYDEPOT) { myself = new Supplydepot(rc); } else if (rc.getType() == RobotType.HANDWASHSTATION) { myself = new Handwashstation(rc); } else if (rc.getType() == RobotType.TANKFACTORY) { myself = new Tankfactory(rc); } else if (rc.getType() == RobotType.TANK) { myself = new Tank(rc); } else if (rc.getType() == RobotType.AEROSPACELAB) { myself = new Aerospacelab(rc); } else if (rc.getType() == RobotType.LAUNCHER) { myself = new Launcher(rc); } else if (rc.getType() == RobotType.MISSILE) { myself = new Missile(rc); } else { myself = new BaseBot(rc); } while (true) { try { myself.go(); } catch (Exception e) { e.printStackTrace(); } } } public static class BaseBot { protected RobotController rc; protected MapLocation myHQ, theirHQ; protected Team myTeam, theirTeam; protected int myRange; protected RobotType myType; static Random rand; public BaseBot(RobotController rc) { this.rc = rc; this.myHQ = rc.senseHQLocation(); this.theirHQ = rc.senseEnemyHQLocation(); this.myTeam = rc.getTeam(); this.theirTeam = this.myTeam.opponent(); this.myType = rc.getType(); this.myRange = myType.attackRadiusSquared; rand = new Random(rc.getID()); } public int getDistanceSquared(MapLocation A, MapLocation B){ return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); } public int getDistanceSquared(MapLocation A){ MapLocation B = rc.getLocation(); return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); } public Direction[] getDirectionsToward(MapLocation dest) { Direction toDest = rc.getLocation().directionTo(dest); Direction[] dirs = new Direction[5]; dirs[0] = toDest; if (rand.nextDouble() < 0.5){ dirs[1] = toDest.rotateLeft(); dirs[2] = toDest.rotateRight(); } else { dirs[2] = toDest.rotateLeft(); dirs[1] = toDest.rotateRight(); } if (rand.nextDouble() < 0.5){ dirs[3] = toDest.rotateLeft().rotateLeft(); dirs[4] = toDest.rotateRight().rotateRight(); } else { dirs[4] = toDest.rotateLeft().rotateLeft(); dirs[3] = toDest.rotateRight().rotateRight(); } return dirs; } public Direction[] getDirectionsAway(MapLocation dest) { Direction toDest = rc.getLocation().directionTo(dest).opposite(); Direction[] dirs = new Direction[5]; dirs[0] = toDest; if (rand.nextDouble() < 0.5){ dirs[1] = toDest.rotateLeft(); dirs[2] = toDest.rotateRight(); } else { dirs[2] = toDest.rotateLeft(); dirs[1] = toDest.rotateRight(); } if (rand.nextDouble() < 0.5){ dirs[3] = toDest.rotateLeft().rotateLeft(); dirs[4] = toDest.rotateRight().rotateRight(); } else { dirs[4] = toDest.rotateLeft().rotateLeft(); dirs[3] = toDest.rotateRight().rotateRight(); } return dirs; } public Direction getMoveDir(MapLocation dest) { Direction[] dirs = getDirectionsToward(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirAway(MapLocation dest) { Direction[] dirs = getDirectionsAway(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirRand(MapLocation dest) { //TODO return a random direction Direction[] dirs = getDirectionsToward(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } public Direction getMoveDirAwayRand(MapLocation dest) { //TODO return a random direction Direction[] dirs = getDirectionsAway(dest); for (Direction d : dirs) { if (rc.canMove(d)) { return d; } } return null; } //Will return a single direction for spawning. (Uses getDirectionsToward()) public Direction getSpawnDir(RobotType type) { Direction[] dirs = getDirectionsToward(this.theirHQ); for (Direction d : dirs) { if (rc.canSpawn(d, type)) { return d; } } dirs = getDirectionsToward(this.myHQ); for (Direction d : dirs) { if (rc.canSpawn(d, type)) { return d; } else { // //System.out.println("Could not find valid spawn location!"); } } return null; } //Will return a single direction for building. (Uses getDirectionsToward()) public Direction getBuildDir(RobotType type) { Direction[] dirs = getDirectionsToward(this.theirHQ); for (Direction d : dirs) { if (rc.canBuild(d, type)) { return d; } } dirs = getDirectionsToward(this.myHQ); for (Direction d : dirs) { if (rc.canBuild(d, type)) { return d; } else { // //System.out.println("Could not find valid build location!"); } } return null; } public RobotInfo[] getAllies() { RobotInfo[] allies = rc.senseNearbyRobots(Integer.MAX_VALUE, myTeam); return allies; } public RobotInfo[] getEnemiesInAttackingRange() { RobotInfo[] enemies = rc.senseNearbyRobots(myRange, theirTeam); return enemies; } public Direction getDirOfLauncherTarget() { int startingByteCode = Clock.getBytecodeNum(); MapLocation myLocation = rc.getLocation(); Direction[] targetDirections = getDirectionsToward(theirHQ); MapLocation[] targets = new MapLocation[5]; for (int i=0; i<targetDirections.length; i++){ targets[i] = myLocation.add(targetDirections[i], 3); } for (int j = 0; j < targets.length; j++) { if (Clock.getBytecodesLeft() > 500) { int teammates = 0; MapLocation targetCenter = targets[j]; RobotInfo[] allRobotsInTargetArea = rc.senseNearbyRobots( targetCenter, 15, null); for (RobotInfo robot : allRobotsInTargetArea) { if (robot.team == myTeam) teammates++; } if (allRobotsInTargetArea.length >= 2 * teammates) { // //System.out.println("getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode)); return myLocation.directionTo(targetCenter); } } } // System.out.println("FAILED getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode)); return null; } public void attackLeastHealthEnemy(RobotInfo[] enemies) throws GameActionException { if (enemies.length == 0) { return; } double minEnergon = Double.MAX_VALUE; MapLocation toAttack = null; for (RobotInfo info : enemies) { if (info.health < minEnergon) { toAttack = info.location; minEnergon = info.health; } } if (toAttack != null) { rc.attackLocation(toAttack); } } public void attackLeastHealthEnemyInRange() throws GameActionException { RobotInfo[] enemies = getEnemiesInAttackingRange(); if (enemies.length > 0) { if (rc.isWeaponReady()) { attackLeastHealthEnemy(enemies); } } } public void moveToRallyPoint() throws GameActionException { if (rc.isCoreReady()) { int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X); int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y); MapLocation rallyPoint = new MapLocation(rallyX, rallyY); if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack && rc.getLocation().distanceSquaredTo(rallyPoint) > 8 + Clock.getRoundNum() / 100) { moveOptimally(getDirectionsToward(rallyPoint)); } else { Direction newDir = getMoveDir(rallyPoint); if (newDir != null && rc.canMove(newDir)) { rc.move(newDir); } } } } //Returns the current rally point MapLocation public MapLocation getRallyPoint() throws GameActionException { int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X); int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y); MapLocation rallyPoint = new MapLocation(rallyX, rallyY); return rallyPoint; } //Moves a random safe direction from input array public void moveOptimally(Direction[] optimalDirections) throws GameActionException { //TODO check safety if (optimalDirections != null) { boolean lookingForDirection = true; int attemptForDirection = 0; while(lookingForDirection){ MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); Direction currentDirection = optimalDirections[attemptForDirection]; //Direction currentDirection = optimalDirections[(int) (rand.nextDouble()*optimalDirections.length)]; MapLocation tileInFront = rc.getLocation().add(currentDirection); //check that the direction in front is not a tile that can be attacked by the enemy towers boolean tileInFrontSafe = true; for(MapLocation m: enemyTowers){ if(m.distanceSquaredTo(tileInFront)<=RobotType.TOWER.attackRadiusSquared+1){ tileInFrontSafe = false; break; } } //check that we are not facing off the edge of the map TerrainTile terrainTileInFront = rc.senseTerrainTile(tileInFront); if(!tileInFrontSafe || !rc.isPathable(myType, tileInFront) || terrainTileInFront == TerrainTile.OFF_MAP || (myType != RobotType.DRONE && terrainTileInFront!=TerrainTile.NORMAL)){ //currentDirection = currentDirection.rotateLeft(); attemptForDirection++; if (attemptForDirection == optimalDirections.length) { // //System.out.println("No suitable direction found!"); return; } }else{ //try to move in the currentDirection direction if(currentDirection != null && rc.isCoreReady() && rc.canMove(currentDirection)){ rc.move(currentDirection); lookingForDirection = false; return; } } } } } //Gets optimal directions and then calls moveOptimally() with those directions. public void moveOptimally() throws GameActionException { Direction[] optimalDirections = getOptimalDirections(); if (optimalDirections != null) { moveOptimally(optimalDirections); } } //TODO Finish public Direction[] getOptimalDirections() throws GameActionException { // The switch statement should result in an array of directions that make sense //for the RobotType. Safety is considered in moveOptimally() RobotType currentRobotType = rc.getType(); Direction[] optimalDirections = null; switch(currentRobotType){ case BASHER: optimalDirections = getDirectionsToward(this.theirHQ); break; case BEAVER: if (getDistanceSquared(this.myHQ) < 50){ optimalDirections = getDirectionsAway(this.myHQ); } optimalDirections = Direction.values(); break; case COMMANDER: break; case COMPUTER: break; case DRONE: optimalDirections = getDirectionsToward(this.theirHQ); break; case LAUNCHER: optimalDirections = getDirectionsToward(this.theirHQ); break; case MINER: if (getDistanceSquared(this.myHQ) < 50){ optimalDirections = getDirectionsToward(this.myHQ); } optimalDirections = Direction.values(); break; case MISSILE: break; case SOLDIER: optimalDirections = getDirectionsToward(this.theirHQ); break; case TANK: optimalDirections = getDirectionsToward(this.theirHQ); break; default: } //Done RobotType specific actions. return optimalDirections; } //Spawns or Queues the unit if it is needed public boolean tryToSpawn(RobotType spawnType) throws GameActionException{ int round = Clock.getRoundNum(); double ore = rc.getTeamOre(); int spawnTypeInt = RobotTypeToInt(spawnType); int spawnQueue = rc.readBroadcast(smuIndices.freqQueue); int currentAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+0); int desiredAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+1); int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+2); //Check if we actually need anymore spawnType units if (round > roundToBeginSpawning && currentAmount < desiredAmount){ if(ore > myType.oreCost){ if (spawnUnit(spawnType)) return true; } else { //Add spawnType to queue if (spawnQueue == 0){ rc.broadcast(smuIndices.freqQueue, spawnTypeInt); } return false; } } return false; } //Spawns unit based on calling type. Performs all checks. public boolean spawnOptimally() throws GameActionException { if (rc.isCoreReady()){ int spawnQueue = rc.readBroadcast(smuIndices.freqQueue); switch(myType){ case BARRACKS: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.SOLDIER)){ if (tryToSpawn(RobotType.SOLDIER)) return true; } if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BASHER)){ if (tryToSpawn(RobotType.BASHER)) return true; } break; case HQ: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BEAVER)){ if (tryToSpawn(RobotType.BEAVER)) return true; } break; case HELIPAD: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.DRONE)){ if (tryToSpawn(RobotType.DRONE)) return true; } break; case AEROSPACELAB: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.LAUNCHER)){ if (tryToSpawn(RobotType.LAUNCHER)) return true; } break; case MINERFACTORY: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.MINER)){ if (tryToSpawn(RobotType.MINER)) return true; } break; case TANKFACTORY: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.TANK)){ if (tryToSpawn(RobotType.TANK)) return true; } break; case TECHNOLOGYINSTITUTE: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMPUTER)){ if (tryToSpawn(RobotType.COMPUTER)) return true; } break; case TRAININGFIELD: if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMMANDER)){ if (tryToSpawn(RobotType.COMMANDER)) return true; } break; default: // System.out.println("ERROR: No building type match found in spawnOptimally()!"); return false; } }//isCoreReady return false; } //Gets direction, checks delays, and spawns unit public boolean spawnUnit(RobotType spawnType) { //Get a direction and then actually spawn the unit. Direction randomDir = getSpawnDir(spawnType); if(rc.isCoreReady() && randomDir != null){ try { if (rc.canSpawn(randomDir, spawnType)) { rc.spawn(randomDir, spawnType); if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == spawnType) { rc.broadcast(smuIndices.freqQueue, 0); } incrementCount(spawnType); return true; } } catch (GameActionException e) { e.printStackTrace(); } } return false; } //Spawns unit based on calling type. Performs all checks. public void buildOptimally() throws GameActionException { int round = Clock.getRoundNum(); double ore = rc.getTeamOre(); boolean buildingsOutrankUnits = true; int queue = rc.readBroadcast(smuIndices.freqQueue); RobotType[] arrayOfStructures = new RobotType[] {RobotType.AEROSPACELAB, RobotType.BARRACKS, RobotType.HANDWASHSTATION, RobotType.HELIPAD, RobotType.HQ, RobotType.MINERFACTORY, RobotType.SUPPLYDEPOT, RobotType.TANKFACTORY, RobotType.TECHNOLOGYINSTITUTE, RobotType.TOWER, RobotType.TRAININGFIELD}; //If there is something in the queue and we can not replace it, then return if (queue != 0 && !buildingsOutrankUnits){ System.out.println("Queue full, can't outrank"); return; } //Check if there is a building in queue if (Arrays.asList(arrayOfStructures).contains(IntToRobotType(queue))) { //Build it if we can afford it if (ore > IntToRobotType(queue).oreCost) { System.out.println("INFO: Satisfying queue. ("+IntToRobotType(queue).name()+")"); buildUnit(IntToRobotType(queue)); } //Return either way, we can't replace buildings in the queue return; } //Loop over structures and build or queue any needed ones for (RobotType structure : arrayOfStructures) { int intStructure = RobotTypeToInt(structure); double weightOfStructure = getWeightOfRobotType(IntToRobotType(intStructure)); if (weightOfStructure == 1.0){ if (ore > IntToRobotType(intStructure).oreCost){ buildUnit(IntToRobotType(intStructure)); System.out.println("Tried to build "+ IntToRobotType(intStructure)); } else { rc.broadcast(smuIndices.freqQueue, intStructure); System.out.println("Scheduled a " + IntToRobotType(intStructure).name() + ". Need " + (IntToRobotType(intStructure).oreCost-ore) + " more ore."); } return; } }//end loop of structures } //Gets direction, checks delays, and builds unit public boolean buildUnit(RobotType buildType) { //Get a direction and then actually build the unit. Direction randomDir = getBuildDir(buildType); if(rc.isCoreReady() && randomDir != null){ try { if (rc.canBuild(randomDir, buildType)) { rc.build(randomDir, buildType); if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == buildType) { rc.broadcast(smuIndices.freqQueue, 0); } incrementCount(buildType); return true; } } catch (GameActionException e) { e.printStackTrace(); } } return false; } //Increment the currentAmount of a RobotType public void incrementCount(RobotType type) throws GameActionException { int intType = RobotTypeToInt(type); int currentAmount = rc.readBroadcast(smuIndices.channel[intType]+0); rc.broadcast(smuIndices.channel[intType+0], currentAmount+1); } public void transferSupplies() throws GameActionException { double lowestSupply = rc.getSupplyLevel(); if (lowestSupply == 0) { return; } int roundStart = Clock.getRoundNum(); final MapLocation myLocation = rc.getLocation(); RobotInfo[] nearbyAllies = rc.senseNearbyRobots(myLocation,GameConstants.SUPPLY_TRANSFER_RADIUS_SQUARED,rc.getTeam()); double transferAmount = 0; MapLocation suppliesToThisLocation = null; for(RobotInfo ri:nearbyAllies){ if (!ri.type.isBuilding && ri.supplyLevel < lowestSupply) { lowestSupply = ri.supplyLevel; transferAmount = (rc.getSupplyLevel()-ri.supplyLevel)/2; suppliesToThisLocation = ri.location; } } if(suppliesToThisLocation!=null){ if (roundStart == Clock.getRoundNum() && transferAmount > 0 && Clock.getBytecodesLeft() > 550) { try { rc.transferSupplies((int)transferAmount, suppliesToThisLocation); } catch(GameActionException gax) { gax.printStackTrace(); } } } } // true, I'm in the convoy or going to be // false, no place in the convoy for me public boolean formSupplyConvoy() { try { if (rc.readBroadcast(smuIndices.STRATEGY) == smuConstants.STRATEGY_DRONE_CONTAIN) { return false; } } catch (GameActionException e1) { e1.printStackTrace(); } Direction directionForChain = getSupplyConvoyDirection(myHQ); RobotInfo minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, myHQ, directionForChain); if (minerAtEdge == null){ goToLocation(myHQ.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY)); return true; } else if (minerAtEdge.ID == rc.getID()) { return true; } RobotInfo previousMiner = null; try { while ((minerAtEdge != null || !minerAtEdge.type.isBuilding) && minerAtEdge.location.distanceSquaredTo(getRallyPoint()) > 4) { directionForChain = getSupplyConvoyDirection(minerAtEdge.location); previousMiner = minerAtEdge; minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, minerAtEdge.location, directionForChain); if (minerAtEdge == null) { goToLocation(previousMiner.location.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY)); return true; } else if (minerAtEdge.ID == rc.getID()) { return true; } } } catch (GameActionException e) { e.printStackTrace(); } return false; } public Direction getSupplyConvoyDirection(MapLocation startLocation) { Direction directionForChain = myHQ.directionTo(theirHQ); MapLocation locationToGo = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL && rc.canSenseLocation(locationToGo)) { RobotInfo robotInDirection; try { robotInDirection = rc.senseRobotAtLocation(locationToGo); if (robotInDirection == null || !robotInDirection.type.isBuilding) { return directionForChain; } } catch (GameActionException e) { e.printStackTrace(); } } Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST, Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST}; for (int i = 0; i < directions.length; i++) { locationToGo = startLocation.add(directions[i], smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (directions[i] != directionForChain && directions[i] != Direction.OMNI && directions[i] != Direction.NONE && rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) { RobotInfo robotInDirection; try { robotInDirection = rc.senseRobotAtLocation(locationToGo); if (robotInDirection == null || !robotInDirection.type.isBuilding) { return directions[i]; } } catch (GameActionException e) { e.printStackTrace(); } } } return Direction.NONE; } public RobotInfo getUnitAtEdgeOfSupplyRangeOf(RobotType unitType, MapLocation startLocation, Direction directionForChain) { MapLocation locationInChain = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY); if (rc.canSenseLocation(locationInChain)) { try { return rc.senseRobotAtLocation(locationInChain); } catch (GameActionException e) { e.printStackTrace(); } } return null; } public MapLocation getSecondBaseLocation() { Direction directionToTheirHQ = myHQ.directionTo(theirHQ); MapLocation secondBase = null; if (directionToTheirHQ == Direction.EAST || directionToTheirHQ == Direction.WEST) { secondBase = getSecondBaseLocationInDirections(Direction.NORTH, Direction.SOUTH); } else if (directionToTheirHQ == Direction.NORTH || directionToTheirHQ == Direction.SOUTH) { secondBase = getSecondBaseLocationInDirections(Direction.EAST, Direction.WEST); } else { Direction[] directions = breakdownDirection(directionToTheirHQ); secondBase = getSecondBaseLocationInDirections(directions[0], directions[1]); } if (secondBase != null) { secondBase = secondBase.add(myHQ.directionTo(secondBase), 4); } return secondBase; } public MapLocation getSecondBaseLocationInDirections(Direction dir1, Direction dir2) { MapLocation towers[] = rc.senseTowerLocations(); int maxDistance = Integer.MIN_VALUE; int maxDistanceIndex = -1; Direction dirToEnemy = myHQ.directionTo(theirHQ); Direction dir1left = dir1.rotateLeft(); Direction dir1right = dir1.rotateRight(); Direction dir2left = dir2.rotateLeft(); Direction dir2right = dir2.rotateRight(); for (int i = 0; i<towers.length; i++) { Direction dirToTower = myHQ.directionTo(towers[i]); if (dirToTower == dir1 || dirToTower == dir2 || (dir1left != dirToEnemy && dirToTower == dir1left) || (dir1right != dirToEnemy && dirToTower == dir1right) || (dir2left != dirToEnemy && dirToTower == dir2left) || (dir2right != dirToEnemy && dirToTower == dir2right)) { int distanceToTower = myHQ.distanceSquaredTo(towers[i]); if (distanceToTower > maxDistance) { maxDistance = distanceToTower; maxDistanceIndex = i; } } } if (maxDistanceIndex != -1) { return towers[maxDistanceIndex]; } return null; } public void beginningOfTurn() { if (rc.senseEnemyHQLocation() != null) { this.theirHQ = rc.senseEnemyHQLocation(); } } public void endOfTurn() { } public void go() throws GameActionException { beginningOfTurn(); execute(); endOfTurn(); } public void execute() throws GameActionException { rc.yield(); } public void supplyAndYield() throws GameActionException { transferSupplies(); rc.yield(); } public int myContainDirection = smuConstants.CLOCKWISE; public MapLocation myContainPreviousLocation; public void contain() { MapLocation enemyHQ = rc.senseEnemyHQLocation(); MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); MapLocation myLocation = rc.getLocation(); int radiusFromHQ = 24; if (enemyTowers.length >= 2) { radiusFromHQ = 35; } if (myLocation.distanceSquaredTo(enemyHQ) > radiusFromHQ + 3) { // move towards the HQ try { RobotInfo[] nearbyTeammates = rc.senseNearbyRobots(4, myTeam); int numAttackers = 0; for (RobotInfo teammate : nearbyTeammates) { if (!teammate.type.isBuilding && teammate.type != RobotType.MINER && teammate.type != RobotType.BEAVER) numAttackers++; } if (numAttackers >= getNumAttackersToContain()) { moveOptimally(); } } catch (GameActionException e) { e.printStackTrace(); } } else { MapLocation locationToGo = null; Direction directionToGo = null; if (myContainDirection == smuConstants.CLOCKWISE) { directionToGo = getClockwiseDirection(myLocation, enemyHQ); } else { directionToGo = getCounterClockwiseDirection(myLocation, enemyHQ); } locationToGo = myLocation.add(directionToGo); if (rc.isPathable(myType, locationToGo)) { if (isLocationSafe(locationToGo)) { goToLocation(locationToGo); } else { Direction[] directions = breakdownDirection(directionToGo); for (int i = 0; i < directions.length; i++) { locationToGo = myLocation.add(directions[i]); if (isLocationSafe(locationToGo)) { goToLocation(locationToGo); myContainPreviousLocation = myLocation; return; } } } } else if (myContainPreviousLocation.equals(myLocation)){ if (myContainDirection == smuConstants.CLOCKWISE) { myContainDirection = smuConstants.COUNTERCLOCKWISE; } else { myContainDirection = smuConstants.CLOCKWISE; } } } myContainPreviousLocation = myLocation; } public int getNumAttackersToContain() { if (myType == RobotType.SOLDIER) { return 2; } else if (myType == RobotType.TANK) { return 1; } else { return 2; } } public boolean isLocationSafe(MapLocation location) { int hqAttackRadius = RobotType.HQ.attackRadiusSquared; if (rc.senseEnemyTowerLocations().length >= 2) hqAttackRadius = 35; if (location.distanceSquaredTo(theirHQ) > hqAttackRadius) { for (MapLocation tower : rc.senseEnemyTowerLocations()) { if (location.distanceSquaredTo(tower) <= RobotType.TOWER.attackRadiusSquared) { return false; } } return true; } return false; } public Direction[] breakdownDirection(Direction direction) { Direction[] breakdown = new Direction[2]; switch(direction) { case NORTH_EAST: breakdown[0] = Direction.NORTH; breakdown[1] = Direction.EAST; break; case SOUTH_EAST: breakdown[0] = Direction.SOUTH; breakdown[1] = Direction.EAST; break; case NORTH_WEST: breakdown[0] = Direction.NORTH; breakdown[1] = Direction.WEST; break; case SOUTH_WEST: breakdown[0] = Direction.SOUTH; breakdown[1] = Direction.WEST; break; default: break; } return breakdown; } public Direction getClockwiseDirection(MapLocation myLocation, MapLocation anchor) { Direction directionToAnchor = myLocation.directionTo(anchor); if (directionToAnchor.equals(Direction.EAST) || directionToAnchor.equals(Direction.SOUTH_EAST)) { return Direction.NORTH_EAST; } else if (directionToAnchor.equals(Direction.SOUTH) || directionToAnchor.equals(Direction.SOUTH_WEST)) { return Direction.SOUTH_EAST; } else if (directionToAnchor.equals(Direction.WEST) || directionToAnchor.equals(Direction.NORTH_WEST)) { return Direction.SOUTH_WEST; } else if (directionToAnchor.equals(Direction.NORTH) || directionToAnchor.equals(Direction.NORTH_EAST)) { return Direction.NORTH_WEST; } return Direction.NONE; } public Direction getCounterClockwiseDirection(MapLocation myLocation, MapLocation anchor) { Direction oppositeDirection = getClockwiseDirection(myLocation, anchor); if (oppositeDirection.equals(Direction.NORTH_EAST)) { return Direction.SOUTH_WEST; } else if (oppositeDirection.equals(Direction.SOUTH_EAST)) { return Direction.NORTH_WEST; } else if (oppositeDirection.equals(Direction.SOUTH_WEST)) { return Direction.NORTH_EAST; } else if (oppositeDirection.equals(Direction.NORTH_WEST)) { return Direction.SOUTH_WEST; } return Direction.NONE; } // Defend public boolean defendSelf() { RobotInfo[] nearbyEnemies = getEnemiesInAttackRange(); if(nearbyEnemies != null && nearbyEnemies.length > 0) { try { if (rc.isWeaponReady()) { attackLeastHealthEnemyInRange(); } } catch (GameActionException e) { e.printStackTrace(); } return true; } return false; } public boolean defendTeammates() { RobotInfo[] engagedRobots = getRobotsEngagedInAttack(); if(engagedRobots != null && engagedRobots.length>0) { // Check broadcasts for enemies that are being attacked // TODO: Calculate which enemy is attacking/within range/closest to teammate // For now, just picking the first enemy // Once our unit is in range of the other unit, A1 will takeover for (RobotInfo robot : engagedRobots) { if (robot.team == theirTeam) { goToLocation(robot.location); } } return true; } return false; } public boolean defend() { // A1, Protect Self boolean isProtectingSelf = defendSelf(); if (isProtectingSelf) { return true; } // A2, Protect Nearby boolean isProtectingTeammates = defendTeammates(); if (isProtectingTeammates) { return true; } return false; } public int RobotTypeToInt(RobotType type){ switch(type) { case AEROSPACELAB: return 1; case BARRACKS: return 2; case BASHER: return 3; case BEAVER: return 4; case COMMANDER: return 5; case COMPUTER: return 6; case DRONE: return 7; case HANDWASHSTATION: return 8; case HELIPAD: return 9; case HQ: return 10; case LAUNCHER: return 11; case MINER: return 12; case MINERFACTORY: return 13; case MISSILE: return 14; case SOLDIER: return 15; case SUPPLYDEPOT: return 16; case TANK: return 17; case TANKFACTORY: return 18; case TECHNOLOGYINSTITUTE: return 19; case TOWER: return 20; case TRAININGFIELD: return 21; default: return -1; } } public RobotType IntToRobotType(int type){ switch(type) { case 1: return RobotType.AEROSPACELAB; case 2: return RobotType.BARRACKS; case 3: return RobotType.BASHER; case 4: return RobotType.BEAVER; case 5: return RobotType.COMMANDER; case 6: return RobotType.COMPUTER; case 7: return RobotType.DRONE; case 8: return RobotType.HANDWASHSTATION; case 9: return RobotType.HELIPAD; case 10: return RobotType.HQ; case 11: return RobotType.LAUNCHER; case 12: return RobotType.MINER; case 13: return RobotType.MINERFACTORY; case 14: return RobotType.MISSILE; case 15: return RobotType.SOLDIER; case 16: return RobotType.SUPPLYDEPOT; case 17: return RobotType.TANK; case 18: return RobotType.TANKFACTORY; case 19: return RobotType.TECHNOLOGYINSTITUTE; case 20: return RobotType.TOWER; case 21: return RobotType.TRAININGFIELD; default: return null; } } // //Returns a weight representing the 'need' for the RobotType // public double getWeightOfRobotType(RobotType type) throws GameActionException { // int typeInt = RobotTypeToInt(type); // if (rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) == 0) return 0; // double weight = rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt) + // (rc.readBroadcast(smuIndices.freqRoundToFinish + typeInt) - rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt)) / // rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) * rc.readBroadcast(smuIndices.freqNum[typeInt]); // return weight; // } //Returns a weight representing the 'need' for the RobotType public double getWeightOfRobotType(RobotType type) throws GameActionException { int typeInt = RobotTypeToInt(type); int round = Clock.getRoundNum(); double weight = 0; if (!type.isBuilding) { int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0); int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1); int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+2); int roundToFinishSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+3); //Return zero if unit is not desired. (Divide by zero protection) if (desiredAmount == 0) { //System.out.println("Error: No desired "+IntToRobotType(typeInt)); return 0; } if (roundToBeginSpawning >= roundToFinishSpawning) { //System.out.println("Error: build > finish for: "+IntToRobotType(typeInt)); return 0; } if (round < roundToBeginSpawning) { //System.out.println("Error: Too early for "+IntToRobotType(typeInt)); return 0; } //The weight is equal to a point on the surface drawn by z = x^(m*y) where double x = (double) (round - roundToBeginSpawning) / (double) (roundToFinishSpawning - roundToBeginSpawning); double y = (double) currentAmount / (double) desiredAmount; weight = smuConstants.weightScaleMagic * Math.pow(x, (smuConstants.weightExponentMagic + y)); //System.out.println("type: "+IntToRobotType(typeInt)+" x: " + x + " y: " + y + " weight: " + weight); return weight; } //end units if (type.isBuilding){ int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0); int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1); int nextRoundToBuild = rc.readBroadcast(smuIndices.channel[typeInt]+2+currentAmount); int intQueuedType = rc.readBroadcast(smuIndices.freqQueue); if (currentAmount < desiredAmount && nextRoundToBuild != 0) { if (round > nextRoundToBuild && typeInt != intQueuedType) { //TODO We need to check if we are currently building it... System.out.println("Warning: round > nextRoundToBuild && not queued >> " + type.name()); return 1.0; } if (round == nextRoundToBuild) { return 1.0; } if (round < nextRoundToBuild) { return 0.0; } System.out.println("ERROR: Unexpected return path in getWeightOfRobotType " + type.name()); return weight; } else { return 0; } } //end structures System.out.println("ERROR: Unexpected return path in getWeightOfRobotType"); return weight; } public RobotInfo[] getEnemiesInAttackRange() { return rc.senseNearbyRobots(myRange, theirTeam); } //TODO Use optimally instead? public void goToLocation(MapLocation location) { try { if (rc.canSenseLocation(location) && rc.senseRobotAtLocation(location) != null && rc.getLocation().distanceSquaredTo(location)<3) { // 3 squares return; } Direction direction = getMoveDir(location); RobotInfo[] nearbyEnemies = rc.senseNearbyRobots(rc.getLocation().add(direction), RobotType.TOWER.attackRadiusSquared, theirTeam); boolean towersNearby = false; for (RobotInfo enemy : nearbyEnemies) { if (enemy.type == RobotType.TOWER || enemy.type == RobotType.HQ) { towersNearby = true; break; } } if (!towersNearby || Clock.getRoundNum() > smuConstants.roundToLaunchAttack) { if (direction != null && rc.isCoreReady() && rc.canMove(direction) && Clock.getBytecodesLeft() > 55) { rc.move(direction); } } } catch (GameActionException e1) { e1.printStackTrace(); } } public RobotInfo[] getRobotsEngagedInAttack() { RobotInfo[] nearbyRobots = rc.senseNearbyRobots(smuConstants.PROTECT_OTHERS_RANGE); boolean hasEnemy = false; boolean hasFriendly = false; for (RobotInfo robot : nearbyRobots) { if(robot.team == theirTeam && robot.type != RobotType.TOWER) { hasEnemy = true; if (hasFriendly) { return nearbyRobots; } } else { hasFriendly = true; if (hasEnemy) { return nearbyRobots; } } } return null; } public RobotInfo[] getTeammatesInAttackRange() { return rc.senseNearbyRobots(myRange, myTeam); } public RobotInfo[] getTeammatesNearTower(MapLocation towerLocation) { return rc.senseNearbyRobots(towerLocation, RobotType.TOWER.attackRadiusSquared, myTeam); } // Find out if there are any holes between a teams tower and their HQ public MapLocation[] computeHoles() { MapLocation[] towerLocations = rc.senseTowerLocations(); MapLocation[][] towerRadii = new MapLocation[towerLocations.length][]; for(int i = 0; i < towerLocations.length; i++) { // Get all map locations that a tower can attack MapLocation[] locations = MapLocation.getAllMapLocationsWithinRadiusSq(towerLocations[i], RobotType.TOWER.attackRadiusSquared); Arrays.sort(locations); towerRadii[i] = locations; } if(towerRadii.length == 0 || towerRadii[0] == null) { return null; } // Naively say, if overlapping by two towers, there is no path int[] overlapped = new int[towerRadii.length]; int holesBroadcastIndex = smuIndices.TOWER_HOLES_BEGIN; for(int i = 0; i<towerRadii.length; i++) { MapLocation[] locations = towerRadii[i]; boolean coveredLeft = false; boolean coveredRight = false; boolean coveredTop = false; boolean coveredBottom = false; for (int j = 0; j < towerRadii.length; j++) { if (j != i) { MapLocation[] otherLocations = towerRadii[j]; if (locations[0].x <= otherLocations[otherLocations.length-1].x && otherLocations[0].x <= locations[locations.length-1].x && locations[0].y <= otherLocations[otherLocations.length-1].y && otherLocations[0].y <= locations[locations.length-1].y) { overlapped[i]++; Direction otherTowerDir = towerLocations[i].directionTo(towerLocations[j]); if (otherTowerDir.equals(Direction.EAST) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.SOUTH_EAST)) { coveredLeft = true; } if (otherTowerDir.equals(Direction.WEST) || otherTowerDir.equals(Direction.NORTH_WEST) || otherTowerDir.equals(Direction.SOUTH_WEST)) { coveredRight = true; } if (otherTowerDir.equals(Direction.NORTH) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.NORTH_WEST)) { coveredTop = true; } if (otherTowerDir.equals(Direction.SOUTH) || otherTowerDir.equals(Direction.SOUTH_EAST) || otherTowerDir.equals(Direction.SOUTH_WEST)) { coveredBottom = true; } } } } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x - 1, locations[0].y))) { overlapped[i]++; coveredLeft = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[locations.length-1].x + 1, locations[0].y))) { overlapped[i]++; coveredRight = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[0].y - 1))) { overlapped[i]++; coveredTop = true; } if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[locations.length-1].y + 1))) { overlapped[i]++; coveredBottom = true; } // //System.out.println("Tower " + i + " overlapped " + overlapped[i] + " " + towerLocations[i]); if (overlapped[i] < 2) { try { int towerAttackRadius = (int) Math.sqrt(RobotType.TOWER.attackRadiusSquared) + 1; if (!coveredLeft) { // //System.out.println("Tower " + towerLocations[i] + " Not covered left"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x - towerAttackRadius); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y); holesBroadcastIndex+=2; } if (!coveredRight) { // //System.out.println("Tower " + towerLocations[i] + " Not covered right"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x + towerAttackRadius); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y); holesBroadcastIndex+=2; } if (!coveredTop) { // //System.out.println("Tower " + towerLocations[i] + " Not covered top"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y - towerAttackRadius); holesBroadcastIndex+=2; } if (!coveredBottom) { // //System.out.println("Tower " + towerLocations[i] + " Not covered bottom"); rc.broadcast(holesBroadcastIndex, towerLocations[i].x); rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y + towerAttackRadius); holesBroadcastIndex+=2; } } catch (GameActionException e) { e.printStackTrace(); } } } // Signify end of holes try { rc.broadcast(holesBroadcastIndex, -1); } catch (GameActionException e) { e.printStackTrace(); } // //System.out.println("BYTEEND on " + Clock.getRoundNum() + ": " + Clock.getBytecodeNum()); return null; } } //----- Per RoboType code below ----- //HQ public static class HQ extends BaseBot { public int xMin, xMax, yMin, yMax; public int xpos, ypos; public int totalNormal, totalVoid, totalProcessed; public int towerThreat; public static double ratio; public boolean isFinishedAnalyzing = false; public boolean analyzedTowers = false; public int defaultStrategy = smuConstants.STRATEGY_TANKS_AND_SOLDIERS; public boolean hasChosenStrategyPrior = false; public int strategy = defaultStrategy; public int prevStrategy = 0; public int numTowers; public int numEnemyTowers; public boolean dronesFailed = false; public boolean analyzedPrevMatch = false; public HQ(RobotController rc) { super(rc); numTowers = rc.senseTowerLocations().length; numEnemyTowers = rc.senseEnemyTowerLocations().length; xMin = Math.min(this.myHQ.x, this.theirHQ.x); xMax = Math.max(this.myHQ.x, this.theirHQ.x); yMin = Math.min(this.myHQ.y, this.theirHQ.y); yMax = Math.max(this.myHQ.y, this.theirHQ.y); xpos = xMin; ypos = yMin; totalNormal = totalVoid = totalProcessed = 0; towerThreat = 0; isFinishedAnalyzing = false; try { computeStrategy(); } catch (GameActionException e) { e.printStackTrace(); } computeHoles(); } public void analyzePreviousMatch() { long[] prevGameTeamMemory = rc.getTeamMemory(); boolean hasData = false; for (long memory : prevGameTeamMemory) { if (memory != 0) { hasData = true; break; } } if (hasData) { double prevRatio = ((double) prevGameTeamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT])/100.0; int mostUsed = 0; int mostUsedIndex = -1; int secondMostUsed = 0; int secondMostUsedIndex = -1; for(int i = 0; i < 6; i++) { // 6 is number of different strategies int numRoundsUsed = (int) prevGameTeamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + i]; if (numRoundsUsed > mostUsed) { secondMostUsed = mostUsed; secondMostUsedIndex = mostUsedIndex; mostUsed = numRoundsUsed; mostUsedIndex = i; } else if (numRoundsUsed > secondMostUsed) { secondMostUsed = numRoundsUsed; secondMostUsedIndex = i; } } if (mostUsed == smuConstants.STRATEGY_DRONE_CONTAIN || mostUsed == smuConstants.STRATEGY_DRONE_SWARM) { dronesFailed = true; // System.out.println(Clock.getRoundNum() + " Drones failed."); } else { if (ratio > 0.85 && prevRatio > 0.85) { // Both Traversables int i = 0; while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + i] != 0) { i++; } int ourTowersDestroyed = i; int j = 0; while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + j] != 0) { j++; } int theirTowersDestroyed = j; if (ourTowersDestroyed < theirTowersDestroyed) { defaultStrategy = mostUsedIndex + 1; } else { if (secondMostUsedIndex != -1) { defaultStrategy = secondMostUsedIndex + 1; } } } } for (int i = 0; i < GameConstants.TEAM_MEMORY_LENGTH; i++) { rc.setTeamMemory(i, 0); } } analyzedPrevMatch = true; } public void analyzeMap() { while (ypos < yMax + 1) { TerrainTile t = rc.senseTerrainTile(new MapLocation(xpos, ypos)); if (t == TerrainTile.NORMAL) { totalNormal++; totalProcessed++; } else if (t == TerrainTile.VOID) { totalVoid++; totalProcessed++; } xpos++; if (xpos == xMax + 1) { xpos = xMin; ypos++; } if (Clock.getBytecodesLeft() < 50) { return; } } ratio = (double) totalNormal / totalProcessed; isFinishedAnalyzing = true; } public void analyzeTowers() { MapLocation[] towers = rc.senseEnemyTowerLocations(); towerThreat = 0; for (int i=0; i<towers.length; ++i) { MapLocation towerLoc = towers[i]; if ((xMin <= towerLoc.x && towerLoc.x <= xMax && yMin <= towerLoc.y && towerLoc.y <= yMax) || towerLoc.distanceSquaredTo(this.theirHQ) <= 50) { for (int j=0; j<towers.length; ++j) { if (towers[j].distanceSquaredTo(towerLoc) <= 50) { towerThreat++; } } } } analyzedTowers = true; } public void chooseStrategy() throws GameActionException { if (hasChosenStrategyPrior && Clock.getRoundNum() % 250 != 0) { return; } if (rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) == smuConstants.NOT_CURRENTLY_BEING_CONTAINED) { // Test for Swarms MapLocation[] ourTowers = rc.senseTowerLocations(); RobotType swarmingType = null; if (ourTowers != null && ourTowers.length > 0) { int closestTower = -1; int closestDistanceToEnemyHQ = Integer.MAX_VALUE; for (int i = 0; i < ourTowers.length; i++) { int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ); if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) { closestDistanceToEnemyHQ = currDistanceToEnemyHQ; closestTower = i; } } RobotInfo[] enemiesSwarming = rc.senseNearbyRobots(ourTowers[closestTower], 100, theirTeam); if (enemiesSwarming != null && enemiesSwarming.length > 0) { swarmingType = IntToRobotType(getMajorityRobotType(enemiesSwarming)); } } if (ratio <= 0.85) { // Void heavy map if (towerThreat >= 10) { // Defensive Map strategy = smuConstants.STRATEGY_DRONE_SWARM; } else { // Offensive Map strategy = smuConstants.STRATEGY_DRONE_CONTAIN; } } else { // Traversable Map if (swarmingType == RobotType.SOLDIER) { strategy = smuConstants.STRATEGY_TANKS_AND_LAUNCHERS; } else if (swarmingType == RobotType.DRONE) { strategy = smuConstants.STRATEGY_LAUNCHERS; } else if (swarmingType == RobotType.TANK) { strategy = smuConstants.STRATEGY_TANK_SWARM; } else { strategy = defaultStrategy; } } } else { RobotType containingType = IntToRobotType(rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED_BY)); if (containingType == RobotType.DRONE) { strategy = smuConstants.STRATEGY_LAUNCHERS; } else if (containingType == RobotType.TANK) { strategy = smuConstants.STRATEGY_LAUNCHERS; } } //STRATEGY_DRONE_CONTAIN = 1; //STRATEGY_TANKS_AND_SOLDIERS = 2; //STRATEGY_DRONE_SWARM = 3; //STRATEGY_TANKS_AND_LAUNCHERS = 4; //STRATEGY_LAUNCHERS = 5; //STRATEGY_TANK_SWARM = 6; //strategy = 1; rc.broadcast(smuIndices.STRATEGY, strategy); hasChosenStrategyPrior = true; } public void computeStrategy() throws GameActionException{ if (prevStrategy == strategy) { return; } // [desiredNumOf, roundToBuild, roundToFinish] int[] strategyAEROSPACELAB = new int[3]; int[] strategyBARRACKS = new int[3]; int[] strategyBASHER = new int[3]; int[] strategyBEAVER = new int[3]; int[] strategyCOMMANDER = new int[3]; int[] strategyCOMPUTER = new int[3]; int[] strategyDRONE = new int[3]; int[] strategyHANDWASHSTATION = new int[3]; int[] strategyHELIPAD = new int[3]; int[] strategyHQ = new int[3]; int[] strategyLAUNCHER = new int[3]; int[] strategyMINER = new int[3]; int[] strategyMINERFACTORY = new int[3]; int[] strategyMISSILE = new int[3]; int[] strategySOLDIER = new int[3]; int[] strategySUPPLYDEPOT = new int[3]; int[] strategyTANK = new int[3]; int[] strategyTANKFACTORY = new int[3]; int[] strategyTECHNOLOGYINSTITUTE = new int[3]; int[] strategyTOWER = new int[3]; int[] strategyTRAININGFIELD = new int[3]; if (strategy == smuConstants.STRATEGY_TANKS_AND_SOLDIERS) { System.out.println("COMPUTE STRATEGY: Tanks and Soldiers"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {100, 300, 650, 800}; strategyBASHER = new int[] {50, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 0, 0}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {0}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 0, 0}; strategyMINER = new int[] {50, 1, 500}; strategyMINERFACTORY = new int[] {1, 200}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {120, 200, 1200}; // strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategySUPPLYDEPOT = new int[] {1000, 1400, 1500}; strategyTANK = new int[] {20, 1100, 1800}; strategyTANKFACTORY = new int[] {1000, 1200}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_LAUNCHERS){ System.out.println("COMPUTE STRATEGY: Launchers"); strategyAEROSPACELAB = new int[] {800, 1000}; strategyBARRACKS = new int[] {4, 500, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 0, 0}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {20, 1100, 1700}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {120, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {0, 1100, 1800}; strategyTANKFACTORY = new int[] {0}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_DRONE_CONTAIN) { System.out.println("COMPUTE STRATEGY: Drone Contain"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {0}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 100}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {50, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1, 300}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 1100, 1700}; strategyMINER = new int[] {20, 100, 500}; strategyMINERFACTORY = new int[] {100, 500}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {0, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {0, 1100, 1800}; strategyTANKFACTORY = new int[] {0}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_DRONE_SWARM) { System.out.println("COMPUTE STRATEGY: Drone Swarm"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {2, 500, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {120, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1, 400}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 1100, 1700}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {25, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {0, 0, 0}; strategyTANKFACTORY = new int[] {0}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_TANK_SWARM) { System.out.println("COMPUTE STRATEGY: Tank Swarm"); strategyAEROSPACELAB = new int[] {0}; strategyBARRACKS = new int[] {2, 100, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {00}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {0, 0, 0}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {60, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {100, 300, 1800}; strategyTANKFACTORY = new int[] {200, 400, 600, 800, 1000}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } else if(strategy == smuConstants.STRATEGY_TANKS_AND_LAUNCHERS) { System.out.println("COMPUTE STRATEGY: Tanks and Launchers"); strategyAEROSPACELAB = new int[] {1000, 1200}; strategyBARRACKS = new int[] {0, 100, 1500}; strategyBASHER = new int[] {0, 1200, 1700}; strategyBEAVER = new int[] {10, 0, 0}; strategyCOMMANDER = new int[] {0, 0, 0}; strategyCOMPUTER = new int[] {0, 0, 0}; strategyDRONE = new int[] {0, 100, 1800}; strategyHANDWASHSTATION = new int[] {1850, 1860, 1870}; strategyHELIPAD = new int[] {1, 500, 1000}; strategyHQ = new int[] {0}; strategyLAUNCHER = new int[] {30, 1100, 1700}; strategyMINER = new int[] {30, 1, 500}; strategyMINERFACTORY = new int[] {2, 1, 250}; strategyMISSILE = new int[] {0, 0, 0}; strategySOLDIER = new int[] {0, 200, 1200}; strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500}; strategyTANK = new int[] {100, 800, 1800}; strategyTANKFACTORY = new int[] {5, 500, 1400}; strategyTECHNOLOGYINSTITUTE = new int[] {0}; strategyTOWER = new int[] {0}; strategyTRAININGFIELD = new int[] {0}; } //BE CAREFUL!!! //TODO int[][] strategyUnitArray = new int[][] {strategyBASHER, strategyBEAVER, strategyCOMMANDER, strategyCOMPUTER, strategyDRONE, strategyLAUNCHER, strategyMINER, strategyMISSILE, strategySOLDIER, strategyTANK}; int[] channelUnitArray = new int[] {smuIndices.channelBASHER, smuIndices.channelBEAVER, smuIndices.channelCOMMANDER, smuIndices.channelCOMPUTER, smuIndices.channelDRONE, smuIndices.channelLAUNCHER, smuIndices.channelMINER, smuIndices.channelMISSILE, smuIndices.channelSOLDIER, smuIndices.channelTANK}; int[][] strategyStructureArray = new int[][] {strategyAEROSPACELAB, strategyBARRACKS, strategyHANDWASHSTATION, strategyHELIPAD, strategyHQ, strategyMINERFACTORY, strategySUPPLYDEPOT, strategyTANKFACTORY, strategyTECHNOLOGYINSTITUTE, strategyTOWER, strategyTRAININGFIELD}; int[] channelStructureArray = new int[] {smuIndices.channelAEROSPACELAB, smuIndices.channelBARRACKS, smuIndices.channelHANDWASHSTATION, smuIndices.channelHELIPAD, smuIndices.channelHQ, smuIndices.channelMINERFACTORY, smuIndices.channelSUPPLYDEPOT, smuIndices.channelTANKFACTORY, smuIndices.channelTECHNOLOGYINSTITUTE, smuIndices.channelTOWER, smuIndices.channelTRAININGFIELD}; //Broadcast unit strategies for (int i = 1; i < strategyUnitArray.length; i++) { rc.broadcast(channelUnitArray[i] + 0, 0); rc.broadcast(channelUnitArray[i] + 1, strategyUnitArray[i][0]); rc.broadcast(channelUnitArray[i] + 2, strategyUnitArray[i][1]); rc.broadcast(channelUnitArray[i] + 3, strategyUnitArray[i][2]); } //Broadcast structure strategies for (int i = 1; i < strategyStructureArray.length; i++) { rc.broadcast(channelStructureArray[i] + 0, 0); if (strategyStructureArray[i].length > 1) { rc.broadcast(channelStructureArray[i] + 1, strategyStructureArray[i].length); for (int j = 0; j < strategyStructureArray[i].length; j++) { rc.broadcast(channelStructureArray[i] + j + 2, strategyStructureArray[i][j]); } } else { rc.broadcast(channelStructureArray[i] + 1, 0); rc.broadcast(channelStructureArray[i] + 2, 0); } } prevStrategy = strategy; } public void saveTeamMemory() { long[] teamMemory = rc.getTeamMemory();; int currRound = Clock.getRoundNum(); if (analyzedTowers && teamMemory[smuTeamMemoryIndices.PREV_MAP_TOWER_THREAT] == 0) { rc.setTeamMemory(smuTeamMemoryIndices.PREV_MAP_TOWER_THREAT, towerThreat);; } if (isFinishedAnalyzing && teamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT] == 0) { rc.setTeamMemory(smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT, (long) (ratio * 100)); } rc.setTeamMemory(smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy, teamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy] + 1); if (teamMemory[smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED] == 0) { if (rc.getHealth() < RobotType.HQ.maxHealth) { rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED, currRound); } } int currNumTowers = rc.senseTowerLocations().length; if (currNumTowers < numTowers) { int towersIndex = 0; while (teamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex] != 0) { towersIndex++; } for (int i = 0; i < numTowers - currNumTowers; i++) { rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex + i, currRound); } numTowers = currNumTowers; } int currNumEnemyTowers = rc.senseEnemyTowerLocations().length; if (currNumEnemyTowers < numEnemyTowers) { int towersIndex = 0; while (teamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex] != 0) { towersIndex++; } for (int i = 0; i < numEnemyTowers - currNumEnemyTowers; i++) { rc.setTeamMemory(smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex + i, currRound); } numEnemyTowers = currNumEnemyTowers; } } public RobotType checkContainment() throws GameActionException { RobotInfo[] enemyRobotsContaining = rc.senseNearbyRobots(50, theirTeam); if (enemyRobotsContaining.length > 4) { rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.CURRENTLY_BEING_CONTAINED); int robotTypeContaining = getMajorityRobotType(enemyRobotsContaining); rc.broadcast(smuIndices.HQ_BEING_CONTAINED_BY, robotTypeContaining); return IntToRobotType(robotTypeContaining); } else { rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.NOT_CURRENTLY_BEING_CONTAINED); return null; } } public int getMajorityRobotType(RobotInfo[] enemyRobots) { int[] enemyRobotTypes = new int[22]; //Max RobotType -> int value + 1 int highestValue = 0; int highestValueIndex = -1; for (int i = 0; i < enemyRobots.length; i++) { int robotType = RobotTypeToInt(enemyRobots[i].type); enemyRobotTypes[robotType] = enemyRobotTypes[robotType] + 1; if (enemyRobotTypes[robotType] > highestValue) { highestValue = enemyRobotTypes[robotType]; highestValueIndex = i; } } return highestValueIndex; } public void setRallyPoint() throws GameActionException { MapLocation rallyPoint = null; RobotType beingContained = checkContainment(); if (beingContained == null) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { MapLocation[] ourTowers = rc.senseTowerLocations(); if (ourTowers != null && ourTowers.length > 0) { int closestTower = -1; int closestDistanceToEnemyHQ = Integer.MAX_VALUE; for (int i = 0; i < ourTowers.length; i++) { int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ); if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) { closestDistanceToEnemyHQ = currDistanceToEnemyHQ; closestTower = i; } } rallyPoint = ourTowers[closestTower].add(ourTowers[closestTower].directionTo(theirHQ), 2); } } else { MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); if (enemyTowers == null || enemyTowers.length <= smuConstants.numTowersRemainingToAttackHQ) { rallyPoint = rc.senseEnemyHQLocation(); } else { rallyPoint = enemyTowers[0]; } } } else { rallyPoint = getSecondBaseLocation(); if (rallyPoint != null) { rallyPoint = rallyPoint.add(rallyPoint.directionTo(theirHQ), 8); } } if (rallyPoint != null) { rc.broadcast(smuIndices.RALLY_POINT_X, rallyPoint.x); rc.broadcast(smuIndices.RALLY_POINT_Y, rallyPoint.y); } } public void execute() throws GameActionException { spawnOptimally(); setRallyPoint(); attackLeastHealthEnemyInRange(); transferSupplies(); if (!isFinishedAnalyzing) { analyzeMap(); if (!analyzedTowers) { analyzeTowers(); } } else { if (!analyzedPrevMatch) analyzePreviousMatch(); chooseStrategy(); try { computeStrategy(); } catch (GameActionException e) { e.printStackTrace(); } } if (analyzedPrevMatch) saveTeamMemory(); rc.yield(); } } //BEAVER public static class Beaver extends BaseBot { public MapLocation secondBase; public Beaver(RobotController rc) { super(rc); Random rand = new Random(rc.getID()); if (rand.nextDouble() < smuConstants.percentBeaversToGoToSecondBase) { secondBase = getSecondBaseLocation(); } } public void execute() throws GameActionException { if (secondBase != null && rc.getLocation().distanceSquaredTo(secondBase) > 6) { goToLocation(secondBase); } buildOptimally(); transferSupplies(); if (Clock.getRoundNum() > 400) defend(); if (rc.isCoreReady()) { //mine if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } else { moveOptimally(); } } rc.yield(); } } //MINERFACTORY public static class Minerfactory extends BaseBot { public Minerfactory(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //MINER public static class Miner extends BaseBot { public Miner(RobotController rc) { super(rc); } public void execute() throws GameActionException { boolean inConvoy = false; if (Clock.getRoundNum()>smuConstants.roundToFormSupplyConvoy && rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) != smuConstants.CURRENTLY_BEING_CONTAINED) { inConvoy = formSupplyConvoy(); } if (!inConvoy) { if (!defend()) { if (rc.isCoreReady()) { //mine if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } else { moveOptimally(); } } } } else if(!defendSelf()) { if (rc.isCoreReady()) { if (rc.senseOre(rc.getLocation()) > 0) { rc.mine(); } } } transferSupplies(); rc.yield(); } } //BARRACKS public static class Barracks extends BaseBot { public Barracks(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //SOLDIER public static class Soldier extends BaseBot { public Soldier(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defend()) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } } transferSupplies(); rc.yield(); } } //BASHER public static class Basher extends BaseBot { public Basher(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } transferSupplies(); rc.yield(); } } //TANK public static class Tank extends BaseBot { public Tank(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defend()) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } } transferSupplies(); rc.yield(); } } //DRONE public static class Drone extends BaseBot { public Drone(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (!defendSelf()) { if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) { contain(); } else { moveToRallyPoint(); } } transferSupplies(); rc.yield(); } } //TOWER public static class Tower extends BaseBot { public Tower(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); attackLeastHealthEnemyInRange(); rc.yield(); } } //SUPPLYDEPOT public static class Supplydepot extends BaseBot { public Supplydepot(RobotController rc) { super(rc); } public void execute() throws GameActionException { rc.yield(); } } //HANDWASHSTATION public static class Handwashstation extends BaseBot { public Handwashstation(RobotController rc) { super(rc); } public void execute() throws GameActionException { rc.yield(); } } //TANKFACTORY public static class Tankfactory extends BaseBot { public Tankfactory(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //HELIPAD public static class Helipad extends BaseBot { public Helipad(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //AEROSPACELAB public static class Aerospacelab extends BaseBot { public Aerospacelab(RobotController rc) { super(rc); } public void execute() throws GameActionException { transferSupplies(); spawnOptimally(); rc.yield(); } } //LAUNCHER public static class Launcher extends BaseBot { public Launcher(RobotController rc) { super(rc); } public void execute() throws GameActionException { boolean launched = false; if (rc.getMissileCount() > 0) { Direction targetDir = getDirOfLauncherTarget(); if (targetDir != null && rc.isWeaponReady()){ if (rc.canLaunch(targetDir)){ rc.launchMissile(targetDir); launched = true; } } } if (!launched) { contain(); } rc.yield(); } } //MISSILE public static class Missile extends BaseBot { public Direction dirToTarget = null; public Missile(RobotController rc) { super(rc); } public void execute() throws GameActionException { if (dirToTarget == null) { RobotInfo[] nearbyRobots = rc.senseNearbyRobots(2, myTeam); for (RobotInfo robot : nearbyRobots) { if (robot.type == RobotType.LAUNCHER) { dirToTarget = rc.getLocation().directionTo(robot.location).opposite(); } } // //System.out.println("dirToTarget: "+dirToTarget.name()); } if (rc.isCoreReady() && rc.canMove(dirToTarget)){ rc.move(dirToTarget); } // if (getTeammatesInAttackRange().length <= 1 && getTeammatesInAttackRange().length > 4){ // rc.explode(); // } rc.yield(); } } }
Attack other enemy groups while containing if they're in sight
teams/team353/RobotPlayer.java
Attack other enemy groups while containing if they're in sight
Java
mit
469fab4e6e29607a473916df97aecee704856964
0
charlesrich/Disco,charlesrich/Disco,charlesrich/Disco,charlesrich/Disco
/* Copyright (c) 2008 Charles Rich and Worcester Polytechnic Institute. * All Rights Reserved. Use is subject to license terms. See the file * "license.terms" for information on usage and redistribution of this * file and for a DISCLAIMER OF ALL WARRANTIES. */ package edu.wpi.cetask; import java.beans.Expression; import java.util.*; import javax.xml.xpath.*; import org.w3c.dom.*; import edu.wpi.cetask.ScriptEngineWrapper.Compiled; public class TaskClass extends TaskModel.Member { // TODO check for duplicate slot names final public String precondition, postcondition; final Compiled compiledPrecondition, compiledPostcondition; /** * @return precondition of this task class (or null if none defined) * (Javascript expression that evaluates to true, false or null) */ public String getPrecondition () { return precondition; } /** * @return postcondition of this task class (or null if none defined) * (Javascript expression that evaluates to true, false or null) */ public String getPostcondition () { return postcondition; } private final boolean sufficient; /** * Returns true iff postcondition is provided and is sufficient. */ public boolean isSufficient () { return sufficient; } private Class<? extends Task> builtin; /** * A task class is builtin if its id is defined as a subclass of {@link Task}. * This allows overriding the behavior of the class. * * @see #newInstance() */ public boolean isBuiltin () { return builtin != null; } final private List<String> inputNames, outputNames, declaredInputNames, declaredOutputNames; private List<Script> scripts = Collections.emptyList(); /** * Return all scripts associated with this primitive task class (for all platforms and * device types). * * @see #getScript() */ public List<Script> getScripts () { if ( !scripts.isEmpty() && !isPrimitive() ) { getErr().println("Ignoring grounding script for non-primitive: "+this); return Collections.emptyList(); } return scripts; } /** * Return script to ground instances of this primitive task class appropriate * for platform and device type of this task engine, or null if none. */ public Script getScript () { List<Script> candidates = new ArrayList<Script>(getScripts()); for (Iterator<Script> i = candidates.iterator(); i.hasNext();) { Script script = i.next(); String platform = script.getPlatform(), deviceType = script.getDeviceType(); // remove scripts not appropriate to current platform and deviceType if ( !( (platform == null || platform.equals(engine.getPlatform(this))) && (deviceType == null || deviceType.equals(engine.getDeviceType(this))) ) ) i.remove(); } if ( candidates.isEmpty() ) { // look for default script for model and then overall (must be toplevel) Script global = null; for (TaskModel model : engine.getModels()) { for (Script script : model.getScripts()) { if ( script.isInit() ) continue; TaskClass task = script.getTask(); if ( task == null ) { String ns = script.getModel(); // not checking for multiple global scripts if ( ns == null ) global = script; else if ( ns.equals(getNamespace()) ) candidates.add(script); } else if ( equals(task) ) candidates.add(script); } } if ( candidates.isEmpty() && global != null ) candidates.add(global); } if ( candidates.isEmpty() ) return null; if ( candidates.size() > 1 ) getErr().println("Ignoring multiple scripts for "+this); return candidates.get(0); } private final List<String> primitiveTypes = Arrays.asList(new String[] {"boolean", "string", "number"}); public class Slot { // TODO: make modified a Slot private final String name, type, modified; private final boolean optional; private final Class<?> java; public String getName () { return name; } public String getType () { return type; } public boolean isOptional () { return optional; } public Class<?> getJava () { return java; } private Slot (String name) { this.name = name; // compute type if ( name.equals("success") || name.equals("external") ) this.type = "boolean"; else if ( name.equals("when") ) this.type = "Date"; else { String path = "[@name=\""+name+"\"]/@type"; String type = xpath("./n:input"+path+" | "+"./n:output"+path); // type attribute is optional (extension by CR) if ( type.length() == 0 ) { if ( !declaredInputNames.contains(name) && !declaredOutputNames.contains(name) ) throw new IllegalArgumentException(name+" is not slot of "+this); this.type = null; } else this.type = type; } // compute java class for type, if any if ( type == null || primitiveTypes.contains(type) ) this.java = null; else { Object java = null; try { java = engine.eval(type, "Slot constructor"); } // JavaScript constructor may not yet be defined since init script not evaluated yet catch (RuntimeException e) {} this.java = java instanceof Class ? (Class<?>) java : null; } // cache optional this.optional = getProperty(name, "@optional", false); // compute modified (move eventually to Input subclass) String modified = xpath("./n:input[@name=\""+name+"\"]/@modified"); if ( modified.length() > 0 ) { if ( !declaredOutputNames.contains(modified) ) { getErr().println("WARNING: Ignoring unknown modified output slot: "+modified); this.modified = null; } else if ( primitiveTypes.contains(type) || (java != null && !Cloneable.class.isAssignableFrom(java)) ){ getErr().println("WARNING: Ignoring modified attribute of non-cloneable input slot: "+name); this.modified = null; } else this.modified = modified; } else this.modified = null; } } private final Map<String,Slot> slots; public Slot getSlot (String name) { return slots.get(name); } private final boolean hasModifiedInputs; public boolean hasModifiedInputs () { return hasModifiedInputs; } @SuppressWarnings("unchecked") TaskClass (Node node, TaskModel model, XPath xpath) { model.super(node, xpath); // cache simple name (suppress package for builtin classes) String simple = getId(); try { simple = Utils.getSimpleName(Class.forName(getId()), true); } catch (ClassNotFoundException e) {} simpleName = simple; String pre = xpath("./n:precondition"), post = xpath("./n:postcondition"); precondition = Utils.emptyNull(pre); postcondition = Utils.emptyNull(post); compiledPrecondition = TaskEngine.isCompilable() ? engine.compile(pre, simple+" precondition") : null; compiledPostcondition = TaskEngine.isCompilable() ? engine.compile(post, simple+" postcondition") : null; String attribute = xpath("./n:postcondition/@sufficient"); // default false; sufficient = attribute.length() > 0 && Utils.parseBoolean(attribute); declaredInputNames = xpathValues("./n:input/@name"); for (String name : declaredInputNames) if ( declaredInputNames.indexOf(name) != declaredInputNames.lastIndexOf(name) ) throw new DuplicateSlotNameException(name); inputNames = new ArrayList<String>(declaredInputNames); inputNames.add("external"); declaredOutputNames = xpathValues("./n:output/@name"); if ( declaredInputNames.contains("success") || declaredOutputNames.contains("success") ) throw new ReservedSlotException("success"); if ( declaredInputNames.contains("external") || declaredOutputNames.contains("external") ) throw new ReservedSlotException("external"); for (String name : declaredOutputNames) if ( declaredOutputNames.indexOf(name) != declaredOutputNames.lastIndexOf(name) ) throw new DuplicateSlotNameException(name); outputNames = new ArrayList<String>(declaredOutputNames); outputNames.add("success"); outputNames.add("when"); // cache slot types slots = new HashMap<String,Slot>(inputNames.size()+outputNames.size()); for (String name : outputNames) slots.put(name, new Slot(name)); boolean hasModifiedInputs = false; for (String name : inputNames) { Slot slot; slots.put(name, slot = new Slot(name)); if ( slot.modified != null ) { hasModifiedInputs = true; if ( !Utils.equals(slot.type, getSlotType(slot.modified)) ) { // null types possible getErr().println("WARNING: Modified output slot of different type: "+slot.name); } } } this.hasModifiedInputs = hasModifiedInputs; if ( declaredInputNames.contains("device") && !"string".equals(getSlotType("device")) ) throw new IllegalStateException("Device slot must be of type string in " +getId()); // cache bindings NodeList nodes = (NodeList) xpath("./n:binding", XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { // preserve order Node bindingNode = nodes.item(i); try { String variable = xpath.evaluate("./@slot", bindingNode); if ( !variable.startsWith("$this.") ) throw new TaskModel.Error(this, "Invalid task binding slot "+variable); String slot = variable.substring(6); for (Binding binding : bindings) if ( binding.slot == slot) throw new TaskModel.Error(this, "duplicate bindings for "+variable); String value = xpath.evaluate("./@value", bindingNode); // TODO borrow error checking from DecompositionClass, // e.g, for undefined slots bindings.add(new Binding(slot, value)); } catch (XPathException e) { throw new RuntimeException(e); } } // cache nested scripts for (Node script : xpathNodes("./n:script")) { if ( scripts.isEmpty() ) scripts = new ArrayList<Script>(2); scripts.add(new Script(script, engine, this, xpath)); } try { builtin = (Class<? extends Task>) Class.forName(getId()); builtin.getDeclaredField("CLASS").set(null, this); } catch (ClassNotFoundException|ClassCastException e) {} catch (NoSuchFieldException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } if ( !getId().equals("**ROOT**") && getEngine().isRecognition() ) { if ( getProperty("@top", true) ) // assume this can be top until find decomposition that uses step // see contributes getEngine().topClasses.add(this); } } private class ReservedSlotException extends RuntimeException { public ReservedSlotException (String name) { super("Attempting to redefine reserved slot "+name+" in "+xpath("./@id")); } } private class DuplicateSlotNameException extends RuntimeException { public DuplicateSlotNameException (String name) { super("Attempting to define a duplicate slot name "+name+" in "+xpath("./@id")); } } /** * Thread-safe method to create new instance of this task class. */ public Task newInstance () { return isBuiltin() ? newStep(null, null, false) : new Task(this, engine); } Decomposition.Step newStep (Decomposition decomp, String step, boolean repeat) { // if id corresponds to subclass of Task, then instantiate // that "builtin" class instead try { return (Decomposition.Step) new Expression(builtin, "new", new Object[]{engine, decomp, step, repeat}).getValue(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Test whether this task class is primitive (relative to models in current * task engine). A task class is primitive iff there are no known * decomposition types with this task as goal. Overridden by value * of @primitive, if any. */ public boolean isPrimitive () { Boolean property = getProperty("@primitive", (Boolean) null); return property == null ? getDecompositions().isEmpty() : property; } /** * Force this task class to be treated as primitive or not, regardless * of whether decompositions are known. Usually used to make a task * class non-primitive even though decompositions not (yet) known. * Cannot set to primitive if decompositions are known. */ public void setPrimitive (boolean primitive) { if ( primitive && !getDecompositions().isEmpty() ) throw new UnsupportedOperationException("Cannot make primitive with known decompositions: "+this); setProperty("@primitive", primitive); } /** * Return list of input slot names, including "external". Note "device" * has predefined meaning, but is not automatically an input to every task. * * @see #getDeclaredInputNames() */ public List<String> getInputNames () { return inputNames; } /** * Return list of output slot names, including "success" and "when". * * @see #getDeclaredOutputNames() */ public List<String> getOutputNames () { return outputNames; } /** * Return list of declared input slot names. * * @see #getInputNames() */ public List<String> getDeclaredInputNames () { return declaredInputNames; } /** * Return list of declared output slot names. * * @see #getInputNames() */ public List<String> getDeclaredOutputNames () { return declaredOutputNames; } /** * @return name of modified output for given declared input, or null if input not modified. */ public String getModifiedOutput (String input) { if ( !declaredInputNames.contains(input) ) throw new IllegalArgumentException("Not a declared input: "+input); return slots.get(input).modified; } /** * @return name of corresponding input for given declared output, or null if output not modified */ public String getModifiedInput (String output) { if ( !declaredOutputNames.contains(output) ) throw new IllegalArgumentException("Not a declared output: "+output); for (String input : declaredInputNames) if ( output.equals(slots.get(input).modified) ) return input; return null; } /** * Returns a string identifying the type of given slot name for this task * class, or null if no restriction. * * @return null, "string", "boolean" or "number" or the name of a constructor * defined in the current ECMAScript environment, or an expression * that evaluates to a Java class object. */ public String getSlotType (String name) { return slots.get(name).type; } /** * Tests whether given string is name of a slot of this task class. */ public boolean isSlot (String name) { return slots.containsKey(name); } /** * Return a human-readable string describing given slot of this task class. * * @param definite use definite ("the") form; otherwise indefinite ("a") */ public String formatSlot (String name, boolean definite) { String property = getProperty(name, definite ? "@definite" : "@indefinite"); if ( property != null ) return property; StringBuilder buffer = new StringBuilder( engine.getProperty(definite ? "the@word" : "a@word")); buffer.append(' '); if ( definite ) buffer.append(this).append(' ').append(name); else { String type = getSlotType(name); if ( type != null ) buffer.append(Utils.decapitalize(type)); } return buffer.toString(); } public String getProperty (String slot, String key) { return getProperty('.'+slot+key); } public void setProperty (String slot, String key, String value) { setProperty('.'+slot+key, value); } public Boolean getProperty (String slot, String key, Boolean defaultValue) { String value = getProperty(slot, key); return value == null ? (Boolean) defaultValue : (Boolean) Utils.parseBoolean(value); } // cache decomposition classes List<DecompositionClass> decompositions = Collections.emptyList(); /** * Return non-modifiable list of <em>known</em> decomposition classes for this * task class. * * @see Task#getDecompositions() * @see Plan#getDecompositions() */ public List<DecompositionClass> getDecompositions () { return decompositions; } /** * Return decomposition class with given id for this task class or null if none. */ public DecompositionClass getDecomposition (String id) { for (DecompositionClass decomp : getDecompositions()) if ( decomp.getId().equals(id) ) return decomp; return null; } // useful for CoachedInteraction private Decomposition lastDecomp; /** * Set the last decomposition used to decompose a goal of this type */ public void setLastDecomposition (Decomposition decomp) { lastDecomp = decomp; } /** * @return the decomposition last used to decompose a goal of this type */ public Decomposition getLastDecomposition () { return lastDecomp; } private final String simpleName; @Override public String toString () { // for readability, suppress namespace for unambiguous id's try { engine.getTaskClass(getId()); return simpleName; } catch (TaskEngine.AmbiguousIdException e) { return '{'+getNamespace()+'}'+getId(); } } // for extension to plan recognition private List<TaskClass> contributes = null; private Set<TaskClass> explains = Collections.emptySet(); /** * Test whether this task class can contribute to given task class. * Returns false if given task class is same as this task class. */ public boolean isPathFrom (TaskClass task) { return task.explains.contains(this); } void contributes (TaskClass task) { if ( task != this && (contributes == null || !contributes.contains(task)) ) { if ( contributes == null ) contributes = new ArrayList<TaskClass>(); contributes.add(task); if ( task.explains.isEmpty() ) task.explains = new HashSet<TaskClass>(); task.explains.add(this); task.addExplains(this, explains, new ArrayList<TaskClass>()); if ( !this.getProperty("@top", false) ) getEngine().topClasses.remove(this); } } private void addExplains (TaskClass add, Set<TaskClass> addAll, List<TaskClass> visited) { if ( !visited.contains(this) ) { visited.add(this); explains.add(add); explains.addAll(addAll); if ( contributes != null ) for (TaskClass c : contributes) c.addExplains(add, addAll, visited); } } // for use with extensions to CEA-2018 // a greatly simplified version of DecompositionClass.Binding // TODO does not handle dependencies between bindings private final List<Binding> bindings = new ArrayList<Binding>(4); void updateBindings (Task task) { for (Binding binding : bindings) binding.update(task); } private class Binding { private final String slot, value, expression, where; private final Compiled compiled; private Binding (String slot, String value) { this.slot = slot; this.value = value; where = TaskClass.this.getId() + " binding for " + slot; String expression = Task.makeExpression("$this", TaskClass.this, slot, value, true); if ( TaskEngine.isCompilable() ) { compiled = engine.compile(expression, where); this.expression = null; } else { this.expression = expression; compiled = null; } } private void update (Task task) { // using ..Final methods to avoid calling Decomposition.Step.updateBindings // (see Task constructor) if ( compiled != null ) { if ( !task.evalConditionFinal(compiled, task.bindings, where) ) task.failCheck(slot, "compiled script", where); else task.setModified(true); } else { try { if ( !task.evalConditionFinal(expression, where) ) task.failCheck(slot, value, where); else task.setModified(true); } finally { task.bindings.remove("$$value"); } } } @Override public String toString () { return slot; } } }
task/java/edu/wpi/cetask/TaskClass.java
/* Copyright (c) 2008 Charles Rich and Worcester Polytechnic Institute. * All Rights Reserved. Use is subject to license terms. See the file * "license.terms" for information on usage and redistribution of this * file and for a DISCLAIMER OF ALL WARRANTIES. */ package edu.wpi.cetask; import java.beans.Expression; import java.util.*; import javax.xml.xpath.*; import org.w3c.dom.*; import edu.wpi.cetask.ScriptEngineWrapper.Compiled; public class TaskClass extends TaskModel.Member { // TODO check for duplicate slot names final public String precondition, postcondition; final Compiled compiledPrecondition, compiledPostcondition; /** * @return precondition of this task class (or null if none defined) * (Javascript expression that evaluates to true, false or null) */ public String getPrecondition () { return precondition; } /** * @return postcondition of this task class (or null if none defined) * (Javascript expression that evaluates to true, false or null) */ public String getPostcondition () { return postcondition; } private final boolean sufficient; /** * Returns true iff postcondition is provided and is sufficient. */ public boolean isSufficient () { return sufficient; } private Class<? extends Task> builtin; /** * A task class is builtin if its id is defined as a subclass of {@link Task}. * This allows overriding the behavior of the class. * * @see #newInstance() */ public boolean isBuiltin () { return builtin != null; } final private List<String> inputNames, outputNames, declaredInputNames, declaredOutputNames; private List<Script> scripts = Collections.emptyList(); /** * Return all scripts associated with this primitive task class (for all platforms and * device types). * * @see #getScript() */ public List<Script> getScripts () { if ( !scripts.isEmpty() && !isPrimitive() ) { getErr().println("Ignoring grounding script for non-primitive: "+this); return Collections.emptyList(); } return scripts; } /** * Return script to ground instances of this primitive task class appropriate * for platform and device type of this task engine, or null if none. */ public Script getScript () { List<Script> candidates = new ArrayList<Script>(getScripts()); for (Iterator<Script> i = candidates.iterator(); i.hasNext();) { Script script = i.next(); String platform = script.getPlatform(), deviceType = script.getDeviceType(); // remove scripts not appropriate to current platform and deviceType if ( !( (platform == null || platform.equals(engine.getPlatform(this))) && (deviceType == null || deviceType.equals(engine.getDeviceType(this))) ) ) i.remove(); } if ( candidates.isEmpty() ) { // look for default script for model and then overall (must be toplevel) Script global = null; for (TaskModel model : engine.getModels()) { for (Script script : model.getScripts()) { if ( script.isInit() ) continue; TaskClass task = script.getTask(); if ( task == null ) { String ns = script.getModel(); // not checking for multiple global scripts if ( ns == null ) global = script; else if ( ns.equals(getNamespace()) ) candidates.add(script); } else if ( equals(task) ) candidates.add(script); } } if ( candidates.isEmpty() && global != null ) candidates.add(global); } if ( candidates.isEmpty() ) return null; if ( candidates.size() > 1 ) getErr().println("Ignoring multiple scripts for "+this); return candidates.get(0); } private final List<String> primitiveTypes = Arrays.asList(new String[] {"boolean", "string", "number"}); public class Slot { // TODO: make modified a Slot private final String name, type, modified; private final boolean optional; private final Class<?> java; public String getName () { return name; } public String getType () { return type; } public boolean isOptional () { return optional; } public Class<?> getJava () { return java; } private Slot (String name) { this.name = name; // compute type if ( name.equals("success") || name.equals("external") ) this.type = "boolean"; else if ( name.equals("when") ) this.type = "Date"; else { String path = "[@name=\""+name+"\"]/@type"; String type = xpath("./n:input"+path+" | "+"./n:output"+path); // type attribute is optional (extension by CR) if ( type.length() == 0 ) { if ( !declaredInputNames.contains(name) && !declaredOutputNames.contains(name) ) throw new IllegalArgumentException(name+" is not slot of "+this); this.type = null; } else this.type = type; } // compute java class for type, if any if ( type == null || primitiveTypes.contains(type) ) this.java = null; else { Object java = null; try { java = engine.eval(type, "Slot constructor"); } // JavaScript constructor may not yet be defined since init script not evaluated yet catch (RuntimeException e) {} this.java = java instanceof Class ? (Class<?>) java : null; } // cache optional this.optional = getProperty(name, "@optional", false); // compute modified (move eventually to Input subclass) String modified = xpath("./n:input[@name=\""+name+"\"]/@modified"); if ( modified.length() > 0 ) { if ( !declaredOutputNames.contains(modified) ) { getErr().println("WARNING: Ignoring unknown modified output slot: "+modified); this.modified = null; } else if ( primitiveTypes.contains(type) || (java != null && !Cloneable.class.isAssignableFrom(java)) ){ getErr().println("WARNING: Ignoring modified attribute of non-cloneable input slot: "+name); this.modified = null; } else this.modified = modified; } else this.modified = null; } } private final Map<String,Slot> slots; public Slot getSlot (String name) { return slots.get(name); } private final boolean hasModifiedInputs; public boolean hasModifiedInputs () { return hasModifiedInputs; } @SuppressWarnings("unchecked") TaskClass (Node node, TaskModel model, XPath xpath) { model.super(node, xpath); // cache simple name (suppress package for builtin classes) String simple = getId(); try { simple = Utils.getSimpleName(Class.forName(getId()), true); } catch (ClassNotFoundException e) {} simpleName = simple; String pre = xpath("./n:precondition"), post = xpath("./n:postcondition"); precondition = Utils.emptyNull(pre); postcondition = Utils.emptyNull(post); compiledPrecondition = TaskEngine.isCompilable() ? engine.compile(pre, simple+" precondition") : null; compiledPostcondition = TaskEngine.isCompilable() ? engine.compile(post, simple+" postcondition") : null; String attribute = xpath("./n:postcondition/@sufficient"); // default false; sufficient = attribute.length() > 0 && Utils.parseBoolean(attribute); declaredInputNames = xpathValues("./n:input/@name"); for (String name : declaredInputNames) if ( declaredInputNames.indexOf(name) != declaredInputNames.lastIndexOf(name) ) throw new DuplicateSlotNameException(name); inputNames = new ArrayList<String>(declaredInputNames); inputNames.add("external"); declaredOutputNames = xpathValues("./n:output/@name"); if ( declaredInputNames.contains("success") || declaredOutputNames.contains("success") ) throw new ReservedSlotException("success"); if ( declaredInputNames.contains("external") || declaredOutputNames.contains("external") ) throw new ReservedSlotException("external"); for (String name : declaredOutputNames) if ( declaredOutputNames.indexOf(name) != declaredOutputNames.lastIndexOf(name) ) throw new DuplicateSlotNameException(name); outputNames = new ArrayList<String>(declaredOutputNames); outputNames.add("success"); outputNames.add("when"); // cache slot types slots = new HashMap<String,Slot>(inputNames.size()+outputNames.size()); for (String name : outputNames) slots.put(name, new Slot(name)); boolean hasModifiedInputs = false; for (String name : inputNames) { Slot slot; slots.put(name, slot = new Slot(name)); if ( slot.modified != null ) { hasModifiedInputs = true; if ( !Utils.equals(slot.type, getSlotType(slot.modified)) ) { // null types possible getErr().println("WARNING: Modified output slot of different type: "+slot.name); } } } this.hasModifiedInputs = hasModifiedInputs; if ( declaredInputNames.contains("device") && !"string".equals(getSlotType("device")) ) throw new IllegalStateException("Device slot must be of type string in " +getId()); // cache bindings NodeList nodes = (NodeList) xpath("./n:binding", XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { // preserve order Node bindingNode = nodes.item(i); try { String variable = xpath.evaluate("./@slot", bindingNode); if ( !variable.startsWith("$this.") ) throw new TaskModel.Error(this, "Invalid task binding slot "+variable); String slot = variable.substring(6); for (Binding binding : bindings) if ( binding.slot == slot) throw new TaskModel.Error(this, "duplicate bindings for "+variable); String value = xpath.evaluate("./@value", bindingNode); // TODO borrow error checking from DecompositionClass, // e.g, for undefined slots bindings.add(new Binding(slot, value)); } catch (XPathException e) { throw new RuntimeException(e); } } // cache nested scripts for (Node script : xpathNodes("./n:script")) { if ( scripts.isEmpty() ) scripts = new ArrayList<Script>(2); scripts.add(new Script(script, engine, this, xpath)); } try { builtin = (Class<? extends Task>) Class.forName(getId()); builtin.getDeclaredField("CLASS").set(null, this); } catch (ClassNotFoundException|ClassCastException e) {} catch (NoSuchFieldException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } if ( !getId().equals("**ROOT**") && getEngine().isRecognition() ) { if ( getProperty("@top", true) ) // assume this can be top until find decomposition that uses step // see contributes getEngine().topClasses.add(this); } } private class ReservedSlotException extends RuntimeException { public ReservedSlotException (String name) { super("Attempting to redefine reserved slot "+name+" in "+xpath("./@id")); } } private class DuplicateSlotNameException extends RuntimeException { public DuplicateSlotNameException (String name) { super("Attempting to define a duplicate slot name "+name+" in "+xpath("./@id")); } } /** * Thread-safe method to create new instance of this task class. */ public Task newInstance () { return isBuiltin() ? newStep(null, null, false) : new Task(this, engine); } Decomposition.Step newStep (Decomposition decomp, String step, boolean repeat) { // if id corresponds to subclass of Task, then instantiate // that "builtin" class instead try { return (Decomposition.Step) new Expression(builtin, "new", new Object[]{engine, decomp, step, repeat}).getValue(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Test whether this task class is primitive (relative to models in current * task engine). A task class is primitive iff there are no known * decomposition types with this task as goal. Overridden by value * of @primitive, if any. */ public boolean isPrimitive () { Boolean property = getProperty("@primitive", (Boolean) null); return property == null ? getDecompositions().isEmpty() : property; } /** * Force this task class to be treated as primitive or not, regardless * of whether decompositions are known. Usually used to make a task * class non-primitive even though decompositions not (yet) known. * Cannot set to primitive if decompositions are known. */ public void setPrimitive (boolean primitive) { if ( primitive && !getDecompositions().isEmpty() ) throw new UnsupportedOperationException("Cannot make primitive with known decompositions: "+this); setProperty("@primitive", primitive); } /** * Return list of input slot names, including "external". Note "device" * has predefined meaning, but is not automatically an input to every task. * * @see #getDeclaredInputNames() */ public List<String> getInputNames () { return inputNames; } /** * Return list of output slot names, including "success" and "when". * * @see #getDeclaredOutputNames() */ public List<String> getOutputNames () { return outputNames; } /** * Return list of declared input slot names. * * @see #getInputNames() */ public List<String> getDeclaredInputNames () { return declaredInputNames; } /** * Return list of declared output slot names. * * @see #getInputNames() */ public List<String> getDeclaredOutputNames () { return declaredOutputNames; } /** * @return name of modified output for given declared input, or null if input not modified. */ public String getModifiedOutput (String input) { if ( !declaredInputNames.contains(input) ) throw new IllegalArgumentException("Not a declared input: "+input); return slots.get(input).modified; } /** * @return name of corresponding input for given declared output, or null if output not modified */ public String getModifiedInput (String output) { if ( !declaredOutputNames.contains(output) ) throw new IllegalArgumentException("Not a declared output: "+output); for (String input : declaredInputNames) if ( output.equals(slots.get(input).modified) ) return input; return null; } /** * Returns a string identifying the type of given slot name for this task * class, or null if no restriction. * * @return null, "string", "boolean" or "number" or the name of a constructor * defined in the current ECMAScript environment, or an expression * that evaluates to a Java class object. */ public String getSlotType (String name) { return slots.get(name).type; } /** * Tests whether given string is name of a slot of this task class. */ public boolean isSlot (String name) { return slots.containsKey(name); } /** * Return a human-readable string describing given slot of this task class. * * @param definite use definite ("the") form; otherwise indefinite ("a") */ public String formatSlot (String name, boolean definite) { String property = getProperty(name, definite ? "@definite" : "@indefinite"); if ( property != null ) return property; StringBuilder buffer = new StringBuilder( engine.getProperty(definite ? "the@word" : "a@word")); buffer.append(' '); if ( definite ) buffer.append(this).append(' ').append(name); else { String type = getSlotType(name); if ( type != null ) buffer.append(Utils.decapitalize(type)); } return buffer.toString(); } public String getProperty (String slot, String key) { return getProperty('.'+slot+key); } public void setProperty (String slot, String key, String value) { setProperty('.'+slot+key, value); } public Boolean getProperty (String slot, String key, Boolean defaultValue) { String value = getProperty(slot, key); return value == null ? (Boolean) defaultValue : (Boolean) Utils.parseBoolean(value); } // cache decomposition classes List<DecompositionClass> decompositions = Collections.emptyList(); /** * Return non-modifiable list of <em>known</em> decomposition classes for this * task class. * * @see Task#getDecompositions() * @see Plan#getDecompositions() */ public List<DecompositionClass> getDecompositions () { return decompositions; } /** * Return decomposition class with given id for this task class or null if none. */ public DecompositionClass getDecomposition (String id) { for (DecompositionClass decomp : getDecompositions()) if ( decomp.getId().equals(id) ) return decomp; return null; } // useful for CoachedInteraction private Decomposition lastDecomp; /** * Set the last decomposition used to decompose a goal of this type */ public void setLastDecomposition (Decomposition decomp) { lastDecomp = decomp; } /** * @return the decomposition last used to decompose a goal of this type */ public Decomposition getLastDecomposition () { return lastDecomp; } private final String simpleName; @Override public String toString () { // for readability, suppress namespace for unambiguous id's try { engine.getTaskClass(getId()); return simpleName; } catch (TaskEngine.AmbiguousIdException e) { return '{'+getNamespace()+'}'+getId(); } } // for extension to plan recognition private List<TaskClass> contributes = null; private Set<TaskClass> explains = Collections.emptySet(); /** * Test whether this task class can contribute to given task class. * Returns false if given task class is same as this task class. */ public boolean isPathFrom (TaskClass task) { return task.explains.contains(this); } /** * Comparator to be used, for example, with @link{Collections#sort(List,Comparator)} * to sort a list of task classes relative to how "high" they are in decomposition * hierarchy of currently loaded libraries. Using this comparator will sort * the list so that the primitives are at the start and so on. * * Note: This comparator imposes orderings that are inconsistent with equals. Do * {\em not} use to implement sorted sets (or maps) containing task classes. */ public final static Comparator<TaskClass> COMPARATOR = new Comparator<TaskClass> () { /** * Returns 0 if two classes are equal or if there is no decomposition * path from task1 to task2 or vice versa, i.e., if task1 and task2 * are in the same {\em equivalence class}. Returns -1 if task1 * can appear in the decomposition (recursively) of task2 or +1 * if the reverse. */ @Override public int compare (TaskClass task1, TaskClass task2) { return task1.equals(task2) ? 0 : task1.isPathFrom(task2) ? -1 : task2.isPathFrom(task1) ? 1 : 0; } }; void contributes (TaskClass task) { if ( task != this && (contributes == null || !contributes.contains(task)) ) { if ( contributes == null ) contributes = new ArrayList<TaskClass>(); contributes.add(task); if ( task.explains.isEmpty() ) task.explains = new HashSet<TaskClass>(); task.explains.add(this); task.addExplains(this, explains, new ArrayList<TaskClass>()); if ( !this.getProperty("@top", false) ) getEngine().topClasses.remove(this); } } private void addExplains (TaskClass add, Set<TaskClass> addAll, List<TaskClass> visited) { if ( !visited.contains(this) ) { visited.add(this); explains.add(add); explains.addAll(addAll); if ( contributes != null ) for (TaskClass c : contributes) c.addExplains(add, addAll, visited); } } // for use with extensions to CEA-2018 // a greatly simplified version of DecompositionClass.Binding // TODO does not handle dependencies between bindings private final List<Binding> bindings = new ArrayList<Binding>(4); void updateBindings (Task task) { for (Binding binding : bindings) binding.update(task); } private class Binding { private final String slot, value, expression, where; private final Compiled compiled; private Binding (String slot, String value) { this.slot = slot; this.value = value; where = TaskClass.this.getId() + " binding for " + slot; String expression = Task.makeExpression("$this", TaskClass.this, slot, value, true); if ( TaskEngine.isCompilable() ) { compiled = engine.compile(expression, where); this.expression = null; } else { this.expression = expression; compiled = null; } } private void update (Task task) { // using ..Final methods to avoid calling Decomposition.Step.updateBindings // (see Task constructor) if ( compiled != null ) { if ( !task.evalConditionFinal(compiled, task.bindings, where) ) task.failCheck(slot, "compiled script", where); else task.setModified(true); } else { try { if ( !task.evalConditionFinal(expression, where) ) task.failCheck(slot, value, where); else task.setModified(true); } finally { task.bindings.remove("$$value"); } } } @Override public String toString () { return slot; } } }
Remove useless comparator
task/java/edu/wpi/cetask/TaskClass.java
Remove useless comparator
Java
mit
bacc6d84d3050896170e0d488c28de44a11758a2
0
SpongePowered/Sponge,Grinch/SpongeCommon,kenzierocks/SpongeCommon,Grinch/SpongeCommon,sanman00/SpongeCommon,kenzierocks/SpongeCommon,SpongePowered/Sponge,SpongePowered/Sponge,DDoS/SpongeCommon,SpongePowered/SpongeCommon,DDoS/SpongeCommon,JBYoshi/SpongeCommon,sanman00/SpongeCommon,JBYoshi/SpongeCommon,SpongePowered/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.event; import static com.google.common.base.Preconditions.checkNotNull; import co.aikar.timings.Timing; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.EntityHanging; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.effect.EntityWeatherEffect; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityItemFrame; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.init.Blocks; import net.minecraft.network.Packet; import net.minecraft.network.play.client.C01PacketChatMessage; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.network.play.client.C0EPacketClickWindow; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.stats.StatList; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EntityDamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.EmptyChunk; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntitySnapshot; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.action.LightningEvent; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.NamedCause; import org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource; import org.spongepowered.api.event.cause.entity.spawn.BlockSpawnCause; import org.spongepowered.api.event.cause.entity.spawn.SpawnCause; import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes; import org.spongepowered.api.event.entity.DestructEntityEvent; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.event.message.MessageEvent; import org.spongepowered.api.text.channel.MessageChannel; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.SpongeImplHooks; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.data.util.NbtDataUtil; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.interfaces.IMixinChunk; import org.spongepowered.common.interfaces.IMixinNextTickListEntry; import org.spongepowered.common.interfaces.entity.IMixinEntity; import org.spongepowered.common.interfaces.entity.IMixinEntityLightningBolt; import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP; import org.spongepowered.common.interfaces.world.IMixinWorld; import org.spongepowered.common.util.SpongeHooks; import org.spongepowered.common.util.StaticMixinHelper; import org.spongepowered.common.util.VecHelper; import org.spongepowered.common.world.CaptureType; import org.spongepowered.common.world.SpongeProxyBlockAccess; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Optional; import java.util.Random; import javax.annotation.Nullable; public final class CauseTracker { private final net.minecraft.world.World targetWorld; private boolean captureSpawnedEntities = false; private boolean captureBlockDecay = false; private boolean captureTerrainGen = false; private boolean captureBlocks = false; private boolean captureCommand = false; private boolean restoringBlocks = false; private boolean ignoreSpawnEvents = false; private boolean specificCapture = false; private List<Entity> capturedSpawnedEntities = new ArrayList<>(); private List<Entity> capturedSpawnedEntityItems = new ArrayList<>(); private List<BlockSnapshot> capturedSpongeBlockSnapshots = new ArrayList<>(); // used internally to handle specific captures and not conflict with rest private List<Entity> capturedSpecificSpawnedEntities = new ArrayList<>(); private List<Entity> capturedSpecificSpawnedEntityItems = new ArrayList<>(); private List<BlockSnapshot> capturedSpecificSpongeBlockSnapshots = new ArrayList<>(); private List<Transaction<BlockSnapshot>> invalidTransactions = new ArrayList<>(); @Nullable private User currentNotifier; @Nullable private BlockSnapshot currentTickBlock; @Nullable private Entity currentTickEntity; @Nullable private TileEntity currentTickTileEntity; @Nullable public IMixinNextTickListEntry currentPendingBlockUpdate; @Nullable private Cause pluginCause; private boolean worldSpawnerRunning; private boolean chunkSpawnerRunning; private Deque<Cause> causeStack = new ArrayDeque<>(); private Packet<?> currentPlayerPacket; public final Timing causeTrackerBlockTimer; public final Timing causeTrackerBlockBreakTimer; public final Timing causeTrackerEntityTimer; public final Timing causeTrackerEntityItemTimer; public CauseTracker(net.minecraft.world.World targetWorld) { this.targetWorld = targetWorld; this.causeTrackerBlockTimer = this.getMixinWorld().getTimingsHandler().causeTrackerBlockTimer; this.causeTrackerBlockBreakTimer = this.getMixinWorld().getTimingsHandler().causeTrackerBlockBreakTimer; this.causeTrackerEntityTimer = this.getMixinWorld().getTimingsHandler().causeTrackerEntityTimer; this.causeTrackerEntityItemTimer = this.getMixinWorld().getTimingsHandler().causeTrackerEntityItemTimer; } public World getWorld() { return (World) this.targetWorld; } public net.minecraft.world.World getMinecraftWorld() { return this.targetWorld; } public IMixinWorld getMixinWorld() { return (IMixinWorld) this.targetWorld; } public boolean isIgnoringSpawnEvents() { return this.ignoreSpawnEvents; } public void setIgnoreSpawnEvents(boolean ignoreSpawnEvents) { this.ignoreSpawnEvents = ignoreSpawnEvents; } public boolean isCapturingSpawnedEntities() { return this.captureSpawnedEntities; } public void setCaptureSpawnedEntities(boolean captureSpawnedEntities) { this.captureSpawnedEntities = captureSpawnedEntities; } public List<Entity> getCapturedSpawnedEntities() { if (this.specificCapture) { return this.capturedSpecificSpawnedEntities; } return this.capturedSpawnedEntities; } public List<Entity> getCapturedSpawnedEntityItems() { if (this.specificCapture) { return this.capturedSpecificSpawnedEntityItems; } return this.capturedSpawnedEntityItems; } public boolean isCaptureBlockDecay() { return this.captureBlockDecay; } public void setCapturingBlockDecay(boolean captureBlockDecay) { this.captureBlockDecay = captureBlockDecay; } public boolean isCapturingTerrainGen() { return this.captureTerrainGen; } public void setCapturingTerrainGen(boolean captureTerrainGen) { this.captureTerrainGen = captureTerrainGen; } public boolean isCapturingBlocks() { return this.captureBlocks; } public void setCaptureBlocks(boolean captureBlocks) { this.captureBlocks = captureBlocks; } public boolean isCaptureCommand() { return this.captureCommand; } public void setCapturingCommand(boolean captureCommand) { this.captureCommand = captureCommand; } public boolean isRestoringBlocks() { return this.restoringBlocks; } public void setRestoringBlocks(boolean restoringBlocks) { this.restoringBlocks = restoringBlocks; } public boolean hasNotifier() { return this.currentNotifier != null; } public Optional<User> getCurrentNotifier() { return Optional.ofNullable(this.currentNotifier); } public void setCurrentNotifier(@Nullable User currentNotifier) { this.currentNotifier = currentNotifier; } public boolean hasTickingBlock() { return this.currentTickBlock != null; } public Optional<BlockSnapshot> getCurrentTickBlock() { return Optional.ofNullable(this.currentTickBlock); } public void setCurrentTickBlock(@Nullable BlockSnapshot currentTickBlock) { this.currentTickBlock = currentTickBlock; } public boolean hasTickingEntity() { return this.currentTickEntity != null; } public Optional<Entity> getCurrentTickEntity() { return Optional.ofNullable(this.currentTickEntity); } public void setCurrentTickEntity(@Nullable Entity currentTickEntity) { this.currentTickEntity = currentTickEntity; } public boolean hasTickingTileEntity() { return this.currentTickTileEntity != null; } public Optional<TileEntity> getCurrentTickTileEntity() { return Optional.ofNullable(this.currentTickTileEntity); } public void setCurrentTickTileEntity(TileEntity currentTickTileEntity) { this.currentTickTileEntity = currentTickTileEntity; } public List<BlockSnapshot> getCapturedSpongeBlockSnapshots() { if (this.specificCapture) { return this.capturedSpecificSpongeBlockSnapshots; } return this.capturedSpongeBlockSnapshots; } public List<Transaction<BlockSnapshot>> getInvalidTransactions() { return this.invalidTransactions; } public void setInvalidTransactions(List<Transaction<BlockSnapshot>> invalidTransactions) { this.invalidTransactions = invalidTransactions; } public boolean isWorldSpawnerRunning() { return this.worldSpawnerRunning; } public void setWorldSpawnerRunning(boolean worldSpawnerRunning) { this.worldSpawnerRunning = worldSpawnerRunning; } public boolean isChunkSpawnerRunning() { return this.chunkSpawnerRunning; } public void setChunkSpawnerRunning(boolean chunkSpawnerRunning) { this.chunkSpawnerRunning = chunkSpawnerRunning; } public Optional<Cause> getPluginCause() { return Optional.ofNullable(this.pluginCause); } public void setPluginCause(@Nullable Cause pluginCause) { this.pluginCause = pluginCause; } public boolean hasPluginCause() { return this.pluginCause != null; } public Cause getCurrentCause() { return this.causeStack.peekFirst(); } public void addCause(Cause cause) { this.causeStack.addFirst(cause); } public void removeCurrentCause() { this.causeStack.removeFirst(); } public Packet<?> getCurrentPlayerPacket() { return this.currentPlayerPacket; } public void setCurrentPlayerPacket(@Nullable Packet<?> currentPlayerPacket) { this.currentPlayerPacket = currentPlayerPacket; } public void preTrackEntity(Entity entity) { this.currentTickEntity = entity; this.addCause(Cause.of(NamedCause.source(entity))); this.trackEntityCausePreTick((net.minecraft.entity.Entity) entity); } public void postTrackEntity() { this.handlePostTickCaptures(); this.removeCurrentCause(); this.currentTickEntity = null; this.currentNotifier = null; } public void preTrackTileEntity(TileEntity tile) { this.currentTickTileEntity = tile; this.trackBlockPositionCausePreTick(((net.minecraft.tileentity.TileEntity) tile).getPos()); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickTileEntity)); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } this.addCause(Cause.of(namedCauses)); } public void postTrackTileEntity() { this.handlePostTickCaptures(); this.removeCurrentCause(); this.currentTickTileEntity = null; this.currentNotifier = null; } public void preTrackBlock(IBlockState state, BlockPos pos) { this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0); this.trackBlockPositionCausePreTick(pos); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickBlock)); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } this.addCause(Cause.of(namedCauses)); } public void postTrackBlock() { this.handlePostTickCaptures(); this.removeCurrentCause(); this.currentTickBlock = null; this.currentNotifier = null; } public void setSpecificCapture(boolean flag) { this.specificCapture = flag; } public void handlePostTickCaptures() { if (this.getMinecraftWorld().isRemote || this.restoringBlocks || this.causeStack.isEmpty()) { return; } else if (this.getCapturedSpawnedEntities().isEmpty() && this.getCapturedSpawnedEntityItems().isEmpty() && this.getCapturedSpongeBlockSnapshots().isEmpty() && StaticMixinHelper.packetPlayer == null) { return; // nothing was captured, return } EntityPlayerMP player = StaticMixinHelper.packetPlayer; Cause cause = this.getCurrentCause(); // Handle Block Captures handleBlockCaptures(); // Handle Player kill commands if (player != null && this.currentPlayerPacket instanceof C01PacketChatMessage) { C01PacketChatMessage chatPacket = (C01PacketChatMessage) this.currentPlayerPacket; if (chatPacket.getMessage().contains("kill")) { if (!cause.contains(player)) { cause = cause.with(NamedCause.of("Player", player)); } } } // Inventory Events if (this.currentPlayerPacket instanceof C0EPacketClickWindow){ SpongeCommonEventFactory.handleClickInteractInventoryEvent(Cause.of(NamedCause.source(player)), player, (C0EPacketClickWindow) this.currentPlayerPacket); } // Handle Entity captures if (!this.getCapturedSpawnedEntityItems().isEmpty()) { handleDroppedItems(); } if (!this.getCapturedSpawnedEntities().isEmpty()) { handleSpawnedEntities(); } this.invalidTransactions.clear(); } public void handleSpawnedEntities() { List<Entity> capturedEntityList = this.getCapturedSpawnedEntities(); if (capturedEntityList.size() == 0) { return; } this.causeTrackerEntityTimer.startTiming(); Iterator<Entity> iter = capturedEntityList.iterator(); ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>(); while (iter.hasNext()) { Entity currentEntity = iter.next(); if (this.invalidTransactions != null) { // check to see if this spawn is invalid and if so, remove boolean invalid = false; for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) { if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) { invalid = true; iter.remove(); break; } } if (invalid) { continue; } } // determine if this was caused by a block break and if so, fire as single event IMixinEntity spongeEntity = (IMixinEntity) currentEntity; SpawnCause spawnCause = spongeEntity.getSpawnCause(); if (spawnCause != null) { ImmutableList.Builder<EntitySnapshot> entitySingleSnapshotBuilder = new ImmutableList.Builder<>(); entitySingleSnapshotBuilder.add(currentEntity.createSnapshot()); List<Entity> entityList = new ArrayList<>(); entityList.add(currentEntity); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(spawnCause)); User currentUser = StaticMixinHelper.packetPlayer != null ? (User) StaticMixinHelper.packetPlayer : this.currentNotifier; if (currentUser != null) { namedCauses.add(NamedCause.owner(currentUser)); } Cause cause = Cause.of(namedCauses); causeTrackerEntityTimer.stopTiming(); SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(cause, entityList, entitySingleSnapshotBuilder.build(), this.getWorld()); handlePostEntityEvent(cause, event); causeTrackerEntityTimer.startTiming(); iter.remove(); continue; } entitySnapshotBuilder.add(currentEntity.createSnapshot()); } if (capturedEntityList.isEmpty()) { this.causeTrackerEntityTimer.stopTiming(); return; } Cause cause = this.getCurrentCause(); if (cause != null && !cause.first(SpawnCause.class).isPresent()) { Cause spawnCause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityList.get(0)); cause = spawnCause.merge(cause); } else if (cause == null) { cause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityList.get(0)); } List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build(); if (entitySnapshots.isEmpty()) { this.causeTrackerEntityTimer.stopTiming(); return; } this.causeTrackerEntityTimer.stopTiming(); SpawnEntityEvent event = null; if (this.worldSpawnerRunning) { event = SpongeEventFactory.createSpawnEntityEventSpawner(cause, capturedEntityList, entitySnapshots, this.getWorld()); } else if (this.chunkSpawnerRunning){ event = SpongeEventFactory.createSpawnEntityEventChunkLoad(cause, capturedEntityList, entitySnapshots, this.getWorld()); } else { event = SpongeEventFactory.createSpawnEntityEventCustom(cause, capturedEntityList, entitySnapshots, this.getWorld()); } if (handlePostEntityEvent(cause, event)) { capturedEntityList.clear(); } } public void handleDroppedItems() { List<Entity> capturedEntityItemList = this.getCapturedSpawnedEntityItems(); if (capturedEntityItemList.size() == 0) { return; } this.causeTrackerEntityItemTimer.startTiming(); Iterator<Entity> iter = capturedEntityItemList.iterator(); ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>(); while (iter.hasNext()) { Entity currentEntity = iter.next(); if (this.invalidTransactions != null) { // check to see if this drop is invalid and if so, remove boolean invalid = false; for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) { if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) { invalid = true; iter.remove(); break; } } if (invalid) { continue; } } // determine if this was caused by a block break and if so, fire as single event IMixinEntity spongeEntity = (IMixinEntity) currentEntity; SpawnCause spawnCause = spongeEntity.getSpawnCause(); if (spawnCause != null) { ImmutableList.Builder<EntitySnapshot> entityItemSnapshotBuilder = new ImmutableList.Builder<>(); entityItemSnapshotBuilder.add(currentEntity.createSnapshot()); List<Entity> entityItemList = new ArrayList<>(); entityItemList.add(currentEntity); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(spawnCause)); User currentUser = StaticMixinHelper.packetPlayer != null ? (User) StaticMixinHelper.packetPlayer : this.currentNotifier; if (currentUser != null) { namedCauses.add(NamedCause.owner(currentUser)); } Cause cause = Cause.of(namedCauses); this.causeTrackerEntityItemTimer.stopTiming(); DropItemEvent.Destruct event = SpongeEventFactory.createDropItemEventDestruct(cause, entityItemList, entityItemSnapshotBuilder.build(), this.getWorld()); if (handlePostEntityEvent(cause, event)) { if (StaticMixinHelper.packetPlayer != null) { ((IMixinEntityPlayerMP) StaticMixinHelper.packetPlayer).restorePacketItem(); } } this.causeTrackerEntityItemTimer.startTiming(); iter.remove(); continue; } entitySnapshotBuilder.add(currentEntity.createSnapshot()); } if (capturedEntityItemList.isEmpty()) { this.causeTrackerEntityItemTimer.stopTiming(); return; } List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build(); if (entitySnapshots.isEmpty()) { this.causeTrackerEntityItemTimer.stopTiming(); return; } Cause cause = this.getCurrentCause(); if (cause != null && !cause.first(SpawnCause.class).isPresent()) { Cause spawnCause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityItemList.get(0)); cause = spawnCause.merge(cause); } else if (cause == null) { cause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityItemList.get(0)); } this.causeTrackerEntityItemTimer.stopTiming(); DropItemEvent.Dispense event = SpongeEventFactory.createDropItemEventDispense(cause, capturedEntityItemList, entitySnapshots, this.getWorld()); if (handlePostEntityEvent(cause, event)) { if (StaticMixinHelper.packetPlayer != null) { ((IMixinEntityPlayerMP) StaticMixinHelper.packetPlayer).restorePacketItem(); } capturedEntityItemList.clear(); } } private boolean handlePostEntityEvent(Cause cause, Event event) { if (!(SpongeImpl.postEvent(event))) { Iterator<Entity> iterator = ((SpawnEntityEvent) event).getEntities().iterator(); while (iterator.hasNext()) { Entity entity = iterator.next(); if (entity.isRemoved()) { // Entity removed in an event handler iterator.remove(); continue; } net.minecraft.entity.Entity nmsEntity = (net.minecraft.entity.Entity) entity; if (nmsEntity instanceof EntityWeatherEffect) { addWeatherEffect(nmsEntity, cause); } else { int x = MathHelper.floor_double(nmsEntity.posX / 16.0D); int z = MathHelper.floor_double(nmsEntity.posZ / 16.0D); this.getMinecraftWorld().getChunkFromChunkCoords(x, z).addEntity(nmsEntity); this.getMinecraftWorld().loadedEntityList.add(nmsEntity); this.getMixinWorld().onSpongeEntityAdded(nmsEntity); SpongeHooks.logEntitySpawn(cause, nmsEntity); } iterator.remove(); } return false; } return true; } private boolean addWeatherEffect(net.minecraft.entity.Entity entity, Cause cause) { if (entity instanceof EntityLightningBolt) { LightningEvent.Pre event = SpongeEventFactory.createLightningEventPre(((IMixinEntityLightningBolt) entity).getCause()); SpongeImpl.postEvent(event); if (!event.isCancelled()) { return getMinecraftWorld().addWeatherEffect(entity); } } else { return getMinecraftWorld().addWeatherEffect(entity); } return false; } // Special handling for single block breaks in order to allow plugins to modify entity captures per block break public void handleBlockBreak(int preEntitySize, int preEntityItemSize, BlockPos pos, IBlockState currentState, BlockSnapshot originalBlockSnapshot) { this.causeTrackerBlockBreakTimer.startTiming(); int postEntitySize = this.capturedSpawnedEntities.size(); int postEntityItemSize = this.capturedSpawnedEntityItems.size(); // handle captured entities if (preEntitySize != postEntitySize && postEntitySize > preEntitySize) { // add spawn causes for newly captured items for (int x = preEntitySize; x < postEntitySize; x++) { Entity entity = this.capturedSpawnedEntities.get(x); BlockSnapshot blockSnapshot = originalBlockSnapshot; if (blockSnapshot == null) { Location<org.spongepowered.api.world.World> location = new Location<>((org.spongepowered.api.world.World) this.getMinecraftWorld(), VecHelper.toVector(pos)); blockSnapshot = BlockSnapshot.builder().from(location).blockState((BlockState) currentState).build(); } BlockSpawnCause spawnCause = BlockSpawnCause.builder() .block(blockSnapshot) .type(SpawnTypes.DROPPED_ITEM) .build(); IMixinEntity spongeEntity = (IMixinEntity) entity; spongeEntity.setSpawnCause(spawnCause); spongeEntity.setSpawnedFromBlockBreak(true); } } // handle captured entity items if (preEntityItemSize != postEntityItemSize && postEntityItemSize > preEntityItemSize) { // add spawn causes for newly captured items for (int x = preEntityItemSize; x < postEntityItemSize; x++) { Entity entity = this.capturedSpawnedEntityItems.get(x); BlockSnapshot blockSnapshot = originalBlockSnapshot; if (blockSnapshot == null) { Location<org.spongepowered.api.world.World> location = new Location<>((org.spongepowered.api.world.World) this.getMinecraftWorld(), VecHelper.toVector(pos)); blockSnapshot = BlockSnapshot.builder().from(location).blockState((BlockState) currentState).build(); } BlockSpawnCause spawnCause = BlockSpawnCause.builder() .block(blockSnapshot) .type(entity instanceof EntityXPOrb ? SpawnTypes.EXPERIENCE : SpawnTypes.BLOCK_SPAWNING) .build(); IMixinEntity spongeEntity = (IMixinEntity) entity; spongeEntity.setSpawnCause(spawnCause); spongeEntity.setSpawnedFromBlockBreak(true); } } this.causeTrackerBlockBreakTimer.stopTiming(); } public boolean handleBlockCaptures() { List<BlockSnapshot> capturedBlockList = this.getCapturedSpongeBlockSnapshots(); if (capturedBlockList.size() == 0) { return false; } this.causeTrackerBlockTimer.startTiming(); Cause cause = this.getCurrentCause(); EntityPlayerMP player = StaticMixinHelper.packetPlayer; ImmutableList<Transaction<BlockSnapshot>> blockBreakTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockModifyTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockPlaceTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockDecayTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockMultiTransactions = null; ImmutableList.Builder<Transaction<BlockSnapshot>> breakBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> placeBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> decayBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> modifyBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> multiBuilder = new ImmutableList.Builder<>(); ChangeBlockEvent.Break breakEvent = null; ChangeBlockEvent.Modify modifyEvent = null; ChangeBlockEvent.Place placeEvent = null; List<ChangeBlockEvent> blockEvents = new ArrayList<>(); Iterator<BlockSnapshot> iterator = capturedBlockList.iterator(); while (iterator.hasNext()) { SpongeBlockSnapshot blockSnapshot = (SpongeBlockSnapshot) iterator.next(); CaptureType captureType = blockSnapshot.captureType; BlockPos pos = VecHelper.toBlockPos(blockSnapshot.getPosition()); IBlockState currentState = this.getMinecraftWorld().getBlockState(pos); Transaction<BlockSnapshot> transaction = new Transaction<>(blockSnapshot, this.getMixinWorld().createSpongeBlockSnapshot(currentState, currentState.getBlock() .getActualState(currentState, this.getMinecraftWorld(), pos), pos, 0)); if (captureType == CaptureType.BREAK) { breakBuilder.add(transaction); } else if (captureType == CaptureType.DECAY) { decayBuilder.add(transaction); } else if (captureType == CaptureType.PLACE) { placeBuilder.add(transaction); } else if (captureType == CaptureType.MODIFY) { modifyBuilder.add(transaction); } multiBuilder.add(transaction); iterator.remove(); } blockBreakTransactions = breakBuilder.build(); blockDecayTransactions = decayBuilder.build(); blockModifyTransactions = modifyBuilder.build(); blockPlaceTransactions = placeBuilder.build(); blockMultiTransactions = multiBuilder.build(); this.causeTrackerBlockTimer.stopTiming(); ChangeBlockEvent changeBlockEvent; if (blockBreakTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventBreak(cause, this.getWorld(), blockBreakTransactions); SpongeImpl.postEvent(changeBlockEvent); breakEvent = (ChangeBlockEvent.Break) changeBlockEvent; blockEvents.add(changeBlockEvent); } if (blockModifyTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventModify(cause, this.getWorld(), blockModifyTransactions); SpongeImpl.postEvent(changeBlockEvent); modifyEvent = (ChangeBlockEvent.Modify) changeBlockEvent; blockEvents.add(changeBlockEvent); } if (blockPlaceTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventPlace(cause, this.getWorld(), blockPlaceTransactions); SpongeImpl.postEvent(changeBlockEvent); placeEvent = (ChangeBlockEvent.Place) changeBlockEvent; blockEvents.add(changeBlockEvent); } this.causeTrackerBlockTimer.startTiming(); if (blockEvents.size() > 1) { if (breakEvent != null) { int count = cause.allOf(ChangeBlockEvent.Break.class).size(); String namedCause = "BreakEvent" + (count != 0 ? count : ""); cause = cause.with(NamedCause.of(namedCause, breakEvent)); } if (modifyEvent != null) { int count = cause.allOf(ChangeBlockEvent.Modify.class).size(); String namedCause = "ModifyEvent" + (count != 0 ? count : ""); cause = cause.with(NamedCause.of(namedCause, modifyEvent)); } if (placeEvent != null) { int count = cause.allOf(ChangeBlockEvent.Place.class).size(); String namedCause = "PlaceEvent" + (count != 0 ? count : ""); cause = cause.with(NamedCause.of(namedCause, placeEvent)); } this.causeTrackerBlockTimer.stopTiming(); changeBlockEvent = SpongeEventFactory.createChangeBlockEventPost(cause, this.getWorld(), blockMultiTransactions); SpongeImpl.postEvent(changeBlockEvent); this.causeTrackerBlockTimer.startTiming(); if (changeBlockEvent.isCancelled()) { // Restore original blocks ListIterator<Transaction<BlockSnapshot>> listIterator = changeBlockEvent.getTransactions().listIterator(changeBlockEvent.getTransactions().size()); processList(listIterator); if (player != null) { CaptureType captureType = null; if (this.currentPlayerPacket instanceof C08PacketPlayerBlockPlacement) { captureType = CaptureType.PLACE; } else if (this.currentPlayerPacket instanceof C07PacketPlayerDigging) { captureType = CaptureType.BREAK; } if (captureType != null) { handlePostPlayerBlockEvent(captureType, changeBlockEvent.getTransactions()); } } // clear entity list and return to avoid spawning items if (this.specificCapture) { this.capturedSpecificSpawnedEntities.clear(); this.capturedSpecificSpawnedEntityItems.clear(); } else { this.capturedSpawnedEntities.clear(); this.capturedSpawnedEntityItems.clear(); } return false; } } this.causeTrackerBlockTimer.stopTiming(); if (blockDecayTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventDecay(cause, this.getWorld(), blockDecayTransactions); SpongeImpl.postEvent(changeBlockEvent); blockEvents.add(changeBlockEvent); } this.causeTrackerBlockTimer.startTiming(); for (ChangeBlockEvent blockEvent : blockEvents) { CaptureType captureType = null; if (blockEvent instanceof ChangeBlockEvent.Break) { captureType = CaptureType.BREAK; } else if (blockEvent instanceof ChangeBlockEvent.Decay) { captureType = CaptureType.DECAY; } else if (blockEvent instanceof ChangeBlockEvent.Modify) { captureType = CaptureType.MODIFY; } else if (blockEvent instanceof ChangeBlockEvent.Place) { captureType = CaptureType.PLACE; } C08PacketPlayerBlockPlacement packet = null; if (this.currentPlayerPacket instanceof C08PacketPlayerBlockPlacement) { packet = (C08PacketPlayerBlockPlacement) this.currentPlayerPacket; } if (blockEvent.isCancelled()) { // Restore original blocks ListIterator<Transaction<BlockSnapshot>> listIterator = blockEvent.getTransactions().listIterator(blockEvent.getTransactions().size()); processList(listIterator); handlePostPlayerBlockEvent(captureType, blockEvent.getTransactions()); // clear entity list and return to avoid spawning items if (this.specificCapture) { this.capturedSpecificSpawnedEntities.clear(); this.capturedSpecificSpawnedEntityItems.clear(); } else { this.capturedSpawnedEntities.clear(); this.capturedSpawnedEntityItems.clear(); } return false; } else { for (Transaction<BlockSnapshot> transaction : blockEvent.getTransactions()) { if (!transaction.isValid()) { this.invalidTransactions.add(transaction); } else { if (captureType == CaptureType.BREAK && !(transaction.getOriginal().getState().getType() instanceof BlockLiquid) && cause.first(User.class).isPresent()) { BlockPos pos = VecHelper.toBlockPos(transaction.getOriginal().getPosition()); for (EntityHanging hanging : SpongeHooks.findHangingEntities(this.getMinecraftWorld(), pos)) { if (hanging != null) { if (hanging instanceof EntityItemFrame) { EntityItemFrame itemFrame = (EntityItemFrame) hanging; net.minecraft.entity.Entity dropCause = null; if (cause.root() instanceof net.minecraft.entity.Entity) { dropCause = (net.minecraft.entity.Entity) cause.root(); } itemFrame.dropItemOrSelf(dropCause, true); itemFrame.setDead(); } } } } if (captureType == CaptureType.PLACE && player != null && this.currentPlayerPacket instanceof C08PacketPlayerBlockPlacement) { BlockPos pos = VecHelper.toBlockPos(transaction.getFinal().getPosition()); IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(pos); spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos, (User) player, PlayerTracker.Type.OWNER); spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos, (User) player, PlayerTracker.Type.NOTIFIER); } } } if (this.invalidTransactions.size() > 0) { for (Transaction<BlockSnapshot> transaction : Lists.reverse(this.invalidTransactions)) { this.restoringBlocks = true; transaction.getOriginal().restore(true, false); this.restoringBlocks = false; } handlePostPlayerBlockEvent(captureType, this.invalidTransactions); } this.markAndNotifyBlockPost(blockEvent.getTransactions(), captureType); if (captureType == CaptureType.PLACE && player != null && packet != null && packet.getStack() != null) { player.addStat(StatList.objectUseStats[net.minecraft.item.Item.getIdFromItem(packet.getStack().getItem())], 1); } } } this.causeTrackerBlockTimer.stopTiming(); return true; } private void handlePostPlayerBlockEvent(CaptureType captureType, List<Transaction<BlockSnapshot>> transactions) { if (StaticMixinHelper.packetPlayer == null) { return; } if (captureType == CaptureType.BREAK) { // Let the client know the blocks still exist for (Transaction<BlockSnapshot> transaction : transactions) { BlockSnapshot snapshot = transaction.getOriginal(); BlockPos pos = VecHelper.toBlockPos(snapshot.getPosition()); StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(new S23PacketBlockChange(this.getMinecraftWorld(), pos)); // Update any tile entity data for this block net.minecraft.tileentity.TileEntity tileentity = this.getMinecraftWorld().getTileEntity(pos); if (tileentity != null) { Packet<?> pkt = tileentity.getDescriptionPacket(); if (pkt != null) { StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(pkt); } } } } if (StaticMixinHelper.packetPlayer != null) { ((IMixinEntityPlayerMP) StaticMixinHelper.packetPlayer).restorePacketItem(); } } public void handleNonLivingEntityDestruct(net.minecraft.entity.Entity entityIn) { if (entityIn.isDead && (!(entityIn instanceof EntityLivingBase) || entityIn instanceof EntityArmorStand)) { MessageChannel originalChannel = MessageChannel.TO_NONE; IMixinEntity spongeEntity = (IMixinEntity) entityIn; Cause cause = spongeEntity.getNonLivingDestructCause();; if (cause == null) { cause = Cause.of(NamedCause.source(entityIn.worldObj)); } if (cause.root() instanceof EntityDamageSource) { EntityDamageSource entityDamageSource = (EntityDamageSource) cause.root(); if (entityDamageSource.getSourceOfDamage() instanceof Player) { originalChannel = ((Player) entityDamageSource.getSourceOfDamage()).getMessageChannel(); } else if (entityDamageSource instanceof IndirectEntityDamageSource) { IndirectEntityDamageSource indirectDamageSource = (IndirectEntityDamageSource) entityDamageSource; if (indirectDamageSource.getIndirectSource() instanceof Player) { originalChannel = ((Player) indirectDamageSource.getIndirectSource()).getMessageChannel(); } } } else if (cause.root() instanceof Player) { originalChannel = ((Player) cause.root()).getMessageChannel(); } DestructEntityEvent event = SpongeEventFactory.createDestructEntityEvent( cause, originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(), (Entity) entityIn, true ); SpongeImpl.getGame().getEventManager().post(event); if (!event.isMessageCancelled()) { event.getChannel().ifPresent(channel -> channel.send(entityIn, event.getMessage())); } } } private void processList(ListIterator<Transaction<BlockSnapshot>> listIterator) { while (listIterator.hasPrevious()) { Transaction<BlockSnapshot> transaction = listIterator.previous(); this.restoringBlocks = true; transaction.getOriginal().restore(true, false); this.restoringBlocks = false; } } public boolean processSpawnEntity(Entity entity, Cause spawnCause) { checkNotNull(entity, "Entity cannot be null!"); checkNotNull(spawnCause, "Cause cannot be null!"); this.trackEntityOwner(entity); // Very first thing - fire events that are from entity construction if (((IMixinEntity) entity).isInConstructPhase()) { ((IMixinEntity) entity).firePostConstructEvents(); } net.minecraft.entity.Entity entityIn = (net.minecraft.entity.Entity) entity; // do not drop any items while restoring blocksnapshots. Prevents dupes if (!this.getMinecraftWorld().isRemote && (entityIn == null || (entityIn instanceof net.minecraft.entity.item.EntityItem && this.restoringBlocks))) { return false; } int i = MathHelper.floor_double(entityIn.posX / 16.0D); int j = MathHelper.floor_double(entityIn.posZ / 16.0D); boolean flag = entityIn.forceSpawn; // This is usually null during world gen Cause cause = this.getCurrentCause(); if (cause != null && !cause.first(SpawnCause.class).isPresent()) { cause = spawnCause.merge(cause); } else if (cause == null) { cause = spawnCause; } if (entityIn instanceof EntityPlayer) { flag = true; } else if (entityIn instanceof EntityLightningBolt) { ((IMixinEntityLightningBolt) entityIn).setCause(cause); } if (!flag && !this.getMinecraftWorld().isChunkLoaded(i, j, true)) { return false; } else { if (flag) { if (entityIn instanceof EntityPlayer) { EntityPlayer entityplayer = (EntityPlayer) entityIn; net.minecraft.world.World world = this.targetWorld; world.playerEntities.add(entityplayer); world.updateAllPlayersSleepingFlag(); } if (SpongeImpl.postEvent(SpongeEventFactory.createSpawnEntityEvent(cause, Lists.newArrayList(entity), Lists.newArrayList(entity.createSnapshot()), getWorld())) && !flag) { return false; } this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn); this.getMinecraftWorld().loadedEntityList.add(entityIn); this.getMixinWorld().onSpongeEntityAdded(entityIn); return true; } if (entityIn instanceof EntityFishHook && ((EntityFishHook) entityIn).angler == null) { // TODO MixinEntityFishHook.setShooter makes angler null // sometimes, but that will cause NPE when ticking return false; } org.spongepowered.api.event.Event event = null; List<Entity> entitiesToSpawn = Lists.newArrayList(entity); ImmutableList<EntitySnapshot> entitySnapshots = ImmutableList.of(entity.createSnapshot()); EntityLivingBase entityLiving = null; net.minecraft.entity.Entity nonLivingEntity = null; if (this.currentTickEntity instanceof EntityLivingBase) { entityLiving = (EntityLivingBase) this.currentTickEntity; } else if (this.currentTickEntity != null) { nonLivingEntity = (net.minecraft.entity.Entity) this.currentTickEntity; } if (entityIn instanceof EntityItem) { if ((nonLivingEntity != null && nonLivingEntity.isDead) || entityIn instanceof EntityXPOrb || (entityLiving != null && (entityLiving.getHealth() <= 0 || entityLiving.isDead))) { event = SpongeEventFactory.createDropItemEventDestruct(cause, entitiesToSpawn, entitySnapshots, this.getWorld()); } else { event = SpongeEventFactory.createDropItemEventDispense(cause, entitiesToSpawn, entitySnapshots, this.getWorld()); } } else { event = SpongeEventFactory.createSpawnEntityEvent(cause, entitiesToSpawn, entitySnapshots, this.getWorld()); } if (!SpongeImpl.postEvent(event)) { if (entityIn instanceof EntityWeatherEffect) { return addWeatherEffect(entityIn, cause); } this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn); this.getMinecraftWorld().loadedEntityList.add(entityIn); this.getMixinWorld().onSpongeEntityAdded(entityIn); return true; } return false; } } public void randomTickBlock(Block block, BlockPos pos, IBlockState state, Random random) { boolean captureBlocks = this.isCapturingBlocks(); this.captureBlocks = true; this.preTrackBlock(state, pos); block.randomTick(this.getMinecraftWorld(), pos, state, random); this.postTrackBlock(); this.captureBlocks = captureBlocks; } // By this point, currentPending(NextTickListEntry) should always be available public void updateTickBlock(Block block, BlockPos pos, IBlockState state, Random rand) { this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickBlock)); if (this.currentPendingBlockUpdate.hasTickingBlock()) { namedCauses.add(NamedCause.of("SchedulerSource", this.currentPendingBlockUpdate.getCurrentTickBlock().get())); if (this.currentPendingBlockUpdate.hasTickingTileEntity()) { namedCauses.add(NamedCause.of("SchedulerParentSource", this.currentPendingBlockUpdate.getCurrentTickTileEntity().get())); } } else if (this.currentPendingBlockUpdate.hasTickingTileEntity()) { namedCauses.add(NamedCause.of("SchedulerSource", this.currentPendingBlockUpdate.getCurrentTickTileEntity().get())); } if (!this.currentPendingBlockUpdate.hasSourceUser()) { this.trackBlockPositionCausePreTick(pos); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } } else { this.currentNotifier = this.currentPendingBlockUpdate.getSourceUser().get(); namedCauses.add(NamedCause.notifier(this.currentNotifier)); } this.addCause(Cause.of(namedCauses)); boolean captureBlocks = this.isCapturingBlocks(); this.captureBlocks = true; block.updateTick(this.getMinecraftWorld(), pos, state, rand); this.postTrackBlock(); this.captureBlocks = captureBlocks; this.currentPendingBlockUpdate = null; this.currentTickTileEntity = null; } public void notifyBlockOfStateChange(BlockPos notifyPos, final Block sourceBlock, BlockPos sourcePos) { if (!this.getMinecraftWorld().isRemote) { IBlockState iblockstate = this.getMinecraftWorld().getBlockState(notifyPos); if (iblockstate == Blocks.air.getDefaultState() || !this.isCapturingBlocks()) { iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock); return; } try { if (!this.tryAndTrackActiveUser(notifyPos, PlayerTracker.Type.NOTIFIER).isPresent()) { if (this.hasTickingBlock()) { this.trackTargetBlockFromSource(((SpongeBlockSnapshot) this.currentTickBlock).getBlockPos(), sourcePos, iblockstate.getBlock(), notifyPos, PlayerTracker.Type.NOTIFIER); } } iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock); } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while updating neighbours"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated"); // TODO /*crashreportcategory.addCrashSectionCallable("Source block type", new Callable() { public String call() { try { return String.format("ID #%d (%s // %s)", new Object[] {Integer.valueOf(Block.getIdFromBlock(blockIn)), blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName()}); } catch (Throwable throwable1) { return "ID #" + Block.getIdFromBlock(blockIn); } } });*/ CrashReportCategory.addBlockInfo(crashreportcategory, notifyPos, iblockstate); throw new ReportedException(crashreport); } } } public void markAndNotifyBlockPost(List<Transaction<BlockSnapshot>> transactions, CaptureType type) { // We have to use a proxy so that our pending changes are notified such that any accessors from block // classes do not fail on getting the incorrect block state from the IBlockAccess SpongeProxyBlockAccess proxyBlockAccess = new SpongeProxyBlockAccess(this.getMinecraftWorld(), transactions); for (Transaction<BlockSnapshot> transaction : transactions) { if (!transaction.isValid()) { continue; // Don't use invalidated block transactions during notifications, these only need to be restored } // Handle custom replacements if (transaction.getCustom().isPresent()) { transaction.getFinal().restore(true, false); } Cause cause = this.getCurrentCause(); SpongeBlockSnapshot oldBlockSnapshot = (SpongeBlockSnapshot) transaction.getOriginal(); SpongeBlockSnapshot newBlockSnapshot = (SpongeBlockSnapshot) transaction.getFinal(); SpongeHooks.logBlockAction(cause, this.getMinecraftWorld(), type, transaction); int updateFlag = oldBlockSnapshot.getUpdateFlag(); BlockPos pos = VecHelper.toBlockPos(oldBlockSnapshot.getPosition()); IBlockState originalState = (IBlockState) oldBlockSnapshot.getState(); IBlockState newState = (IBlockState) newBlockSnapshot.getState(); BlockSnapshot currentTickingBlock = this.getCurrentTickBlock().orElse(null); // Containers get placed automatically if (originalState.getBlock() != newState.getBlock() && !SpongeImplHooks.blockHasTileEntity(newState.getBlock(), newState)) { this.setCurrentTickBlock(this.getMixinWorld().createSpongeBlockSnapshot(newState, newState.getBlock().getActualState(newState, proxyBlockAccess, pos), pos, updateFlag)); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickBlock)); namedCauses.add(NamedCause.of("ParentSource", cause.root())); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } else if (StaticMixinHelper.packetPlayer != null) { namedCauses.add(NamedCause.owner(StaticMixinHelper.packetPlayer)); } this.addCause(Cause.of(namedCauses)); this.causeTrackerBlockTimer.stopTiming(); boolean captureBlocks = this.captureBlocks; this.captureBlocks = true; newState.getBlock().onBlockAdded(this.getMinecraftWorld(), pos, newState); // Handle any additional captures during onBlockAdded // This is to ensure new captures do not leak into next tick with wrong cause if (this.getCapturedSpongeBlockSnapshots().size() > 0) { this.handlePostTickCaptures(); } this.captureBlocks = captureBlocks; this.causeTrackerBlockTimer.startTiming(); this.removeCurrentCause(); } proxyBlockAccess.proceed(); this.causeTrackerBlockTimer.stopTiming(); boolean captureBlocks = this.captureBlocks; this.captureBlocks = true; this.getMixinWorld().markAndNotifyNeighbors(pos, null, originalState, newState, updateFlag); // Handle any additional captures during notify // This is to ensure new captures do not leak into next tick with wrong cause if (this.getCapturedSpongeBlockSnapshots().size() > 0) { this.handlePostTickCaptures(); } this.captureBlocks = captureBlocks; this.setCurrentTickBlock(currentTickingBlock); } } /*private boolean shouldChainCause(Cause cause) { return !this.isCapturingTerrainGen() && !this.isWorldSpawnerRunning() && !this.isChunkSpawnerRunning() && !this.isProcessingBlockRandomTicks() && !this.isCaptureCommand() && this.hasTickingBlock() && this.pluginCause == null && !cause.contains(this.getCurrentTickBlock().get()) && !(StaticMixinHelper.processingPacket instanceof C03PacketPlayer); }*/ private Predicate<net.minecraft.entity.Entity> entityTrackerPredicate = new Predicate<net.minecraft.entity.Entity>() { @Override public boolean apply(net.minecraft.entity.Entity input) { if (input instanceof EntityLivingBase) { return false; } if (input instanceof EntityItem) { return false; } return true; } }; private static AxisAlignedBB entityAABB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); private AxisAlignedBB getEntityAABBForBlockPos(BlockPos pos) { entityAABB.minX = pos.getX(); entityAABB.minY = pos.getY(); entityAABB.minZ = pos.getZ(); entityAABB.maxX = pos.getX() + 0.1; entityAABB.maxY = pos.getY() + 0.1; entityAABB.maxZ = pos.getZ() + 0.1; return entityAABB; } public Optional<User> tryAndTrackActiveUser(BlockPos targetPos, PlayerTracker.Type type) { net.minecraft.world.World world = this.getMinecraftWorld(); if (targetPos == null || !world.isBlockLoaded(targetPos)) { return Optional.empty(); } User user = null; IMixinChunk spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(targetPos); if (spongeChunk != null && !(spongeChunk instanceof EmptyChunk)) { if (StaticMixinHelper.packetPlayer != null) { user = (User) StaticMixinHelper.packetPlayer; spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, user, type); } else if (this.currentNotifier != null) { user = this.currentNotifier; spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, user, type); } // check if a non-living entity exists at target block position (ex. minecarts) if (user != null) { Chunk chunk = (Chunk) spongeChunk; List<net.minecraft.entity.Entity> entityList = new ArrayList<>(); chunk.getEntitiesOfTypeWithinAAAB(net.minecraft.entity.Entity.class, this.getEntityAABBForBlockPos(targetPos), entityList, this.entityTrackerPredicate); for (net.minecraft.entity.Entity entity : entityList) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_NOTIFIER, user.getUniqueId()); } } } return Optional.ofNullable(user); } public Optional<User> trackTargetBlockFromSource(Object source, BlockPos sourcePos, Block targetBlock, BlockPos targetPos, PlayerTracker.Type type) { // first check to see if we have an active user Optional<User> user = tryAndTrackActiveUser(targetPos, type); if (user.isPresent()) { return user; } net.minecraft.world.World world = this.getMinecraftWorld(); if (sourcePos == null || !world.isBlockLoaded(sourcePos)) { return Optional.empty(); } IMixinChunk spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(sourcePos); if (spongeChunk != null && !(spongeChunk instanceof EmptyChunk)) { Optional<User> owner = spongeChunk.getBlockOwner(sourcePos); Optional<User> notifier = spongeChunk.getBlockNotifier(sourcePos); if (notifier.isPresent()) { spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(targetPos); spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, notifier.get(), type); return notifier; } else if (owner.isPresent()) { spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, owner.get(), type); return owner; } } return Optional.empty(); } public Optional<User> trackBlockPositionCausePreTick(BlockPos pos) { net.minecraft.world.World world = this.getMinecraftWorld(); if (pos == null || !world.isBlockLoaded(pos)) { return Optional.empty(); } IMixinChunk spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(pos); if (spongeChunk != null && !(spongeChunk instanceof EmptyChunk)) { Optional<User> owner = spongeChunk.getBlockOwner(pos); Optional<User> notifier = spongeChunk.getBlockNotifier(pos); if (notifier.isPresent()) { User user = notifier.get(); this.currentNotifier = user; return notifier; } else if (owner.isPresent()) { User user = owner.get(); this.currentNotifier = user; return owner; } if (notifier.isPresent()) { return notifier; } else { return owner; } } return Optional.empty(); } public void trackEntityCausePreTick(net.minecraft.entity.Entity entity) { if (entity == null || this.causeStack.isEmpty()) { return; } Cause cause = this.getCurrentCause(); IMixinEntity spongeEntity = (IMixinEntity) entity; Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR); if (!owner.isPresent()) { if (entity instanceof EntityTameable) { EntityTameable tameable = (EntityTameable) entity; if (tameable.getOwner() != null) { owner = Optional.of((User) tameable.getOwner()); } } } Optional<User> notifier = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_NOTIFIER); if (notifier.isPresent()) { User user = notifier.get(); this.currentNotifier = user; this.causeStack.pop(); this.addCause(cause.merge(Cause.of(NamedCause.notifier(user)))); } else if (owner.isPresent()) { User user = owner.get(); this.currentNotifier = user; this.causeStack.pop(); this.addCause(cause.merge(Cause.of(NamedCause.owner(user)))); } } // Handle entity ownership tracking public void trackEntityOwner(Entity entity) { User currentUser = StaticMixinHelper.packetPlayer != null ? (User) StaticMixinHelper.packetPlayer : this.currentNotifier; if (currentUser != null) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, currentUser.getUniqueId()); } else if (this.currentTickEntity != null) { IMixinEntity spongeEntity = (IMixinEntity) this.currentTickEntity; Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR); if (owner.isPresent()) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, owner.get().getUniqueId()); } else { Optional<User> notifier = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_NOTIFIER); if (notifier.isPresent()) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, notifier.get().getUniqueId()); } } } else if (entity instanceof EntityTameable) { EntityTameable tameable = (EntityTameable) entity; if (tameable.getOwner() != null) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, tameable.getOwner().getUniqueID()); } } } }
src/main/java/org/spongepowered/common/event/CauseTracker.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.event; import static com.google.common.base.Preconditions.checkNotNull; import co.aikar.timings.Timing; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.EntityHanging; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.effect.EntityWeatherEffect; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityItemFrame; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.init.Blocks; import net.minecraft.network.Packet; import net.minecraft.network.play.client.C01PacketChatMessage; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.network.play.client.C0EPacketClickWindow; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.stats.StatList; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EntityDamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.EmptyChunk; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntitySnapshot; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.action.LightningEvent; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.NamedCause; import org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource; import org.spongepowered.api.event.cause.entity.spawn.BlockSpawnCause; import org.spongepowered.api.event.cause.entity.spawn.SpawnCause; import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes; import org.spongepowered.api.event.entity.DestructEntityEvent; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.event.message.MessageEvent; import org.spongepowered.api.text.channel.MessageChannel; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.SpongeImplHooks; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.data.util.NbtDataUtil; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.interfaces.IMixinChunk; import org.spongepowered.common.interfaces.IMixinNextTickListEntry; import org.spongepowered.common.interfaces.entity.IMixinEntity; import org.spongepowered.common.interfaces.entity.IMixinEntityLightningBolt; import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP; import org.spongepowered.common.interfaces.world.IMixinWorld; import org.spongepowered.common.util.SpongeHooks; import org.spongepowered.common.util.StaticMixinHelper; import org.spongepowered.common.util.VecHelper; import org.spongepowered.common.world.CaptureType; import org.spongepowered.common.world.SpongeProxyBlockAccess; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Optional; import java.util.Random; import javax.annotation.Nullable; public final class CauseTracker { private final net.minecraft.world.World targetWorld; private boolean captureSpawnedEntities = false; private boolean captureBlockDecay = false; private boolean captureTerrainGen = false; private boolean captureBlocks = false; private boolean captureCommand = false; private boolean restoringBlocks = false; private boolean ignoreSpawnEvents = false; private boolean specificCapture = false; private List<Entity> capturedSpawnedEntities = new ArrayList<>(); private List<Entity> capturedSpawnedEntityItems = new ArrayList<>(); private List<BlockSnapshot> capturedSpongeBlockSnapshots = new ArrayList<>(); // used internally to handle specific captures and not conflict with rest private List<Entity> capturedSpecificSpawnedEntities = new ArrayList<>(); private List<Entity> capturedSpecificSpawnedEntityItems = new ArrayList<>(); private List<BlockSnapshot> capturedSpecificSpongeBlockSnapshots = new ArrayList<>(); private List<Transaction<BlockSnapshot>> invalidTransactions = new ArrayList<>(); @Nullable private User currentNotifier; @Nullable private BlockSnapshot currentTickBlock; @Nullable private Entity currentTickEntity; @Nullable private TileEntity currentTickTileEntity; @Nullable public IMixinNextTickListEntry currentPendingBlockUpdate; @Nullable private Cause pluginCause; private boolean worldSpawnerRunning; private boolean chunkSpawnerRunning; private Deque<Cause> causeStack = new ArrayDeque<>(); private Packet<?> currentPlayerPacket; public final Timing causeTrackerBlockTimer; public final Timing causeTrackerBlockBreakTimer; public final Timing causeTrackerEntityTimer; public final Timing causeTrackerEntityItemTimer; public CauseTracker(net.minecraft.world.World targetWorld) { this.targetWorld = targetWorld; this.causeTrackerBlockTimer = this.getMixinWorld().getTimingsHandler().causeTrackerBlockTimer; this.causeTrackerBlockBreakTimer = this.getMixinWorld().getTimingsHandler().causeTrackerBlockBreakTimer; this.causeTrackerEntityTimer = this.getMixinWorld().getTimingsHandler().causeTrackerEntityTimer; this.causeTrackerEntityItemTimer = this.getMixinWorld().getTimingsHandler().causeTrackerEntityItemTimer; } public World getWorld() { return (World) this.targetWorld; } public net.minecraft.world.World getMinecraftWorld() { return this.targetWorld; } public IMixinWorld getMixinWorld() { return (IMixinWorld) this.targetWorld; } public boolean isIgnoringSpawnEvents() { return this.ignoreSpawnEvents; } public void setIgnoreSpawnEvents(boolean ignoreSpawnEvents) { this.ignoreSpawnEvents = ignoreSpawnEvents; } public boolean isCapturingSpawnedEntities() { return this.captureSpawnedEntities; } public void setCaptureSpawnedEntities(boolean captureSpawnedEntities) { this.captureSpawnedEntities = captureSpawnedEntities; } public List<Entity> getCapturedSpawnedEntities() { if (this.specificCapture) { return this.capturedSpecificSpawnedEntities; } return this.capturedSpawnedEntities; } public List<Entity> getCapturedSpawnedEntityItems() { if (this.specificCapture) { return this.capturedSpecificSpawnedEntityItems; } return this.capturedSpawnedEntityItems; } public boolean isCaptureBlockDecay() { return this.captureBlockDecay; } public void setCapturingBlockDecay(boolean captureBlockDecay) { this.captureBlockDecay = captureBlockDecay; } public boolean isCapturingTerrainGen() { return this.captureTerrainGen; } public void setCapturingTerrainGen(boolean captureTerrainGen) { this.captureTerrainGen = captureTerrainGen; } public boolean isCapturingBlocks() { return this.captureBlocks; } public void setCaptureBlocks(boolean captureBlocks) { this.captureBlocks = captureBlocks; } public boolean isCaptureCommand() { return this.captureCommand; } public void setCapturingCommand(boolean captureCommand) { this.captureCommand = captureCommand; } public boolean isRestoringBlocks() { return this.restoringBlocks; } public void setRestoringBlocks(boolean restoringBlocks) { this.restoringBlocks = restoringBlocks; } public boolean hasNotifier() { return this.currentNotifier != null; } public Optional<User> getCurrentNotifier() { return Optional.ofNullable(this.currentNotifier); } public void setCurrentNotifier(@Nullable User currentNotifier) { this.currentNotifier = currentNotifier; } public boolean hasTickingBlock() { return this.currentTickBlock != null; } public Optional<BlockSnapshot> getCurrentTickBlock() { return Optional.ofNullable(this.currentTickBlock); } public void setCurrentTickBlock(@Nullable BlockSnapshot currentTickBlock) { this.currentTickBlock = currentTickBlock; } public boolean hasTickingEntity() { return this.currentTickEntity != null; } public Optional<Entity> getCurrentTickEntity() { return Optional.ofNullable(this.currentTickEntity); } public void setCurrentTickEntity(@Nullable Entity currentTickEntity) { this.currentTickEntity = currentTickEntity; } public boolean hasTickingTileEntity() { return this.currentTickTileEntity != null; } public Optional<TileEntity> getCurrentTickTileEntity() { return Optional.ofNullable(this.currentTickTileEntity); } public void setCurrentTickTileEntity(TileEntity currentTickTileEntity) { this.currentTickTileEntity = currentTickTileEntity; } public List<BlockSnapshot> getCapturedSpongeBlockSnapshots() { if (this.specificCapture) { return this.capturedSpecificSpongeBlockSnapshots; } return this.capturedSpongeBlockSnapshots; } public List<Transaction<BlockSnapshot>> getInvalidTransactions() { return this.invalidTransactions; } public void setInvalidTransactions(List<Transaction<BlockSnapshot>> invalidTransactions) { this.invalidTransactions = invalidTransactions; } public boolean isWorldSpawnerRunning() { return this.worldSpawnerRunning; } public void setWorldSpawnerRunning(boolean worldSpawnerRunning) { this.worldSpawnerRunning = worldSpawnerRunning; } public boolean isChunkSpawnerRunning() { return this.chunkSpawnerRunning; } public void setChunkSpawnerRunning(boolean chunkSpawnerRunning) { this.chunkSpawnerRunning = chunkSpawnerRunning; } public Optional<Cause> getPluginCause() { return Optional.ofNullable(this.pluginCause); } public void setPluginCause(@Nullable Cause pluginCause) { this.pluginCause = pluginCause; } public boolean hasPluginCause() { return this.pluginCause != null; } public Cause getCurrentCause() { return this.causeStack.peekFirst(); } public void addCause(Cause cause) { this.causeStack.addFirst(cause); } public void removeCurrentCause() { this.causeStack.removeFirst(); } public Packet<?> getCurrentPlayerPacket() { return this.currentPlayerPacket; } public void setCurrentPlayerPacket(@Nullable Packet<?> currentPlayerPacket) { this.currentPlayerPacket = currentPlayerPacket; } public void preTrackEntity(Entity entity) { this.currentTickEntity = entity; this.addCause(Cause.of(NamedCause.source(entity))); this.trackEntityCausePreTick((net.minecraft.entity.Entity) entity); } public void postTrackEntity() { this.handlePostTickCaptures(); this.removeCurrentCause(); this.currentTickEntity = null; this.currentNotifier = null; } public void preTrackTileEntity(TileEntity tile) { this.currentTickTileEntity = tile; this.trackBlockPositionCausePreTick(((net.minecraft.tileentity.TileEntity) tile).getPos()); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickTileEntity)); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } this.addCause(Cause.of(namedCauses)); } public void postTrackTileEntity() { this.handlePostTickCaptures(); this.removeCurrentCause(); this.currentTickTileEntity = null; this.currentNotifier = null; } public void preTrackBlock(IBlockState state, BlockPos pos) { this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0); this.trackBlockPositionCausePreTick(pos); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickBlock)); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } this.addCause(Cause.of(namedCauses)); } public void postTrackBlock() { this.handlePostTickCaptures(); this.removeCurrentCause(); this.currentTickBlock = null; this.currentNotifier = null; } public void setSpecificCapture(boolean flag) { this.specificCapture = flag; } public void handlePostTickCaptures() { if (this.getMinecraftWorld().isRemote || this.restoringBlocks || this.causeStack.isEmpty()) { return; } else if (this.getCapturedSpawnedEntities().isEmpty() && this.getCapturedSpawnedEntityItems().isEmpty() && this.getCapturedSpongeBlockSnapshots().isEmpty() && StaticMixinHelper.packetPlayer == null) { return; // nothing was captured, return } EntityPlayerMP player = StaticMixinHelper.packetPlayer; Cause cause = this.getCurrentCause(); // Handle Block Captures handleBlockCaptures(); // Handle Player kill commands if (player != null && this.currentPlayerPacket instanceof C01PacketChatMessage) { C01PacketChatMessage chatPacket = (C01PacketChatMessage) this.currentPlayerPacket; if (chatPacket.getMessage().contains("kill")) { if (!cause.contains(player)) { cause = cause.with(NamedCause.of("Player", player)); } } } // Inventory Events if (this.currentPlayerPacket instanceof C0EPacketClickWindow){ SpongeCommonEventFactory.handleClickInteractInventoryEvent(Cause.of(NamedCause.source(player)), player, (C0EPacketClickWindow) this.currentPlayerPacket); } // Handle Entity captures if (!this.getCapturedSpawnedEntityItems().isEmpty()) { handleDroppedItems(); } if (!this.getCapturedSpawnedEntities().isEmpty()) { handleSpawnedEntities(); } this.invalidTransactions.clear(); } public void handleSpawnedEntities() { List<Entity> capturedEntityList = this.getCapturedSpawnedEntities(); if (capturedEntityList.size() == 0) { return; } this.causeTrackerEntityTimer.startTiming(); Iterator<Entity> iter = capturedEntityList.iterator(); ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>(); while (iter.hasNext()) { Entity currentEntity = iter.next(); if (this.invalidTransactions != null) { // check to see if this spawn is invalid and if so, remove boolean invalid = false; for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) { if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) { invalid = true; iter.remove(); break; } } if (invalid) { continue; } } // determine if this was caused by a block break and if so, fire as single event IMixinEntity spongeEntity = (IMixinEntity) currentEntity; SpawnCause spawnCause = spongeEntity.getSpawnCause(); if (spawnCause != null) { ImmutableList.Builder<EntitySnapshot> entitySingleSnapshotBuilder = new ImmutableList.Builder<>(); entitySingleSnapshotBuilder.add(currentEntity.createSnapshot()); List<Entity> entityList = new ArrayList<>(); entityList.add(currentEntity); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(spawnCause)); User currentUser = StaticMixinHelper.packetPlayer != null ? (User) StaticMixinHelper.packetPlayer : this.currentNotifier; if (currentUser != null) { namedCauses.add(NamedCause.owner(currentUser)); } Cause cause = Cause.of(namedCauses); causeTrackerEntityTimer.stopTiming(); SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(cause, entityList, entitySingleSnapshotBuilder.build(), this.getWorld()); handlePostEntityEvent(cause, event); causeTrackerEntityTimer.startTiming(); iter.remove(); continue; } entitySnapshotBuilder.add(currentEntity.createSnapshot()); } if (capturedEntityList.isEmpty()) { this.causeTrackerEntityTimer.stopTiming(); return; } Cause cause = this.getCurrentCause(); if (cause != null && !cause.first(SpawnCause.class).isPresent()) { Cause spawnCause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityList.get(0)); cause = spawnCause.merge(cause); } else if (cause == null) { cause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityList.get(0)); } List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build(); if (entitySnapshots.isEmpty()) { this.causeTrackerEntityTimer.stopTiming(); return; } this.causeTrackerEntityTimer.stopTiming(); SpawnEntityEvent event = null; if (this.worldSpawnerRunning) { event = SpongeEventFactory.createSpawnEntityEventSpawner(cause, capturedEntityList, entitySnapshots, this.getWorld()); } else if (this.chunkSpawnerRunning){ event = SpongeEventFactory.createSpawnEntityEventChunkLoad(cause, capturedEntityList, entitySnapshots, this.getWorld()); } else { event = SpongeEventFactory.createSpawnEntityEventCustom(cause, capturedEntityList, entitySnapshots, this.getWorld()); } if (handlePostEntityEvent(cause, event)) { capturedEntityList.clear(); } } public void handleDroppedItems() { List<Entity> capturedEntityItemList = this.getCapturedSpawnedEntityItems(); if (capturedEntityItemList.size() == 0) { return; } this.causeTrackerEntityItemTimer.startTiming(); Iterator<Entity> iter = capturedEntityItemList.iterator(); ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>(); while (iter.hasNext()) { Entity currentEntity = iter.next(); if (this.invalidTransactions != null) { // check to see if this drop is invalid and if so, remove boolean invalid = false; for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) { if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) { invalid = true; iter.remove(); break; } } if (invalid) { continue; } } // determine if this was caused by a block break and if so, fire as single event IMixinEntity spongeEntity = (IMixinEntity) currentEntity; SpawnCause spawnCause = spongeEntity.getSpawnCause(); if (spawnCause != null) { ImmutableList.Builder<EntitySnapshot> entityItemSnapshotBuilder = new ImmutableList.Builder<>(); entityItemSnapshotBuilder.add(currentEntity.createSnapshot()); List<Entity> entityItemList = new ArrayList<>(); entityItemList.add(currentEntity); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(spawnCause)); User currentUser = StaticMixinHelper.packetPlayer != null ? (User) StaticMixinHelper.packetPlayer : this.currentNotifier; if (currentUser != null) { namedCauses.add(NamedCause.owner(currentUser)); } Cause cause = Cause.of(namedCauses); this.causeTrackerEntityItemTimer.stopTiming(); DropItemEvent.Destruct event = SpongeEventFactory.createDropItemEventDestruct(cause, entityItemList, entityItemSnapshotBuilder.build(), this.getWorld()); if (handlePostEntityEvent(cause, event)) { if (StaticMixinHelper.packetPlayer != null) { ((IMixinEntityPlayerMP) StaticMixinHelper.packetPlayer).restorePacketItem(); } } this.causeTrackerEntityItemTimer.startTiming(); iter.remove(); continue; } entitySnapshotBuilder.add(currentEntity.createSnapshot()); } if (capturedEntityItemList.isEmpty()) { this.causeTrackerEntityItemTimer.stopTiming(); return; } List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build(); if (entitySnapshots.isEmpty()) { this.causeTrackerEntityItemTimer.stopTiming(); return; } Cause cause = this.getCurrentCause(); if (cause != null && !cause.first(SpawnCause.class).isPresent()) { Cause spawnCause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityItemList.get(0)); cause = spawnCause.merge(cause); } else if (cause == null) { cause = SpongeCommonEventFactory.getEntitySpawnCause((net.minecraft.entity.Entity) capturedEntityItemList.get(0)); } this.causeTrackerEntityItemTimer.stopTiming(); DropItemEvent.Dispense event = SpongeEventFactory.createDropItemEventDispense(cause, capturedEntityItemList, entitySnapshots, this.getWorld()); if (handlePostEntityEvent(cause, event)) { if (StaticMixinHelper.packetPlayer != null) { ((IMixinEntityPlayerMP) StaticMixinHelper.packetPlayer).restorePacketItem(); } capturedEntityItemList.clear(); } } private boolean handlePostEntityEvent(Cause cause, Event event) { if (!(SpongeImpl.postEvent(event))) { Iterator<Entity> iterator = ((SpawnEntityEvent) event).getEntities().iterator(); while (iterator.hasNext()) { Entity entity = iterator.next(); if (entity.isRemoved()) { // Entity removed in an event handler iterator.remove(); continue; } net.minecraft.entity.Entity nmsEntity = (net.minecraft.entity.Entity) entity; if (nmsEntity instanceof EntityWeatherEffect) { addWeatherEffect(nmsEntity, cause); } else { int x = MathHelper.floor_double(nmsEntity.posX / 16.0D); int z = MathHelper.floor_double(nmsEntity.posZ / 16.0D); this.getMinecraftWorld().getChunkFromChunkCoords(x, z).addEntity(nmsEntity); this.getMinecraftWorld().loadedEntityList.add(nmsEntity); this.getMixinWorld().onSpongeEntityAdded(nmsEntity); SpongeHooks.logEntitySpawn(cause, nmsEntity); } iterator.remove(); } return false; } return true; } private boolean addWeatherEffect(net.minecraft.entity.Entity entity, Cause cause) { if (entity instanceof EntityLightningBolt) { LightningEvent.Pre event = SpongeEventFactory.createLightningEventPre(((IMixinEntityLightningBolt) entity).getCause()); SpongeImpl.postEvent(event); if (!event.isCancelled()) { return getMinecraftWorld().addWeatherEffect(entity); } } else { return getMinecraftWorld().addWeatherEffect(entity); } return false; } // Special handling for single block breaks in order to allow plugins to modify entity captures per block break public void handleBlockBreak(int preEntitySize, int preEntityItemSize, BlockPos pos, IBlockState currentState, BlockSnapshot originalBlockSnapshot) { this.causeTrackerBlockBreakTimer.startTiming(); int postEntitySize = this.capturedSpawnedEntities.size(); int postEntityItemSize = this.capturedSpawnedEntityItems.size(); // handle captured entities if (preEntitySize != postEntitySize && postEntitySize > preEntitySize) { // add spawn causes for newly captured items for (int x = preEntitySize; x < postEntitySize; x++) { Entity entity = this.capturedSpawnedEntities.get(x); BlockSnapshot blockSnapshot = originalBlockSnapshot; if (blockSnapshot == null) { Location<org.spongepowered.api.world.World> location = new Location<>((org.spongepowered.api.world.World) this.getMinecraftWorld(), VecHelper.toVector(pos)); blockSnapshot = BlockSnapshot.builder().from(location).blockState((BlockState) currentState).build(); } BlockSpawnCause spawnCause = BlockSpawnCause.builder() .block(blockSnapshot) .type(SpawnTypes.DROPPED_ITEM) .build(); IMixinEntity spongeEntity = (IMixinEntity) entity; spongeEntity.setSpawnCause(spawnCause); spongeEntity.setSpawnedFromBlockBreak(true); } } // handle captured entity items if (preEntityItemSize != postEntityItemSize && postEntityItemSize > preEntityItemSize) { // add spawn causes for newly captured items for (int x = preEntityItemSize; x < postEntityItemSize; x++) { Entity entity = this.capturedSpawnedEntityItems.get(x); BlockSnapshot blockSnapshot = originalBlockSnapshot; if (blockSnapshot == null) { Location<org.spongepowered.api.world.World> location = new Location<>((org.spongepowered.api.world.World) this.getMinecraftWorld(), VecHelper.toVector(pos)); blockSnapshot = BlockSnapshot.builder().from(location).blockState((BlockState) currentState).build(); } BlockSpawnCause spawnCause = BlockSpawnCause.builder() .block(blockSnapshot) .type(entity instanceof EntityXPOrb ? SpawnTypes.EXPERIENCE : SpawnTypes.BLOCK_SPAWNING) .build(); IMixinEntity spongeEntity = (IMixinEntity) entity; spongeEntity.setSpawnCause(spawnCause); spongeEntity.setSpawnedFromBlockBreak(true); } } this.causeTrackerBlockBreakTimer.stopTiming(); } public boolean handleBlockCaptures() { List<BlockSnapshot> capturedBlockList = this.getCapturedSpongeBlockSnapshots(); if (capturedBlockList.size() == 0) { return false; } this.causeTrackerBlockTimer.startTiming(); Cause cause = this.getCurrentCause(); EntityPlayerMP player = StaticMixinHelper.packetPlayer; ImmutableList<Transaction<BlockSnapshot>> blockBreakTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockModifyTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockPlaceTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockDecayTransactions = null; ImmutableList<Transaction<BlockSnapshot>> blockMultiTransactions = null; ImmutableList.Builder<Transaction<BlockSnapshot>> breakBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> placeBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> decayBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> modifyBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Transaction<BlockSnapshot>> multiBuilder = new ImmutableList.Builder<>(); ChangeBlockEvent.Break breakEvent = null; ChangeBlockEvent.Modify modifyEvent = null; ChangeBlockEvent.Place placeEvent = null; List<ChangeBlockEvent> blockEvents = new ArrayList<>(); Iterator<BlockSnapshot> iterator = capturedBlockList.iterator(); while (iterator.hasNext()) { SpongeBlockSnapshot blockSnapshot = (SpongeBlockSnapshot) iterator.next(); CaptureType captureType = blockSnapshot.captureType; BlockPos pos = VecHelper.toBlockPos(blockSnapshot.getPosition()); IBlockState currentState = this.getMinecraftWorld().getBlockState(pos); Transaction<BlockSnapshot> transaction = new Transaction<>(blockSnapshot, this.getMixinWorld().createSpongeBlockSnapshot(currentState, currentState.getBlock() .getActualState(currentState, this.getMinecraftWorld(), pos), pos, 0)); if (captureType == CaptureType.BREAK) { breakBuilder.add(transaction); } else if (captureType == CaptureType.DECAY) { decayBuilder.add(transaction); } else if (captureType == CaptureType.PLACE) { placeBuilder.add(transaction); } else if (captureType == CaptureType.MODIFY) { modifyBuilder.add(transaction); } multiBuilder.add(transaction); iterator.remove(); } blockBreakTransactions = breakBuilder.build(); blockDecayTransactions = decayBuilder.build(); blockModifyTransactions = modifyBuilder.build(); blockPlaceTransactions = placeBuilder.build(); blockMultiTransactions = multiBuilder.build(); this.causeTrackerBlockTimer.stopTiming(); ChangeBlockEvent changeBlockEvent; if (blockBreakTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventBreak(cause, this.getWorld(), blockBreakTransactions); SpongeImpl.postEvent(changeBlockEvent); breakEvent = (ChangeBlockEvent.Break) changeBlockEvent; blockEvents.add(changeBlockEvent); } if (blockModifyTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventModify(cause, this.getWorld(), blockModifyTransactions); SpongeImpl.postEvent(changeBlockEvent); modifyEvent = (ChangeBlockEvent.Modify) changeBlockEvent; blockEvents.add(changeBlockEvent); } if (blockPlaceTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventPlace(cause, this.getWorld(), blockPlaceTransactions); SpongeImpl.postEvent(changeBlockEvent); placeEvent = (ChangeBlockEvent.Place) changeBlockEvent; blockEvents.add(changeBlockEvent); } this.causeTrackerBlockTimer.startTiming(); if (blockEvents.size() > 1) { if (breakEvent != null) { int count = cause.allOf(ChangeBlockEvent.Break.class).size(); String namedCause = "BreakEvent" + (count != 0 ? count : ""); cause = cause.with(NamedCause.of(namedCause, breakEvent)); } if (modifyEvent != null) { int count = cause.allOf(ChangeBlockEvent.Modify.class).size(); String namedCause = "ModifyEvent" + (count != 0 ? count : ""); cause = cause.with(NamedCause.of(namedCause, modifyEvent)); } if (placeEvent != null) { int count = cause.allOf(ChangeBlockEvent.Place.class).size(); String namedCause = "PlaceEvent" + (count != 0 ? count : ""); cause = cause.with(NamedCause.of(namedCause, placeEvent)); } this.causeTrackerBlockTimer.stopTiming(); changeBlockEvent = SpongeEventFactory.createChangeBlockEventPost(cause, this.getWorld(), blockMultiTransactions); SpongeImpl.postEvent(changeBlockEvent); this.causeTrackerBlockTimer.startTiming(); if (changeBlockEvent.isCancelled()) { // Restore original blocks ListIterator<Transaction<BlockSnapshot>> listIterator = changeBlockEvent.getTransactions().listIterator(changeBlockEvent.getTransactions().size()); processList(listIterator); if (player != null) { CaptureType captureType = null; if (this.currentPlayerPacket instanceof C08PacketPlayerBlockPlacement) { captureType = CaptureType.PLACE; } else if (this.currentPlayerPacket instanceof C07PacketPlayerDigging) { captureType = CaptureType.BREAK; } if (captureType != null) { handlePostPlayerBlockEvent(captureType, changeBlockEvent.getTransactions()); } } // clear entity list and return to avoid spawning items if (this.specificCapture) { this.capturedSpecificSpawnedEntities.clear(); this.capturedSpecificSpawnedEntityItems.clear(); } else { this.capturedSpawnedEntities.clear(); this.capturedSpawnedEntityItems.clear(); } return false; } } this.causeTrackerBlockTimer.stopTiming(); if (blockDecayTransactions.size() > 0) { changeBlockEvent = SpongeEventFactory.createChangeBlockEventDecay(cause, this.getWorld(), blockDecayTransactions); SpongeImpl.postEvent(changeBlockEvent); blockEvents.add(changeBlockEvent); } this.causeTrackerBlockTimer.startTiming(); for (ChangeBlockEvent blockEvent : blockEvents) { CaptureType captureType = null; if (blockEvent instanceof ChangeBlockEvent.Break) { captureType = CaptureType.BREAK; } else if (blockEvent instanceof ChangeBlockEvent.Decay) { captureType = CaptureType.DECAY; } else if (blockEvent instanceof ChangeBlockEvent.Modify) { captureType = CaptureType.MODIFY; } else if (blockEvent instanceof ChangeBlockEvent.Place) { captureType = CaptureType.PLACE; } C08PacketPlayerBlockPlacement packet = null; if (this.currentPlayerPacket instanceof C08PacketPlayerBlockPlacement) { packet = (C08PacketPlayerBlockPlacement) this.currentPlayerPacket; } if (blockEvent.isCancelled()) { // Restore original blocks ListIterator<Transaction<BlockSnapshot>> listIterator = blockEvent.getTransactions().listIterator(blockEvent.getTransactions().size()); processList(listIterator); handlePostPlayerBlockEvent(captureType, blockEvent.getTransactions()); // clear entity list and return to avoid spawning items if (this.specificCapture) { this.capturedSpecificSpawnedEntities.clear(); this.capturedSpecificSpawnedEntityItems.clear(); } else { this.capturedSpawnedEntities.clear(); this.capturedSpawnedEntityItems.clear(); } return false; } else { for (Transaction<BlockSnapshot> transaction : blockEvent.getTransactions()) { if (!transaction.isValid()) { this.invalidTransactions.add(transaction); } else { if (captureType == CaptureType.BREAK && !(transaction.getOriginal().getState().getType() instanceof BlockLiquid) && cause.first(User.class).isPresent()) { BlockPos pos = VecHelper.toBlockPos(transaction.getOriginal().getPosition()); for (EntityHanging hanging : SpongeHooks.findHangingEntities(this.getMinecraftWorld(), pos)) { if (hanging != null) { if (hanging instanceof EntityItemFrame) { EntityItemFrame itemFrame = (EntityItemFrame) hanging; net.minecraft.entity.Entity dropCause = null; if (cause.root() instanceof net.minecraft.entity.Entity) { dropCause = (net.minecraft.entity.Entity) cause.root(); } itemFrame.dropItemOrSelf(dropCause, true); itemFrame.setDead(); } } } } if (captureType == CaptureType.PLACE && player != null && this.currentPlayerPacket instanceof C08PacketPlayerBlockPlacement) { BlockPos pos = VecHelper.toBlockPos(transaction.getFinal().getPosition()); IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(pos); spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos, (User) player, PlayerTracker.Type.OWNER); spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos, (User) player, PlayerTracker.Type.NOTIFIER); } } } if (this.invalidTransactions.size() > 0) { for (Transaction<BlockSnapshot> transaction : Lists.reverse(this.invalidTransactions)) { this.restoringBlocks = true; transaction.getOriginal().restore(true, false); this.restoringBlocks = false; } handlePostPlayerBlockEvent(captureType, this.invalidTransactions); } this.markAndNotifyBlockPost(blockEvent.getTransactions(), captureType); if (captureType == CaptureType.PLACE && player != null && packet != null && packet.getStack() != null) { player.addStat(StatList.objectUseStats[net.minecraft.item.Item.getIdFromItem(packet.getStack().getItem())], 1); } } } this.causeTrackerBlockTimer.stopTiming(); return true; } private void handlePostPlayerBlockEvent(CaptureType captureType, List<Transaction<BlockSnapshot>> transactions) { if (StaticMixinHelper.packetPlayer == null) { return; } if (captureType == CaptureType.BREAK) { // Let the client know the blocks still exist for (Transaction<BlockSnapshot> transaction : transactions) { BlockSnapshot snapshot = transaction.getOriginal(); BlockPos pos = VecHelper.toBlockPos(snapshot.getPosition()); StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(new S23PacketBlockChange(this.getMinecraftWorld(), pos)); // Update any tile entity data for this block net.minecraft.tileentity.TileEntity tileentity = this.getMinecraftWorld().getTileEntity(pos); if (tileentity != null) { Packet<?> pkt = tileentity.getDescriptionPacket(); if (pkt != null) { StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(pkt); } } } } if (StaticMixinHelper.packetPlayer != null) { ((IMixinEntityPlayerMP) StaticMixinHelper.packetPlayer).restorePacketItem(); } } public void handleNonLivingEntityDestruct(net.minecraft.entity.Entity entityIn) { if (entityIn.isDead && (!(entityIn instanceof EntityLivingBase) || entityIn instanceof EntityArmorStand)) { MessageChannel originalChannel = MessageChannel.TO_NONE; IMixinEntity spongeEntity = (IMixinEntity) entityIn; Cause cause = spongeEntity.getNonLivingDestructCause();; if (cause == null) { cause = Cause.of(NamedCause.source(entityIn.worldObj)); } if (cause.root() instanceof EntityDamageSource) { EntityDamageSource entityDamageSource = (EntityDamageSource) cause.root(); if (entityDamageSource.getSourceOfDamage() instanceof Player) { originalChannel = ((Player) entityDamageSource.getSourceOfDamage()).getMessageChannel(); } else if (entityDamageSource instanceof IndirectEntityDamageSource) { IndirectEntityDamageSource indirectDamageSource = (IndirectEntityDamageSource) entityDamageSource; if (indirectDamageSource.getIndirectSource() instanceof Player) { originalChannel = ((Player) indirectDamageSource.getIndirectSource()).getMessageChannel(); } } } else if (cause.root() instanceof Player) { originalChannel = ((Player) cause.root()).getMessageChannel(); } DestructEntityEvent event = SpongeEventFactory.createDestructEntityEvent( cause, originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(), (Entity) entityIn, true ); SpongeImpl.getGame().getEventManager().post(event); if (!event.isMessageCancelled()) { event.getChannel().ifPresent(channel -> channel.send(entityIn, event.getMessage())); } } } private void processList(ListIterator<Transaction<BlockSnapshot>> listIterator) { while (listIterator.hasPrevious()) { Transaction<BlockSnapshot> transaction = listIterator.previous(); this.restoringBlocks = true; transaction.getOriginal().restore(true, false); this.restoringBlocks = false; } } public boolean processSpawnEntity(Entity entity, Cause spawnCause) { checkNotNull(entity, "Entity cannot be null!"); checkNotNull(spawnCause, "Cause cannot be null!"); this.trackEntityOwner(entity); // Very first thing - fire events that are from entity construction if (((IMixinEntity) entity).isInConstructPhase()) { ((IMixinEntity) entity).firePostConstructEvents(); } net.minecraft.entity.Entity entityIn = (net.minecraft.entity.Entity) entity; // do not drop any items while restoring blocksnapshots. Prevents dupes if (!this.getMinecraftWorld().isRemote && (entityIn == null || (entityIn instanceof net.minecraft.entity.item.EntityItem && this.restoringBlocks))) { return false; } int i = MathHelper.floor_double(entityIn.posX / 16.0D); int j = MathHelper.floor_double(entityIn.posZ / 16.0D); boolean flag = entityIn.forceSpawn; // This is usually null during world gen Cause cause = this.getCurrentCause(); if (cause != null && !cause.first(SpawnCause.class).isPresent()) { cause = spawnCause.merge(cause); } else if (cause == null) { cause = spawnCause; } if (entityIn instanceof EntityPlayer) { flag = true; } else if (entityIn instanceof EntityLightningBolt) { ((IMixinEntityLightningBolt) entityIn).setCause(cause); } if (!flag && !this.getMinecraftWorld().isChunkLoaded(i, j, true)) { return false; } else { if (flag) { if (entityIn instanceof EntityPlayer) { EntityPlayer entityplayer = (EntityPlayer) entityIn; net.minecraft.world.World world = this.targetWorld; world.playerEntities.add(entityplayer); world.updateAllPlayersSleepingFlag(); } if (SpongeImpl.postEvent(SpongeEventFactory.createSpawnEntityEvent(cause, Lists.newArrayList(entity), Lists.newArrayList(entity.createSnapshot()), getWorld())) && !flag) { return false; } this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn); this.getMinecraftWorld().loadedEntityList.add(entityIn); this.getMixinWorld().onSpongeEntityAdded(entityIn); return true; } if (entityIn instanceof EntityFishHook && ((EntityFishHook) entityIn).angler == null) { // TODO MixinEntityFishHook.setShooter makes angler null // sometimes, but that will cause NPE when ticking return false; } org.spongepowered.api.event.Event event = null; List<Entity> entitiesToSpawn = Lists.newArrayList(entity); ImmutableList<EntitySnapshot> entitySnapshots = ImmutableList.of(entity.createSnapshot()); EntityLivingBase entityLiving = null; net.minecraft.entity.Entity nonLivingEntity = null; if (this.currentTickEntity instanceof EntityLivingBase) { entityLiving = (EntityLivingBase) this.currentTickEntity; } else if (this.currentTickEntity != null) { nonLivingEntity = (net.minecraft.entity.Entity) this.currentTickEntity; } if (entityIn instanceof EntityItem) { if ((nonLivingEntity != null && nonLivingEntity.isDead) || entityIn instanceof EntityXPOrb || (entityLiving != null && (entityLiving.getHealth() <= 0 || entityLiving.isDead))) { event = SpongeEventFactory.createDropItemEventDestruct(cause, entitiesToSpawn, entitySnapshots, this.getWorld()); } else { event = SpongeEventFactory.createDropItemEventDispense(cause, entitiesToSpawn, entitySnapshots, this.getWorld()); } } else { event = SpongeEventFactory.createSpawnEntityEvent(cause, entitiesToSpawn, entitySnapshots, this.getWorld()); } if (!SpongeImpl.postEvent(event)) { if (entityIn instanceof EntityWeatherEffect) { return addWeatherEffect(entityIn, cause); } this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn); this.getMinecraftWorld().loadedEntityList.add(entityIn); this.getMixinWorld().onSpongeEntityAdded(entityIn); return true; } return false; } } public void randomTickBlock(Block block, BlockPos pos, IBlockState state, Random random) { boolean captureBlocks = this.isCapturingBlocks(); this.captureBlocks = true; this.preTrackBlock(state, pos); block.randomTick(this.getMinecraftWorld(), pos, state, random); this.postTrackBlock(); this.captureBlocks = captureBlocks; } // By this point, currentPending(NextTickListEntry) should always be available public void updateTickBlock(Block block, BlockPos pos, IBlockState state, Random rand) { this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickBlock)); if (this.currentPendingBlockUpdate.hasTickingBlock()) { namedCauses.add(NamedCause.of("SchedulerSource", this.currentPendingBlockUpdate.getCurrentTickBlock().get())); if (this.currentPendingBlockUpdate.hasTickingTileEntity()) { namedCauses.add(NamedCause.of("SchedulerParentSource", this.currentPendingBlockUpdate.getCurrentTickTileEntity().get())); } } else if (this.currentPendingBlockUpdate.hasTickingTileEntity()) { namedCauses.add(NamedCause.of("SchedulerSource", this.currentPendingBlockUpdate.getCurrentTickTileEntity().get())); } if (!this.currentPendingBlockUpdate.hasSourceUser()) { this.trackBlockPositionCausePreTick(pos); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } } else { this.currentNotifier = this.currentPendingBlockUpdate.getSourceUser().get(); namedCauses.add(NamedCause.notifier(this.currentNotifier)); } this.addCause(Cause.of(namedCauses)); boolean captureBlocks = this.isCapturingBlocks(); this.captureBlocks = true; block.updateTick(this.getMinecraftWorld(), pos, state, rand); this.postTrackBlock(); this.captureBlocks = captureBlocks; this.currentPendingBlockUpdate = null; this.currentTickTileEntity = null; } public void notifyBlockOfStateChange(BlockPos notifyPos, final Block sourceBlock, BlockPos sourcePos) { if (!this.getMinecraftWorld().isRemote) { IBlockState iblockstate = this.getMinecraftWorld().getBlockState(notifyPos); if (iblockstate == Blocks.air.getDefaultState() || !this.isCapturingBlocks()) { iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock); return; } try { if (!this.tryAndTrackActiveUser(notifyPos, PlayerTracker.Type.NOTIFIER).isPresent()) { if (this.hasTickingBlock()) { this.trackTargetBlockFromSource(((SpongeBlockSnapshot) this.currentTickBlock).getBlockPos(), sourcePos, iblockstate.getBlock(), notifyPos, PlayerTracker.Type.NOTIFIER); } } iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock); } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while updating neighbours"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated"); // TODO /*crashreportcategory.addCrashSectionCallable("Source block type", new Callable() { public String call() { try { return String.format("ID #%d (%s // %s)", new Object[] {Integer.valueOf(Block.getIdFromBlock(blockIn)), blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName()}); } catch (Throwable throwable1) { return "ID #" + Block.getIdFromBlock(blockIn); } } });*/ CrashReportCategory.addBlockInfo(crashreportcategory, notifyPos, iblockstate); throw new ReportedException(crashreport); } } } public void markAndNotifyBlockPost(List<Transaction<BlockSnapshot>> transactions, CaptureType type) { // We have to use a proxy so that our pending changes are notified such that any accessors from block // classes do not fail on getting the incorrect block state from the IBlockAccess SpongeProxyBlockAccess proxyBlockAccess = new SpongeProxyBlockAccess(this.getMinecraftWorld(), transactions); for (Transaction<BlockSnapshot> transaction : transactions) { if (!transaction.isValid()) { continue; // Don't use invalidated block transactions during notifications, these only need to be restored } // Handle custom replacements if (transaction.getCustom().isPresent()) { transaction.getFinal().restore(true, false); } Cause cause = this.getCurrentCause(); SpongeBlockSnapshot oldBlockSnapshot = (SpongeBlockSnapshot) transaction.getOriginal(); SpongeBlockSnapshot newBlockSnapshot = (SpongeBlockSnapshot) transaction.getFinal(); SpongeHooks.logBlockAction(cause, this.getMinecraftWorld(), type, transaction); int updateFlag = oldBlockSnapshot.getUpdateFlag(); BlockPos pos = VecHelper.toBlockPos(oldBlockSnapshot.getPosition()); IBlockState originalState = (IBlockState) oldBlockSnapshot.getState(); IBlockState newState = (IBlockState) newBlockSnapshot.getState(); BlockSnapshot currentTickingBlock = this.getCurrentTickBlock().orElse(null); // Containers get placed automatically if (originalState.getBlock() != newState.getBlock() && !SpongeImplHooks.blockHasTileEntity(newState.getBlock(), newState)) { this.setCurrentTickBlock(this.getMixinWorld().createSpongeBlockSnapshot(newState, newState.getBlock().getActualState(newState, proxyBlockAccess, pos), pos, updateFlag)); List<NamedCause> namedCauses = new ArrayList<>(); namedCauses.add(NamedCause.source(this.currentTickBlock)); namedCauses.add(NamedCause.of("ParentSource", cause.root())); if (this.currentNotifier != null) { namedCauses.add(NamedCause.notifier(this.currentNotifier)); } else if (StaticMixinHelper.packetPlayer != null) { namedCauses.add(NamedCause.owner(StaticMixinHelper.packetPlayer)); } this.addCause(Cause.of(namedCauses)); this.causeTrackerBlockTimer.stopTiming(); boolean captureBlocks = this.captureBlocks; this.captureBlocks = true; newState.getBlock().onBlockAdded(this.getMinecraftWorld(), pos, newState); // Handle any additional captures during onBlockAdded // This is to ensure new captures do not leak into next tick with wrong cause if (this.getCapturedSpongeBlockSnapshots().size() > 0) { this.handlePostTickCaptures(); } this.captureBlocks = captureBlocks; this.causeTrackerBlockTimer.startTiming(); this.removeCurrentCause(); } proxyBlockAccess.proceed(); this.causeTrackerBlockTimer.stopTiming(); boolean captureBlocks = this.captureBlocks; this.captureBlocks = true; this.getMixinWorld().markAndNotifyNeighbors(pos, null, originalState, newState, updateFlag); // Handle any additional captures during notify // This is to ensure new captures do not leak into next tick with wrong cause if (this.getCapturedSpongeBlockSnapshots().size() > 0) { this.handlePostTickCaptures(); } this.captureBlocks = captureBlocks; this.setCurrentTickBlock(currentTickingBlock); } } /*private boolean shouldChainCause(Cause cause) { return !this.isCapturingTerrainGen() && !this.isWorldSpawnerRunning() && !this.isChunkSpawnerRunning() && !this.isProcessingBlockRandomTicks() && !this.isCaptureCommand() && this.hasTickingBlock() && this.pluginCause == null && !cause.contains(this.getCurrentTickBlock().get()) && !(StaticMixinHelper.processingPacket instanceof C03PacketPlayer); }*/ private Predicate<net.minecraft.entity.Entity> entityTrackerPredicate = new Predicate<net.minecraft.entity.Entity>() { @Override public boolean apply(net.minecraft.entity.Entity input) { if (input instanceof EntityLivingBase) { return false; } if (input instanceof EntityItem) { return false; } return true; } }; private static AxisAlignedBB entityAABB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); private AxisAlignedBB getEntityAABBForBlockPos(BlockPos pos) { entityAABB.minX = pos.getX(); entityAABB.minY = pos.getY(); entityAABB.minZ = pos.getZ(); entityAABB.maxX = pos.getX() + 0.1; entityAABB.maxY = pos.getY() + 0.1; entityAABB.maxZ = pos.getZ() + 0.1; return entityAABB; } public Optional<User> tryAndTrackActiveUser(BlockPos targetPos, PlayerTracker.Type type) { net.minecraft.world.World world = this.getMinecraftWorld(); if (targetPos == null || !world.isBlockLoaded(targetPos)) { return Optional.empty(); } User user = null; IMixinChunk spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(targetPos); if (spongeChunk != null && !(spongeChunk instanceof EmptyChunk)) { if (StaticMixinHelper.packetPlayer != null) { user = (User) StaticMixinHelper.packetPlayer; spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, user, type); } else if (this.currentNotifier != null) { user = this.currentNotifier; spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, user, type); } // check if a non-living entity exists at target block position (ex. minecarts) if (user != null) { Chunk chunk = (Chunk) spongeChunk; List<net.minecraft.entity.Entity> entityList = new ArrayList<>(); chunk.getEntitiesOfTypeWithinAAAB(net.minecraft.entity.Entity.class, this.getEntityAABBForBlockPos(targetPos), entityList, this.entityTrackerPredicate); for (net.minecraft.entity.Entity entity : entityList) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_NOTIFIER, user.getUniqueId()); } } } return Optional.ofNullable(user); } public Optional<User> trackTargetBlockFromSource(Object source, BlockPos sourcePos, Block targetBlock, BlockPos targetPos, PlayerTracker.Type type) { // first check to see if we have an active user Optional<User> user = tryAndTrackActiveUser(targetPos, type); if (user.isPresent()) { return user; } net.minecraft.world.World world = this.getMinecraftWorld(); if (sourcePos == null || !world.isBlockLoaded(sourcePos)) { return Optional.empty(); } IMixinChunk spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(sourcePos); if (spongeChunk != null && !(spongeChunk instanceof EmptyChunk)) { Optional<User> owner = spongeChunk.getBlockOwner(sourcePos); Optional<User> notifier = spongeChunk.getBlockNotifier(sourcePos); if (notifier.isPresent()) { spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(targetPos); spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, notifier.get(), type); return notifier; } else if (owner.isPresent()) { spongeChunk.addTrackedBlockPosition(world.getBlockState(targetPos).getBlock(), targetPos, owner.get(), type); return owner; } } return Optional.empty(); } public Optional<User> trackBlockPositionCausePreTick(BlockPos pos) { net.minecraft.world.World world = this.getMinecraftWorld(); if (pos == null || !world.isBlockLoaded(pos)) { return Optional.empty(); } IMixinChunk spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(pos); if (spongeChunk != null && !(spongeChunk instanceof EmptyChunk)) { Optional<User> owner = spongeChunk.getBlockOwner(pos); Optional<User> notifier = spongeChunk.getBlockNotifier(pos); if (notifier.isPresent()) { User user = notifier.get(); this.currentNotifier = user; return notifier; } else if (owner.isPresent()) { User user = owner.get(); this.currentNotifier = user; return owner; } if (notifier.isPresent()) { return notifier; } else { return owner; } } return Optional.empty(); } public void trackEntityCausePreTick(net.minecraft.entity.Entity entity) { if (entity == null || this.causeStack.isEmpty()) { return; } Cause cause = this.getCurrentCause(); IMixinEntity spongeEntity = (IMixinEntity) entity; Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR); if (!owner.isPresent()) { if (entity instanceof EntityTameable) { EntityTameable tameable = (EntityTameable) entity; if (tameable.getOwner() != null) { owner = Optional.of((User) tameable.getOwner()); } } } Optional<User> notifier = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_NOTIFIER); if (notifier.isPresent()) { User user = notifier.get(); this.currentNotifier = user; this.causeStack.pop(); this.addCause(cause.merge(Cause.of(NamedCause.notifier(user)))); } else if (owner.isPresent()) { User user = owner.get(); this.currentNotifier = user; this.causeStack.pop(); this.addCause(cause.merge(Cause.of(NamedCause.owner(user)))); } } // Handle entity ownership tracking public void trackEntityOwner(Entity entity) { User currentUser = StaticMixinHelper.packetPlayer != null ? (User) StaticMixinHelper.packetPlayer : this.currentNotifier; if (currentUser != null) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, currentUser.getUniqueId()); } else if (this.currentTickEntity != null) { IMixinEntity spongeEntity = (IMixinEntity) this.currentTickEntity; Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR); if (owner.isPresent()) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, owner.get().getUniqueId()); } else { Optional<User> notifier = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_NOTIFIER); if (notifier.isPresent()) { ((IMixinEntity) entity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, notifier.get().getUniqueId()); } } } } }
Add support for tracking pixelmon when spawned by pokeballs.
src/main/java/org/spongepowered/common/event/CauseTracker.java
Add support for tracking pixelmon when spawned by pokeballs.
Java
mit
4d8e35655d07d3e39929c35429ceef015321a873
0
JetBrains/ideavim,JetBrains/ideavim
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2014 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim; import com.intellij.notification.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.actionSystem.TypedAction; import com.intellij.openapi.editor.event.EditorFactoryAdapter; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.keymap.impl.DefaultKeymap; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import com.intellij.util.messages.MessageBusConnection; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.ex.CommandParser; import com.maddyhome.idea.vim.ex.VimScriptParser; import com.maddyhome.idea.vim.group.*; import com.maddyhome.idea.vim.helper.*; import com.maddyhome.idea.vim.option.Options; import com.maddyhome.idea.vim.ui.VimEmulationConfigurable; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import java.awt.*; import java.io.File; /** * This plugin attempts to emulate the key binding and general functionality of Vim and gVim. See the supplied * documentation for a complete list of supported and unsupported Vim emulation. The code base contains some debugging * output that can be enabled in necessary. * <p/> * This is an application level plugin meaning that all open projects will share a common instance of the plugin. * Registers and marks are shared across open projects so you can copy and paste between files of different projects. * * @version 0.1 */ @State( name = "VimSettings", storages = {@Storage( id = "main", file = "$APP_CONFIG$/vim_settings.xml")}) public class VimPlugin implements ApplicationComponent, PersistentStateComponent<Element> { private static final String IDEAVIM_COMPONENT_NAME = "VimPlugin"; private static final String IDEAVIM_PLUGIN_ID = "IdeaVIM"; public static final String IDEAVIM_NOTIFICATION_ID = "ideavim"; public static final String IDEAVIM_STICKY_NOTIFICATION_ID = "ideavim-sticky"; public static final String IDEAVIM_NOTIFICATION_TITLE = "IdeaVim"; public static final int STATE_VERSION = 4; private static final boolean BLOCK_CURSOR_VIM_VALUE = true; private static final boolean ANIMATED_SCROLLING_VIM_VALUE = false; private static final boolean REFRAIN_FROM_SCROLLING_VIM_VALUE = true; private VimTypedActionHandler vimHandler; private boolean isBlockCursor = false; private boolean isAnimatedScrolling = false; private boolean isRefrainFromScrolling = false; private boolean error = false; private int previousStateVersion = 0; private String previousKeyMap = ""; // It is enabled by default to avoid any special configuration after plugin installation private boolean enabled = true; private static Logger LOG = Logger.getInstance(VimPlugin.class); private final Application myApp; private MotionGroup motion; private ChangeGroup change; private CopyGroup copy; private MarkGroup mark; private RegisterGroup register; private FileGroup file; private SearchGroup search; private ProcessGroup process; private MacroGroup macro; private DigraphGroup digraph; private HistoryGroup history; private KeyGroup key; public VimPlugin(final Application app) { myApp = app; motion = new MotionGroup(); change = new ChangeGroup(); copy = new CopyGroup(); mark = new MarkGroup(); register = new RegisterGroup(); file = new FileGroup(); search = new SearchGroup(); process = new ProcessGroup(); macro = new MacroGroup(); digraph = new DigraphGroup(); history = new HistoryGroup(); key = new KeyGroup(); LOG.debug("VimPlugin ctr"); } @NotNull @Override public String getComponentName() { return IDEAVIM_COMPONENT_NAME; } @Override public void initComponent() { LOG.debug("initComponent"); Notifications.Bus.register(IDEAVIM_STICKY_NOTIFICATION_ID, NotificationDisplayType.STICKY_BALLOON); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { updateState(); } }); // Replace the default key handler with the Vim key handler final TypedAction typedAction = EditorActionManager.getInstance().getTypedAction(); vimHandler = new VimTypedActionHandler(typedAction.getHandler()); typedAction.setupHandler(vimHandler); // Register vim actions in command mode RegisterActions.registerActions(); // Add some listeners so we can handle special events setupListeners(); // Register ex handlers CommandParser.getInstance().registerHandlers(); if (!ApplicationManager.getApplication().isUnitTestMode()) { final File ideaVimRc = VimScriptParser.findIdeaVimRc(); if (ideaVimRc != null) { VimScriptParser.executeFile(ideaVimRc); } } LOG.debug("done"); } @Override public void disposeComponent() { LOG.debug("disposeComponent"); turnOffPlugin(); final TypedAction action = EditorActionManager.getInstance().getTypedAction(); action.setupHandler(vimHandler.getOriginalTypedHandler()); LOG.debug("done"); } @Override public Element getState() { LOG.debug("Saving state"); final Element element = new Element("ideavim"); // Save whether the plugin is enabled or not final Element state = new Element("state"); state.setAttribute("version", Integer.toString(STATE_VERSION)); state.setAttribute("enabled", Boolean.toString(enabled)); element.addContent(state); mark.saveData(element); register.saveData(element); search.saveData(element); history.saveData(element); key.saveData(element); return element; } @Override public void loadState(@NotNull final Element element) { LOG.debug("Loading state"); // Restore whether the plugin is enabled or not Element state = element.getChild("state"); if (state != null) { try { previousStateVersion = Integer.valueOf(state.getAttributeValue("version")); } catch (NumberFormatException ignored) { } enabled = Boolean.valueOf(state.getAttributeValue("enabled")); previousKeyMap = state.getAttributeValue("keymap"); } mark.readData(element); register.readData(element); search.readData(element); history.readData(element); key.readData(element); } public static MotionGroup getMotion() { return getInstance().motion; } public static ChangeGroup getChange() { return getInstance().change; } public static CopyGroup getCopy() { return getInstance().copy; } public static MarkGroup getMark() { return getInstance().mark; } public static RegisterGroup getRegister() { return getInstance().register; } public static FileGroup getFile() { return getInstance().file; } public static SearchGroup getSearch() { return getInstance().search; } public static ProcessGroup getProcess() { return getInstance().process; } public static MacroGroup getMacro() { return getInstance().macro; } public static DigraphGroup getDigraph() { return getInstance().digraph; } public static HistoryGroup getHistory() { return getInstance().history; } public static KeyGroup getKey() { return getInstance().key; } public static PluginId getPluginId() { return PluginId.getId(IDEAVIM_PLUGIN_ID); } public static boolean isEnabled() { return getInstance().enabled; } public static void setEnabled(final boolean enabled) { if (!enabled) { getInstance().turnOffPlugin(); } getInstance().enabled = enabled; if (enabled) { getInstance().turnOnPlugin(); } } public static boolean isError() { return getInstance().error; } /** * Indicate to the user that an error has occurred. Just beep. */ public static void indicateError() { if (ApplicationManager.getApplication().isUnitTestMode()) { getInstance().error = true; } else if (!Options.getInstance().isSet("visualbell")) { Toolkit.getDefaultToolkit().beep(); } } public static void clearError() { if (ApplicationManager.getApplication().isUnitTestMode()) { getInstance().error = false; } } public static void showMode(String msg) { showMessage(msg); } public static void showMessage(@Nullable String msg) { ProjectManager pm = ProjectManager.getInstance(); Project[] projects = pm.getOpenProjects(); for (Project project : projects) { StatusBar bar = WindowManager.getInstance().getStatusBar(project); if (bar != null) { if (msg == null || msg.length() == 0) { bar.setInfo(""); } else { bar.setInfo("VIM - " + msg); } } } } @NotNull private static VimPlugin getInstance() { return (VimPlugin)ApplicationManager.getApplication().getComponent(IDEAVIM_COMPONENT_NAME); } private void turnOnPlugin() { KeyHandler.getInstance().fullReset(null); setCursors(BLOCK_CURSOR_VIM_VALUE); setAnimatedScrolling(ANIMATED_SCROLLING_VIM_VALUE); setRefrainFromScrolling(REFRAIN_FROM_SCROLLING_VIM_VALUE); getMotion().turnOn(); } private void turnOffPlugin() { KeyHandler.getInstance().fullReset(null); setCursors(isBlockCursor); setAnimatedScrolling(isAnimatedScrolling); setRefrainFromScrolling(isRefrainFromScrolling); getMotion().turnOff(); } private void updateState() { if (isEnabled() && !ApplicationManager.getApplication().isUnitTestMode()) { boolean requiresRestart = false; if (previousStateVersion < 2 && SystemInfo.isMac) { final MacKeyRepeat keyRepeat = MacKeyRepeat.getInstance(); final Boolean enabled = keyRepeat.isEnabled(); if (enabled == null || !enabled) { if (Messages.showYesNoDialog("Do you want to enable repeating keys in Mac OS X on press and hold " + "(requires restart)?\n\n" + "(You can do it manually by running 'defaults write -g " + "ApplePressAndHoldEnabled 0' in the console).", IDEAVIM_NOTIFICATION_TITLE, Messages.getQuestionIcon() ) == Messages.YES) { keyRepeat.setEnabled(true); requiresRestart = true; } } } if (previousStateVersion > 0 && previousStateVersion < 3) { final KeymapManagerEx manager = KeymapManagerEx.getInstanceEx(); Keymap keymap = null; if (previousKeyMap != null) { keymap = manager.getKeymap(previousKeyMap); } if (keymap == null) { keymap = manager.getKeymap(DefaultKeymap.getInstance().getDefaultKeymapName()); } assert keymap != null : "Default keymap not found"; new Notification( VimPlugin.IDEAVIM_STICKY_NOTIFICATION_ID, VimPlugin.IDEAVIM_NOTIFICATION_TITLE, String.format("IdeaVim plugin doesn't use the special \"Vim\" keymap any longer. " + "Switching to \"%s\" keymap.<br/><br/>" + "Now it is possible to set up:<br/>" + "<ul>" + "<li>Vim keys in your ~/.ideavimrc file using key mapping commands</li>" + "<li>IDE action shortcuts in \"File | Settings | Keymap\"</li>" + "<li>Vim or IDE handlers for conflicting shortcuts in <a href='#settings'>Vim Emulation</a> settings</li>" + "</ul>", keymap.getPresentableName()), NotificationType.INFORMATION, new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { ShowSettingsUtil.getInstance().editConfigurable((Project)null, new VimEmulationConfigurable()); } }).notify(null); manager.setActiveKeymap(keymap); } if (previousStateVersion > 0 && previousStateVersion < 4) { new Notification( VimPlugin.IDEAVIM_STICKY_NOTIFICATION_ID, VimPlugin.IDEAVIM_NOTIFICATION_TITLE, "The ~/.vimrc file is no longer read by default, use ~/.ideavimrc instead. You can read it from your " + "~/.ideavimrc using this command:<br/><br/>" + "<code>source ~/.vimrc</code>", NotificationType.INFORMATION).notify(null); } if (requiresRestart) { final ApplicationEx app = ApplicationManagerEx.getApplicationEx(); app.restart(); } } } /** * This sets up some listeners so we can handle various events that occur */ private void setupListeners() { DocumentManager.getInstance().addDocumentListener(new MarkGroup.MarkUpdater()); DocumentManager.getInstance().addDocumentListener(new SearchGroup.DocumentSearchListener()); EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); isBlockCursor = editor.getSettings().isBlockCursor(); isAnimatedScrolling = editor.getSettings().isAnimatedScrolling(); isRefrainFromScrolling = editor.getSettings().isRefrainFromScrolling(); EditorData.initializeEditor(editor); DocumentManager.getInstance().addListeners(editor.getDocument()); key.registerRequiredShortcutKeys(editor); if (VimPlugin.isEnabled()) { // Turn on insert mode if editor doesn't have any file if (!EditorData.isFileEditor(editor) && editor.getDocument().isWritable() && !CommandState.inInsertMode(editor)) { KeyHandler.getInstance().handleKey(editor, KeyStroke.getKeyStroke('i'), new EditorDataContext(editor)); } editor.getSettings().setBlockCursor(!CommandState.inInsertMode(editor)); editor.getSettings().setAnimatedScrolling(ANIMATED_SCROLLING_VIM_VALUE); editor.getSettings().setRefrainFromScrolling(REFRAIN_FROM_SCROLLING_VIM_VALUE); } } @Override public void editorReleased(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); EditorData.uninitializeEditor(editor); key.unregisterShortcutKeys(editor); editor.getSettings().setAnimatedScrolling(isAnimatedScrolling); editor.getSettings().setRefrainFromScrolling(isRefrainFromScrolling); DocumentManager.getInstance().removeListeners(editor.getDocument()); } }, myApp); ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() { @Override public void projectOpened(@NotNull final Project project) { final MessageBusConnection connection = project.getMessageBus().connect(); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MotionGroup.MotionEditorChange()); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileGroup.SelectionCheck()); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new SearchGroup.EditorSelectionCheck()); } }); CommandProcessor.getInstance().addCommandListener(DelegateCommandListener.getInstance()); } private void setCursors(boolean isBlock) { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { // Vim plugin should be turned on in insert mode ((EditorEx)editor).setInsertMode(true); editor.getSettings().setBlockCursor(isBlock); } } private void setAnimatedScrolling(boolean isOn) { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { editor.getSettings().setAnimatedScrolling(isOn); } } private void setRefrainFromScrolling(boolean isOn) { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { editor.getSettings().setRefrainFromScrolling(isOn); } } }
src/com/maddyhome/idea/vim/VimPlugin.java
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2014 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim; import com.intellij.notification.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.actionSystem.TypedAction; import com.intellij.openapi.editor.event.EditorFactoryAdapter; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.keymap.impl.DefaultKeymap; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.ex.CommandParser; import com.maddyhome.idea.vim.ex.VimScriptParser; import com.maddyhome.idea.vim.group.*; import com.maddyhome.idea.vim.helper.*; import com.maddyhome.idea.vim.option.Options; import com.maddyhome.idea.vim.ui.VimEmulationConfigurable; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import java.awt.*; import java.io.File; /** * This plugin attempts to emulate the key binding and general functionality of Vim and gVim. See the supplied * documentation for a complete list of supported and unsupported Vim emulation. The code base contains some debugging * output that can be enabled in necessary. * <p/> * This is an application level plugin meaning that all open projects will share a common instance of the plugin. * Registers and marks are shared across open projects so you can copy and paste between files of different projects. * * @version 0.1 */ @State( name = "VimSettings", storages = {@Storage( id = "main", file = "$APP_CONFIG$/vim_settings.xml")}) public class VimPlugin implements ApplicationComponent, PersistentStateComponent<Element> { private static final String IDEAVIM_COMPONENT_NAME = "VimPlugin"; private static final String IDEAVIM_PLUGIN_ID = "IdeaVIM"; public static final String IDEAVIM_NOTIFICATION_ID = "ideavim"; public static final String IDEAVIM_STICKY_NOTIFICATION_ID = "ideavim-sticky"; public static final String IDEAVIM_NOTIFICATION_TITLE = "IdeaVim"; public static final int STATE_VERSION = 4; private static final boolean BLOCK_CURSOR_VIM_VALUE = true; private static final boolean ANIMATED_SCROLLING_VIM_VALUE = false; private static final boolean REFRAIN_FROM_SCROLLING_VIM_VALUE = true; private VimTypedActionHandler vimHandler; private boolean isBlockCursor = false; private boolean isAnimatedScrolling = false; private boolean isRefrainFromScrolling = false; private boolean error = false; private int previousStateVersion = 0; private String previousKeyMap = ""; // It is enabled by default to avoid any special configuration after plugin installation private boolean enabled = true; private static Logger LOG = Logger.getInstance(VimPlugin.class); private final Application myApp; private MotionGroup motion; private ChangeGroup change; private CopyGroup copy; private MarkGroup mark; private RegisterGroup register; private FileGroup file; private SearchGroup search; private ProcessGroup process; private MacroGroup macro; private DigraphGroup digraph; private HistoryGroup history; private KeyGroup key; public VimPlugin(final Application app) { myApp = app; motion = new MotionGroup(); change = new ChangeGroup(); copy = new CopyGroup(); mark = new MarkGroup(); register = new RegisterGroup(); file = new FileGroup(); search = new SearchGroup(); process = new ProcessGroup(); macro = new MacroGroup(); digraph = new DigraphGroup(); history = new HistoryGroup(); key = new KeyGroup(); LOG.debug("VimPlugin ctr"); } @NotNull @Override public String getComponentName() { return IDEAVIM_COMPONENT_NAME; } @Override public void initComponent() { LOG.debug("initComponent"); Notifications.Bus.register(IDEAVIM_STICKY_NOTIFICATION_ID, NotificationDisplayType.STICKY_BALLOON); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { updateState(); } }); EditorActionManager manager = EditorActionManager.getInstance(); TypedAction action = manager.getTypedAction(); // Replace the default key handler with the Vim key handler vimHandler = new VimTypedActionHandler(action.getHandler()); action.setupHandler(vimHandler); // Register vim actions in command mode RegisterActions.registerActions(); // Add some listeners so we can handle special events setupListeners(); // Register ex handlers CommandParser.getInstance().registerHandlers(); if (!ApplicationManager.getApplication().isUnitTestMode()) { final File ideaVimRc = VimScriptParser.findIdeaVimRc(); if (ideaVimRc != null) { VimScriptParser.executeFile(ideaVimRc); } } LOG.debug("done"); } @Override public void disposeComponent() { LOG.debug("disposeComponent"); turnOffPlugin(); EditorActionManager manager = EditorActionManager.getInstance(); TypedAction action = manager.getTypedAction(); action.setupHandler(vimHandler.getOriginalTypedHandler()); LOG.debug("done"); } @Override public Element getState() { LOG.debug("Saving state"); final Element element = new Element("ideavim"); // Save whether the plugin is enabled or not final Element state = new Element("state"); state.setAttribute("version", Integer.toString(STATE_VERSION)); state.setAttribute("enabled", Boolean.toString(enabled)); element.addContent(state); mark.saveData(element); register.saveData(element); search.saveData(element); history.saveData(element); key.saveData(element); return element; } @Override public void loadState(@NotNull final Element element) { LOG.debug("Loading state"); // Restore whether the plugin is enabled or not Element state = element.getChild("state"); if (state != null) { try { previousStateVersion = Integer.valueOf(state.getAttributeValue("version")); } catch (NumberFormatException ignored) { } enabled = Boolean.valueOf(state.getAttributeValue("enabled")); previousKeyMap = state.getAttributeValue("keymap"); } mark.readData(element); register.readData(element); search.readData(element); history.readData(element); key.readData(element); } public static MotionGroup getMotion() { return getInstance().motion; } public static ChangeGroup getChange() { return getInstance().change; } public static CopyGroup getCopy() { return getInstance().copy; } public static MarkGroup getMark() { return getInstance().mark; } public static RegisterGroup getRegister() { return getInstance().register; } public static FileGroup getFile() { return getInstance().file; } public static SearchGroup getSearch() { return getInstance().search; } public static ProcessGroup getProcess() { return getInstance().process; } public static MacroGroup getMacro() { return getInstance().macro; } public static DigraphGroup getDigraph() { return getInstance().digraph; } public static HistoryGroup getHistory() { return getInstance().history; } public static KeyGroup getKey() { return getInstance().key; } public static PluginId getPluginId() { return PluginId.getId(IDEAVIM_PLUGIN_ID); } public static boolean isEnabled() { return getInstance().enabled; } public static void setEnabled(final boolean enabled) { if (!enabled) { getInstance().turnOffPlugin(); } getInstance().enabled = enabled; if (enabled) { getInstance().turnOnPlugin(); } } public static boolean isError() { return getInstance().error; } /** * Indicate to the user that an error has occurred. Just beep. */ public static void indicateError() { if (ApplicationManager.getApplication().isUnitTestMode()) { getInstance().error = true; } else if (!Options.getInstance().isSet("visualbell")) { Toolkit.getDefaultToolkit().beep(); } } public static void clearError() { if (ApplicationManager.getApplication().isUnitTestMode()) { getInstance().error = false; } } public static void showMode(String msg) { showMessage(msg); } public static void showMessage(@Nullable String msg) { ProjectManager pm = ProjectManager.getInstance(); Project[] projects = pm.getOpenProjects(); for (Project project : projects) { StatusBar bar = WindowManager.getInstance().getStatusBar(project); if (bar != null) { if (msg == null || msg.length() == 0) { bar.setInfo(""); } else { bar.setInfo("VIM - " + msg); } } } } @NotNull private static VimPlugin getInstance() { return (VimPlugin)ApplicationManager.getApplication().getComponent(IDEAVIM_COMPONENT_NAME); } private void turnOnPlugin() { KeyHandler.getInstance().fullReset(null); setCursors(BLOCK_CURSOR_VIM_VALUE); setAnimatedScrolling(ANIMATED_SCROLLING_VIM_VALUE); setRefrainFromScrolling(REFRAIN_FROM_SCROLLING_VIM_VALUE); getMotion().turnOn(); } private void turnOffPlugin() { KeyHandler.getInstance().fullReset(null); setCursors(isBlockCursor); setAnimatedScrolling(isAnimatedScrolling); setRefrainFromScrolling(isRefrainFromScrolling); getMotion().turnOff(); } private void updateState() { if (isEnabled() && !ApplicationManager.getApplication().isUnitTestMode()) { boolean requiresRestart = false; if (previousStateVersion < 2 && SystemInfo.isMac) { final MacKeyRepeat keyRepeat = MacKeyRepeat.getInstance(); final Boolean enabled = keyRepeat.isEnabled(); if (enabled == null || !enabled) { if (Messages.showYesNoDialog("Do you want to enable repeating keys in Mac OS X on press and hold " + "(requires restart)?\n\n" + "(You can do it manually by running 'defaults write -g " + "ApplePressAndHoldEnabled 0' in the console).", IDEAVIM_NOTIFICATION_TITLE, Messages.getQuestionIcon() ) == Messages.YES) { keyRepeat.setEnabled(true); requiresRestart = true; } } } if (previousStateVersion > 0 && previousStateVersion < 3) { final KeymapManagerEx manager = KeymapManagerEx.getInstanceEx(); Keymap keymap = null; if (previousKeyMap != null) { keymap = manager.getKeymap(previousKeyMap); } if (keymap == null) { keymap = manager.getKeymap(DefaultKeymap.getInstance().getDefaultKeymapName()); } assert keymap != null : "Default keymap not found"; new Notification( VimPlugin.IDEAVIM_STICKY_NOTIFICATION_ID, VimPlugin.IDEAVIM_NOTIFICATION_TITLE, String.format("IdeaVim plugin doesn't use the special \"Vim\" keymap any longer. " + "Switching to \"%s\" keymap.<br/><br/>" + "Now it is possible to set up:<br/>" + "<ul>" + "<li>Vim keys in your ~/.ideavimrc file using key mapping commands</li>" + "<li>IDE action shortcuts in \"File | Settings | Keymap\"</li>" + "<li>Vim or IDE handlers for conflicting shortcuts in <a href='#settings'>Vim Emulation</a> settings</li>" + "</ul>", keymap.getPresentableName()), NotificationType.INFORMATION, new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { ShowSettingsUtil.getInstance().editConfigurable((Project)null, new VimEmulationConfigurable()); } }).notify(null); manager.setActiveKeymap(keymap); } if (previousStateVersion > 0 && previousStateVersion < 4) { new Notification( VimPlugin.IDEAVIM_STICKY_NOTIFICATION_ID, VimPlugin.IDEAVIM_NOTIFICATION_TITLE, "The ~/.vimrc file is no longer read by default, use ~/.ideavimrc instead. You can read it from your " + "~/.ideavimrc using this command:<br/><br/>" + "<code>source ~/.vimrc</code>", NotificationType.INFORMATION).notify(null); } if (requiresRestart) { final ApplicationEx app = ApplicationManagerEx.getApplicationEx(); app.restart(); } } } /** * This sets up some listeners so we can handle various events that occur */ private void setupListeners() { DocumentManager.getInstance().addDocumentListener(new MarkGroup.MarkUpdater()); DocumentManager.getInstance().addDocumentListener(new SearchGroup.DocumentSearchListener()); EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); isBlockCursor = editor.getSettings().isBlockCursor(); isAnimatedScrolling = editor.getSettings().isAnimatedScrolling(); isRefrainFromScrolling = editor.getSettings().isRefrainFromScrolling(); EditorData.initializeEditor(editor); DocumentManager.getInstance().addListeners(editor.getDocument()); key.registerRequiredShortcutKeys(editor); if (VimPlugin.isEnabled()) { // Turn on insert mode if editor doesn't have any file if (!EditorData.isFileEditor(editor) && editor.getDocument().isWritable() && !CommandState.inInsertMode(editor)) { KeyHandler.getInstance().handleKey(editor, KeyStroke.getKeyStroke('i'), new EditorDataContext(editor)); } editor.getSettings().setBlockCursor(!CommandState.inInsertMode(editor)); editor.getSettings().setAnimatedScrolling(ANIMATED_SCROLLING_VIM_VALUE); editor.getSettings().setRefrainFromScrolling(REFRAIN_FROM_SCROLLING_VIM_VALUE); } } @Override public void editorReleased(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); EditorData.uninitializeEditor(editor); key.unregisterShortcutKeys(editor); editor.getSettings().setAnimatedScrolling(isAnimatedScrolling); editor.getSettings().setRefrainFromScrolling(isRefrainFromScrolling); DocumentManager.getInstance().removeListeners(editor.getDocument()); } }, myApp); // Since the Vim plugin custom actions aren't available to the call to <code>initComponent()</code> // we need to force the generation of the key map when the first project is opened. ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() { @Override public void projectOpened(@NotNull final Project project) { project.getMessageBus().connect() .subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MotionGroup.MotionEditorChange()); project.getMessageBus().connect() .subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileGroup.SelectionCheck()); project.getMessageBus().connect() .subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new SearchGroup.EditorSelectionCheck()); } @Override public void projectClosed(final Project project) { } }); CommandProcessor.getInstance().addCommandListener(DelegateCommandListener.getInstance()); } private void setCursors(boolean isBlock) { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { // Vim plugin should be turned on in insert mode ((EditorEx)editor).setInsertMode(true); editor.getSettings().setBlockCursor(isBlock); } } private void setAnimatedScrolling(boolean isOn) { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { editor.getSettings().setAnimatedScrolling(isOn); } } private void setRefrainFromScrolling(boolean isOn) { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { editor.getSettings().setRefrainFromScrolling(isOn); } } }
Extracted and inlined some variables
src/com/maddyhome/idea/vim/VimPlugin.java
Extracted and inlined some variables
Java
mit
6d64d6246eaa604dc0d2d4e213cbff73cde0e997
0
zhangls2014/Weibo
package cn.zhangls.android.weibo.ui.home.weibo; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import cn.zhangls.android.weibo.R; import cn.zhangls.android.weibo.databinding.ItemFgHomeRtHavePicBinding; import cn.zhangls.android.weibo.databinding.ItemFgHomeRtNoPicBinding; import cn.zhangls.android.weibo.databinding.ItemFgHomeStatusHavePicBinding; import cn.zhangls.android.weibo.databinding.ItemFgHomeStatusNoPicBinding; import cn.zhangls.android.weibo.network.model.Status; import cn.zhangls.android.weibo.network.model.StatusList; import cn.zhangls.android.weibo.ui.user.UserActivity; import cn.zhangls.android.weibo.utils.TextUtil; /** * Created by zhangls on 2016/10/20. * */ class WeiboRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener { /** * 上下文对象 */ private Context mContext; /** * 数据 */ private StatusList publicData; /** * RecyclerView Item 点击事件接口实例 */ private OnItemClickListener mOnItemClickListener = null; private RecyclerView mRecyclerView = null; /** * ItemViewType 微博不包含图片 */ private static final int ITEM_VIEW_TYPE_STATUS_NO_PIC = 0; /** * ItemViewType 微博包含图片 */ private static final int ITEM_VIEW_TYPE_STATUS_HAVE_PIC = 1; /** * ItemViewType 被转发微博不包含图片 */ private static final int ITEM_VIEW_TYPE_RETWEETED_STATUS_NO_PIC = 2; /** * ItemViewType 被转发微博包含图片 */ private static final int ITEM_VIEW_TYPE_RETWEETED_STATUS_HAVE_PIC = 3; WeiboRecyclerAdapter(Context mContext, StatusList publicData) { this.mContext = mContext; this.publicData = publicData; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case ITEM_VIEW_TYPE_STATUS_NO_PIC: return createStatusNoPicHolder(parent); case ITEM_VIEW_TYPE_STATUS_HAVE_PIC: return createStatusHavePicHolder(parent); case ITEM_VIEW_TYPE_RETWEETED_STATUS_NO_PIC: return createRtNoPicHolder(parent); case ITEM_VIEW_TYPE_RETWEETED_STATUS_HAVE_PIC: return createRtHavePicHolder(parent); default: return createStatusNoPicHolder(parent); } } /** * 创建ViewHolder * * @param parent 父容器 * @return StatusNoPicHolder */ private StatusNoPicHolder createStatusNoPicHolder(ViewGroup parent) { ItemFgHomeStatusNoPicBinding statusNoPicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_status_no_pic, parent, false ); StatusNoPicHolder statusNoPicHolder = new StatusNoPicHolder(statusNoPicBinding.getRoot()); statusNoPicHolder.setBinding(statusNoPicBinding); statusNoPicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return statusNoPicHolder; } /** * 创建ViewHolder * * @param parent 父容器 * @return StatusHavePicHolder */ private StatusHavePicHolder createStatusHavePicHolder(ViewGroup parent) { ItemFgHomeStatusHavePicBinding statusHavePicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_status_have_pic, parent, false ); StatusHavePicHolder statusHavePicHolder = new StatusHavePicHolder(statusHavePicBinding.getRoot()); statusHavePicHolder.setBinding(statusHavePicBinding); statusHavePicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return statusHavePicHolder; } /** * 创建ViewHolder * * @param parent 父容器 * @return RtNoPicHolder */ private RtNoPicHolder createRtNoPicHolder(ViewGroup parent) { ItemFgHomeRtNoPicBinding rtNoPicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_rt_no_pic, parent, false ); RtNoPicHolder rtNoPicHolder = new RtNoPicHolder(rtNoPicBinding.getRoot()); rtNoPicHolder.setBinding(rtNoPicBinding); rtNoPicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return rtNoPicHolder; } /** * 创建ViewHolder * * @param parent 父容器 * @return RtHavePicHolder */ private RtHavePicHolder createRtHavePicHolder(ViewGroup parent) { ItemFgHomeRtHavePicBinding rtHavePicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_rt_have_pic, parent, false ); RtHavePicHolder rtHavePicHolder = new RtHavePicHolder(rtHavePicBinding.getRoot()); rtHavePicHolder.setBinding(rtHavePicBinding); rtHavePicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return rtHavePicHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { //为Status注入上下文对象 Status status = publicData.getStatuses().get(position); status.setContext(mContext); if (holder instanceof StatusNoPicHolder) { showStatusNoPic((StatusNoPicHolder) holder, status); } else if (holder instanceof StatusHavePicHolder) { showStatusHavePic((StatusHavePicHolder) holder, status); } else if (holder instanceof RtNoPicHolder) { showRtNoPic((RtNoPicHolder) holder, status); } else if (holder instanceof RtHavePicHolder) { showRtsHavePic((RtHavePicHolder) holder, status); } else { System.out.println("===类型出错==="); } } /** * 显示微博,无图片,无被转发微博 * * @param holder StatusNoPicHolder * @param status Status */ private void showStatusNoPic(StatusNoPicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); } /** * 显示微博,有图片,无被转发微博 * * @param holder StatusHavePicHolder * @param status Status */ private void showStatusHavePic(StatusHavePicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); // 设置图片 RecyclerView PictureRecyclerAdapter picAdapter = new PictureRecyclerAdapter(mContext, status); holder.binding.rvWeibo9Pic.setLayoutManager(new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false)); holder.binding.rvWeibo9Pic.addItemDecoration(new SpaceItemDecoration(mContext)); holder.binding.rvWeibo9Pic.setAdapter(picAdapter); } /** * 显示微博,有被转发微博(无图片) * * @param holder RtNoPicHolder * @param status Status */ private void showRtNoPic(RtNoPicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); // 设置转发微博 // 设置数据 StringBuffer buffer = new StringBuffer(); if (status.getRetweeted_status().getUser() != null) { buffer.append("@"); buffer.append(status.getRetweeted_status().getUser().getName() != null ? status.getRetweeted_status().getUser().getName() : status.getRetweeted_status().getUser().getScreen_name() != null ? status.getRetweeted_status().getUser().getScreen_name() : "") .append(" :"); } buffer.append(status.getRetweeted_status().getText()); holder.binding.tvRetweetedText.setText( TextUtil.convertText( mContext, buffer.toString(), (int) holder.binding.tvRetweetedText.getTextSize() ) ); } /** * 显示微博,有图片,有被转发微博(有图片) * * @param holder RtHavePicHolder * @param status Status */ private void showRtsHavePic(RtHavePicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); // 设置转发微博 // 设置数据 StringBuffer buffer = new StringBuffer(); if (status.getRetweeted_status().getUser() != null) {// 如果不存在,则该被转发微博被删除 buffer.append("@"); buffer.append(status.getRetweeted_status().getUser().getName() != null ? status.getRetweeted_status().getUser().getName() : status.getRetweeted_status().getUser().getScreen_name() != null ? status.getRetweeted_status().getUser().getScreen_name() : "") .append(" :"); } buffer.append(status.getRetweeted_status().getText()); holder.binding.tvRetweetedText.setText( TextUtil.convertText( mContext, buffer.toString(), (int) holder.binding.tvRetweetedText.getTextSize() ) ); // 设置图片 RecyclerView PictureRecyclerAdapter picAdapter = new PictureRecyclerAdapter(mContext, status.getRetweeted_status()); holder.binding.rvWeibo9Pic.setLayoutManager(new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false)); holder.binding.rvWeibo9Pic.addItemDecoration(new SpaceItemDecoration(mContext)); holder.binding.rvWeibo9Pic.setAdapter(picAdapter); } @Override public int getItemCount() { return publicData.getStatuses() != null ? publicData.getStatuses().size() : 0; } @Override public void onClick(View v) { if (mRecyclerView != null && mOnItemClickListener != null) { int position = mRecyclerView.getChildAdapterPosition((View) v.getParent()); mOnItemClickListener.OnItemClick(mRecyclerView, v, position); } } /** * Return the view type of the item at <code>position</code> for the purposes * of view recycling. * <p> * <p>The default implementation of this method returns 0, making the assumption of * a single view type for the adapter. Unlike ListView adapters, types need not * be contiguous. Consider using id resources to uniquely identify item view types. * * ItemViewType: * 0:微博不包含图片 * 1:微博包含图片 * 2:被转发微博不包含图片 * 3:欸转发微博包含图片 * * @param position position to query * @return integer value identifying the type of the view needed to represent the item at * <code>position</code>. Type codes need not be contiguous. */ @Override public int getItemViewType(int position) { Status status = publicData.getStatuses().get(position); if (status.getRetweeted_status() != null && status.getRetweeted_status().getPic_urls() != null && !status.getRetweeted_status().getPic_urls().isEmpty()) {// 被转发微博存在图片 return ITEM_VIEW_TYPE_RETWEETED_STATUS_HAVE_PIC; } else if (status.getRetweeted_status() != null && status.getRetweeted_status().getPic_urls() == null) {// 被转发微博不存在图片 return ITEM_VIEW_TYPE_RETWEETED_STATUS_NO_PIC; } else if (status.getRetweeted_status() == null && status.getPic_urls() != null && !status.getPic_urls().isEmpty()) {// 微博包含图片 return ITEM_VIEW_TYPE_STATUS_HAVE_PIC; } else {// 微博不包含图片 return ITEM_VIEW_TYPE_STATUS_NO_PIC; } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); mRecyclerView = recyclerView; } @Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); mRecyclerView = null; } /** * 设置RecyclerView Item 点击事件监听 * * @param mOnItemClickListener 监听接口 */ public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) { this.mOnItemClickListener = mOnItemClickListener; } /** * 刷新所有数据 */ void changeData(StatusList publicData) { if (publicData.getStatuses().size() > 0) { this.publicData = publicData; notifyDataSetChanged(); } } /** * RecyclerView Item 点击事件接口 */ interface OnItemClickListener { void OnItemClick(RecyclerView recyclerView, View view, int position); } /** * ViewHolder * StatusNoPic */ private static class StatusNoPicHolder extends RecyclerView.ViewHolder { private ItemFgHomeStatusNoPicBinding binding; StatusNoPicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeStatusNoPicBinding binding) { this.binding = binding; } } /** * ViewHolder * StatusHavePic */ private static class StatusHavePicHolder extends RecyclerView.ViewHolder { private ItemFgHomeStatusHavePicBinding binding; StatusHavePicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeStatusHavePicBinding binding) { this.binding = binding; } } /** * ViewHolder * RetwetedStatusNoPic */ private static class RtNoPicHolder extends RecyclerView.ViewHolder { private ItemFgHomeRtNoPicBinding binding; RtNoPicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeRtNoPicBinding binding) { this.binding = binding; } } /** * ViewHolder * RetwetedStatusHavePic */ private static class RtHavePicHolder extends RecyclerView.ViewHolder { private ItemFgHomeRtHavePicBinding binding; RtHavePicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeRtHavePicBinding binding) { this.binding = binding; } } }
app/src/main/java/cn/zhangls/android/weibo/ui/home/weibo/WeiboRecyclerAdapter.java
package cn.zhangls.android.weibo.ui.home.weibo; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import cn.zhangls.android.weibo.R; import cn.zhangls.android.weibo.databinding.ItemFgHomeRtHavePicBinding; import cn.zhangls.android.weibo.databinding.ItemFgHomeRtNoPicBinding; import cn.zhangls.android.weibo.databinding.ItemFgHomeStatusHavePicBinding; import cn.zhangls.android.weibo.databinding.ItemFgHomeStatusNoPicBinding; import cn.zhangls.android.weibo.network.model.Status; import cn.zhangls.android.weibo.network.model.StatusList; import cn.zhangls.android.weibo.ui.user.UserActivity; import cn.zhangls.android.weibo.utils.TextUtil; /** * Created by zhangls on 2016/10/20. * */ class WeiboRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener { /** * 上下文对象 */ private Context mContext; /** * 数据 */ private StatusList publicData; /** * RecyclerView Item 点击事件接口实例 */ private OnItemClickListener mOnItemClickListener = null; private RecyclerView mRecyclerView = null; /** * ItemViewType 微博不包含图片 */ private static final int ITEM_VIEW_TYPE_STATUS_NO_PIC = 0; /** * ItemViewType 微博包含图片 */ private static final int ITEM_VIEW_TYPE_STATUS_HAVE_PIC = 1; /** * ItemViewType 被转发微博不包含图片 */ private static final int ITEM_VIEW_TYPE_RETWEETED_STATUS_NO_PIC = 2; /** * ItemViewType 被转发微博包含图片 */ private static final int ITEM_VIEW_TYPE_RETWEETED_STATUS_HAVE_PIC = 3; WeiboRecyclerAdapter(Context mContext, StatusList publicData) { this.mContext = mContext; this.publicData = publicData; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case ITEM_VIEW_TYPE_STATUS_NO_PIC: return createStatusNoPicHolder(parent); case ITEM_VIEW_TYPE_STATUS_HAVE_PIC: return createStatusHavePicHolder(parent); case ITEM_VIEW_TYPE_RETWEETED_STATUS_NO_PIC: return createRtNoPicHolder(parent); case ITEM_VIEW_TYPE_RETWEETED_STATUS_HAVE_PIC: return createRtHavePicHolder(parent); default: return createStatusNoPicHolder(parent); } } /** * 创建ViewHolder * * @param parent 父容器 * @return StatusNoPicHolder */ private StatusNoPicHolder createStatusNoPicHolder(ViewGroup parent) { ItemFgHomeStatusNoPicBinding statusNoPicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_status_no_pic, parent, false ); StatusNoPicHolder statusNoPicHolder = new StatusNoPicHolder(statusNoPicBinding.getRoot()); statusNoPicHolder.setBinding(statusNoPicBinding); statusNoPicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return statusNoPicHolder; } /** * 创建ViewHolder * * @param parent 父容器 * @return StatusHavePicHolder */ private StatusHavePicHolder createStatusHavePicHolder(ViewGroup parent) { ItemFgHomeStatusHavePicBinding statusHavePicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_status_have_pic, parent, false ); StatusHavePicHolder statusHavePicHolder = new StatusHavePicHolder(statusHavePicBinding.getRoot()); statusHavePicHolder.setBinding(statusHavePicBinding); statusHavePicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return statusHavePicHolder; } /** * 创建ViewHolder * * @param parent 父容器 * @return RtNoPicHolder */ private RtNoPicHolder createRtNoPicHolder(ViewGroup parent) { ItemFgHomeRtNoPicBinding rtNoPicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_rt_no_pic, parent, false ); RtNoPicHolder rtNoPicHolder = new RtNoPicHolder(rtNoPicBinding.getRoot()); rtNoPicHolder.setBinding(rtNoPicBinding); rtNoPicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return rtNoPicHolder; } /** * 创建ViewHolder * * @param parent 父容器 * @return RtHavePicHolder */ private RtHavePicHolder createRtHavePicHolder(ViewGroup parent) { ItemFgHomeRtHavePicBinding rtHavePicBinding = DataBindingUtil.inflate( LayoutInflater.from(mContext), R.layout.item_fg_home_rt_have_pic, parent, false ); RtHavePicHolder rtHavePicHolder = new RtHavePicHolder(rtHavePicBinding.getRoot()); rtHavePicHolder.setBinding(rtHavePicBinding); rtHavePicHolder.binding.llWeiboContentList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mContext.startActivity(new Intent(mContext, UserActivity.class)); } }); return rtHavePicHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { //为Status注入上下文对象 Status status = publicData.getStatuses().get(position); status.setContext(mContext); if (holder instanceof StatusNoPicHolder) { showStatusNoPic((StatusNoPicHolder) holder, status); } else if (holder instanceof StatusHavePicHolder) { showStatusHavePic((StatusHavePicHolder) holder, status); } else if (holder instanceof RtNoPicHolder) { showRtNoPic((RtNoPicHolder) holder, status); } else if (holder instanceof RtHavePicHolder) { showRtsHavePic((RtHavePicHolder) holder, status); } else { System.out.println("===类型出错==="); } } /** * 显示微博,无图片,无被转发微博 * * @param holder StatusNoPicHolder * @param status Status */ private void showStatusNoPic(StatusNoPicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); } /** * 显示微博,有图片,无被转发微博 * * @param holder StatusHavePicHolder * @param status Status */ private void showStatusHavePic(StatusHavePicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); // 设置图片 RecyclerView PictureRecyclerAdapter picAdapter = new PictureRecyclerAdapter(mContext, status); holder.binding.rvWeibo9Pic.setLayoutManager(new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false)); holder.binding.rvWeibo9Pic.addItemDecoration(new SpaceItemDecoration(mContext)); holder.binding.rvWeibo9Pic.setAdapter(picAdapter); } /** * 显示微博,有被转发微博(无图片) * * @param holder RtNoPicHolder * @param status Status */ private void showRtNoPic(RtNoPicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); // 设置转发微博 // 设置数据 StringBuffer buffer = new StringBuffer(); if (status.getRetweeted_status().getUser() != null) { buffer.append("@"); buffer.append(status.getRetweeted_status().getUser().getName() != null ? status.getRetweeted_status().getUser().getName() : status.getRetweeted_status().getUser().getScreen_name() != null ? status.getRetweeted_status().getUser().getScreen_name() : "") .append(" :"); } buffer.append(status.getRetweeted_status().getText()); holder.binding.tvRetweetedText.setText( TextUtil.convertText( mContext, buffer.toString(), (int) holder.binding.tvRetweetedText.getTextSize() ) ); } /** * 显示微博,有图片,有被转发微博(有图片) * * @param holder RtHavePicHolder * @param status Status */ private void showRtsHavePic(RtHavePicHolder holder, Status status) { holder.binding.setStatus(status); holder.binding.setUser(status.getUser()); //设置微博头像 Glide.with(mContext) .load(holder.binding.getUser().getProfile_image_url()) .centerCrop() .crossFade() .dontAnimate() .error(R.drawable.avator_default) .placeholder(R.drawable.avator_default) .into(holder.binding.fgHomeRecyclerItemAvatar); //设置微博正文getBinding() holder.binding.tvWeiboText.setText(TextUtil.convertText(mContext, status.getText(), (int) holder.binding.tvWeiboText.getTextSize())); // 设置转发微博 // 设置数据 StringBuffer buffer = new StringBuffer(); if (status.getRetweeted_status().getUser() != null) {// 如果不存在,则该被转发微博被删除 buffer.append("@"); buffer.append(status.getRetweeted_status().getUser().getName() != null ? status.getRetweeted_status().getUser().getName() : status.getRetweeted_status().getUser().getScreen_name() != null ? status.getRetweeted_status().getUser().getScreen_name() : "") .append(" :"); } buffer.append(status.getRetweeted_status().getText()); holder.binding.tvRetweetedText.setText( TextUtil.convertText( mContext, buffer.toString(), (int) holder.binding.tvRetweetedText.getTextSize() ) ); // 设置图片 RecyclerView PictureRecyclerAdapter picAdapter = new PictureRecyclerAdapter(mContext, status.getRetweeted_status()); holder.binding.rvWeibo9Pic.setLayoutManager(new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false)); holder.binding.rvWeibo9Pic.addItemDecoration(new SpaceItemDecoration(mContext)); holder.binding.rvWeibo9Pic.setAdapter(picAdapter); } @Override public int getItemCount() { return publicData.getStatuses() != null ? publicData.getStatuses().size() : 0; } @Override public void onClick(View v) { if (mRecyclerView != null && mOnItemClickListener != null) { int position = mRecyclerView.getChildAdapterPosition((View) v.getParent()); mOnItemClickListener.OnItemClick(mRecyclerView, v, position); } } /** * Return the view type of the item at <code>position</code> for the purposes * of view recycling. * <p> * <p>The default implementation of this method returns 0, making the assumption of * a single view type for the adapter. Unlike ListView adapters, types need not * be contiguous. Consider using id resources to uniquely identify item view types. * * ItemViewType: * 0:微博不包含图片 * 1:微博包含图片 * 2:被转发微博不包含图片 * 3:欸转发微博包含图片 * * @param position position to query * @return integer value identifying the type of the view needed to represent the item at * <code>position</code>. Type codes need not be contiguous. */ @Override public int getItemViewType(int position) { Status status = publicData.getStatuses().get(position); if (status.getRetweeted_status() != null && status.getRetweeted_status().getPic_urls() != null && !status.getRetweeted_status().getPic_urls().isEmpty()) {// 被转发微博存在图片 return ITEM_VIEW_TYPE_RETWEETED_STATUS_HAVE_PIC; } else if (status.getRetweeted_status() != null && status.getRetweeted_status().getPic_urls() == null) {// 被转发微博不存在图片 return ITEM_VIEW_TYPE_RETWEETED_STATUS_NO_PIC; } else if (status.getRetweeted_status() == null && status.getPic_urls() != null && !status.getPic_urls().isEmpty()) {// 微博包含图片 return ITEM_VIEW_TYPE_STATUS_HAVE_PIC; } else {// 微博不包含图片 return ITEM_VIEW_TYPE_STATUS_NO_PIC; } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); mRecyclerView = recyclerView; } @Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); mRecyclerView = null; } /** * 设置RecyclerView Item 点击事件监听 * * @param mOnItemClickListener 监听接口 */ public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) { this.mOnItemClickListener = mOnItemClickListener; } /** * 刷新所有数据 */ void changeData(StatusList publicData) { if (publicData.getStatuses().size() > 0) { this.publicData = publicData; notifyDataSetChanged(); } } /** * RecyclerView Item 点击事件接口 */ interface OnItemClickListener { void OnItemClick(RecyclerView recyclerView, View view, int position); } /** * ViewHolder * StatusNoPic */ private static class StatusNoPicHolder extends RecyclerView.ViewHolder { private ItemFgHomeStatusNoPicBinding binding; StatusNoPicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeStatusNoPicBinding binding) { this.binding = binding; } } /** * ViewHolder * StatusHavePic */ private static class StatusHavePicHolder extends RecyclerView.ViewHolder { private ItemFgHomeStatusHavePicBinding binding; StatusHavePicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeStatusHavePicBinding binding) { this.binding = binding; } } /** * ViewHolder * RetwetedStatusNoPic */ private static class RtNoPicHolder extends RecyclerView.ViewHolder { private ItemFgHomeRtNoPicBinding binding; RtNoPicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeRtNoPicBinding binding) { this.binding = binding; } } /** * ViewHolder * RetwetedStatusHavePic */ private static class RtHavePicHolder extends RecyclerView.ViewHolder { private ItemFgHomeRtHavePicBinding binding; RtHavePicHolder(View itemView) { super(itemView); } void setBinding(ItemFgHomeRtHavePicBinding binding) { this.binding = binding; } } }
微博显示Bug修复
app/src/main/java/cn/zhangls/android/weibo/ui/home/weibo/WeiboRecyclerAdapter.java
微博显示Bug修复
Java
epl-1.0
21cc55ccd1b099397c6c3897903834262eb2ede5
0
Alma-Sanchez/ChessAI2
//import necessary libraries import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Scanner; public class BoardMouseListener implements MouseListener{ static int globaldepth=4; //controlled depth, set to medium currently. Will determine diffuculty of AI. public static Chess chess; //position of mouse public static int posx, posy, posxfinal, posyfinal; //boolean so white always moves first public static boolean whiteturn = true; //using recursion to search and create tree public static String alphaBeta(int depth, int beta, int alpha, String move, int player){ String list=possiblemoves(); //base case. Lets the program know what to do if it reaches the end of possible moves //or if there are no possible moves if (depth==0 || list.length()==0) { return move+(rating()*(player*2-1)); } //sort(the best that we can) later to help speed up alpha beta choosing the best move player=1-player;//either 1 or 0, switches who the current player is //Go through every possible move for (int i=0;i<list.length();i+=5){ //make a move makemove(list.substring(i,i+5)); //flip the chess board to predict the human player's moves flipboard(); //the recursion part, gives the function different depth and move String returnString=alphaBeta(depth-1, beta, alpha, list.substring(i,i+5), player); int value=Integer.valueOf(returnString.substring(5)); //flip board back to normal flipboard(); undomove(list.substring(i,i+5)); //else refers to other player if (player==0) { //if it's a good move return the move value if (value<=beta) { beta=value; if (depth==globaldepth){ move=returnString.substring(0,5); } } } else { if (value>alpha){ alpha=value; if (depth==globaldepth) { move=returnString.substring(0,5); } } } if (alpha>=beta) { if (player==0) { return move+beta; } else { return move+alpha; } } } //incase the algorithm found no good move, just return what it has if (player==0) { return move+beta; } else { return move+alpha; } } public static String possiblemoves(){ //finds possible moves for each peice String themoves=""; // tells the alpha beta alogritm what moves to evaluate int count=0; for (int i=0; i<8; i++){ for (int j=0; j<8; j++){ if (Chess.pieces[i][j]!=null){ for (int k=0; k<8; k++){ for (int l=0; l<8; l++){ //System.out.println("Initial y is "+ i+" Initial x is "+j+ " Final y is "+k+ " Final x is "+ l); if (Chess.pieces[i][j].canMove(j, i, l ,k)){ count++; String istring=Integer.toString(i); String jstring=Integer.toString(j); String kstring=Integer.toString(k); String lstring=Integer.toString(l); if (Chess.pieces[l][k]!=null){ String newmove=jstring+istring+lstring+kstring+Chess.pieces[l][k].pieceletter; if (count<100){ themoves+=newmove; } } else{ String newmove=jstring+istring+lstring+kstring+" "; if (count<100){ themoves+=newmove; } } } } } } } } return themoves; } public static int rating(){ //System.out.print("What is the score: "); //Scanner sc=new Scanner(System.in); return 0; } //flips the board public static void flipboard(){ for (int i=0; i<32; i++){ int r= i/8; int c= i%8; // System.out.println(r); // System.out.println(c); // System.out.println(chess.pieces[c][r].pieceletter); Piece temp=chess.pieces[c][r]; chess.pieces[c][r]=chess.pieces[7-c][7-r]; chess.pieces[7-c][7-r]=temp; //if (Character.isUpperCase(chess.pieces[c][r].pieceletter.charAt(0))) if(chess.pieces[c][r]!=null){ if (chess.pieces[c][r].isWhite){ chess.pieces[c][r].isWhite=false; } else{ chess.pieces[c][r].isWhite=true; } } } } public static void makemove(String moveinfo){ int posx=Character.getNumericValue(moveinfo.charAt(0)); int posy=Character.getNumericValue(moveinfo.charAt(1)); int posxfinal=Character.getNumericValue(moveinfo.charAt(2)); int posyfinal=Character.getNumericValue(moveinfo.charAt(3)); //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); System.out.println(test); } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); } } } } public static void undomove(String moveinfo){ posx=Character.getNumericValue(moveinfo.charAt(0)); posy=Character.getNumericValue(moveinfo.charAt(1)); posxfinal=Character.getNumericValue(moveinfo.charAt(2)); posyfinal=Character.getNumericValue(moveinfo.charAt(3)); chess.pieces[posy][posx]=chess.pieces[posyfinal][posxfinal]; //chess.pieces[posyfinal][posxfinal]=null; if (moveinfo.charAt(4)==' '){ Chess.pieces[posyfinal][posxfinal]=null; } else if (moveinfo.charAt(4)=='r'){ Chess.pieces[posyfinal][posxfinal]=new Rook(false, chess); } else if (moveinfo.charAt(4)=='R'){ Chess.pieces[posyfinal][posxfinal]=new Rook(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new Knight(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new Knight(true, chess); } else if (moveinfo.charAt(4)=='b'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(false, chess); } else if (moveinfo.charAt(4)=='B'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(true, chess); } else if (moveinfo.charAt(4)=='q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(false, chess); } else if (moveinfo.charAt(4)=='Q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new King(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new King(true, chess); } else if (moveinfo.charAt(4)=='p'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(false, chess); } else if(moveinfo.charAt(4)=='P'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(true, chess); } } public BoardMouseListener(Chess chess) { this.chess = chess; } public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { //equates initial mouse/piece position with tile position on board posx = e.getX() / 62; posy = e.getY() / 62; } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub //equates final mouse/piece position with tile position on board posxfinal = e.getX() / 62; posyfinal = e.getY() / 62; //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); } } } makemove(alphaBeta(globaldepth,1000000,-1000000,"",0)); } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } }
src/BoardMouseListener.java
import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Scanner; public class BoardMouseListener implements MouseListener { static int globaldepth=4; public static Chess chess; //position of mouse public static int posx, posy, posxfinal, posyfinal; //boolean so white always moves first public static boolean whiteturn = true; public static String alphaBeta(int depth, int beta, int alpha, String move, int player) { //return in the form of 1234b########## String list=possiblemoves(); //String list="1"; if (depth==0 || list.length()==0) { return move+(rating()*(player*2-1)); } //list=""; //System.out.print("How many moves are there: "); //Scanner sc=new Scanner(System.in); //int temp=sc.nextInt(); //for (int i=0;i<temp;i++) { // list+="1111b"; //} //sort later player=1-player;//either 1 or 0 for (int i=0;i<list.length();i+=5) { makemove(list.substring(i,i+5)); flipboard(); String returnString=alphaBeta(depth-1, beta, alpha, list.substring(i,i+5), player); int value=Integer.valueOf(returnString.substring(5)); flipboard(); undomove(list.substring(i,i+5)); if (player==0) { if (value<=beta) { beta=value; if (depth==globaldepth) {move=returnString.substring(0,5); } } } else { if (value>alpha) { alpha=value; if (depth==globaldepth) { move=returnString.substring(0,5); } } } if (alpha>=beta) { if (player==0) { return move+beta; } else { return move+alpha; } } } if (player==0) { return move+beta; } else { return move+alpha; } } /*String alphaBeta(int depth, int beta, int alpha, String move, int player ) { String list= possiblemoves(); //String list="1"; if (depth==0 || list.length()==0){ return move+(rating() *(player*2-1)); } //sort with be here list=""; System.out.print("How many moves are there: "); Scanner sc=new Scanner(System.in); int temp=sc.nextInt(); for (int i=0; i<temp; i++){ list="1111b"; } player=1-player; for (int i=0; i<list.length(); i+=5){ makemove(list.substring(i, i+5)); flipboard(); String returnstring= alphaBeta(depth-1, beta, alpha, list.substring(i, +i+5), player); int value= Integer.valueOf(returnstring.substring(5)); flipboard(); undomove(list.substring(i,i+5)); if (player==0){ if (value<=beta){ beta=value; if (depth==globaldepth){ move=returnstring.substring(0,5); } } } else{ if (value>=alpha){ alpha=value; if (depth==globaldepth){ move=returnstring.substring(0,5); } } } if (alpha>=beta){ if (player==0){ return move+beta; } else{ return move+alpha; } } } if (player==0){ return move+beta; } else{ return move+alpha; } }*/ public static String possiblemoves(){ String themoves=""; int count=0; for (int i=0; i<8; i++){ for (int j=0; j<8; j++){ if (Chess.pieces[i][j]!=null){ for (int k=0; k<8; k++){ for (int l=0; l<8; l++){ //System.out.println("Initial y is "+ i+" Initial x is "+j+ " Final y is "+k+ " Final x is "+ l); if (Chess.pieces[i][j].canMove(j, i, l ,k)){ count++; String istring=Integer.toString(i); String jstring=Integer.toString(j); String kstring=Integer.toString(k); String lstring=Integer.toString(l); if (Chess.pieces[l][k]!=null){ String newmove=jstring+istring+lstring+kstring+Chess.pieces[l][k].pieceletter; if (count<100){ themoves+=newmove; } } else{ String newmove=jstring+istring+lstring+kstring+" "; if (count<100){ themoves+=newmove; } } } } } } } } return themoves; } public static int rating(){ System.out.print("What is the score: "); Scanner sc=new Scanner(System.in); return sc.nextInt(); } public static void flipboard(){ String temp; for (int i=0; i<32; i++){ int r= i/8; int c= i%8; System.out.println(r); System.out.println(c); if (Character.isUpperCase(chess.pieces[c][r].pieceletter.charAt(0))) { temp=chess.pieces[c][r].pieceletter.toLowerCase(); } else{ temp=chess.pieces[c][r].pieceletter.toUpperCase(); } if (Character.isUpperCase(chess.pieces[7-c][7-r].pieceletter.charAt(0))) { chess.pieces[c][r].pieceletter=chess.pieces[7-c][7-r].pieceletter.toLowerCase(); } else{ chess.pieces[c][r].pieceletter=chess.pieces[7-c][7-r].pieceletter.toUpperCase(); } /*if (chess.pieces[c][r].pieceletter=="k" || chess.pieces[c][r].pieceletter=="K"){ int kingtempy=c; int kingtempx=r; }*/ chess.pieces[7-c][7-r].pieceletter=temp; } } public static void makemove(String moveinfo){ int posx=Character.getNumericValue(moveinfo.charAt(0)); int posy=Character.getNumericValue(moveinfo.charAt(1)); int posxfinal=Character.getNumericValue(moveinfo.charAt(2)); int posyfinal=Character.getNumericValue(moveinfo.charAt(3)); //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); System.out.println(test); } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); } } } } public static void undomove(String moveinfo){ posx=Character.getNumericValue(moveinfo.charAt(0)); posy=Character.getNumericValue(moveinfo.charAt(1)); posxfinal=Character.getNumericValue(moveinfo.charAt(2)); posyfinal=Character.getNumericValue(moveinfo.charAt(3)); chess.pieces[posy][posx]=chess.pieces[posyfinal][posxfinal]; if (moveinfo.charAt(4)==' '){ Chess.pieces[posyfinal][posxfinal]=null; } else if (moveinfo.charAt(4)=='r'){ Chess.pieces[posyfinal][posxfinal]=new Rook(false, chess); } else if (moveinfo.charAt(4)=='R'){ Chess.pieces[posyfinal][posxfinal]=new Rook(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new Knight(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new Knight(true, chess); } else if (moveinfo.charAt(4)=='b'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(false, chess); } else if (moveinfo.charAt(4)=='B'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(true, chess); } else if (moveinfo.charAt(4)=='q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(false, chess); } else if (moveinfo.charAt(4)=='Q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new King(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new King(true, chess); } else if (moveinfo.charAt(4)=='p'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(false, chess); } else if(moveinfo.charAt(4)=='P'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(true, chess); } } public BoardMouseListener(Chess chess) { this.chess = chess; } public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { //equates initial mouse/piece position with tile position on board posx = e.getX() / 62; posy = e.getY() / 62; } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub //equates final mouse/piece position with tile position on board posxfinal = e.getX() / 62; posyfinal = e.getY() / 62; //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); /*for (int i=0; i<100; i++){ if (test[i]!=null){ System.out.println(test[i]); } }*/ //System.out.println(possiblemoves()); /*if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move System.out.println(chess.pieces[posy][posx]); if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints board chess.theboard.repaint(); //insert ai here //System.out.println(possiblemoves()); } }*/ } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); /*for (int i=0; i<100; i++){ if (test[i]!=null){ System.out.println(test[i]); } }*/ //insert ai here /*if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints board chess.theboard.repaint(); } }*/ } } } makemove(alphaBeta(globaldepth,1000000,-1000000,"",0)); } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } }
comments
src/BoardMouseListener.java
comments
Java
lgpl-2.1
6d53ba7b77c2ebea62373723293f9053b2d9fe5c
0
postspectacular/toxiclibs,ruby-processing/toxiclibs,rekii/toxiclibs,rekii/toxiclibs,postspectacular/toxiclibs
/* * Some classes in this package have been partly inspired by & bits ported from * Python code written by Tom De Smedt & Frederik De Bleser for the "colors" library * of Nodebox.net. * * http://nodebox.net/code/index.php/Colors * * Copyright (c) 2006-2008 Karsten Schmidt <info at postspectacular.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * http://creativecommons.org/licenses/LGPL/2.1/ * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package toxi.color; import toxi.geom.Vec2D; import toxi.geom.Vec3D; import toxi.math.MathUtils; /** * Floating point color class with implicit RGB, HSV, CMYK access modes, * conversion and color theory utils. Based on the <a href="">Colors library</a> * for <a href="http:/Nodebox.net/">NodeBox</a> * */ public class TColor implements ReadonlyTColor { protected static final float INV60DEGREES = 60.0f / 360; protected static final float INV8BIT = 1f / 255; protected static final double EPS = .001; protected static final Vec2D[] RYB_WHEEL = new Vec2D[] { new Vec2D(0, 0), new Vec2D(15, 8), new Vec2D(30, 17), new Vec2D(45, 26), new Vec2D(60, 34), new Vec2D(75, 41), new Vec2D(90, 48), new Vec2D(105, 54), new Vec2D(120, 60), new Vec2D(135, 81), new Vec2D(150, 103), new Vec2D(165, 123), new Vec2D(180, 138), new Vec2D(195, 155), new Vec2D(210, 171), new Vec2D(225, 187), new Vec2D(240, 204), new Vec2D(255, 219), new Vec2D(270, 234), new Vec2D(285, 251), new Vec2D(300, 267), new Vec2D(315, 282), new Vec2D(330, 298), new Vec2D(345, 329), new Vec2D(360, 0) }; /** * Maximum rgb component value for a color to be classified as black. * * @see #isBlack() */ public static float BLACK_POINT = 0.08f; /** * Minimum rgb component value for a color to be classified as white. * * @see #isWhite() */ public static float WHITE_POINT = 1f; /** * Maximum saturations value for a color to be classified as grey * * @see #isGrey() */ public static float GREY_THRESHOLD = 0.01f; public static final ReadonlyTColor RED = newRGB(1, 0, 0); public static final ReadonlyTColor GREEN = newRGB(0, 1, 0); public static final ReadonlyTColor BLUE = newRGB(0, 0, 1); public static final ReadonlyTColor CYAN = newRGB(0, 1, 1); public static final ReadonlyTColor MAGENTA = newRGB(1, 0, 1); public static final ReadonlyTColor YELLOW = newRGB(1, 1, 0); public static final ReadonlyTColor BLACK = newRGB(0, 0, 0); public static final ReadonlyTColor WHITE = newRGB(1, 1, 1); /** * Converts CMYK floats into an RGB array. * * @param c * @param m * @param y * @param k * @return rgb array */ public static final float[] cmykToRGB(float c, float m, float y, float k) { return cmykToRGB(c, m, y, k, new float[3]); } /** * Converts CMYK floats into the given RGB array. * * @param c * @param m * @param y * @param k * @param rgb * @return rgb array */ public static final float[] cmykToRGB(float c, float m, float y, float k, float[] rgb) { rgb[0] = 1.0f - MathUtils.min(1.0f, c + k); rgb[1] = 1.0f - MathUtils.min(1.0f, m + k); rgb[2] = 1.0f - MathUtils.min(1.0f, y + k); return rgb; } /** * Converts hex string into a RGB array. * * @param hexRGB * @return rgb array */ public static final float[] hexToRGB(String hexRGB) { return hexToRGB(hexRGB, new float[3]); } public static final float[] hexToRGB(String hexRGB, float[] rgb) { try { int rgbInt = Integer.parseInt(hexRGB, 16); rgb[0] = ((rgbInt >> 16) & 0xff) * INV8BIT; rgb[1] = ((rgbInt >> 8) & 0xff) * INV8BIT; rgb[2] = (rgbInt & 0xff) * INV8BIT; } catch (NumberFormatException e) { rgb[0] = rgb[1] = rgb[2] = 0; } return rgb; } /** * Converts HSV values into RGB array. * * @param h * @param s * @param v * @return rgb array */ public static final float[] hsvToRGB(float h, float s, float v) { return hsvToRGB(h, s, v, new float[3]); } public static final float[] hsvToRGB(float h, float s, float v, float[] rgb) { if (Float.compare(s, 0.0f) == 0) { rgb[0] = rgb[1] = rgb[2] = v; } else { h /= INV60DEGREES; int i = (int) h; float f = h - i; float p = v * (1 - s); float q = v * (1 - s * f); float t = v * (1 - s * (1 - f)); if (i == 0) { rgb[0] = v; rgb[1] = t; rgb[2] = p; } else if (i == 1) { rgb[0] = q; rgb[1] = v; rgb[2] = p; } else if (i == 2) { rgb[0] = p; rgb[1] = v; rgb[2] = t; } else if (i == 3) { rgb[0] = p; rgb[1] = q; rgb[2] = v; } else if (i == 4) { rgb[0] = t; rgb[1] = p; rgb[2] = v; } else { rgb[0] = v; rgb[1] = p; rgb[2] = q; } } return rgb; } public static final float[] labToRGB(float l, float a, float b) { return labToRGB(l, a, b, new float[3]); } /** * Converts CIE Lab to RGB components. * * First we have to convert to XYZ color space. Conversion involves using a * white point, in this case D65 which represents daylight illumination. * * Algorithm adopted from: http://www.easyrgb.com/math.php * * @param l * @param a * @param b * @param rgb * @return rgb array */ public static final float[] labToRGB(float l, float a, float b, float[] rgb) { float y = (l + 16) / 116.0f; float x = a / 500.0f + y; float z = y - b / 200.0f; rgb[0] = x; rgb[1] = y; rgb[2] = z; for (int i = 0; i < 3; i++) { float p = (float) Math.pow(rgb[i], 3); if (p > 0.008856) { rgb[i] = p; } else { rgb[i] = (rgb[i] - 16 / 116.0f) / 7.787f; } } // Observer = 2, Illuminant = D65 x = rgb[0] * 0.95047f; y = rgb[1]; z = rgb[2] * 1.08883f; rgb[0] = x * 3.2406f + y * -1.5372f + z * -0.4986f; rgb[1] = x * -0.9689f + y * 1.8758f + z * 0.0415f; rgb[2] = x * 0.0557f + y * -0.2040f + z * 1.0570f; double tpow = 1 / 2.4; for (int i = 0; i < 3; i++) { if (rgb[i] > 0.0031308) { rgb[i] = (float) (1.055 * Math.pow(rgb[i], tpow) - 0.055); } else { rgb[i] = 12.92f * rgb[i]; } } return rgb; } /** * Factory method. Creates new color from ARGB int. * * @param argb * @return new color */ public static final TColor newARGB(int argb) { return newRGBA(((argb >> 16) & 0xff) * INV8BIT, ((argb >> 8) & 0xff) * INV8BIT, (argb & 0xff) * INV8BIT, (argb >>> 24) * INV8BIT); } /** * Factory method. Creates new color from CMYK values. * * @param c * @param m * @param y * @param k * @return new color */ public static final TColor newCMYK(float c, float m, float y, float k) { return newCMYKA(c, m, y, k, 1); } /** * Factory method. Creates new color from CMYK + alpha values. * * @param c * @param m * @param y * @param k * @param a * @return new color */ public static final TColor newCMYKA(float c, float m, float y, float k, float a) { TColor col = new TColor(); col.setCMYK(new float[] { c, m, y, k }); col.alpha = MathUtils.clip(a, 0, 1); return col; } /** * Factory method. Creates a new shade of gray + alpha. * * @param gray * @return new color. */ public static final TColor newGray(float gray) { return newGrayAlpha(gray, 1); } public static final TColor newGrayAlpha(float gray, float alpha) { TColor c = new TColor(); c.setRGB(new float[] { gray, gray, gray }); c.alpha = alpha; return c; } /** * Factory method. New color from hex string. * * @param hexRGB * @return new color */ public static final TColor newHex(String hexRGB) { TColor c = new TColor(); c.setRGB(hexToRGB(hexRGB)); c.alpha = 1; return c; } /** * Factory method. New color from hsv values. * * @param h * @param s * @param v * @return new color */ public static final TColor newHSV(float h, float s, float v) { return newHSVA(h, s, v, 1); } public static ReadonlyTColor newHSV(Hue h, float s, float v) { return newHSV(h.getHue(), s, v); } public static final TColor newHSVA(float h, float s, float v, float a) { TColor c = new TColor(); c.setHSV(h, s, v); c.alpha = MathUtils.clip(a, 0, 1); return c; } /** * Factory method. Creates new random color. Alpha is always 1.0. * * @return random color */ public static final TColor newRandom() { return newRGBA(MathUtils.random(1f), MathUtils.random(1f), MathUtils .random(1f), 1); } /** * Factory method. Creates new color from RGB values. Alpha is set to 1.0. * * @param r * @param g * @param b * @return new color */ public static final TColor newRGB(float r, float g, float b) { return newRGBA(r, g, b, 1); } public static final TColor newRGBA(float r, float g, float b, float a) { TColor c = new TColor(); c.setRGB(new float[] { r, g, b }); c.alpha = MathUtils.clip(a, 0, 1); return c; } /** * Converts the RGB values into a CMYK array. * * @param r * @param g * @param b * @return cmyk array */ public static final float[] rgbToCMYK(float r, float g, float b) { return rgbToCMYK(r, g, b, new float[4]); } public static final float[] rgbToCMYK(float r, float g, float b, float[] cmyk) { cmyk[0] = 1 - r; cmyk[1] = 1 - g; cmyk[2] = 1 - b; cmyk[3] = MathUtils.min(cmyk[0], cmyk[1], cmyk[2]); cmyk[0] = MathUtils.clip(cmyk[0] - cmyk[3], 0, 1); cmyk[1] = MathUtils.clip(cmyk[1] - cmyk[3], 0, 1); cmyk[2] = MathUtils.clip(cmyk[2] - cmyk[3], 0, 1); cmyk[3] = MathUtils.clip(cmyk[3], 0, 1); return cmyk; } /** * Formats the RGB float values into hex integers. * * @param r * @param g * @param b * @return hex string */ public static final String rgbToHex(float r, float g, float b) { String hex = Integer.toHexString((int) (MathUtils.clip(r, 0, 1) * 0xff)) + Integer .toHexString((int) (MathUtils.clip(g, 0, 1) * 0xff)) + Integer .toHexString((int) (MathUtils.clip(b, 0, 1) * 0xff)); return hex; } /** * Converts the RGB values into an HSV array. * * @param r * @param g * @param b * @return hsv array */ public static final float[] rgbToHSV(float r, float g, float b) { return rgbToHSV(r, g, b, new float[3]); } public static final float[] rgbToHSV(float r, float g, float b, float[] hsv) { float h = 0, s = 0; float v = MathUtils.max(r, g, b); float d = v - MathUtils.min(r, g, b); if (v != 0.0) { s = d / v; } if (s != 0.0) { if (Float.compare(r, v) == 0) { h = (g - b) / d; } else if (Float.compare(g, v) == 0) { h = 2 + (b - r) / d; } else { h = 4 + (r - g) / d; } } h *= INV60DEGREES; if (h < 0) { h += 1.0f; } hsv[0] = h; hsv[1] = s; hsv[2] = v; return hsv; } protected float[] rgb; protected float[] cmyk; protected float[] hsv; public float alpha; protected TColor() { rgb = new float[3]; hsv = new float[3]; cmyk = new float[4]; } /** * Creates a deep copy of the given color. * * @param c */ public TColor(ReadonlyTColor c) { this(); float[] buffer = c.toCMYKAArray(null); System.arraycopy(buffer, 0, cmyk, 0, 4); System.arraycopy(c.toHSVAArray(buffer), 0, hsv, 0, 3); System.arraycopy(c.toRGBAArray(buffer), 0, rgb, 0, 3); this.alpha = c.alpha(); } /** * Changes the brightness of the color by the given amount in the direction * towards either the black or white point (depending on if current * brightness >= 50%) * * @param amount * @return itself */ public ReadonlyTColor adjustConstrast(float amount) { return hsv[2] < 0.5 ? darken(amount) : lighten(amount); } /** * Adds the given HSV values as offsets to the current color. Hue will * automatically wrap. * * @param h * @param s * @param v * @return itself */ public ReadonlyTColor adjustHSV(float h, float s, float v) { return setHSV(new float[] { hsv[0] + h, hsv[1] + s, hsv[2] + v }); } /** * Adds the given RGB values as offsets to the current color. TColor will * clip at black or white. * * @param r * @param g * @param b * @return itself */ public ReadonlyTColor adjustRGB(float r, float g, float b) { return setRGB(new float[] { rgb[0] + r, rgb[1] + g, rgb[2] + b }); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#alpha() */ public float alpha() { return alpha; } /** * Rotates this color by a random amount (not exceeding the one specified) * and creates variations in saturation and brightness based on the 2nd * parameter. * * @param theta * max. rotation angle (in radians) * @param delta * max. sat/bri variance * @return itself */ public TColor analog(float theta, float delta) { return analog(MathUtils.degrees(theta), delta); } public TColor analog(int angle, float delta) { rotateRYB((int) (angle * MathUtils.normalizedRandom())); hsv[1] += delta * MathUtils.normalizedRandom(); hsv[2] += delta * MathUtils.normalizedRandom(); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#black() */ public float black() { return cmyk[0]; } /** * Blends the color with the given one by the stated amount * * @param c * target color * @param t * interpolation factor * @return itself */ public TColor blend(ReadonlyTColor c, float t) { float[] crgb = c.toRGBAArray(null); rgb[0] += (crgb[0] - rgb[0]) * t; rgb[1] += (crgb[1] - rgb[1]) * t; rgb[2] += (crgb[2] - rgb[2]) * t; alpha += (c.alpha() - alpha) * t; return setRGB(rgb); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#blue() */ public float blue() { return rgb[2]; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#brightness() */ public float brightness() { return hsv[2]; } /** * @return ifself, as complementary color */ public TColor complement() { return rotateRYB(180); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#copy() */ public TColor copy() { return new TColor(this); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#cyan() */ public float cyan() { return cmyk[0]; } /** * Reduces the color's brightness by the given amount (e.g 0.1 = 10% * darker). * * @param step * @return itself */ public TColor darken(float step) { hsv[2] = MathUtils.clip(hsv[2] - step, 0, 1); return setHSV(hsv); } /** * Reduced the color's saturation by the given amount. * * @param step * @return itself */ public TColor desaturate(float step) { hsv[1] = MathUtils.clip(hsv[1] - step, 0, 1); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#distanceToCMYK(toxi.color.TColor) */ public float distanceToCMYK(ReadonlyTColor c) { float[] ccmyk = c.toCMYKAArray(null); float dc = cmyk[0] - ccmyk[0]; float dm = cmyk[1] - ccmyk[1]; float dy = cmyk[2] - ccmyk[2]; float dk = cmyk[3] - ccmyk[3]; return (float) Math.sqrt(dc * dc + dm * dm + dy * dy + dk * dk); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#distanceToHSV(toxi.color.TColor) */ public float distanceToHSV(ReadonlyTColor c) { float hue = hsv[0] * MathUtils.TWO_PI; float hue2 = c.hue() * MathUtils.TWO_PI; Vec3D v1 = new Vec3D((MathUtils.cos(hue) * hsv[1]), (MathUtils.sin(hue) * hsv[1]), hsv[2]); Vec3D v2 = new Vec3D((MathUtils.cos(hue2) * c.saturation()), (MathUtils .sin(hue2) * c.saturation()), c.brightness()); return v1.distanceTo(v2); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#distanceToRGB(toxi.color.TColor) */ public float distanceToRGB(ReadonlyTColor c) { float[] crgb = c.toRGBAArray(null); float dr = rgb[0] - crgb[0]; float dg = rgb[1] - crgb[1]; float db = rgb[2] - crgb[2]; return (float) Math.sqrt(dr * dr + dg * dg + db * db); } @Override public boolean equals(Object o) { if (o != null && o instanceof TColor) { TColor c = (TColor) o; float dr = c.rgb[0] - rgb[0]; float dg = c.rgb[1] - rgb[1]; float db = c.rgb[2] - rgb[2]; float da = c.alpha - alpha; double d = Math.sqrt(dr * dr + dg * dg + db * db + da * da); return d < EPS; } return false; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getAnalog(float, float) */ public TColor getAnalog(float theta, float delta) { return new TColor(this).analog(theta, delta); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getAnalog(int, float) */ public TColor getAnalog(int angle, float delta) { return new TColor(this).analog(angle, delta); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getBlended(toxi.color.ReadonlyTColor, * float) */ public TColor getBlended(ReadonlyTColor c, float t) { return new TColor(this).blend(c, t); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getClosestHue() */ public Hue getClosestHue() { return Hue.getClosest(hsv[0], false); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getClosestHue(boolean) */ public Hue getClosestHue(boolean primaryOnly) { return Hue.getClosest(hsv[0], primaryOnly); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getComplement() */ public TColor getComplement() { return new TColor(this).complement(); } /* * (non-Javadoc) * * @see * toxi.color.ReadonlyTColor#getComponentValue(toxi.color.AccessCriteria) */ public float getComponentValue(AccessCriteria criteria) { switch (criteria.getMode()) { case HSV: return hsv[criteria.getComponent()]; case RGB: return rgb[criteria.getComponent()]; case CMYK: return cmyk[criteria.getComponent()]; case ALPHA: return alpha; } return 0; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getDarkened(float) */ public TColor getDarkened(float step) { return new TColor(this).darken(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getDesaturated(float) */ public TColor getDesaturated(float step) { return new TColor(this).desaturate(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getInverted() */ public TColor getInverted() { return new TColor(this).invert(); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getLightened(float) */ public TColor getLightened(float step) { return new TColor(this).lighten(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getRotatedRYB(float) */ public TColor getRotatedRYB(float theta) { return new TColor(this).rotateRYB(theta); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getRotatedRYB(int) */ public TColor getRotatedRYB(int angle) { return new TColor(this).rotateRYB(angle); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getSaturated(float) */ public TColor getSaturated(float step) { return new TColor(this).saturate(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#green() */ public float green() { return rgb[1]; } @Override public int hashCode() { int hash = 37; hash += 37 * hash + Float.floatToIntBits(rgb[0]); hash += 37 * hash + Float.floatToIntBits(rgb[1]); hash += 37 * hash + Float.floatToIntBits(rgb[2]); hash += 37 * hash + Float.floatToIntBits(alpha); return hash; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#hue() */ public float hue() { return hsv[0]; } /** * Inverts the color. * * @return itself */ public TColor invert() { rgb[0] = 1 - rgb[0]; rgb[1] = 1 - rgb[1]; rgb[2] = 1 - rgb[2]; return setRGB(rgb); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isBlack() */ public boolean isBlack() { return (rgb[0] <= BLACK_POINT && Float.compare(rgb[0], rgb[1]) == 0 && Float .compare(rgb[0], rgb[2]) == 0); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isGrey() */ public boolean isGrey() { return hsv[1] < GREY_THRESHOLD; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isPrimary() */ public boolean isPrimary() { return Hue.isPrimary(hsv[0]); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isWhite() */ public boolean isWhite() { return (rgb[0] >= WHITE_POINT && Float.compare(rgb[0], rgb[1]) == 0 && Float .compare(rgb[0], rgb[2]) == 0); } /** * Lightens the color by stated amount. * * @param step * lighten amount * @return itself */ public TColor lighten(float step) { hsv[2] = MathUtils.clip(hsv[2] + step, 0, 1); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#luminance() */ public float luminance() { return rgb[0] * 0.299f + rgb[1] * 0.587f + rgb[2] * 0.114f; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#magenta() */ public float magenta() { return cmyk[0]; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#red() */ public float red() { return rgb[0]; } public TColor rotateRYB(float theta) { return rotateRYB((int) MathUtils.degrees(theta)); } /** * Rotates the color by x degrees along the <a * href="http://en.wikipedia.org/wiki/RYB_color_model">RYB color wheel</a> * * @param theta * @return itself */ public TColor rotateRYB(int theta) { float h = hsv[0] * 360; theta %= 360; float resultHue = 0; for (int i = 0; i < RYB_WHEEL.length - 1; i++) { Vec2D p = RYB_WHEEL[i]; Vec2D q = RYB_WHEEL[i + 1]; if (q.y < p.y) { q.y += 360; } if (p.y <= h && h <= q.y) { resultHue = p.x + (q.x - p.x) * (h - p.y) / (q.y - p.y); break; } } // And the user-given angle (e.g. complement). resultHue = (resultHue + theta) % 360; // For the given angle, find out what hue is // located there on the artistic color wheel. for (int i = 0; i < RYB_WHEEL.length - 1; i++) { Vec2D p = RYB_WHEEL[i]; Vec2D q = RYB_WHEEL[i + 1]; if (q.y < p.y) { q.y += 360; } if (p.x <= resultHue && resultHue <= q.x) { h = p.y + (q.y - p.y) * (resultHue - p.x) / (q.x - p.x); break; } } hsv[0] = (h % 360) / 360.0f; return setHSV(hsv); } /** * Adds the given value to the current saturation component. * * @param step * @return itself */ public TColor saturate(float step) { hsv[1] = MathUtils.clip(hsv[1] + step, 0, 1); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#saturation() */ public float saturation() { return hsv[1]; } public TColor setAlpha(float alpha) { this.alpha = alpha; return this; } /** * Sets all color components to new values interpreted from the given packed * ARGB 32bit color value. * * @param argb * @return itself */ public TColor setARGB(int argb) { setRGB(((argb >> 16) & 0xff) * INV8BIT, ((argb >> 8) & 0xff) * INV8BIT, (argb & 0xff) * INV8BIT); alpha = (argb >>> 24) * INV8BIT; return this; } public TColor setBlack(float val) { cmyk[3] = val; return setCMYK(cmyk); } public TColor setBlue(float blue) { rgb[2] = blue; return setRGB(rgb); } public TColor setBrightness(float brightness) { hsv[2] = MathUtils.clip(brightness, 0, 1); return setHSV(hsv); } public TColor setCMYK(float c, float m, float y, float k) { cmyk[0] = c; cmyk[1] = m; cmyk[2] = y; cmyk[3] = k; return setCMYK(cmyk); } public TColor setCMYK(float[] newCMYK) { cmyk[0] = MathUtils.clip(newCMYK[0], 0, 1); cmyk[1] = MathUtils.clip(newCMYK[1], 0, 1); cmyk[2] = MathUtils.clip(newCMYK[2], 0, 1); cmyk[3] = MathUtils.clip(newCMYK[3], 0, 1); cmykToRGB(cmyk[0], cmyk[1], cmyk[2], cmyk[3], rgb); rgbToHSV(rgb[0], rgb[1], rgb[2], hsv); return this; } /** * Sets a color component by name. * * @param criteria * @param val * @return itself * * @see AccessCriteria */ public TColor setComponent(AccessCriteria criteria, float val) { switch (criteria.getMode()) { case RGB: rgb[criteria.getComponent()] = val; return setRGB(rgb); case HSV: hsv[criteria.getComponent()] = val; return setHSV(hsv); case ALPHA: return setAlpha(val); case CMYK: cmyk[criteria.getComponent()] = val; return setCMYK(cmyk); default: throw new IllegalArgumentException( "Invalid ColorAccessCriteria mode used"); } } public TColor setCyan(float val) { cmyk[0] = val; return setCMYK(cmyk); } public TColor setGreen(float green) { rgb[1] = green; return setRGB(rgb); } public TColor setHSV(float h, float s, float v) { hsv[0] = h; hsv[1] = s; hsv[2] = v; return setHSV(hsv); } public TColor setHSV(float[] newHSV) { hsv[0] = newHSV[0] % 1; if (hsv[0] < 0) { hsv[0]++; } hsv[1] = MathUtils.clip(newHSV[1], 0, 1); hsv[2] = MathUtils.clip(newHSV[2], 0, 1); hsvToRGB(hsv[0], hsv[1], hsv[2], rgb); rgbToCMYK(rgb[0], rgb[1], rgb[2], cmyk); return this; } public void setHue(float hue) { hue %= 1.0; if (hue < 0.0) { hue++; } hsv[0] = hue; setHSV(hsv); } public TColor setMagenta(float val) { cmyk[1] = val; return setCMYK(cmyk); } public TColor setRed(float red) { rgb[0] = red; return setRGB(rgb); } public TColor setRGB(float r, float g, float b) { rgb[0] = r; rgb[1] = g; rgb[2] = b; return setRGB(rgb); } public TColor setRGB(float[] newRGB) { rgb[0] = MathUtils.clip(newRGB[0], 0, 1); rgb[1] = MathUtils.clip(newRGB[1], 0, 1); rgb[2] = MathUtils.clip(newRGB[2], 0, 1); rgbToCMYK(rgb[0], rgb[1], rgb[2], cmyk); rgbToHSV(rgb[0], rgb[1], rgb[2], hsv); return this; } public TColor setSaturation(float saturation) { hsv[1] = MathUtils.clip(saturation, 0, 1); return setHSV(hsv); } public TColor setYellow(float val) { cmyk[2] = val; return setCMYK(cmyk); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toARGB() */ public int toARGB() { return (int) (rgb[0] * 255) << 16 | (int) (rgb[1] * 255) << 8 | (int) (rgb[2] * 255) | (int) (alpha * 255) << 24; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toCMYKAArray(float[]) */ public float[] toCMYKAArray(float[] cmyka) { if (cmyka == null) { cmyka = new float[4]; } cmyka[0] = cmyk[0]; cmyka[1] = cmyk[1]; cmyka[2] = cmyk[2]; cmyka[3] = alpha; return cmyka; } /** * Converts the color into a 6 digit hex string. * * @return color as hex */ public String toHex() { String hex = Integer.toHexString(toARGB()); if (hex.length() > 6) { hex = hex.substring(2); } return hex; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toHSVAArray(float[]) */ public float[] toHSVAArray(float[] hsva) { if (hsva == null) { hsva = new float[4]; } hsva[0] = hsv[0]; hsva[1] = hsv[1]; hsva[2] = hsv[2]; hsva[3] = alpha; return hsva; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toRGBAArray(float[]) */ public float[] toRGBAArray(float[] rgba) { return toRGBAArray(rgba, 0); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toRGBAArray(float[], int) */ public float[] toRGBAArray(float[] rgba, int offset) { if (rgba == null) { rgba = new float[4]; offset = 0; } rgba[offset++] = rgb[0]; rgba[offset++] = rgb[1]; rgba[offset++] = rgb[2]; rgba[offset] = alpha; return rgba; } @Override public String toString() { return "TColor: rgb: " + rgb[0] + "," + rgb[1] + "," + rgb[2] + " hsv: " + hsv[0] + "," + hsv[1] + "," + hsv[2] + " cmyk: " + cmyk[0] + "," + cmyk[1] + "," + cmyk[2] + "," + cmyk[3] + " alpha: " + alpha; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#yellow() */ public float yellow() { return cmyk[0]; } }
src.color/toxi/color/TColor.java
/* * Some classes in this package have been partly inspired by & bits ported from * Python code written by Tom De Smedt & Frederik De Bleser for the "colors" library * of Nodebox.net. * * http://nodebox.net/code/index.php/Colors * * Copyright (c) 2006-2008 Karsten Schmidt <info at postspectacular.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * http://creativecommons.org/licenses/LGPL/2.1/ * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package toxi.color; import toxi.geom.Vec2D; import toxi.geom.Vec3D; import toxi.math.MathUtils; /** * Floating point color class with implicit RGB, HSV, CMYK access modes, * conversion and color theory utils. Based on the <a href="">Colors library</a> * for <a href="http:/Nodebox.net/">NodeBox</a> * */ public class TColor implements ReadonlyTColor { protected static final float INV60DEGREES = 60.0f / 360; protected static final float INV8BIT = 1f / 255; protected static final double EPS = .001; protected static final Vec2D[] RYB_WHEEL = new Vec2D[] { new Vec2D(0, 0), new Vec2D(15, 8), new Vec2D(30, 17), new Vec2D(45, 26), new Vec2D(60, 34), new Vec2D(75, 41), new Vec2D(90, 48), new Vec2D(105, 54), new Vec2D(120, 60), new Vec2D(135, 81), new Vec2D(150, 103), new Vec2D(165, 123), new Vec2D(180, 138), new Vec2D(195, 155), new Vec2D(210, 171), new Vec2D(225, 187), new Vec2D(240, 204), new Vec2D(255, 219), new Vec2D(270, 234), new Vec2D(285, 251), new Vec2D(300, 267), new Vec2D(315, 282), new Vec2D(330, 298), new Vec2D(345, 329), new Vec2D(360, 0) }; /** * Maximum rgb component value for a color to be classified as black. * * @see #isBlack() */ public static float BLACK_POINT = 0.08f; /** * Minimum rgb component value for a color to be classified as white. * * @see #isWhite() */ public static float WHITE_POINT = 1f; /** * Maximum saturations value for a color to be classified as grey * * @see #isGrey() */ public static float GREY_THRESHOLD = 0.01f; public static final ReadonlyTColor RED = newRGB(1, 0, 0); public static final ReadonlyTColor GREEN = newRGB(0, 1, 0); public static final ReadonlyTColor BLUE = newRGB(0, 0, 1); public static final ReadonlyTColor CYAN = newRGB(0, 1, 1); public static final ReadonlyTColor MAGENTA = newRGB(1, 0, 1); public static final ReadonlyTColor YELLOW = newRGB(1, 1, 0); public static final ReadonlyTColor BLACK = newRGB(0, 0, 0); public static final ReadonlyTColor WHITE = newRGB(1, 1, 1); /** * Converts CMYK floats into an RGB array. * * @param c * @param m * @param y * @param k * @return rgb array */ public static final float[] cmykToRGB(float c, float m, float y, float k) { return cmykToRGB(c, m, y, k, new float[3]); } /** * Converts CMYK floats into the given RGB array. * * @param c * @param m * @param y * @param k * @param rgb * @return rgb array */ public static final float[] cmykToRGB(float c, float m, float y, float k, float[] rgb) { rgb[0] = 1.0f - MathUtils.min(1.0f, c + k); rgb[1] = 1.0f - MathUtils.min(1.0f, m + k); rgb[2] = 1.0f - MathUtils.min(1.0f, y + k); return rgb; } /** * Converts hex string into a RGB array. * * @param hexRGB * @return rgb array */ public static final float[] hexToRGB(String hexRGB) { return hexToRGB(hexRGB, new float[3]); } public static final float[] hexToRGB(String hexRGB, float[] rgb) { try { int rgbInt = Integer.parseInt(hexRGB, 16); rgb[0] = ((rgbInt >> 16) & 0xff) * INV8BIT; rgb[1] = ((rgbInt >> 8) & 0xff) * INV8BIT; rgb[2] = (rgbInt & 0xff) * INV8BIT; } catch (NumberFormatException e) { rgb[0] = rgb[1] = rgb[2] = 0; } return rgb; } /** * Converts HSV values into RGB array. * * @param h * @param s * @param v * @return rgb array */ public static final float[] hsvToRGB(float h, float s, float v) { return hsvToRGB(h, s, v, new float[3]); } public static final float[] hsvToRGB(float h, float s, float v, float[] rgb) { if (Float.compare(s, 0.0f) == 0) { rgb[0] = rgb[1] = rgb[2] = v; } else { h /= INV60DEGREES; int i = (int) h; float f = h - i; float p = v * (1 - s); float q = v * (1 - s * f); float t = v * (1 - s * (1 - f)); if (i == 0) { rgb[0] = v; rgb[1] = t; rgb[2] = p; } else if (i == 1) { rgb[0] = q; rgb[1] = v; rgb[2] = p; } else if (i == 2) { rgb[0] = p; rgb[1] = v; rgb[2] = t; } else if (i == 3) { rgb[0] = p; rgb[1] = q; rgb[2] = v; } else if (i == 4) { rgb[0] = t; rgb[1] = p; rgb[2] = v; } else { rgb[0] = v; rgb[1] = p; rgb[2] = q; } } return rgb; } public static final float[] labToRGB(float l, float a, float b) { return labToRGB(l, a, b, new float[3]); } /** * Converts CIE Lab to RGB components. * * First we have to convert to XYZ color space. Conversion involves using a * white point, in this case D65 which represents daylight illumination. * * Algorithm adopted from: http://www.easyrgb.com/math.php * * @param l * @param a * @param b * @param rgb * @return rgb array */ public static final float[] labToRGB(float l, float a, float b, float[] rgb) { float y = (l + 16) / 116.0f; float x = a / 500.0f + y; float z = y - b / 200.0f; rgb[0] = x; rgb[1] = y; rgb[2] = z; for (int i = 0; i < 3; i++) { float p = (float) Math.pow(rgb[i], 3); if (p > 0.008856) { rgb[i] = p; } else { rgb[i] = (rgb[i] - 16 / 116.0f) / 7.787f; } } // Observer = 2, Illuminant = D65 x = rgb[0] * 0.95047f; y = rgb[1]; z = rgb[2] * 1.08883f; rgb[0] = x * 3.2406f + y * -1.5372f + z * -0.4986f; rgb[1] = x * -0.9689f + y * 1.8758f + z * 0.0415f; rgb[2] = x * 0.0557f + y * -0.2040f + z * 1.0570f; double tpow = 1 / 2.4; for (int i = 0; i < 3; i++) { if (rgb[i] > 0.0031308) { rgb[i] = (float) (1.055 * Math.pow(rgb[i], tpow) - 0.055); } else { rgb[i] = 12.92f * rgb[i]; } } return rgb; } /** * Factory method. Creates new color from ARGB int. * * @param argb * @return new color */ public static final TColor newARGB(int argb) { return newRGBA(((argb >> 16) & 0xff) * INV8BIT, ((argb >> 8) & 0xff) * INV8BIT, (argb & 0xff) * INV8BIT, (argb >>> 24) * INV8BIT); } /** * Factory method. Creates new color from CMYK values. * * @param c * @param m * @param y * @param k * @return new color */ public static final TColor newCMYK(float c, float m, float y, float k) { return newCMYKA(c, m, y, k, 1); } /** * Factory method. Creates new color from CMYK + alpha values. * * @param c * @param m * @param y * @param k * @param a * @return new color */ public static final TColor newCMYKA(float c, float m, float y, float k, float a) { TColor col = new TColor(); col.setCMYK(new float[] { c, m, y, k }); col.alpha = MathUtils.clip(a, 0, 1); return col; } /** * Factory method. Creates a new shade of gray + alpha. * * @param gray * @return new color. */ public static final TColor newGray(float gray) { return newGrayAlpha(gray, 1); } public static final TColor newGrayAlpha(float gray, float alpha) { TColor c = new TColor(); c.setRGB(new float[] { gray, gray, gray }); c.alpha = alpha; return c; } /** * Factory method. New color from hex string. * * @param hexRGB * @return new color */ public static final TColor newHex(String hexRGB) { TColor c = new TColor(); c.setRGB(hexToRGB(hexRGB)); c.alpha = 1; return c; } /** * Factory method. New color from hsv values. * * @param h * @param s * @param v * @return new color */ public static final TColor newHSV(float h, float s, float v) { return newHSVA(h, s, v, 1); } public static ReadonlyTColor newHSV(Hue h, float s, float v) { return newHSV(h.getHue(), s, v); } public static final TColor newHSVA(float h, float s, float v, float a) { TColor c = new TColor(); c.setHSV(new float[] { h, s, v }); c.alpha = MathUtils.clip(a, 0, 1); return c; } /** * Factory method. Creates new random color. * * @return random color */ public static final TColor newRandom() { return newRGBA(MathUtils.random(1f), MathUtils.random(1f), MathUtils .random(1f), 1); } /** * Factory method. Creates new color from RGB values. * * @param r * @param g * @param b * @return new color */ public static final TColor newRGB(float r, float g, float b) { return newRGBA(r, g, b, 1); } public static final TColor newRGBA(float r, float g, float b, float a) { TColor c = new TColor(); c.setRGB(new float[] { r, g, b }); c.alpha = MathUtils.clip(a, 0, 1); return c; } /** * Converts the RGB values into a CMYK array. * * @param r * @param g * @param b * @return cmyk array */ public static final float[] rgbToCMYK(float r, float g, float b) { return rgbToCMYK(r, g, b, new float[4]); } public static final float[] rgbToCMYK(float r, float g, float b, float[] cmyk) { cmyk[0] = 1 - r; cmyk[1] = 1 - g; cmyk[2] = 1 - b; cmyk[3] = MathUtils.min(cmyk[0], cmyk[1], cmyk[2]); cmyk[0] = MathUtils.clip(cmyk[0] - cmyk[3], 0, 1); cmyk[1] = MathUtils.clip(cmyk[1] - cmyk[3], 0, 1); cmyk[2] = MathUtils.clip(cmyk[2] - cmyk[3], 0, 1); cmyk[3] = MathUtils.clip(cmyk[3], 0, 1); return cmyk; } /** * Formats the RGB float values into hex integers. * * @param r * @param g * @param b * @return hex string */ public static final String rgbToHex(float r, float g, float b) { String hex = Integer.toHexString((int) (MathUtils.clip(r, 0, 1) * 0xff)) + Integer .toHexString((int) (MathUtils.clip(g, 0, 1) * 0xff)) + Integer .toHexString((int) (MathUtils.clip(b, 0, 1) * 0xff)); return hex; } /** * Converts the RGB values into an HSV array. * * @param r * @param g * @param b * @return hsv array */ public static final float[] rgbToHSV(float r, float g, float b) { return rgbToHSV(r, g, b, new float[3]); } public static final float[] rgbToHSV(float r, float g, float b, float[] hsv) { float h = 0, s = 0; float v = MathUtils.max(r, g, b); float d = v - MathUtils.min(r, g, b); if (v != 0.0) { s = d / v; } if (s != 0.0) { if (Float.compare(r, v) == 0) { h = (g - b) / d; } else if (Float.compare(g, v) == 0) { h = 2 + (b - r) / d; } else { h = 4 + (r - g) / d; } } h *= INV60DEGREES; if (h < 0) { h += 1.0f; } hsv[0] = h; hsv[1] = s; hsv[2] = v; return hsv; } protected float[] rgb; protected float[] cmyk; protected float[] hsv; public float alpha; protected TColor() { rgb = new float[3]; hsv = new float[3]; cmyk = new float[4]; } /** * Creates a deep copy of the given color. * * @param c */ public TColor(ReadonlyTColor c) { this(); float[] buffer = c.toCMYKAArray(null); System.arraycopy(buffer, 0, cmyk, 0, 4); System.arraycopy(c.toHSVAArray(buffer), 0, hsv, 0, 3); System.arraycopy(c.toRGBAArray(buffer), 0, rgb, 0, 3); this.alpha = c.alpha(); } /** * Changes the brightness of the color by the given amount in the direction * towards either the black or white point (depending on if current * brightness >= 50%) * * @param amount * @return itself */ public ReadonlyTColor adjustConstrast(float amount) { return hsv[2] < 0.5 ? darken(amount) : lighten(amount); } /** * Adds the given HSV values as offsets to the current color. Hue will * automatically wrap. * * @param h * @param s * @param v * @return itself */ public ReadonlyTColor adjustHSV(float h, float s, float v) { return setHSV(new float[] { hsv[0] + h, hsv[1] + s, hsv[2] + v }); } /** * Adds the given RGB values as offsets to the current color. TColor will * clip at black or white. * * @param r * @param g * @param b * @return itself */ public ReadonlyTColor adjustRGB(float r, float g, float b) { return setRGB(new float[] { rgb[0] + r, rgb[1] + g, rgb[2] + b }); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#alpha() */ public float alpha() { return alpha; } /** * Rotates this color by a random amount (not exceeding the one specified) * and creates variations in saturation and brightness based on the 2nd * parameter. * * @param theta * max. rotation angle (in radians) * @param delta * max. sat/bri variance * @return itself */ public TColor analog(float theta, float delta) { return analog(MathUtils.degrees(theta), delta); } public TColor analog(int angle, float delta) { rotateRYB((int) (angle * MathUtils.normalizedRandom())); hsv[1] += delta * MathUtils.normalizedRandom(); hsv[2] += delta * MathUtils.normalizedRandom(); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#black() */ public float black() { return cmyk[0]; } /** * Blends the color with the given one by the stated amount * * @param c * target color * @param t * interpolation factor * @return itself */ public TColor blend(ReadonlyTColor c, float t) { float[] crgb = c.toRGBAArray(null); rgb[0] += (crgb[0] - rgb[0]) * t; rgb[1] += (crgb[1] - rgb[1]) * t; rgb[2] += (crgb[2] - rgb[2]) * t; alpha += (c.alpha() - alpha) * t; return setRGB(rgb); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#blue() */ public float blue() { return rgb[2]; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#brightness() */ public float brightness() { return hsv[2]; } /** * @return ifself, as complementary color */ public TColor complement() { return rotateRYB(180); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#copy() */ public TColor copy() { return new TColor(this); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#cyan() */ public float cyan() { return cmyk[0]; } /** * Reduces the color's brightness by the given amount (e.g 0.1 = 10% * darker). * * @param step * @return itself */ public TColor darken(float step) { hsv[2] = MathUtils.clip(hsv[2] - step, 0, 1); return setHSV(hsv); } /** * Reduced the color's saturation by the given amount. * * @param step * @return itself */ public TColor desaturate(float step) { hsv[1] = MathUtils.clip(hsv[1] - step, 0, 1); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#distanceToCMYK(toxi.color.TColor) */ public float distanceToCMYK(ReadonlyTColor c) { float[] ccmyk = c.toCMYKAArray(null); float dc = cmyk[0] - ccmyk[0]; float dm = cmyk[1] - ccmyk[1]; float dy = cmyk[2] - ccmyk[2]; float dk = cmyk[3] - ccmyk[3]; return (float) Math.sqrt(dc * dc + dm * dm + dy * dy + dk * dk); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#distanceToHSV(toxi.color.TColor) */ public float distanceToHSV(ReadonlyTColor c) { float[] chsv = c.toHSVAArray(null); float hue = hsv[0] * MathUtils.TWO_PI; float hue2 = chsv[0] * MathUtils.TWO_PI; Vec3D v1 = new Vec3D((float) (Math.cos(hue) * hsv[1]), (float) (Math .sin(hue) * hsv[1]), hsv[2]); Vec3D v2 = new Vec3D((float) (Math.cos(hue2) * chsv[1]), (float) (Math .sin(hue2) * chsv[1]), chsv[2]); return v1.distanceTo(v2); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#distanceToRGB(toxi.color.TColor) */ public float distanceToRGB(ReadonlyTColor c) { float[] crgb = c.toRGBAArray(null); float dr = rgb[0] - crgb[0]; float dg = rgb[1] - crgb[1]; float db = rgb[2] - crgb[2]; return (float) Math.sqrt(dr * dr + dg * dg + db * db); } @Override public boolean equals(Object o) { if (o != null && o instanceof TColor) { TColor c = (TColor) o; float dr = c.rgb[0] - rgb[0]; float dg = c.rgb[1] - rgb[1]; float db = c.rgb[2] - rgb[2]; float da = c.alpha - alpha; double d = Math.sqrt(dr * dr + dg * dg + db * db + da * da); return d < EPS; } return false; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getAnalog(float, float) */ public TColor getAnalog(float theta, float delta) { return new TColor(this).analog(theta, delta); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getAnalog(int, float) */ public TColor getAnalog(int angle, float delta) { return new TColor(this).analog(angle, delta); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getBlended(toxi.color.ReadonlyTColor, * float) */ public TColor getBlended(ReadonlyTColor c, float t) { return new TColor(this).blend(c, t); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getClosestHue() */ public Hue getClosestHue() { return Hue.getClosest(hsv[0], false); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getClosestHue(boolean) */ public Hue getClosestHue(boolean primaryOnly) { return Hue.getClosest(hsv[0], primaryOnly); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getComplement() */ public TColor getComplement() { return new TColor(this).complement(); } /* * (non-Javadoc) * * @see * toxi.color.ReadonlyTColor#getComponentValue(toxi.color.AccessCriteria) */ public float getComponentValue(AccessCriteria criteria) { switch (criteria.getMode()) { case HSV: return hsv[criteria.getComponent()]; case RGB: return rgb[criteria.getComponent()]; case CMYK: return cmyk[criteria.getComponent()]; case ALPHA: return alpha; } return 0; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getDarkened(float) */ public TColor getDarkened(float step) { return new TColor(this).darken(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getDesaturated(float) */ public TColor getDesaturated(float step) { return new TColor(this).desaturate(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getInverted() */ public TColor getInverted() { return new TColor(this).invert(); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getLightened(float) */ public TColor getLightened(float step) { return new TColor(this).lighten(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getRotatedRYB(float) */ public TColor getRotatedRYB(float theta) { return new TColor(this).rotateRYB(theta); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getRotatedRYB(int) */ public TColor getRotatedRYB(int angle) { return new TColor(this).rotateRYB(angle); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#getSaturated(float) */ public TColor getSaturated(float step) { return new TColor(this).saturate(step); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#green() */ public float green() { return rgb[1]; } @Override public int hashCode() { int hash = 37; hash += 37 * hash + Float.floatToIntBits(rgb[0]); hash += 37 * hash + Float.floatToIntBits(rgb[1]); hash += 37 * hash + Float.floatToIntBits(rgb[2]); hash += 37 * hash + Float.floatToIntBits(alpha); return hash; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#hue() */ public float hue() { return hsv[0]; } /** * Inverts the color. * * @return itself */ public TColor invert() { rgb[0] = 1 - rgb[0]; rgb[1] = 1 - rgb[1]; rgb[2] = 1 - rgb[2]; return setRGB(rgb); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isBlack() */ public boolean isBlack() { return (rgb[0] <= BLACK_POINT && Float.compare(rgb[0], rgb[1]) == 0 && Float .compare(rgb[0], rgb[2]) == 0); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isGrey() */ public boolean isGrey() { return hsv[1] < GREY_THRESHOLD; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isPrimary() */ public boolean isPrimary() { return Hue.isPrimary(hsv[0]); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#isWhite() */ public boolean isWhite() { return (rgb[0] >= WHITE_POINT && Float.compare(rgb[0], rgb[1]) == 0 && Float .compare(rgb[0], rgb[2]) == 0); } /** * Lightens the color by stated amount. * * @param step * lighten amount * @return itself */ public TColor lighten(float step) { hsv[2] = MathUtils.clip(hsv[2] + step, 0, 1); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#luminance() */ public float luminance() { return rgb[0] * 0.299f + rgb[1] * 0.587f + rgb[2] * 0.114f; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#magenta() */ public float magenta() { return cmyk[0]; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#red() */ public float red() { return rgb[0]; } public TColor rotateRYB(float theta) { return rotateRYB((int) MathUtils.degrees(theta)); } /** * Rotates the color by x degrees along the <a * href="http://en.wikipedia.org/wiki/RYB_color_model">RYB color wheel</a> * * @param theta * @return itself */ public TColor rotateRYB(int theta) { float h = hsv[0] * 360; theta %= 360; float resultHue = 0; for (int i = 0; i < RYB_WHEEL.length - 1; i++) { Vec2D p = RYB_WHEEL[i]; Vec2D q = RYB_WHEEL[i + 1]; if (q.y < p.y) { q.y += 360; } if (p.y <= h && h <= q.y) { resultHue = p.x + (q.x - p.x) * (h - p.y) / (q.y - p.y); break; } } // And the user-given angle (e.g. complement). resultHue = (resultHue + theta) % 360; // For the given angle, find out what hue is // located there on the artistic color wheel. for (int i = 0; i < RYB_WHEEL.length - 1; i++) { Vec2D p = RYB_WHEEL[i]; Vec2D q = RYB_WHEEL[i + 1]; if (q.y < p.y) { q.y += 360; } if (p.x <= resultHue && resultHue <= q.x) { h = p.y + (q.y - p.y) * (resultHue - p.x) / (q.x - p.x); break; } } hsv[0] = (h % 360) / 360.0f; return setHSV(hsv); } /** * Adds the given value to the current saturation component. * * @param step * @return itself */ public TColor saturate(float step) { hsv[1] = MathUtils.clip(hsv[1] + step, 0, 1); return setHSV(hsv); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#saturation() */ public float saturation() { return hsv[1]; } public TColor setAlpha(float alpha) { this.alpha = alpha; return this; } /** * Sets all color components to new values interpreted from the given packed * ARGB 32bit color value. * * @param argb * @return itself */ public TColor setARGB(int argb) { setRGB(((argb >> 16) & 0xff) * INV8BIT, ((argb >> 8) & 0xff) * INV8BIT, (argb & 0xff) * INV8BIT); alpha = (argb >>> 24) * INV8BIT; return this; } public TColor setBlack(float val) { cmyk[3] = val; return setCMYK(cmyk); } public TColor setBlue(float blue) { rgb[2] = blue; return setRGB(rgb); } public TColor setBrightness(float brightness) { hsv[2] = MathUtils.clip(brightness, 0, 1); return setHSV(hsv); } public TColor setCMYK(float c, float m, float y, float k) { cmyk[0] = c; cmyk[1] = m; cmyk[2] = y; cmyk[3] = k; return setCMYK(cmyk); } public TColor setCMYK(float[] newCMYK) { cmyk[0] = MathUtils.clip(newCMYK[0], 0, 1); cmyk[1] = MathUtils.clip(newCMYK[1], 0, 1); cmyk[2] = MathUtils.clip(newCMYK[2], 0, 1); cmyk[3] = MathUtils.clip(newCMYK[3], 0, 1); cmykToRGB(cmyk[0], cmyk[1], cmyk[2], cmyk[3], rgb); rgbToHSV(rgb[0], rgb[1], rgb[2], hsv); return this; } /** * Sets a color component by name. * * @param criteria * @param val * @return itself * * @see AccessCriteria */ public TColor setComponent(AccessCriteria criteria, float val) { switch (criteria.getMode()) { case RGB: rgb[criteria.getComponent()] = val; return setRGB(rgb); case HSV: hsv[criteria.getComponent()] = val; return setHSV(hsv); case ALPHA: return setAlpha(val); case CMYK: cmyk[criteria.getComponent()] = val; return setCMYK(cmyk); default: throw new IllegalArgumentException( "Invalid ColorAccessCriteria mode used"); } } public TColor setCyan(float val) { cmyk[0] = val; return setCMYK(cmyk); } public TColor setGreen(float green) { rgb[1] = green; return setRGB(rgb); } public TColor setHSV(float h, float s, float v) { hsv[0] = h; hsv[1] = s; hsv[2] = v; return setHSV(hsv); } public TColor setHSV(float[] newHSV) { hsv[0] = newHSV[0] % 1; if (hsv[0] < 0) { hsv[0]++; } hsv[1] = MathUtils.clip(newHSV[1], 0, 1); hsv[2] = MathUtils.clip(newHSV[2], 0, 1); hsvToRGB(hsv[0], hsv[1], hsv[2], rgb); rgbToCMYK(rgb[0], rgb[1], rgb[2], cmyk); return this; } public void setHue(float hue) { hue %= 1.0; if (hue < 0.0) { hue++; } hsv[0] = hue; setHSV(hsv); } public TColor setMagenta(float val) { cmyk[1] = val; return setCMYK(cmyk); } public TColor setRed(float red) { rgb[0] = red; return setRGB(rgb); } public TColor setRGB(float r, float g, float b) { rgb[0] = r; rgb[1] = g; rgb[2] = b; return setRGB(rgb); } public TColor setRGB(float[] newRGB) { rgb[0] = MathUtils.clip(newRGB[0], 0, 1); rgb[1] = MathUtils.clip(newRGB[1], 0, 1); rgb[2] = MathUtils.clip(newRGB[2], 0, 1); rgbToCMYK(rgb[0], rgb[1], rgb[2], cmyk); rgbToHSV(rgb[0], rgb[1], rgb[2], hsv); return this; } public TColor setSaturation(float saturation) { hsv[1] = MathUtils.clip(saturation, 0, 1); return setHSV(hsv); } public TColor setYellow(float val) { cmyk[2] = val; return setCMYK(cmyk); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toARGB() */ public int toARGB() { return (int) (rgb[0] * 255) << 16 | (int) (rgb[1] * 255) << 8 | (int) (rgb[2] * 255) | (int) (alpha * 255) << 24; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toCMYKAArray(float[]) */ public float[] toCMYKAArray(float[] cmyka) { if (cmyka == null) { cmyka = new float[4]; } cmyka[0] = cmyk[0]; cmyka[1] = cmyk[1]; cmyka[2] = cmyk[2]; cmyka[3] = alpha; return cmyka; } /** * Converts the color into a 6 digit hex string. * * @return color as hex */ public String toHex() { String hex = Integer.toHexString(toARGB()); if (hex.length() > 6) { hex = hex.substring(2); } return hex; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toHSVAArray(float[]) */ public float[] toHSVAArray(float[] hsva) { if (hsva == null) { hsva = new float[4]; } hsva[0] = hsv[0]; hsva[1] = hsv[1]; hsva[2] = hsv[2]; hsva[3] = alpha; return hsva; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toRGBAArray(float[]) */ public float[] toRGBAArray(float[] rgba) { return toRGBAArray(rgba, 0); } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#toRGBAArray(float[], int) */ public float[] toRGBAArray(float[] rgba, int offset) { if (rgba == null) { rgba = new float[4]; offset = 0; } rgba[offset++] = rgb[0]; rgba[offset++] = rgb[1]; rgba[offset++] = rgb[2]; rgba[offset] = alpha; return rgba; } @Override public String toString() { return "TColor: rgb: " + rgb[0] + "," + rgb[1] + "," + rgb[2] + " hsv: " + hsv[0] + "," + hsv[1] + "," + hsv[2] + " cmyk: " + cmyk[0] + "," + cmyk[1] + "," + cmyk[2] + "," + cmyk[3] + " alpha: " + alpha; } /* * (non-Javadoc) * * @see toxi.color.ReadonlyTColor#yellow() */ public float yellow() { return cmyk[0]; } }
refactoring distanceToHSV() to use MathUtils trigonometry instead of default Math --HG-- branch : toxiclibs
src.color/toxi/color/TColor.java
refactoring distanceToHSV() to use MathUtils trigonometry instead of default Math
Java
lgpl-2.1
bc05d5eaebe1040fc43c1597b268eb54de976186
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import bak.pcj.list.IntList; import com.exedio.dsmf.Driver; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; abstract class Database { protected static final int TWOPOW8 = 1<<8; protected static final int TWOPOW16 = 1<<16; protected static final int TWOPOW24 = 1<<24; private static final String NO_SUCH_ROW = "no such row"; private final ArrayList<Table> tables = new ArrayList<Table>(); private final HashMap<String, UniqueConstraint> uniqueConstraintsByID = new HashMap<String, UniqueConstraint>(); private boolean buildStage = true; final Driver driver; private final boolean prepare; private final boolean log; private final boolean butterflyPkSource; private final boolean fulltextIndex; final ConnectionPool connectionPool; private final java.util.Properties forcedNames; final java.util.Properties tableOptions; final LimitSupport limitSupport; final long blobLengthFactor; // probed on the initial connection final boolean supportsReadCommitted; final String databaseProductName; final String databaseProductVersion; final int databaseMajorVersion; final int databaseMinorVersion; final String driverName; final String driverVersion; final int driverMajorVersion; final int driverMinorVersion; final boolean oracle; // TODO remove protected Database(final Driver driver, final Properties properties) { this.driver = driver; this.prepare = !properties.getDatabaseDontSupportPreparedStatements(); this.log = properties.getDatabaseLog(); this.butterflyPkSource = properties.getPkSourceButterfly(); this.fulltextIndex = properties.getFulltextIndex(); this.connectionPool = new ConnectionPool(properties); this.forcedNames = properties.getDatabaseForcedNames(); this.tableOptions = properties.getDatabaseTableOptions(); this.limitSupport = properties.getDatabaseDontSupportLimit() ? LimitSupport.NONE : getLimitSupport(); this.blobLengthFactor = getBlobLengthFactor(); this.oracle = getClass().getName().equals("com.exedio.cope.OracleDatabase"); //System.out.println("using database "+getClass()); assert limitSupport!=null; Connection probeConnection = null; String probeError = "unknown"; try { probeConnection = connectionPool.getConnection(); probeError = "getMetaData()"; final DatabaseMetaData dmd = probeConnection.getMetaData(); probeError = "supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED)"; supportsReadCommitted = !fakesSupportReadCommitted() && dmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED); probeError = "getInfo"; databaseProductName = dmd.getDatabaseProductName(); databaseProductVersion = dmd.getDatabaseProductVersion(); databaseMajorVersion = dmd.getDatabaseMajorVersion(); databaseMinorVersion = dmd.getDatabaseMinorVersion(); driverName = dmd.getDriverName(); driverVersion = dmd.getDriverVersion(); driverMajorVersion = dmd.getDriverMajorVersion(); driverMinorVersion = dmd.getDriverMinorVersion(); } catch(SQLException e) { throw new SQLRuntimeException(e, probeError); } finally { if(probeConnection!=null) { try { connectionPool.putConnection(probeConnection); probeConnection = null; } catch(SQLException e) { throw new SQLRuntimeException(e, "putConnection"); } } } } public final Driver getDriver() { return driver; } public final java.util.Properties getTableOptions() { return tableOptions; } public final ConnectionPool getConnectionPool() { return connectionPool; } public final void addTable(final Table table) { if(!buildStage) throw new RuntimeException(); tables.add(table); } public final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint) { if(!buildStage) throw new RuntimeException(); final Object collision = uniqueConstraintsByID.put(constraintID, constraint); if(collision!=null) throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision); } protected final Statement createStatement() { return createStatement(true); } protected final Statement createStatement(final boolean qualifyTable) { return new Statement(this, prepare, qualifyTable, isDefiningColumnTypes()); } protected final Statement createStatement(final Query<? extends Object> query) { return new Statement(this, prepare, query, isDefiningColumnTypes()); } public void createDatabase() { buildStage = false; makeSchema().create(); } public void createDatabaseConstraints(final int mask) { buildStage = false; makeSchema().createConstraints(mask); } //private static int checkTableTime = 0; public void checkDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); // IMPLEMENTATION NOTE // MySQL can have at most 63 joined tables in one statement // and other databases probably have similar constraints as // well, so we limit the number of joined table here. final int CHUNK_LENGTH = 60; final int tablesSize = tables.size(); for(int chunkFromIndex = 0; chunkFromIndex<tablesSize; chunkFromIndex+=CHUNK_LENGTH) { final int chunkToIndex = Math.min(chunkFromIndex+CHUNK_LENGTH, tablesSize); final List<Table> tableChunk = tables.subList(chunkFromIndex, chunkToIndex); final Statement bf = createStatement(true); bf.append("select count(*) from ").defineColumnInteger(); boolean first = true; for(final Table table : tableChunk) { if(first) first = false; else bf.append(','); bf.append(table.protectedID); } bf.append(" where "); first = true; for(final Table table : tableChunk) { if(first) first = false; else bf.append(" and "); final Column primaryKey = table.primaryKey; bf.append(primaryKey). append('='). appendParameter(Type.NOT_A_PK); for(final Column column : table.getColumns()) { bf.append(" and "). append(column); if(column instanceof BlobColumn || (oracle && column instanceof StringColumn && ((StringColumn)column).maximumLength>=4000)) { bf.append("is not null"); } else { bf.append('='). appendParameter(column, column.getCheckValue()); } } } //System.out.println("-----------"+chunkFromIndex+"-"+chunkToIndex+"----"+bf); executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); } }, false ); } } public void dropDatabase() { buildStage = false; makeSchema().drop(); } public void dropDatabaseConstraints(final int mask) { buildStage = false; makeSchema().dropConstraints(mask); } public void tearDownDatabase() { buildStage = false; makeSchema().tearDown(); } public void tearDownDatabaseConstraints(final int mask) { buildStage = false; makeSchema().tearDownConstraints(mask); } public void checkEmptyDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); for(final Table table : tables) { final int count = countTable(connection, table); if(count>0) throw new RuntimeException("there are "+count+" items left for table "+table.id); } //final long amount = (System.currentTimeMillis()-time); //checkEmptyTableTime += amount; //System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime); } public final ArrayList<Object> search(final Connection connection, final Query<? extends Object> query, final boolean doCountOnly) { buildStage = false; listener.search(connection, query, doCountOnly); final int limitStart = query.limitStart; final int limitCount = query.limitCount; final boolean limitActive = limitStart>0 || limitCount!=Query.UNLIMITED_COUNT; final ArrayList<Join> queryJoins = query.joins; final Statement bf = createStatement(query); if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSES_AROUND) appendLimitClause(bf, limitStart, limitCount); bf.append("select"); if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSE_AFTER_SELECT) appendLimitClause(bf, limitStart, limitCount); bf.append(' '); if(query.distinct) bf.append("distinct "); final Selectable[] selects = query.selects; final Column[] selectColumns = new Column[selects.length]; final Type[] selectTypes = new Type[selects.length]; if(doCountOnly) { bf.append("count(*)"); } else { for(int selectIndex = 0; selectIndex<selects.length; selectIndex++) { final Selectable select = selects[selectIndex]; final Column selectColumn; final Type selectType = select.getType(); final Table selectTable; final Column selectPrimaryKey; if(selectIndex>0) bf.append(','); if(select instanceof Aggregate) { bf.append(select, null).defineColumn(select); final Function selectSource = ((Aggregate)select).getSource(); if(selectSource instanceof FunctionAttribute) { selectColumn = ((FunctionAttribute)selectSource).getColumn(); } else if(selectSource instanceof Type.This) { selectTable = selectType.getTable(); selectPrimaryKey = selectTable.primaryKey; selectColumn = selectPrimaryKey; if(selectColumn.primaryKey) { final StringColumn selectTypeColumn = selectColumn.getTypeColumn(); if(selectTypeColumn==null) selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else { selectColumn = null; final View view = (View)selectSource; bf.append(view, (Join)null).defineColumn(view); } } else if(select instanceof FunctionAttribute) { selectColumn = ((FunctionAttribute)select).getColumn(); bf.append(select, (Join)null).defineColumn(select); if(select instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)select).getTypeColumn(); if(typeColumn!=null) bf.append(',').append(typeColumn).defineColumn(typeColumn); } } else if(select instanceof Type.This) { selectTable = selectType.getTable(); selectPrimaryKey = selectTable.primaryKey; selectColumn = selectPrimaryKey; bf.appendPK(selectType, (Join)null).defineColumn(select); if(selectColumn.primaryKey) { final StringColumn selectTypeColumn = selectColumn.getTypeColumn(); if(selectTypeColumn!=null) { bf.append(','). append(selectTypeColumn).defineColumn(selectTypeColumn); } else selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else { selectColumn = null; final View view = (View)select; bf.append(view, (Join)null).defineColumn(view); } selectColumns[selectIndex] = selectColumn; } } bf.append(" from "). appendTableDefinition((Join)null, query.type.getTable()). appendTypeDefinition((Join)null, query.type); if(queryJoins!=null) { for(final Join join : queryJoins) { bf.append(' '). append(join.kind.sql). append(" join "). appendTableDefinition(join, join.type.getTable()); final Condition joinCondition = join.condition; if(joinCondition!=null) { bf.append(" on "); joinCondition.append(bf); } bf.appendTypeDefinition(join, join.type); } } if(query.condition!=null) { bf.append(" where "); query.condition.append(bf); } if(!doCountOnly) { final Function[] orderBy = query.orderBy; if(orderBy!=null) { final boolean[] orderAscending = query.orderAscending; for(int i = 0; i<orderBy.length; i++) { if(i==0) bf.append(" order by "); else bf.append(','); if(orderBy[i] instanceof ItemAttribute) { final ItemAttribute<? extends Item> itemOrderBy = (ItemAttribute<? extends Item>)orderBy[i]; itemOrderBy.getValueType().getPkSource().appendOrderByExpression(bf, itemOrderBy); } else if(orderBy[i] instanceof Type.This) { final Type.This<? extends Item> itemOrderBy = (Type.This<? extends Item>)orderBy[i]; itemOrderBy.type.getPkSource().appendOrderByExpression(bf, itemOrderBy); } else bf.append(orderBy[i], (Join)null); if(!orderAscending[i]) bf.append(" desc"); // TODO break here, if already ordered by some unique function } } if(limitActive && limitSupport==LimitSupport.CLAUSE_AFTER_WHERE) appendLimitClause(bf, limitStart, limitCount); } if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSES_AROUND) appendLimitClause2(bf, limitStart, limitCount); final Type[] types = selectTypes; final Model model = query.model; final ArrayList<Object> result = new ArrayList<Object>(); if(limitStart<0) throw new RuntimeException(); if(selects.length!=selectColumns.length) throw new RuntimeException(); if(selects.length!=types.length) throw new RuntimeException(); //System.out.println(bf.toString()); query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(doCountOnly) { resultSet.next(); result.add(Integer.valueOf(resultSet.getInt(1))); if(resultSet.next()) throw new RuntimeException(); return; } if(limitStart>0 && limitSupport==LimitSupport.NONE) { // TODO: ResultSet.relative // Would like to use // resultSet.relative(limitStart+1); // but this throws a java.sql.SQLException: // Invalid operation for forward only resultset : relative for(int i = limitStart; i>0; i--) resultSet.next(); } int i = ((limitCount==Query.UNLIMITED_COUNT||(limitSupport!=LimitSupport.NONE)) ? Integer.MAX_VALUE : limitCount ); if(i<=0) throw new RuntimeException(String.valueOf(limitCount)); while(resultSet.next() && (--i)>=0) { int columnIndex = 1; final Object[] resultRow = (selects.length > 1) ? new Object[selects.length] : null; final Row dummyRow = new Row(); for(int selectIndex = 0; selectIndex<selects.length; selectIndex++) { final Selectable select; { Selectable select0 = selects[selectIndex]; if(select0 instanceof Aggregate) select0 = ((Aggregate)select0).getSource(); select = select0; } final Object resultCell; if(select instanceof FunctionAttribute) { selectColumns[selectIndex].load(resultSet, columnIndex++, dummyRow); final FunctionAttribute selectAttribute = (FunctionAttribute)select; if(select instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn(); if(typeColumn!=null) typeColumn.load(resultSet, columnIndex++, dummyRow); } resultCell = selectAttribute.get(dummyRow); } else if(select instanceof View) { final View selectFunction = (View)select; resultCell = selectFunction.load(resultSet, columnIndex++); } else { final Number pk = (Number)resultSet.getObject(columnIndex++); //System.out.println("pk:"+pk); if(pk==null) { // can happen when using right outer joins resultCell = null; } else { final Type type = types[selectIndex]; final Type currentType; if(type==null) { final String typeID = resultSet.getString(columnIndex++); currentType = model.findTypeByID(typeID); if(currentType==null) throw new RuntimeException("no type with type id "+typeID); } else currentType = type; resultCell = currentType.getItemObject(pk.intValue()); } } if(resultRow!=null) resultRow[selectIndex] = resultCell; else result.add(resultCell); } if(resultRow!=null) result.add(Collections.unmodifiableList(Arrays.asList(resultRow))); } } }, query.makeStatementInfo)); return result; } private void log(final long start, final long end, final Statement statement) { final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS"); System.out.println(df.format(new Date(start)) + " " + (end-start) + "ms: " + statement.getText()+" "+statement.parameters); } public void load(final Connection connection, final PersistentState state) { buildStage = false; listener.load(connection, state); final Statement bf = createStatement(state.type.supertype!=null); bf.append("select "); boolean first = true; for(Type type = state.type; type!=null; type = type.supertype) { for(final Column column : type.getTable().getColumns()) { if(!(column instanceof BlobColumn)) { if(first) first = false; else bf.append(','); bf.append(column).defineColumn(column); } } } if(first) { // no columns in type bf.appendPK(state.type, (Join)null); } bf.append(" from "); first = true; for(Type type = state.type; type!=null; type = type.supertype) { if(first) first = false; else bf.append(','); bf.append(type.getTable().protectedID); } bf.append(" where "); first = true; for(Type type = state.type; type!=null; type = type.supertype) { if(first) first = false; else bf.append(" and "); bf.appendPK(type, (Join)null). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail // Here this also checks for Model#findByID, // that the item has the type given in the ID. final StringColumn typeColumn = type.getTable().typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn). append('='). appendParameter(state.type.id); } } //System.out.println(bf.toString()); executeSQLQuery(connection, bf, state, false); } public void store( final Connection connection, final State state, final boolean present, final Map<BlobColumn, byte[]> blobs) { store(connection, state, present, blobs, state.type); } private void store( final Connection connection, final State state, final boolean present, final Map<BlobColumn, byte[]> blobs, final Type type) { buildStage = false; final Type supertype = type.supertype; if(supertype!=null) store(connection, state, present, blobs, supertype); final Table table = type.getTable(); final List<Column> columns = table.getColumns(); final Statement bf = createStatement(); final StringColumn typeColumn = table.typeColumn; if(present) { bf.append("update "). append(table.protectedID). append(" set "); boolean first = true; for(final Column column : columns) { if(!(column instanceof BlobColumn) || blobs.containsKey(column)) { if(first) first = false; else bf.append(','); bf.append(column.protectedID). append('='); if(column instanceof BlobColumn) bf.appendParameterBlob((BlobColumn)column, blobs.get(column)); else bf.appendParameter(column, state.store(column)); } } if(first) // no columns in table return; bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(state.type.id); } } else { bf.append("insert into "). append(table.protectedID). append("("). append(table.primaryKey.protectedID); if(typeColumn!=null) { bf.append(','). append(typeColumn.protectedID); } for(final Column column : columns) { if(!(column instanceof BlobColumn) || blobs.containsKey(column)) { bf.append(','). append(column.protectedID); } } bf.append(")values("). appendParameter(state.pk); if(typeColumn!=null) { bf.append(','). appendParameter(state.type.id); } for(final Column column : columns) { if(column instanceof BlobColumn) { if(blobs.containsKey(column)) { bf.append(','). appendParameterBlob((BlobColumn)column, blobs.get(column)); } } else { bf.append(','). appendParameter(column, state.store(column)); } } bf.append(')'); } //System.out.println("storing "+bf.toString()); final List uqs = type.declaredUniqueConstraints; executeSQLUpdate(connection, bf, 1, uqs.size()==1?(UniqueConstraint)uqs.iterator().next():null); } public void delete(final Connection connection, final Item item) { buildStage = false; final Type type = item.type; final int pk = item.pk; for(Type currentType = type; currentType!=null; currentType = currentType.supertype) { final Table currentTable = currentType.getTable(); final Statement bf = createStatement(); bf.append("delete from "). append(currentTable.protectedID). append(" where "). append(currentTable.primaryKey.protectedID). append('='). appendParameter(pk); //System.out.println("deleting "+bf.toString()); try { executeSQLUpdate(connection, bf, 1); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } } public final byte[] load(final Connection connection, final BlobColumn column, final Item item) { // TODO reuse code in load blob methods buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobResultSetHandler handler = new LoadBlobResultSetHandler(supportsGetBytes()); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class LoadBlobResultSetHandler implements ResultSetHandler { final boolean supportsGetBytes; LoadBlobResultSetHandler(final boolean supportsGetBytes) { this.supportsGetBytes = supportsGetBytes; } byte[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = supportsGetBytes ? resultSet.getBytes(1) : loadBlob(resultSet.getBlob(1)); } private static final byte[] loadBlob(final Blob blob) throws SQLException { if(blob==null) return null; return DataAttribute.copy(blob.getBinaryStream(), blob.length()); } } public final void load(final Connection connection, final BlobColumn column, final Item item, final OutputStream data, final DataAttribute attribute) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } executeSQLQuery(connection, bf, new ResultSetHandler(){ public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Blob blob = resultSet.getBlob(1); if(blob!=null) { InputStream source = null; try { source = blob.getBinaryStream(); attribute.copy(source, data, blob.length(), item); } catch(IOException e) { throw new RuntimeException(e); } finally { if(source!=null) { try { source.close(); } catch(IOException e) {/*IGNORE*/} } } } } }, false); } public final long loadLength(final Connection connection, final BlobColumn column, final Item item) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select length("). append(column.protectedID).defineColumnInteger(). append(") from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobLengthResultSetHandler handler = new LoadBlobLengthResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private class LoadBlobLengthResultSetHandler implements ResultSetHandler { long result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object o = resultSet.getObject(1); if(o!=null) { long value = ((Number)o).longValue(); final long factor = blobLengthFactor; if(factor!=1) { if(value%factor!=0) throw new RuntimeException("not dividable "+value+'/'+factor); value /= factor; } result = value; } else result = -1; } } public final void store( final Connection connection, final BlobColumn column, final Item item, final InputStream data, final DataAttribute attribute) throws IOException { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("update "). append(table.protectedID). append(" set "). append(column.protectedID). append('='); if(data!=null) bf.appendParameterBlob(column, data, attribute, item); else bf.append("NULL"); bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } //System.out.println("storing "+bf.toString()); try { executeSQLUpdate(connection, bf, 1, null); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } static interface ResultSetHandler { public void run(ResultSet resultSet) throws SQLException; } private final static int convertSQLResult(final Object sqlInteger) { // IMPLEMENTATION NOTE // Whether the returned object is an Integer, a Long or a BigDecimal, // depends on the database used and for oracle on whether // OracleStatement.defineColumnType is used or not, so we support all // here. return ((Number)sqlInteger).intValue(); } //private static int timeExecuteQuery = 0; protected final StatementInfo executeSQLQuery( final Connection connection, final Statement statement, final ResultSetHandler resultSetHandler, final boolean makeStatementInfo) { java.sql.Statement sqlStatement = null; ResultSet resultSet = null; try { final boolean log = this.log || makeStatementInfo; final String sqlText = statement.getText(); final long logStart = log ? System.currentTimeMillis() : 0; final long logPrepared; final long logExecuted; if(!prepare) { sqlStatement = connection.createStatement(); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = log ? System.currentTimeMillis() : 0; resultSet = sqlStatement.executeQuery(sqlText); logExecuted = log ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = log ? System.currentTimeMillis() : 0; resultSet = prepared.executeQuery(); logExecuted = log ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } final long logResultRead = log ? System.currentTimeMillis() : 0; if(resultSet!=null) { resultSet.close(); resultSet = null; } if(sqlStatement!=null) { sqlStatement.close(); sqlStatement = null; } final long logEnd = log ? System.currentTimeMillis() : 0; if(this.log) log(logStart, logEnd, statement); if(makeStatementInfo) return makeStatementInfo(statement, connection, logStart, logPrepared, logExecuted, logResultRead, logEnd); else return null; } catch(SQLException e) { throw new SQLRuntimeException(e, statement.toString()); } finally { if(resultSet!=null) { try { resultSet.close(); } catch(SQLException e) { // exception is already thrown } } if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows) throws UniqueViolationException { executeSQLUpdate(connection, statement, expectedRows, null); } private final void executeSQLUpdate( final Connection connection, final Statement statement, final int expectedRows, final UniqueConstraint onlyThreatenedUniqueConstraint) throws UniqueViolationException { java.sql.Statement sqlStatement = null; try { final String sqlText = statement.getText(); final long logStart = log ? System.currentTimeMillis() : 0; final int rows; if(!prepare) { sqlStatement = connection.createStatement(); rows = sqlStatement.executeUpdate(sqlText); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); rows = prepared.executeUpdate(); } final long logEnd = log ? System.currentTimeMillis() : 0; if(log) log(logStart, logEnd, statement); //System.out.println("("+rows+"): "+statement.getText()); if(rows!=expectedRows) throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText); } catch(SQLException e) { final UniqueViolationException wrappedException = wrapException(e, onlyThreatenedUniqueConstraint); if(wrappedException!=null) throw wrappedException; else throw new SQLRuntimeException(e, statement.toString()); } finally { if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private static final void setObject(String s, final PreparedStatement statement, final int parameterIndex, final Object value) throws SQLException { //try{ statement.setObject(parameterIndex, value); //}catch(SQLException e){ throw new SQLRuntimeException(e, "setObject("+parameterIndex+","+value+")"+s); } } protected static final String EXPLAIN_PLAN = "explain plan"; protected StatementInfo makeStatementInfo( final Statement statement, final Connection connection, final long start, final long prepared, final long executed, final long resultRead, final long end) { final StatementInfo result = new StatementInfo(statement.getText()); result.addChild(new StatementInfo("timing "+(end-start)+'/'+(prepared-start)+'/'+(executed-prepared)+'/'+(resultRead-executed)+'/'+(end-resultRead)+" (total/prepare/execute/readResult/close in ms)")); return result; } protected abstract String extractUniqueConstraintName(SQLException e); protected final static String ANY_CONSTRAINT = "--ANY--"; private final UniqueViolationException wrapException( final SQLException e, final UniqueConstraint onlyThreatenedUniqueConstraint) { final String uniqueConstraintID = extractUniqueConstraintName(e); if(uniqueConstraintID!=null) { final UniqueConstraint constraint; if(ANY_CONSTRAINT.equals(uniqueConstraintID)) constraint = onlyThreatenedUniqueConstraint; else { constraint = uniqueConstraintsByID.get(uniqueConstraintID); if(constraint==null) throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID +"<, has only "+uniqueConstraintsByID.keySet()); } return new UniqueViolationException(constraint, null, e); } return null; } /** * Trims a name to length for being a suitable qualifier for database entities, * such as tables, columns, indexes, constraints, partitions etc. */ protected static final String trimString(final String longString, final int maxLength) { if(maxLength<=0) throw new RuntimeException("maxLength must be greater zero"); if(longString.length()==0) throw new RuntimeException("longString must not be empty"); if(longString.length()<=maxLength) return longString; int longStringLength = longString.length(); final int[] trimPotential = new int[maxLength]; final ArrayList<String> words = new ArrayList<String>(); { final StringBuffer buf = new StringBuffer(); for(int i=0; i<longString.length(); i++) { final char c = longString.charAt(i); if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } if(buf.length()<maxLength) buf.append(c); else longStringLength--; } if(buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } } final int expectedTrimPotential = longStringLength - maxLength; //System.out.println("expected trim potential = "+expectedTrimPotential); int wordLength; int remainder = 0; for(wordLength = trimPotential.length-1; wordLength>=0; wordLength--) { //System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]); remainder = trimPotential[wordLength] - expectedTrimPotential; if(remainder>=0) break; } final StringBuffer result = new StringBuffer(longStringLength); for(final String word : words) { //System.out.println("word "+word+" remainder:"+remainder); if((word.length()>wordLength) && remainder>0) { result.append(word.substring(0, wordLength+1)); remainder--; } else if(word.length()>wordLength) result.append(word.substring(0, wordLength)); else result.append(word); } //System.out.println("---- trimName("+longString+","+maxLength+") == "+result+" --- "+words); if(result.length()!=maxLength) throw new RuntimeException(result.toString()+maxLength); return result.toString(); } public String makeName(final String longName) { return makeName(null, longName); } public String makeName(final String prefix, final String longName) { final String query = prefix==null ? longName : prefix+'.'+longName; final String forcedName = forcedNames.getProperty(query); //System.out.println("---------"+query+"--"+forcedName); if(forcedName!=null) return forcedName; return trimString(longName, 25); } public boolean supportsGetBytes() { return true; } public boolean supportsEmptyStrings() { return true; } public boolean supportsRightOuterJoins() { return true; } public boolean fakesSupportReadCommitted() { return false; } public int getBlobLengthFactor() { return 1; } public abstract String getIntegerType(long minimum, long maximum); public abstract String getDoubleType(); public abstract String getStringType(int maxLength); public abstract String getDayType(); /** * Returns a column type suitable for storing timestamps * with milliseconds resolution. * This method may return null, * if the database does not support such a column type. * The framework will then fall back to store the number of milliseconds. */ public abstract String getDateTimestampType(); public abstract String getBlobType(long maximumLength); abstract LimitSupport getLimitSupport(); static enum LimitSupport { NONE, CLAUSE_AFTER_SELECT, CLAUSE_AFTER_WHERE, CLAUSES_AROUND; } /** * Appends a clause to the statement causing the database limiting the query result. * This method is never called for <tt>start==0 && count=={@link Query#UNLIMITED_COUNT}</tt>. * NOTE: Don't forget the space before the keyword 'limit'! * @param start the number of rows to be skipped * or zero, if no rows to be skipped. * Is never negative. * @param count the number of rows to be returned * or {@link Query#UNLIMITED_COUNT} if all rows to be returned. * Is always positive (greater zero). */ abstract void appendLimitClause(Statement bf, int start, int count); /** * Same as {@link #appendLimitClause(Statement, int, int)}. * Is used for {@link LimitSupport#CLAUSES_AROUND} only, * for the postfix. */ abstract void appendLimitClause2(Statement bf, int start, int count); abstract void appendMatchClauseFullTextIndex(Statement bf, StringFunction function, String value); /** * Search full text. */ public final void appendMatchClause(final Statement bf, final StringFunction function, final String value) { if(fulltextIndex) appendMatchClauseFullTextIndex(bf, function, value); else appendMatchClauseByLike(bf, function, value); } protected final void appendMatchClauseByLike(final Statement bf, final StringFunction function, final String value) { bf.append(function, (Join)null). append(" like "). appendParameter(function, '%'+value+'%'); } private int countTable(final Connection connection, final Table table) { final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(). append(table.protectedID); final CountResultSetHandler handler = new CountResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class CountResultSetHandler implements ResultSetHandler { int result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = convertSQLResult(resultSet.getObject(1)); } } public final PkSource makePkSource(final Table table) { return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table); } public final int[] getMinMaxPK(final Connection connection, final Table table) { buildStage = false; final Statement bf = createStatement(); final String primaryKeyProtectedID = table.primaryKey.protectedID; bf.append("select min("). append(primaryKeyProtectedID).defineColumnInteger(). append("),max("). append(primaryKeyProtectedID).defineColumnInteger(). append(") from "). append(table.protectedID); final NextPKResultSetHandler handler = new NextPKResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class NextPKResultSetHandler implements ResultSetHandler { int[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object oLo = resultSet.getObject(1); if(oLo!=null) { result = new int[2]; result[0] = convertSQLResult(oLo); final Object oHi = resultSet.getObject(2); result[1] = convertSQLResult(oHi); } } } final int checkTypeColumn(final Connection connection, final Type type) { buildStage = false; final Table table = type.getTable(); final Table superTable = type.getSupertype().getTable(); final Statement bf = createStatement(true); bf.append("select count(*) from "). append(table).append(',').append(superTable). append(" where "). append(table.primaryKey).append('=').append(superTable.primaryKey). append(" and "); if(table.typeColumn!=null) bf.append(table.typeColumn); else bf.appendParameter(type.id); bf.append("<>").append(superTable.typeColumn); //System.out.println("CHECKT:"+bf.toString()); final CheckTypeColumnResultSetHandler handler = new CheckTypeColumnResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } final int checkTypeColumn(final Connection connection, final ItemAttribute attribute) { buildStage = false; final Table table = attribute.getType().getTable(); final Table valueTable = attribute.getValueType().getTable(); final String alias1 = driver.protectName(Table.SQL_ALIAS_1); final String alias2 = driver.protectName(Table.SQL_ALIAS_2); final Statement bf = createStatement(false); bf.append("select count(*) from "). append(table).append(' ').append(alias1). append(','). append(valueTable).append(' ').append(alias2). append(" where "). append(alias1).append('.').append(attribute.getColumn()). append('='). append(alias2).append('.').append(valueTable.primaryKey). append(" and "). append(alias1).append('.').append(attribute.getTypeColumn()). append("<>"). append(alias2).append('.').append(valueTable.typeColumn); //System.out.println("CHECKA:"+bf.toString()); final CheckTypeColumnResultSetHandler handler = new CheckTypeColumnResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class CheckTypeColumnResultSetHandler implements ResultSetHandler { int result = Integer.MIN_VALUE; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException(); result = resultSet.getInt(1); } } public final Schema makeSchema() { final Schema result = new Schema(driver, connectionPool); for(final Table t : tables) t.makeSchema(result); completeSchema(result); return result; } protected void completeSchema(final Schema schema) { // empty default implementation } public final Schema makeVerifiedSchema() { final Schema result = makeSchema(); result.verify(); return result; } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated protected static final void printMeta(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println("------"+i+":"+metaData.getColumnName(i)+":"+metaData.getColumnType(i)); } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated protected static final void printRow(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println("----------"+i+":"+resultSet.getObject(i)); } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated static final ResultSetHandler logHandler = new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { final int columnCount = resultSet.getMetaData().getColumnCount(); System.out.println("columnCount:"+columnCount); final ResultSetMetaData meta = resultSet.getMetaData(); for(int i = 1; i<=columnCount; i++) { System.out.println(meta.getColumnName(i)+"|"); } while(resultSet.next()) { for(int i = 1; i<=columnCount; i++) { System.out.println(resultSet.getObject(i)+"|"); } } } }; public boolean isDefiningColumnTypes() { return false; } public void defineColumnTypes(IntList columnTypes, java.sql.Statement statement) throws SQLException { // default implementation does nothing, may be overwritten by subclasses } protected void close() { getConnectionPool().flush(); } // listeners ------------------ private static final DatabaseListener noopListener = new DatabaseListener() { public void load(Connection connection, PersistentState state) {/* DOES NOTHING */} public void search(Connection connection, Query query, boolean doCountOnly) {/* DOES NOTHING */} }; private DatabaseListener listener = noopListener; private final Object listenerLock = new Object(); public DatabaseListener setListener(DatabaseListener listener) { if(listener==null) listener = noopListener; DatabaseListener result; synchronized(listenerLock) { result = this.listener; this.listener = listener; } if(result==noopListener) result = null; return result; } }
runtime/src/com/exedio/cope/Database.java
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import bak.pcj.list.IntList; import com.exedio.dsmf.Driver; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; abstract class Database { protected static final int TWOPOW8 = 1<<8; protected static final int TWOPOW16 = 1<<16; protected static final int TWOPOW24 = 1<<24; private static final String NO_SUCH_ROW = "no such row"; private final ArrayList<Table> tables = new ArrayList<Table>(); private final HashMap<String, UniqueConstraint> uniqueConstraintsByID = new HashMap<String, UniqueConstraint>(); private boolean buildStage = true; final Driver driver; private final boolean prepare; private final boolean log; private final boolean butterflyPkSource; private final boolean fulltextIndex; final ConnectionPool connectionPool; private final java.util.Properties forcedNames; final java.util.Properties tableOptions; final LimitSupport limitSupport; final long blobLengthFactor; // probed on the initial connection final boolean supportsReadCommitted; final String databaseProductName; final String databaseProductVersion; final int databaseMajorVersion; final int databaseMinorVersion; final String driverName; final String driverVersion; final int driverMajorVersion; final int driverMinorVersion; final boolean oracle; // TODO remove protected Database(final Driver driver, final Properties properties) { this.driver = driver; this.prepare = !properties.getDatabaseDontSupportPreparedStatements(); this.log = properties.getDatabaseLog(); this.butterflyPkSource = properties.getPkSourceButterfly(); this.fulltextIndex = properties.getFulltextIndex(); this.connectionPool = new ConnectionPool(properties); this.forcedNames = properties.getDatabaseForcedNames(); this.tableOptions = properties.getDatabaseTableOptions(); this.limitSupport = properties.getDatabaseDontSupportLimit() ? LimitSupport.NONE : getLimitSupport(); this.blobLengthFactor = getBlobLengthFactor(); this.oracle = getClass().getName().equals("com.exedio.cope.OracleDatabase"); //System.out.println("using database "+getClass()); assert limitSupport!=null; Connection probeConnection = null; String probeError = "unknown"; try { probeConnection = connectionPool.getConnection(); probeError = "getMetaData()"; final DatabaseMetaData dmd = probeConnection.getMetaData(); probeError = "supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED)"; supportsReadCommitted = !fakesSupportReadCommitted() && dmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED); probeError = "getInfo"; databaseProductName = dmd.getDatabaseProductName(); databaseProductVersion = dmd.getDatabaseProductVersion(); databaseMajorVersion = dmd.getDatabaseMajorVersion(); databaseMinorVersion = dmd.getDatabaseMinorVersion(); driverName = dmd.getDriverName(); driverVersion = dmd.getDriverVersion(); driverMajorVersion = dmd.getDriverMajorVersion(); driverMinorVersion = dmd.getDriverMinorVersion(); } catch(SQLException e) { throw new SQLRuntimeException(e, probeError); } finally { if(probeConnection!=null) { try { connectionPool.putConnection(probeConnection); probeConnection = null; } catch(SQLException e) { throw new SQLRuntimeException(e, "putConnection"); } } } } public final Driver getDriver() { return driver; } public final java.util.Properties getTableOptions() { return tableOptions; } public final ConnectionPool getConnectionPool() { return connectionPool; } public final void addTable(final Table table) { if(!buildStage) throw new RuntimeException(); tables.add(table); } public final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint) { if(!buildStage) throw new RuntimeException(); final Object collision = uniqueConstraintsByID.put(constraintID, constraint); if(collision!=null) throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision); } protected final Statement createStatement() { return createStatement(true); } protected final Statement createStatement(final boolean qualifyTable) { return new Statement(this, prepare, qualifyTable, isDefiningColumnTypes()); } protected final Statement createStatement(final Query<? extends Object> query) { return new Statement(this, prepare, query, isDefiningColumnTypes()); } public void createDatabase() { buildStage = false; makeSchema().create(); } public void createDatabaseConstraints(final int mask) { buildStage = false; makeSchema().createConstraints(mask); } //private static int checkTableTime = 0; public void checkDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); // IMPLEMENTATION NOTE // MySQL can have at most 63 joined tables in one statement // and other databases probably have similar constraints as // well, so we limit the number of joined table here. final int CHUNK_LENGTH = 60; final int tablesSize = tables.size(); for(int chunkFromIndex = 0; chunkFromIndex<tablesSize; chunkFromIndex+=CHUNK_LENGTH) { final int chunkToIndex = Math.min(chunkFromIndex+CHUNK_LENGTH, tablesSize); final List<Table> tableChunk = tables.subList(chunkFromIndex, chunkToIndex); final Statement bf = createStatement(true); bf.append("select count(*) from ").defineColumnInteger(); boolean first = true; for(final Table table : tableChunk) { if(first) first = false; else bf.append(','); bf.append(table.protectedID); } bf.append(" where "); first = true; for(final Table table : tableChunk) { if(first) first = false; else bf.append(" and "); final Column primaryKey = table.primaryKey; bf.append(primaryKey). append('='). appendParameter(Type.NOT_A_PK); for(final Column column : table.getColumns()) { bf.append(" and "). append(column); if(column instanceof BlobColumn || (oracle && column instanceof StringColumn && ((StringColumn)column).maximumLength>=4000)) { bf.append("is not null"); } else { bf.append('='). appendParameter(column, column.getCheckValue()); } } } //System.out.println("-----------"+chunkFromIndex+"-"+chunkToIndex+"----"+bf); executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); } }, false ); } } public void dropDatabase() { buildStage = false; makeSchema().drop(); } public void dropDatabaseConstraints(final int mask) { buildStage = false; makeSchema().dropConstraints(mask); } public void tearDownDatabase() { buildStage = false; makeSchema().tearDown(); } public void tearDownDatabaseConstraints(final int mask) { buildStage = false; makeSchema().tearDownConstraints(mask); } public void checkEmptyDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); for(final Table table : tables) { final int count = countTable(connection, table); if(count>0) throw new RuntimeException("there are "+count+" items left for table "+table.id); } //final long amount = (System.currentTimeMillis()-time); //checkEmptyTableTime += amount; //System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime); } public final ArrayList<Object> search(final Connection connection, final Query<? extends Object> query, final boolean doCountOnly) { buildStage = false; listener.search(connection, query, doCountOnly); final int limitStart = query.limitStart; final int limitCount = query.limitCount; final boolean limitActive = limitStart>0 || limitCount!=Query.UNLIMITED_COUNT; final ArrayList<Join> queryJoins = query.joins; final Statement bf = createStatement(query); if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSES_AROUND) appendLimitClause(bf, limitStart, limitCount); bf.append("select"); if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSE_AFTER_SELECT) appendLimitClause(bf, limitStart, limitCount); bf.append(' '); if(query.distinct) bf.append("distinct "); final Selectable[] selects = query.selects; final Column[] selectColumns = new Column[selects.length]; final Type[] selectTypes = new Type[selects.length]; if(doCountOnly) { bf.append("count(*)"); } else { for(int selectIndex = 0; selectIndex<selects.length; selectIndex++) { final Selectable select = selects[selectIndex]; final Column selectColumn; final Type selectType = select.getType(); final Table selectTable; final Column selectPrimaryKey; if(selectIndex>0) bf.append(','); if(select instanceof Aggregate) { bf.append(select, null).defineColumn(select); final Function selectSource = ((Aggregate)select).getSource(); if(selectSource instanceof FunctionAttribute) { selectColumn = ((FunctionAttribute)selectSource).getColumn(); } else if(selectSource instanceof Type.This) { selectTable = selectType.getTable(); selectPrimaryKey = selectTable.primaryKey; selectColumn = selectPrimaryKey; if(selectColumn.primaryKey) { final StringColumn selectTypeColumn = selectColumn.getTypeColumn(); if(selectTypeColumn==null) selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else { selectColumn = null; final View view = (View)selectSource; bf.append(view, (Join)null).defineColumn(view); } } else if(select instanceof FunctionAttribute) { selectColumn = ((FunctionAttribute)select).getColumn(); bf.append(select, (Join)null).defineColumn(select); if(select instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)select).getTypeColumn(); if(typeColumn!=null) bf.append(',').append(typeColumn).defineColumn(typeColumn); } } else if(select instanceof Type.This) { selectTable = selectType.getTable(); selectPrimaryKey = selectTable.primaryKey; selectColumn = selectPrimaryKey; bf.appendPK(selectType, (Join)null).defineColumn(select); if(selectColumn.primaryKey) { final StringColumn selectTypeColumn = selectColumn.getTypeColumn(); if(selectTypeColumn!=null) { bf.append(','). append(selectTypeColumn).defineColumn(selectTypeColumn); } else selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else { selectColumn = null; final View view = (View)select; bf.append(view, (Join)null).defineColumn(view); } selectColumns[selectIndex] = selectColumn; } } bf.append(" from "). appendTableDefinition((Join)null, query.type.getTable()). appendTypeDefinition((Join)null, query.type); if(queryJoins!=null) { for(final Join join : queryJoins) { bf.append(' '). append(join.kind.sql). append(" join "). appendTableDefinition(join, join.type.getTable()); final Condition joinCondition = join.condition; if(joinCondition!=null) { bf.append(" on "); joinCondition.append(bf); } bf.appendTypeDefinition(join, join.type); } } if(query.condition!=null) { bf.append(" where "); query.condition.append(bf); } if(!doCountOnly) { final Function[] orderBy = query.orderBy; if(orderBy!=null) { final boolean[] orderAscending = query.orderAscending; for(int i = 0; i<orderBy.length; i++) { if(i==0) bf.append(" order by "); else bf.append(','); if(orderBy[i] instanceof ItemAttribute) { final ItemAttribute<? extends Item> itemOrderBy = (ItemAttribute<? extends Item>)orderBy[i]; itemOrderBy.getValueType().getPkSource().appendOrderByExpression(bf, itemOrderBy); } else if(orderBy[i] instanceof Type.This) { final Type.This<? extends Item> itemOrderBy = (Type.This<? extends Item>)orderBy[i]; itemOrderBy.type.getPkSource().appendOrderByExpression(bf, itemOrderBy); } else bf.append(orderBy[i], (Join)null); if(!orderAscending[i]) bf.append(" desc"); // TODO break here, if already ordered by some unique function } } if(limitActive && limitSupport==LimitSupport.CLAUSE_AFTER_WHERE) appendLimitClause(bf, limitStart, limitCount); } if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSES_AROUND) appendLimitClause2(bf, limitStart, limitCount); final Type[] types = selectTypes; final Model model = query.model; final ArrayList<Object> result = new ArrayList<Object>(); if(limitStart<0) throw new RuntimeException(); if(selects.length!=selectColumns.length) throw new RuntimeException(); if(selects.length!=types.length) throw new RuntimeException(); //System.out.println(bf.toString()); query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(doCountOnly) { resultSet.next(); result.add(Integer.valueOf(resultSet.getInt(1))); if(resultSet.next()) throw new RuntimeException(); return; } if(limitStart>0 && limitSupport==LimitSupport.NONE) { // TODO: ResultSet.relative // Would like to use // resultSet.relative(limitStart+1); // but this throws a java.sql.SQLException: // Invalid operation for forward only resultset : relative for(int i = limitStart; i>0; i--) resultSet.next(); } int i = ((limitCount==Query.UNLIMITED_COUNT||(limitSupport!=LimitSupport.NONE)) ? Integer.MAX_VALUE : limitCount ); if(i<=0) throw new RuntimeException(String.valueOf(limitCount)); while(resultSet.next() && (--i)>=0) { int columnIndex = 1; final Object[] resultRow = (selects.length > 1) ? new Object[selects.length] : null; final Row dummyRow = new Row(); for(int selectIndex = 0; selectIndex<selects.length; selectIndex++) { final Selectable select; { Selectable select0 = selects[selectIndex]; if(select0 instanceof Aggregate) select0 = ((Aggregate)select0).getSource(); select = select0; } final Object resultCell; if(select instanceof FunctionAttribute) { selectColumns[selectIndex].load(resultSet, columnIndex++, dummyRow); final FunctionAttribute selectAttribute = (FunctionAttribute)select; if(select instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn(); if(typeColumn!=null) typeColumn.load(resultSet, columnIndex++, dummyRow); } resultCell = selectAttribute.get(dummyRow); } else if(select instanceof View) { final View selectFunction = (View)select; resultCell = selectFunction.load(resultSet, columnIndex++); } else { final Number pk = (Number)resultSet.getObject(columnIndex++); //System.out.println("pk:"+pk); if(pk==null) { // can happen when using right outer joins resultCell = null; } else { final Type type = types[selectIndex]; final Type currentType; if(type==null) { final String typeID = resultSet.getString(columnIndex++); currentType = model.findTypeByID(typeID); if(currentType==null) throw new RuntimeException("no type with type id "+typeID); } else currentType = type; resultCell = currentType.getItemObject(pk.intValue()); } } if(resultRow!=null) resultRow[selectIndex] = resultCell; else result.add(resultCell); } if(resultRow!=null) result.add(Collections.unmodifiableList(Arrays.asList(resultRow))); } } }, query.makeStatementInfo)); return result; } private void log(final long start, final long end, final String sqlText) { final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS"); System.out.println(df.format(new Date(start)) + " " + (end-start) + "ms: " + sqlText); } public void load(final Connection connection, final PersistentState state) { buildStage = false; listener.load(connection, state); final Statement bf = createStatement(state.type.supertype!=null); bf.append("select "); boolean first = true; for(Type type = state.type; type!=null; type = type.supertype) { for(final Column column : type.getTable().getColumns()) { if(!(column instanceof BlobColumn)) { if(first) first = false; else bf.append(','); bf.append(column).defineColumn(column); } } } if(first) { // no columns in type bf.appendPK(state.type, (Join)null); } bf.append(" from "); first = true; for(Type type = state.type; type!=null; type = type.supertype) { if(first) first = false; else bf.append(','); bf.append(type.getTable().protectedID); } bf.append(" where "); first = true; for(Type type = state.type; type!=null; type = type.supertype) { if(first) first = false; else bf.append(" and "); bf.appendPK(type, (Join)null). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail // Here this also checks for Model#findByID, // that the item has the type given in the ID. final StringColumn typeColumn = type.getTable().typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn). append('='). appendParameter(state.type.id); } } //System.out.println(bf.toString()); executeSQLQuery(connection, bf, state, false); } public void store( final Connection connection, final State state, final boolean present, final Map<BlobColumn, byte[]> blobs) { store(connection, state, present, blobs, state.type); } private void store( final Connection connection, final State state, final boolean present, final Map<BlobColumn, byte[]> blobs, final Type type) { buildStage = false; final Type supertype = type.supertype; if(supertype!=null) store(connection, state, present, blobs, supertype); final Table table = type.getTable(); final List<Column> columns = table.getColumns(); final Statement bf = createStatement(); final StringColumn typeColumn = table.typeColumn; if(present) { bf.append("update "). append(table.protectedID). append(" set "); boolean first = true; for(final Column column : columns) { if(!(column instanceof BlobColumn) || blobs.containsKey(column)) { if(first) first = false; else bf.append(','); bf.append(column.protectedID). append('='); if(column instanceof BlobColumn) bf.appendParameterBlob((BlobColumn)column, blobs.get(column)); else bf.appendParameter(column, state.store(column)); } } if(first) // no columns in table return; bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(state.type.id); } } else { bf.append("insert into "). append(table.protectedID). append("("). append(table.primaryKey.protectedID); if(typeColumn!=null) { bf.append(','). append(typeColumn.protectedID); } for(final Column column : columns) { if(!(column instanceof BlobColumn) || blobs.containsKey(column)) { bf.append(','). append(column.protectedID); } } bf.append(")values("). appendParameter(state.pk); if(typeColumn!=null) { bf.append(','). appendParameter(state.type.id); } for(final Column column : columns) { if(column instanceof BlobColumn) { if(blobs.containsKey(column)) { bf.append(','). appendParameterBlob((BlobColumn)column, blobs.get(column)); } } else { bf.append(','). appendParameter(column, state.store(column)); } } bf.append(')'); } //System.out.println("storing "+bf.toString()); final List uqs = type.declaredUniqueConstraints; executeSQLUpdate(connection, bf, 1, uqs.size()==1?(UniqueConstraint)uqs.iterator().next():null); } public void delete(final Connection connection, final Item item) { buildStage = false; final Type type = item.type; final int pk = item.pk; for(Type currentType = type; currentType!=null; currentType = currentType.supertype) { final Table currentTable = currentType.getTable(); final Statement bf = createStatement(); bf.append("delete from "). append(currentTable.protectedID). append(" where "). append(currentTable.primaryKey.protectedID). append('='). appendParameter(pk); //System.out.println("deleting "+bf.toString()); try { executeSQLUpdate(connection, bf, 1); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } } public final byte[] load(final Connection connection, final BlobColumn column, final Item item) { // TODO reuse code in load blob methods buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobResultSetHandler handler = new LoadBlobResultSetHandler(supportsGetBytes()); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class LoadBlobResultSetHandler implements ResultSetHandler { final boolean supportsGetBytes; LoadBlobResultSetHandler(final boolean supportsGetBytes) { this.supportsGetBytes = supportsGetBytes; } byte[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = supportsGetBytes ? resultSet.getBytes(1) : loadBlob(resultSet.getBlob(1)); } private static final byte[] loadBlob(final Blob blob) throws SQLException { if(blob==null) return null; return DataAttribute.copy(blob.getBinaryStream(), blob.length()); } } public final void load(final Connection connection, final BlobColumn column, final Item item, final OutputStream data, final DataAttribute attribute) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } executeSQLQuery(connection, bf, new ResultSetHandler(){ public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Blob blob = resultSet.getBlob(1); if(blob!=null) { InputStream source = null; try { source = blob.getBinaryStream(); attribute.copy(source, data, blob.length(), item); } catch(IOException e) { throw new RuntimeException(e); } finally { if(source!=null) { try { source.close(); } catch(IOException e) {/*IGNORE*/} } } } } }, false); } public final long loadLength(final Connection connection, final BlobColumn column, final Item item) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select length("). append(column.protectedID).defineColumnInteger(). append(") from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobLengthResultSetHandler handler = new LoadBlobLengthResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private class LoadBlobLengthResultSetHandler implements ResultSetHandler { long result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object o = resultSet.getObject(1); if(o!=null) { long value = ((Number)o).longValue(); final long factor = blobLengthFactor; if(factor!=1) { if(value%factor!=0) throw new RuntimeException("not dividable "+value+'/'+factor); value /= factor; } result = value; } else result = -1; } } public final void store( final Connection connection, final BlobColumn column, final Item item, final InputStream data, final DataAttribute attribute) throws IOException { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("update "). append(table.protectedID). append(" set "). append(column.protectedID). append('='); if(data!=null) bf.appendParameterBlob(column, data, attribute, item); else bf.append("NULL"); bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } //System.out.println("storing "+bf.toString()); try { executeSQLUpdate(connection, bf, 1, null); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } static interface ResultSetHandler { public void run(ResultSet resultSet) throws SQLException; } private final static int convertSQLResult(final Object sqlInteger) { // IMPLEMENTATION NOTE // Whether the returned object is an Integer, a Long or a BigDecimal, // depends on the database used and for oracle on whether // OracleStatement.defineColumnType is used or not, so we support all // here. return ((Number)sqlInteger).intValue(); } //private static int timeExecuteQuery = 0; protected final StatementInfo executeSQLQuery( final Connection connection, final Statement statement, final ResultSetHandler resultSetHandler, final boolean makeStatementInfo) { java.sql.Statement sqlStatement = null; ResultSet resultSet = null; try { final boolean log = this.log || makeStatementInfo; final String sqlText = statement.getText(); final long logStart = log ? System.currentTimeMillis() : 0; final long logPrepared; final long logExecuted; if(!prepare) { sqlStatement = connection.createStatement(); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = log ? System.currentTimeMillis() : 0; resultSet = sqlStatement.executeQuery(sqlText); logExecuted = log ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = log ? System.currentTimeMillis() : 0; resultSet = prepared.executeQuery(); logExecuted = log ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } final long logResultRead = log ? System.currentTimeMillis() : 0; if(resultSet!=null) { resultSet.close(); resultSet = null; } if(sqlStatement!=null) { sqlStatement.close(); sqlStatement = null; } final long logEnd = log ? System.currentTimeMillis() : 0; if(this.log) log(logStart, logEnd, sqlText); if(makeStatementInfo) return makeStatementInfo(statement, connection, logStart, logPrepared, logExecuted, logResultRead, logEnd); else return null; } catch(SQLException e) { throw new SQLRuntimeException(e, statement.toString()); } finally { if(resultSet!=null) { try { resultSet.close(); } catch(SQLException e) { // exception is already thrown } } if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows) throws UniqueViolationException { executeSQLUpdate(connection, statement, expectedRows, null); } private final void executeSQLUpdate( final Connection connection, final Statement statement, final int expectedRows, final UniqueConstraint onlyThreatenedUniqueConstraint) throws UniqueViolationException { java.sql.Statement sqlStatement = null; try { final String sqlText = statement.getText(); final long logStart = log ? System.currentTimeMillis() : 0; final int rows; if(!prepare) { sqlStatement = connection.createStatement(); rows = sqlStatement.executeUpdate(sqlText); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); rows = prepared.executeUpdate(); } final long logEnd = log ? System.currentTimeMillis() : 0; if(log) log(logStart, logEnd, sqlText); //System.out.println("("+rows+"): "+statement.getText()); if(rows!=expectedRows) throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText); } catch(SQLException e) { final UniqueViolationException wrappedException = wrapException(e, onlyThreatenedUniqueConstraint); if(wrappedException!=null) throw wrappedException; else throw new SQLRuntimeException(e, statement.toString()); } finally { if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private static final void setObject(String s, final PreparedStatement statement, final int parameterIndex, final Object value) throws SQLException { //try{ statement.setObject(parameterIndex, value); //}catch(SQLException e){ throw new SQLRuntimeException(e, "setObject("+parameterIndex+","+value+")"+s); } } protected static final String EXPLAIN_PLAN = "explain plan"; protected StatementInfo makeStatementInfo( final Statement statement, final Connection connection, final long start, final long prepared, final long executed, final long resultRead, final long end) { final StatementInfo result = new StatementInfo(statement.getText()); result.addChild(new StatementInfo("timing "+(end-start)+'/'+(prepared-start)+'/'+(executed-prepared)+'/'+(resultRead-executed)+'/'+(end-resultRead)+" (total/prepare/execute/readResult/close in ms)")); return result; } protected abstract String extractUniqueConstraintName(SQLException e); protected final static String ANY_CONSTRAINT = "--ANY--"; private final UniqueViolationException wrapException( final SQLException e, final UniqueConstraint onlyThreatenedUniqueConstraint) { final String uniqueConstraintID = extractUniqueConstraintName(e); if(uniqueConstraintID!=null) { final UniqueConstraint constraint; if(ANY_CONSTRAINT.equals(uniqueConstraintID)) constraint = onlyThreatenedUniqueConstraint; else { constraint = uniqueConstraintsByID.get(uniqueConstraintID); if(constraint==null) throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID +"<, has only "+uniqueConstraintsByID.keySet()); } return new UniqueViolationException(constraint, null, e); } return null; } /** * Trims a name to length for being a suitable qualifier for database entities, * such as tables, columns, indexes, constraints, partitions etc. */ protected static final String trimString(final String longString, final int maxLength) { if(maxLength<=0) throw new RuntimeException("maxLength must be greater zero"); if(longString.length()==0) throw new RuntimeException("longString must not be empty"); if(longString.length()<=maxLength) return longString; int longStringLength = longString.length(); final int[] trimPotential = new int[maxLength]; final ArrayList<String> words = new ArrayList<String>(); { final StringBuffer buf = new StringBuffer(); for(int i=0; i<longString.length(); i++) { final char c = longString.charAt(i); if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } if(buf.length()<maxLength) buf.append(c); else longStringLength--; } if(buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } } final int expectedTrimPotential = longStringLength - maxLength; //System.out.println("expected trim potential = "+expectedTrimPotential); int wordLength; int remainder = 0; for(wordLength = trimPotential.length-1; wordLength>=0; wordLength--) { //System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]); remainder = trimPotential[wordLength] - expectedTrimPotential; if(remainder>=0) break; } final StringBuffer result = new StringBuffer(longStringLength); for(final String word : words) { //System.out.println("word "+word+" remainder:"+remainder); if((word.length()>wordLength) && remainder>0) { result.append(word.substring(0, wordLength+1)); remainder--; } else if(word.length()>wordLength) result.append(word.substring(0, wordLength)); else result.append(word); } //System.out.println("---- trimName("+longString+","+maxLength+") == "+result+" --- "+words); if(result.length()!=maxLength) throw new RuntimeException(result.toString()+maxLength); return result.toString(); } public String makeName(final String longName) { return makeName(null, longName); } public String makeName(final String prefix, final String longName) { final String query = prefix==null ? longName : prefix+'.'+longName; final String forcedName = forcedNames.getProperty(query); //System.out.println("---------"+query+"--"+forcedName); if(forcedName!=null) return forcedName; return trimString(longName, 25); } public boolean supportsGetBytes() { return true; } public boolean supportsEmptyStrings() { return true; } public boolean supportsRightOuterJoins() { return true; } public boolean fakesSupportReadCommitted() { return false; } public int getBlobLengthFactor() { return 1; } public abstract String getIntegerType(long minimum, long maximum); public abstract String getDoubleType(); public abstract String getStringType(int maxLength); public abstract String getDayType(); /** * Returns a column type suitable for storing timestamps * with milliseconds resolution. * This method may return null, * if the database does not support such a column type. * The framework will then fall back to store the number of milliseconds. */ public abstract String getDateTimestampType(); public abstract String getBlobType(long maximumLength); abstract LimitSupport getLimitSupport(); static enum LimitSupport { NONE, CLAUSE_AFTER_SELECT, CLAUSE_AFTER_WHERE, CLAUSES_AROUND; } /** * Appends a clause to the statement causing the database limiting the query result. * This method is never called for <tt>start==0 && count=={@link Query#UNLIMITED_COUNT}</tt>. * NOTE: Don't forget the space before the keyword 'limit'! * @param start the number of rows to be skipped * or zero, if no rows to be skipped. * Is never negative. * @param count the number of rows to be returned * or {@link Query#UNLIMITED_COUNT} if all rows to be returned. * Is always positive (greater zero). */ abstract void appendLimitClause(Statement bf, int start, int count); /** * Same as {@link #appendLimitClause(Statement, int, int)}. * Is used for {@link LimitSupport#CLAUSES_AROUND} only, * for the postfix. */ abstract void appendLimitClause2(Statement bf, int start, int count); abstract void appendMatchClauseFullTextIndex(Statement bf, StringFunction function, String value); /** * Search full text. */ public final void appendMatchClause(final Statement bf, final StringFunction function, final String value) { if(fulltextIndex) appendMatchClauseFullTextIndex(bf, function, value); else appendMatchClauseByLike(bf, function, value); } protected final void appendMatchClauseByLike(final Statement bf, final StringFunction function, final String value) { bf.append(function, (Join)null). append(" like "). appendParameter(function, '%'+value+'%'); } private int countTable(final Connection connection, final Table table) { final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(). append(table.protectedID); final CountResultSetHandler handler = new CountResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class CountResultSetHandler implements ResultSetHandler { int result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = convertSQLResult(resultSet.getObject(1)); } } public final PkSource makePkSource(final Table table) { return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table); } public final int[] getMinMaxPK(final Connection connection, final Table table) { buildStage = false; final Statement bf = createStatement(); final String primaryKeyProtectedID = table.primaryKey.protectedID; bf.append("select min("). append(primaryKeyProtectedID).defineColumnInteger(). append("),max("). append(primaryKeyProtectedID).defineColumnInteger(). append(") from "). append(table.protectedID); final NextPKResultSetHandler handler = new NextPKResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class NextPKResultSetHandler implements ResultSetHandler { int[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object oLo = resultSet.getObject(1); if(oLo!=null) { result = new int[2]; result[0] = convertSQLResult(oLo); final Object oHi = resultSet.getObject(2); result[1] = convertSQLResult(oHi); } } } final int checkTypeColumn(final Connection connection, final Type type) { buildStage = false; final Table table = type.getTable(); final Table superTable = type.getSupertype().getTable(); final Statement bf = createStatement(true); bf.append("select count(*) from "). append(table).append(',').append(superTable). append(" where "). append(table.primaryKey).append('=').append(superTable.primaryKey). append(" and "); if(table.typeColumn!=null) bf.append(table.typeColumn); else bf.appendParameter(type.id); bf.append("<>").append(superTable.typeColumn); //System.out.println("CHECKT:"+bf.toString()); final CheckTypeColumnResultSetHandler handler = new CheckTypeColumnResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } final int checkTypeColumn(final Connection connection, final ItemAttribute attribute) { buildStage = false; final Table table = attribute.getType().getTable(); final Table valueTable = attribute.getValueType().getTable(); final String alias1 = driver.protectName(Table.SQL_ALIAS_1); final String alias2 = driver.protectName(Table.SQL_ALIAS_2); final Statement bf = createStatement(false); bf.append("select count(*) from "). append(table).append(' ').append(alias1). append(','). append(valueTable).append(' ').append(alias2). append(" where "). append(alias1).append('.').append(attribute.getColumn()). append('='). append(alias2).append('.').append(valueTable.primaryKey). append(" and "). append(alias1).append('.').append(attribute.getTypeColumn()). append("<>"). append(alias2).append('.').append(valueTable.typeColumn); //System.out.println("CHECKA:"+bf.toString()); final CheckTypeColumnResultSetHandler handler = new CheckTypeColumnResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class CheckTypeColumnResultSetHandler implements ResultSetHandler { int result = Integer.MIN_VALUE; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException(); result = resultSet.getInt(1); } } public final Schema makeSchema() { final Schema result = new Schema(driver, connectionPool); for(final Table t : tables) t.makeSchema(result); completeSchema(result); return result; } protected void completeSchema(final Schema schema) { // empty default implementation } public final Schema makeVerifiedSchema() { final Schema result = makeSchema(); result.verify(); return result; } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated protected static final void printMeta(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println("------"+i+":"+metaData.getColumnName(i)+":"+metaData.getColumnType(i)); } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated protected static final void printRow(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println("----------"+i+":"+resultSet.getObject(i)); } /** * @deprecated for debugging only, should never be used in committed code */ @Deprecated static final ResultSetHandler logHandler = new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { final int columnCount = resultSet.getMetaData().getColumnCount(); System.out.println("columnCount:"+columnCount); final ResultSetMetaData meta = resultSet.getMetaData(); for(int i = 1; i<=columnCount; i++) { System.out.println(meta.getColumnName(i)+"|"); } while(resultSet.next()) { for(int i = 1; i<=columnCount; i++) { System.out.println(resultSet.getObject(i)+"|"); } } } }; public boolean isDefiningColumnTypes() { return false; } public void defineColumnTypes(IntList columnTypes, java.sql.Statement statement) throws SQLException { // default implementation does nothing, may be overwritten by subclasses } protected void close() { getConnectionPool().flush(); } // listeners ------------------ private static final DatabaseListener noopListener = new DatabaseListener() { public void load(Connection connection, PersistentState state) {/* DOES NOTHING */} public void search(Connection connection, Query query, boolean doCountOnly) {/* DOES NOTHING */} }; private DatabaseListener listener = noopListener; private final Object listenerLock = new Object(); public DatabaseListener setListener(DatabaseListener listener) { if(listener==null) listener = noopListener; DatabaseListener result; synchronized(listenerLock) { result = this.listener; this.listener = listener; } if(result==noopListener) result = null; return result; } }
include statement parameters in log git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@5754 e7d4fc99-c606-0410-b9bf-843393a9eab7
runtime/src/com/exedio/cope/Database.java
include statement parameters in log
Java
lgpl-2.1
b0165a81cda0f4c9aa32fbb99ca4fea68f2a73a2
0
petalslink/petals-bc-jbi-gateway
/** * Copyright (c) 2016 Linagora * * This program/library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or (at your * option) any later version. * * This program/library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program/library; If not, see <http://www.gnu.org/licenses/> * for the GNU Lesser General Public License version 2.1. */ package org.ow2.petals.bc.gateway.messages; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.xml.transform.TransformerException; import org.eclipse.jdt.annotation.Nullable; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.ebmwebsourcing.easycommons.xml.XMLHelper; public class TransportedPropagatedConsumes implements Serializable { private static final long serialVersionUID = -5787838058168540231L; public final ServiceKey service; public transient @Nullable Document description; public TransportedPropagatedConsumes(final ServiceKey service, final @Nullable Document description) { this.service = service; this.description = description; } private void readObject(final ObjectInputStream s) throws IOException { try { s.defaultReadObject(); if (s.readBoolean()) { this.description = XMLHelper.createDocumentFromString((String) s.readObject()); } } catch (final ClassNotFoundException | SAXException e) { throw new IOException(e); } } private void writeObject(final ObjectOutputStream s) throws IOException { s.defaultWriteObject(); final Document description = this.description; if (description != null) { s.writeBoolean(true); try { s.writeObject(XMLHelper.createStringFromDOMNode(description)); } catch (final TransformerException e) { throw new IOException(e); } } else { s.writeBoolean(false); } } }
src/main/java/org/ow2/petals/bc/gateway/messages/TransportedPropagatedConsumes.java
/** * Copyright (c) 2016 Linagora * * This program/library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or (at your * option) any later version. * * This program/library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program/library; If not, see <http://www.gnu.org/licenses/> * for the GNU Lesser General Public License version 2.1. */ package org.ow2.petals.bc.gateway.messages; import java.io.Serializable; import org.eclipse.jdt.annotation.Nullable; import org.w3c.dom.Document; public class TransportedPropagatedConsumes implements Serializable { private static final long serialVersionUID = -5787838058168540231L; public final ServiceKey service; // TODO or should we serialize it ourselves? public final @Nullable Document description; public TransportedPropagatedConsumes(final ServiceKey service, final @Nullable Document description) { this.service = service; this.description = description; } }
Actually serialize the Document
src/main/java/org/ow2/petals/bc/gateway/messages/TransportedPropagatedConsumes.java
Actually serialize the Document
Java
apache-2.0
fea01cf073e7f321b8c3fd2b0b10fee5e5a7ad85
0
Khyzad/PID-webservice,HawaiiStateDigitalArchives/PID-webservice,HawaiiStateDigitalArchives/PID-webservice,Khyzad/PID-webservice
package com.hida.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.hida.model.Purl; import com.hida.service.ResolverService; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.math.BigDecimal; import java.util.Set; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMethod; /** * A controller class that paths the user to all jsp files in WEB_INF/jsp. * * @author leland lopez * @author lruffin */ @Controller @RequestMapping("/") public class ResolverController { /* * Logger; logfile to be stored in resource folder */ private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(ResolverController.class); @Autowired private ResolverService ResolverService; /** * Maps to the home page. * * @return view to the home page */ @RequestMapping(value = {""}, method = {RequestMethod.GET}) public ModelAndView displayIndex() { ModelAndView model = new ModelAndView(); model.setViewName("home"); return model; } /** * matches url: /PURL/retrieve retrieves corresponding purl row of provided * purlid returns model - purl and view : retrieve if successful returns * model - null if not * * @param purlid purlid of desired retrieved row * @return ModelAndView * @throws IOException throws if connection could not be made */ @RequestMapping("/retrieve") public ModelAndView retrieve(@RequestParam(value = "purlid", required = true) String purlid) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Retrieve was Called"); } Purl purl = ResolverService.retrieveModel(purlid); //retrieve purl object if (purl != null) { //show retrieve view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("retrieve", "purl", this.convertListToJson(purl)); Logger.info("Retrieve returned: " + purl.toJSON()); return mv; } else { ModelAndView mv = new ModelAndView("null"); Logger.info("insert returned: " + null); return mv; } } /** * matches url: /PURL/edit edit purlid row url, with provided url returns * model : purl and view : edit if successful returns model : null if not * * @param purlid purlid of desired edited row * @param url url that desired row url will be changed to * @return ModelAndView * @throws IOException throws if connection could not be made */ @RequestMapping("/edit") public ModelAndView edit(@RequestParam(value = "purlid", required = true) String purlid, @RequestParam(value = "url", required = true) String url) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Edit was Called"); } ResolverService.editURL(purlid, url); Purl purl = ResolverService.retrieveModel(purlid); if (purl != null) { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("edit", "purl", this.convertListToJson(purl)); Logger.info("Edit returned: " + purl.toJSON()); return mv; } else { ModelAndView mv = new ModelAndView("null"); Logger.info("Edit returned: " + null); return mv; } } /** * matches url: /PURL/insert inserts purlid, url, erc, who, what, when to * new row of table returns model : purl and view : insert if successful * returns model : null if not * * @param purlid purlid to be inserted * @param url url to be inserted * @param erc erc to be inserted * @param who who to be inserted * @param what what to be inserted * @param when when to be insertd * @return ModelAndView * @throws IOException throws if db conn not successful */ @RequestMapping("/insert") public ModelAndView insert(@RequestParam(value = "purlid", required = true) String purlid, @RequestParam(value = "url", required = true) String url, @RequestParam(value = "erc", required = true) String erc, @RequestParam(value = "who", required = true) String who, @RequestParam(value = "what", required = true) String what, @RequestParam(value = "when", required = true) String when ) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Insert was Called"); } Purl purl = new Purl(purlid, url, erc, who, what, when); if (ResolverService.insertPURL(purl)) { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("insert", "purl", this.convertListToJson(purl)); Logger.info("insert returned: " + this.convertListToJson(purl)); return mv; } else { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("null"); Logger.info("insert returned: " + null); return mv; } } /** * matches url: /PURL/delete deletes row of table with corresponding purlid * returns view : deleted if successful returns model : null if not * * @param purlid purlid of desired deleted row * @return ModelAndView * @throws IOException throws if dbConn is not successful */ @RequestMapping("/delete") public ModelAndView delete(@RequestParam(value = "purlid", required = true) String purlid) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Insert was Called"); } if (ResolverService.deletePURL(purlid)) { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("deleted"); Logger.info("{\"result\":\"success\"}"); return mv; } else { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("null"); Logger.info("insert returned: " + null); return mv; } } /** * Throws any exception that may be caught within the program * * @param req the HTTP request * @param exception the caught exception * @return The view of the error message */ @ExceptionHandler(Exception.class) public ModelAndView handleGeneralError(HttpServletRequest req, Exception exception) { ModelAndView mav = new ModelAndView(); mav.addObject("status", 500); mav.addObject("exception", exception.getClass().getSimpleName()); mav.addObject("message", exception.getMessage()); Logger.error("General Error: " + exception.getMessage()); StackTraceElement[] trace = exception.getStackTrace(); String error = ""; for (StackTraceElement element : trace) { error += element.toString() + "\n"; } mav.addObject("stacktrace", error); mav.setViewName("error"); return mav; } /** * Creates a Json object based off a set of ids given in the parameter * * @param set A set of ids to display into JSON * @param prepend A value to attach to the beginning of every id. Typically * used to determine the format of the id. For example, ARK or DOI. * @return A reference to a String that contains Json set of ids * @throws IOException thrown whenever a file could not be found */ private String convertListToJson(Purl purl) throws IOException { // Jackson objects to format JSON strings String jsonString; ObjectMapper mapper = new ObjectMapper(); Object formattedJson; // create json object JsonObject jsonObject = Json.createObjectBuilder() .add("pid", purl.getIdentifier()) .add("url", purl.getURL()) .add("erc", purl.getERC()) .add("who", purl.getWho()) .add("what", purl.getWhat()) .add("date", purl.getDate()) .build(); // format json array formattedJson = mapper.readValue(jsonObject.toString(), Object.class); jsonString = mapper.writerWithDefaultPrettyPrinter(). writeValueAsString(formattedJson); return jsonString; } }
PURL/src/main/java/com/hida/controller/ResolverController.java
package com.hida.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.hida.model.Purl; import com.hida.service.ResolverService; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMethod; /** * A controller class that paths the user to all jsp files in WEB_INF/jsp. * * @author leland lopez * @author lruffin */ @Controller @RequestMapping("/") public class ResolverController { /* * Logger; logfile to be stored in resource folder */ private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(ResolverController.class); @Autowired private ResolverService ResolverService; /** * Maps to the home page. * * @return view to the home page */ @RequestMapping(value = {""}, method = {RequestMethod.GET}) public ModelAndView displayIndex() { ModelAndView model = new ModelAndView(); model.setViewName("home"); return model; } /** * matches url: /PURL/retrieve retrieves corresponding purl row of provided * purlid returns model - purl and view : retrieve if successful returns * model - null if not * * @param purlid purlid of desired retrieved row * @return ModelAndView * @throws IOException throws if connection could not be made */ @RequestMapping("/retrieve") public ModelAndView retrieve(@RequestParam(value = "purlid", required = true) String purlid) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Retrieve was Called"); } Purl purl = ResolverService.retrieveModel(purlid); //retrieve purl object if (purl != null) { //show retrieve view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("retrieve", "purl", purl); Logger.info("Retrieve returned: " + purl.toJSON()); return mv; } else { ModelAndView mv = new ModelAndView("null"); Logger.info("insert returned: " + null); return mv; } } /** * matches url: /PURL/edit edit purlid row url, with provided url returns * model : purl and view : edit if successful returns model : null if not * * @param purlid purlid of desired edited row * @param url url that desired row url will be changed to * @return ModelAndView * @throws IOException throws if connection could not be made */ @RequestMapping("/edit") public ModelAndView edit(@RequestParam(value = "purlid", required = true) String purlid, @RequestParam(value = "url", required = true) String url) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Edit was Called"); } ResolverService.editURL(purlid, url); Purl purl = ResolverService.retrieveModel(purlid); if (purl != null) { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("edit", "purl", purl); Logger.info("Edit returned: " + purl.toJSON()); return mv; } else { ModelAndView mv = new ModelAndView("null"); Logger.info("Edit returned: " + null); return mv; } } /** * matches url: /PURL/insert inserts purlid, url, erc, who, what, when to * new row of table returns model : purl and view : insert if successful * returns model : null if not * * @param purlid purlid to be inserted * @param url url to be inserted * @param erc erc to be inserted * @param who who to be inserted * @param what what to be inserted * @param when when to be insertd * @return ModelAndView * @throws IOException throws if db conn not successful */ @RequestMapping("/insert") public ModelAndView insert(@RequestParam(value = "purlid", required = true) String purlid, @RequestParam(value = "url", required = true) String url, @RequestParam(value = "erc", required = true) String erc, @RequestParam(value = "who", required = true) String who, @RequestParam(value = "what", required = true) String what, @RequestParam(value = "when", required = true) String when ) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Insert was Called"); } Purl purl = new Purl(purlid, url, erc, who, what, when); if (ResolverService.insertPURL(purl)) { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("insert", "purl", purl); Logger.info("insert returned: " + purl.toJSON()); return mv; } else { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("null"); Logger.info("insert returned: " + null); return mv; } } /** * matches url: /PURL/delete deletes row of table with corresponding purlid * returns view : deleted if successful returns model : null if not * * @param purlid purlid of desired deleted row * @return ModelAndView * @throws IOException throws if dbConn is not successful */ @RequestMapping("/delete") public ModelAndView delete(@RequestParam(value = "purlid", required = true) String purlid) throws IOException { if (Logger.isInfoEnabled()) { Logger.info("Insert was Called"); } if (ResolverService.deletePURL(purlid)) { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("deleted"); Logger.info("{\"result\":\"success\"}"); return mv; } else { //show edit view, attach purl object. converted to json at view. ModelAndView mv = new ModelAndView("null"); Logger.info("insert returned: " + null); return mv; } } /** * Throws any exception that may be caught within the program * * @param req the HTTP request * @param exception the caught exception * @return The view of the error message */ @ExceptionHandler(Exception.class) public ModelAndView handleGeneralError(HttpServletRequest req, Exception exception) { ModelAndView mav = new ModelAndView(); mav.addObject("status", 500); mav.addObject("exception", exception.getClass().getSimpleName()); mav.addObject("message", exception.getMessage()); Logger.error("General Error: " + exception.getMessage()); StackTraceElement[] trace = exception.getStackTrace(); String error = ""; for(StackTraceElement element : trace){ error += element.toString() + "\n"; } mav.addObject("stacktrace", error); mav.setViewName("error"); return mav; } }
Add method to convert purl entity to Json object
PURL/src/main/java/com/hida/controller/ResolverController.java
Add method to convert purl entity to Json object
Java
apache-2.0
877db52e3765a8099b72f54b03e78e0d4d34476a
0
tbrooks8/netty,fenik17/netty,ejona86/netty,andsel/netty,andsel/netty,Spikhalskiy/netty,zer0se7en/netty,doom369/netty,ejona86/netty,artgon/netty,artgon/netty,NiteshKant/netty,tbrooks8/netty,netty/netty,Spikhalskiy/netty,fenik17/netty,ejona86/netty,NiteshKant/netty,artgon/netty,doom369/netty,zer0se7en/netty,tbrooks8/netty,fenik17/netty,artgon/netty,netty/netty,johnou/netty,andsel/netty,fenik17/netty,zer0se7en/netty,andsel/netty,netty/netty,netty/netty,doom369/netty,Spikhalskiy/netty,artgon/netty,zer0se7en/netty,tbrooks8/netty,johnou/netty,doom369/netty,johnou/netty,Spikhalskiy/netty,NiteshKant/netty,NiteshKant/netty,ejona86/netty,Spikhalskiy/netty,netty/netty,fenik17/netty,andsel/netty,johnou/netty,NiteshKant/netty,tbrooks8/netty,zer0se7en/netty,johnou/netty,ejona86/netty,doom369/netty
/* * Copyright 2013 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelId; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalServerChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.CodecException; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.UnsupportedMessageTypeException; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.util.AbstractReferenceCounted; import io.netty.util.IllegalReferenceCountException; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.ImmediateEventExecutor; import io.netty.util.concurrent.ImmediateExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.PlatformDependent; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Test; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.ClosedChannelException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLProtocolException; import javax.net.ssl.X509ExtendedTrustManager; import static io.netty.buffer.Unpooled.wrappedBuffer; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; public class SslHandlerTest { @Test(timeout = 5000) public void testNonApplicationDataFailureFailsQueuedWrites() throws NoSuchAlgorithmException, InterruptedException { final CountDownLatch writeLatch = new CountDownLatch(1); final Queue<ChannelPromise> writesToFail = new ConcurrentLinkedQueue<ChannelPromise>(); SSLEngine engine = newClientModeSSLEngine(); SslHandler handler = new SslHandler(engine) { @Override public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); writeLatch.countDown(); } }; EmbeddedChannel ch = new EmbeddedChannel(new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof ByteBuf) { if (((ByteBuf) msg).isReadable()) { writesToFail.add(promise); } else { promise.setSuccess(); } } ReferenceCountUtil.release(msg); } }, handler); try { final CountDownLatch writeCauseLatch = new CountDownLatch(1); final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>(); ch.write(Unpooled.wrappedBuffer(new byte[]{1})).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { failureRef.compareAndSet(null, future.cause()); writeCauseLatch.countDown(); } }); writeLatch.await(); // Simulate failing the SslHandler non-application writes after there are applications writes queued. ChannelPromise promiseToFail; while ((promiseToFail = writesToFail.poll()) != null) { promiseToFail.setFailure(new RuntimeException("fake exception")); } writeCauseLatch.await(); Throwable writeCause = failureRef.get(); assertNotNull(writeCause); assertThat(writeCause, is(CoreMatchers.<Throwable>instanceOf(SSLException.class))); Throwable cause = handler.handshakeFuture().cause(); assertNotNull(cause); assertThat(cause, is(CoreMatchers.<Throwable>instanceOf(SSLException.class))); } finally { assertFalse(ch.finishAndReleaseAll()); } } @Test public void testNoSslHandshakeEventWhenNoHandshake() throws Exception { final AtomicBoolean inActive = new AtomicBoolean(false); SSLEngine engine = SSLContext.getDefault().createSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel( DefaultChannelId.newInstance(), false, false, new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Not forward the event to the SslHandler but just close the Channel. ctx.close(); } }, new SslHandler(engine) { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // We want to override what Channel.isActive() will return as otherwise it will // return true and so trigger an handshake. inActive.set(true); super.handlerAdded(ctx); inActive.set(false); } }, new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { throw (Exception) ((SslHandshakeCompletionEvent) evt).cause(); } } }) { @Override public boolean isActive() { return !inActive.get() && super.isActive(); } }; ch.register(); assertFalse(ch.finishAndReleaseAll()); } @Test(expected = SslHandshakeTimeoutException.class, timeout = 3000) public void testClientHandshakeTimeout() throws Exception { testHandshakeTimeout(true); } @Test(expected = SslHandshakeTimeoutException.class, timeout = 3000) public void testServerHandshakeTimeout() throws Exception { testHandshakeTimeout(false); } private static SSLEngine newServerModeSSLEngine() throws NoSuchAlgorithmException { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); // Set the mode before we try to do the handshake as otherwise it may throw an IllegalStateException. // See: // - https://docs.oracle.com/javase/10/docs/api/javax/net/ssl/SSLEngine.html#beginHandshake() // - http://mail.openjdk.java.net/pipermail/security-dev/2018-July/017715.html engine.setUseClientMode(false); return engine; } private static SSLEngine newClientModeSSLEngine() throws NoSuchAlgorithmException { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); // Set the mode before we try to do the handshake as otherwise it may throw an IllegalStateException. // See: // - https://docs.oracle.com/javase/10/docs/api/javax/net/ssl/SSLEngine.html#beginHandshake() // - http://mail.openjdk.java.net/pipermail/security-dev/2018-July/017715.html engine.setUseClientMode(true); return engine; } private static void testHandshakeTimeout(boolean client) throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(client); SslHandler handler = new SslHandler(engine); handler.setHandshakeTimeoutMillis(1); EmbeddedChannel ch = new EmbeddedChannel(handler); try { while (!handler.handshakeFuture().isDone()) { Thread.sleep(10); // We need to run all pending tasks as the handshake timeout is scheduled on the EventLoop. ch.runPendingTasks(); } handler.handshakeFuture().syncUninterruptibly(); } finally { ch.finishAndReleaseAll(); } } @Test(timeout = 5000L) public void testHandshakeAndClosePromiseFailedOnRemoval() throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); SslHandler handler = new SslHandler(engine); final AtomicReference<Throwable> handshakeRef = new AtomicReference<Throwable>(); final AtomicReference<Throwable> closeRef = new AtomicReference<Throwable>(); EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslHandshakeCompletionEvent) { handshakeRef.set(((SslHandshakeCompletionEvent) evt).cause()); } else if (evt instanceof SslCloseCompletionEvent) { closeRef.set(((SslCloseCompletionEvent) evt).cause()); } } }); assertFalse(handler.handshakeFuture().isDone()); assertFalse(handler.sslCloseFuture().isDone()); ch.pipeline().remove(handler); try { while (!handler.handshakeFuture().isDone() || handshakeRef.get() == null || !handler.sslCloseFuture().isDone() || closeRef.get() == null) { Thread.sleep(10); // Continue running all pending tasks until we notified for everything. ch.runPendingTasks(); } assertSame(handler.handshakeFuture().cause(), handshakeRef.get()); assertSame(handler.sslCloseFuture().cause(), closeRef.get()); } finally { ch.finishAndReleaseAll(); } } @Test public void testTruncatedPacket() throws Exception { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); // Push the first part of a 5-byte handshake message. ch.writeInbound(wrappedBuffer(new byte[]{22, 3, 1, 0, 5})); // Should decode nothing yet. assertThat(ch.readInbound(), is(nullValue())); try { // Push the second part of the 5-byte handshake message. ch.writeInbound(wrappedBuffer(new byte[]{2, 0, 0, 1, 0})); fail(); } catch (DecoderException e) { // Be sure we cleanup the channel and release any pending messages that may have been generated because // of an alert. // See https://github.com/netty/netty/issues/6057. ch.finishAndReleaseAll(); // The pushed message is invalid, so it should raise an exception if it decoded the message correctly. assertThat(e.getCause(), is(instanceOf(SSLProtocolException.class))); } } @Test public void testNonByteBufWriteIsReleased() throws Exception { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); AbstractReferenceCounted referenceCounted = new AbstractReferenceCounted() { @Override public ReferenceCounted touch(Object hint) { return this; } @Override protected void deallocate() { } }; try { ch.write(referenceCounted).get(); fail(); } catch (ExecutionException e) { assertThat(e.getCause(), is(instanceOf(UnsupportedMessageTypeException.class))); } assertEquals(0, referenceCounted.refCnt()); assertTrue(ch.finishAndReleaseAll()); } @Test(expected = UnsupportedMessageTypeException.class) public void testNonByteBufNotPassThrough() throws Exception { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); try { ch.writeOutbound(new Object()); } finally { ch.finishAndReleaseAll(); } } @Test public void testIncompleteWriteDoesNotCompletePromisePrematurely() throws NoSuchAlgorithmException { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); ChannelPromise promise = ch.newPromise(); ByteBuf buf = Unpooled.buffer(10).writeZero(10); ch.writeAndFlush(buf, promise); assertFalse(promise.isDone()); assertTrue(ch.finishAndReleaseAll()); assertTrue(promise.isDone()); assertThat(promise.cause(), is(instanceOf(SSLException.class))); } @Test public void testReleaseSslEngine() throws Exception { assumeTrue(OpenSsl.isAvailable()); SelfSignedCertificate cert = new SelfSignedCertificate(); try { SslContext sslContext = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()) .sslProvider(SslProvider.OPENSSL) .build(); try { assertEquals(1, ((ReferenceCounted) sslContext).refCnt()); SSLEngine sslEngine = sslContext.newEngine(ByteBufAllocator.DEFAULT); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(sslEngine)); assertEquals(2, ((ReferenceCounted) sslContext).refCnt()); assertEquals(1, ((ReferenceCounted) sslEngine).refCnt()); assertTrue(ch.finishAndReleaseAll()); ch.close().syncUninterruptibly(); assertEquals(1, ((ReferenceCounted) sslContext).refCnt()); assertEquals(0, ((ReferenceCounted) sslEngine).refCnt()); } finally { ReferenceCountUtil.release(sslContext); } } finally { cert.delete(); } } private static final class TlsReadTest extends ChannelOutboundHandlerAdapter { private volatile boolean readIssued; @Override public void read(ChannelHandlerContext ctx) throws Exception { readIssued = true; super.read(ctx); } public void test(final boolean dropChannelActive) throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); EmbeddedChannel ch = new EmbeddedChannel(false, false, this, new SslHandler(engine), new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (!dropChannelActive) { ctx.fireChannelActive(); } } } ); ch.config().setAutoRead(false); assertFalse(ch.config().isAutoRead()); ch.register(); assertTrue(readIssued); readIssued = false; assertTrue(ch.writeOutbound(Unpooled.EMPTY_BUFFER)); assertTrue(readIssued); assertTrue(ch.finishAndReleaseAll()); } } @Test public void testIssueReadAfterActiveWriteFlush() throws Exception { // the handshake is initiated by channelActive new TlsReadTest().test(false); } @Test public void testIssueReadAfterWriteFlushActive() throws Exception { // the handshake is initiated by flush new TlsReadTest().test(true); } @Test(timeout = 30000) public void testRemoval() throws Exception { NioEventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; try { final Promise<Void> clientPromise = group.next().newPromise(); Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(newHandler(SslContextBuilder.forClient().trustManager( InsecureTrustManagerFactory.INSTANCE).build(), clientPromise)); SelfSignedCertificate ssc = new SelfSignedCertificate(); final Promise<Void> serverPromise = group.next().newPromise(); ServerBootstrap serverBootstrap = new ServerBootstrap() .group(group, group) .channel(NioServerSocketChannel.class) .childHandler(newHandler(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(), serverPromise)); sc = serverBootstrap.bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); cc = bootstrap.connect(sc.localAddress()).syncUninterruptibly().channel(); serverPromise.syncUninterruptibly(); clientPromise.syncUninterruptibly(); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); } } private static ChannelHandler newHandler(final SslContext sslCtx, final Promise<Void> promise) { return new ChannelInitializer() { @Override protected void initChannel(final Channel ch) { final SslHandler sslHandler = sslCtx.newHandler(ch.alloc()); sslHandler.setHandshakeTimeoutMillis(1000); ch.pipeline().addFirst(sslHandler); sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) { ch.pipeline().remove(sslHandler); // Schedule the close so removal has time to propagate exception if any. ch.eventLoop().execute(new Runnable() { @Override public void run() { ch.close(); } }); } }); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof CodecException) { cause = cause.getCause(); } if (cause instanceof IllegalReferenceCountException) { promise.setFailure(cause); } } @Override public void channelInactive(ChannelHandlerContext ctx) { promise.trySuccess(null); } }); } }; } @Test public void testCloseFutureNotified() throws Exception { SSLEngine engine = newServerModeSSLEngine(); SslHandler handler = new SslHandler(engine); EmbeddedChannel ch = new EmbeddedChannel(handler); ch.close(); // When the channel is closed the SslHandler will write an empty buffer to the channel. ByteBuf buf = ch.readOutbound(); assertFalse(buf.isReadable()); buf.release(); assertFalse(ch.finishAndReleaseAll()); assertTrue(handler.handshakeFuture().cause() instanceof ClosedChannelException); assertTrue(handler.sslCloseFuture().cause() instanceof ClosedChannelException); } @Test(timeout = 5000) public void testEventsFired() throws Exception { SSLEngine engine = newServerModeSSLEngine(); final BlockingQueue<SslCompletionEvent> events = new LinkedBlockingQueue<SslCompletionEvent>(); EmbeddedChannel channel = new EmbeddedChannel(new SslHandler(engine), new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslCompletionEvent) { events.add((SslCompletionEvent) evt); } } }); assertTrue(events.isEmpty()); assertTrue(channel.finishAndReleaseAll()); SslCompletionEvent evt = events.take(); assertTrue(evt instanceof SslHandshakeCompletionEvent); assertTrue(evt.cause() instanceof ClosedChannelException); evt = events.take(); assertTrue(evt instanceof SslCloseCompletionEvent); assertTrue(evt.cause() instanceof ClosedChannelException); assertTrue(events.isEmpty()); } @Test(timeout = 5000) public void testHandshakeFailBeforeWritePromise() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); final CountDownLatch latch = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); final BlockingQueue<Object> events = new LinkedBlockingQueue<Object>(); Channel serverChannel = null; Channel clientChannel = null; EventLoopGroup group = new DefaultEventLoopGroup(); try { ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) { ByteBuf buf = ctx.alloc().buffer(10); buf.writeZero(buf.capacity()); ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { events.add(future); latch.countDown(); } }); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslCompletionEvent) { events.add(evt); latch.countDown(); latch2.countDown(); } } }); } }); Bootstrap cb = new Bootstrap(); cb.group(group) .channel(LocalChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) { ByteBuf buf = ctx.alloc().buffer(1000); buf.writeZero(buf.capacity()); ctx.writeAndFlush(buf); } }); } }); serverChannel = sb.bind(new LocalAddress("SslHandlerTest")).sync().channel(); clientChannel = cb.connect(serverChannel.localAddress()).sync().channel(); latch.await(); SslCompletionEvent evt = (SslCompletionEvent) events.take(); assertTrue(evt instanceof SslHandshakeCompletionEvent); assertThat(evt.cause(), is(instanceOf(SSLException.class))); ChannelFuture future = (ChannelFuture) events.take(); assertThat(future.cause(), is(instanceOf(SSLException.class))); serverChannel.close().sync(); serverChannel = null; clientChannel.close().sync(); clientChannel = null; latch2.await(); evt = (SslCompletionEvent) events.take(); assertTrue(evt instanceof SslCloseCompletionEvent); assertThat(evt.cause(), is(instanceOf(ClosedChannelException.class))); assertTrue(events.isEmpty()); } finally { if (serverChannel != null) { serverChannel.close(); } if (clientChannel != null) { clientChannel.close(); } group.shutdownGracefully(); } } @Test public void writingReadOnlyBufferDoesNotBreakAggregation() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final CountDownLatch serverReceiveLatch = new CountDownLatch(1); try { final int expectedBytes = 11; sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { private int readBytes; @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { readBytes += msg.readableBytes(); if (readBytes >= expectedBytes) { serverReceiveLatch.countDown(); } } }); } }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); cc = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc())); } }).connect(sc.localAddress()).syncUninterruptibly().channel(); // We first write a ReadOnlyBuffer because SslHandler will attempt to take the first buffer and append to it // until there is no room, or the aggregation size threshold is exceeded. We want to verify that we don't // throw when a ReadOnlyBuffer is used and just verify that we don't aggregate in this case. ByteBuf firstBuffer = Unpooled.buffer(10); firstBuffer.writeByte(0); firstBuffer = firstBuffer.asReadOnly(); ByteBuf secondBuffer = Unpooled.buffer(10); secondBuffer.writeZero(secondBuffer.capacity()); cc.write(firstBuffer); cc.writeAndFlush(secondBuffer).syncUninterruptibly(); serverReceiveLatch.countDown(); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslServerCtx); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 10000) public void testCloseOnHandshakeFailure() throws Exception { final SelfSignedCertificate ssc = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.key(), ssc.cert()).build(); final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(new SelfSignedCertificate().cert()) .build(); EventLoopGroup group = new NioEventLoopGroup(1); Channel sc = null; Channel cc = null; try { LocalAddress address = new LocalAddress(getClass().getSimpleName() + ".testCloseOnHandshakeFailure"); ServerBootstrap sb = new ServerBootstrap() .group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); } }); sc = sb.bind(address).syncUninterruptibly().channel(); final AtomicReference<SslHandler> sslHandlerRef = new AtomicReference<SslHandler>(); Bootstrap b = new Bootstrap() .group(group) .channel(LocalChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { SslHandler handler = sslClientCtx.newHandler(ch.alloc()); // We propagate the SslHandler via an AtomicReference to the outer-scope as using // pipeline.get(...) may return null if the pipeline was teared down by the time we call it. // This will happen if the channel was closed in the meantime. sslHandlerRef.set(handler); ch.pipeline().addLast(handler); } }); cc = b.connect(sc.localAddress()).syncUninterruptibly().channel(); SslHandler handler = sslHandlerRef.get(); handler.handshakeFuture().awaitUninterruptibly(); assertFalse(handler.handshakeFuture().isSuccess()); cc.closeFuture().syncUninterruptibly(); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslServerCtx); ReferenceCountUtil.release(sslClientCtx); } } @Test public void testOutboundClosedAfterChannelInactive() throws Exception { SslContext context = SslContextBuilder.forClient().build(); SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT); EmbeddedChannel channel = new EmbeddedChannel(); assertFalse(channel.finish()); channel.pipeline().addLast(new SslHandler(engine)); assertFalse(engine.isOutboundDone()); channel.close().syncUninterruptibly(); assertTrue(engine.isOutboundDone()); } @Test(timeout = 10000) public void testHandshakeFailedByWriteBeforeChannelActive() throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .protocols(SslUtils.PROTOCOL_SSL_V3) .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final CountDownLatch activeLatch = new CountDownLatch(1); final AtomicReference<AssertionError> errorRef = new AtomicReference<AssertionError>(); final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); cc = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof AssertionError) { errorRef.set((AssertionError) cause); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { activeLatch.countDown(); } }); } }).connect(sc.localAddress()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // Write something to trigger the handshake before fireChannelActive is called. future.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); } }).syncUninterruptibly().channel(); // Ensure there is no AssertionError thrown by having the handshake failed by the writeAndFlush(...) before // channelActive(...) was called. Let's first wait for the activeLatch countdown to happen and after this // check if we saw and AssertionError (even if we timed out waiting). activeLatch.await(5, TimeUnit.SECONDS); AssertionError error = errorRef.get(); if (error != null) { throw error; } assertThat(sslHandler.handshakeFuture().await().cause(), CoreMatchers.<Throwable>instanceOf(SSLException.class)); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 10000) public void testHandshakeTimeoutFlushStartsHandshake() throws Exception { testHandshakeTimeout0(false); } @Test(timeout = 10000) public void testHandshakeTimeoutStartTLS() throws Exception { testHandshakeTimeout0(true); } private static void testHandshakeTimeout0(final boolean startTls) throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .startTls(true) .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); sslHandler.setHandshakeTimeout(500, TimeUnit.MILLISECONDS); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslHandler); if (startTls) { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 })); } }); } } }).connect(sc.localAddress()); if (!startTls) { future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // Write something to trigger the handshake before fireChannelActive is called. future.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); } }); } cc = future.syncUninterruptibly().channel(); Throwable cause = sslHandler.handshakeFuture().await().cause(); assertThat(cause, CoreMatchers.<Throwable>instanceOf(SSLException.class)); assertThat(cause.getMessage(), containsString("timed out")); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test public void testHandshakeWithExecutorThatExecuteDirecty() throws Exception { testHandshakeWithExecutor(new Executor() { @Override public void execute(Runnable command) { command.run(); } }); } @Test public void testHandshakeWithImmediateExecutor() throws Exception { testHandshakeWithExecutor(ImmediateExecutor.INSTANCE); } @Test public void testHandshakeWithImmediateEventExecutor() throws Exception { testHandshakeWithExecutor(ImmediateEventExecutor.INSTANCE); } @Test public void testHandshakeWithExecutor() throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); try { testHandshakeWithExecutor(executorService); } finally { executorService.shutdown(); } } private static void testHandshakeWithExecutor(Executor executor) throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, executor); final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, executor); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(serverSslHandler) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); } }).connect(sc.localAddress()); cc = future.syncUninterruptibly().channel(); assertTrue(clientSslHandler.handshakeFuture().await().isSuccess()); assertTrue(serverSslHandler.handshakeFuture().await().isSuccess()); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test public void testClientHandshakeTimeoutBecauseExecutorNotExecute() throws Exception { testHandshakeTimeoutBecauseExecutorNotExecute(true); } @Test public void testServerHandshakeTimeoutBecauseExecutorNotExecute() throws Exception { testHandshakeTimeoutBecauseExecutorNotExecute(false); } private static void testHandshakeTimeoutBecauseExecutorNotExecute(final boolean client) throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, new Executor() { @Override public void execute(Runnable command) { if (!client) { command.run(); } // Do nothing to simulate slow execution. } }); if (client) { clientSslHandler.setHandshakeTimeout(100, TimeUnit.MILLISECONDS); } final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, new Executor() { @Override public void execute(Runnable command) { if (client) { command.run(); } // Do nothing to simulate slow execution. } }); if (!client) { serverSslHandler.setHandshakeTimeout(100, TimeUnit.MILLISECONDS); } try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(serverSslHandler) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); } }).connect(sc.localAddress()); cc = future.syncUninterruptibly().channel(); if (client) { Throwable cause = clientSslHandler.handshakeFuture().await().cause(); assertThat(cause, CoreMatchers.<Throwable>instanceOf(SSLException.class)); assertThat(cause.getMessage(), containsString("timed out")); assertFalse(serverSslHandler.handshakeFuture().await().isSuccess()); } else { Throwable cause = serverSslHandler.handshakeFuture().await().cause(); assertThat(cause, CoreMatchers.<Throwable>instanceOf(SSLException.class)); assertThat(cause.getMessage(), containsString("timed out")); assertFalse(clientSslHandler.handshakeFuture().await().isSuccess()); } } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv12() throws Throwable { testSessionTickets(SslUtils.PROTOCOL_TLS_V1_2, true); } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv13() throws Throwable { assumeTrue(OpenSsl.isTlsv13Supported()); testSessionTickets(SslUtils.PROTOCOL_TLS_V1_3, true); } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv12AndNoKey() throws Throwable { testSessionTickets(SslUtils.PROTOCOL_TLS_V1_2, false); } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv13AndNoKey() throws Throwable { assumeTrue(OpenSsl.isTlsv13Supported()); testSessionTickets(SslUtils.PROTOCOL_TLS_V1_3, false); } private static void testSessionTickets(String protocol, boolean withKey) throws Throwable { assumeTrue(OpenSsl.isAvailable()); final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.OPENSSL) .protocols(protocol) .build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.OPENSSL) .protocols(protocol) .build(); if (withKey) { OpenSslSessionTicketKey key = new OpenSslSessionTicketKey(new byte[OpenSslSessionTicketKey.NAME_SIZE], new byte[OpenSslSessionTicketKey.HMAC_KEY_SIZE], new byte[OpenSslSessionTicketKey.AES_KEY_SIZE]); ((OpenSslSessionContext) sslClientCtx.sessionContext()).setTicketKeys(key); ((OpenSslSessionContext) sslServerCtx.sessionContext()).setTicketKeys(key); } else { ((OpenSslSessionContext) sslClientCtx.sessionContext()).setTicketKeys(); ((OpenSslSessionContext) sslServerCtx.sessionContext()).setTicketKeys(); } EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>(); final byte[] bytes = new byte[96]; PlatformDependent.threadLocalRandom().nextBytes(bytes); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(serverSslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslHandshakeCompletionEvent) { ctx.writeAndFlush(Unpooled.wrappedBuffer(bytes)); } } }); } }) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); ch.pipeline().addLast(new ByteToMessageDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (in.readableBytes() == bytes.length) { queue.add(in.readBytes(bytes.length)); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { queue.add(cause); } }); } }).connect(sc.localAddress()); cc = future.syncUninterruptibly().channel(); assertTrue(clientSslHandler.handshakeFuture().await().isSuccess()); assertTrue(serverSslHandler.handshakeFuture().await().isSuccess()); Object obj = queue.take(); if (obj instanceof ByteBuf) { ByteBuf buffer = (ByteBuf) obj; ByteBuf expected = Unpooled.wrappedBuffer(bytes); try { assertEquals(expected, buffer); } finally { expected.release(); } } else { throw (Throwable) obj; } } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 10000L) public void testHandshakeFailureOnlyFireExceptionOnce() throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(new X509ExtendedTrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { failVerification(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { failVerification(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { failVerification(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { failVerification(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { failVerification(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { failVerification(); } @Override public X509Certificate[] getAcceptedIssuers() { return EmptyArrays.EMPTY_X509_CERTIFICATES; } private void failVerification() throws CertificateException { throw new CertificateException(); } }) .sslProvider(SslProvider.JDK).build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); try { final Object terminalEvent = new Object(); final BlockingQueue<Object> errorQueue = new LinkedBlockingQueue<Object>(); sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(serverSslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) { errorQueue.add(cause); } @Override public void channelInactive(ChannelHandlerContext ctx) { errorQueue.add(terminalEvent); } }); } }) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); final ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); } }).connect(sc.localAddress()); future.syncUninterruptibly(); clientSslHandler.handshakeFuture().addListener(new FutureListener<Channel>() { @Override public void operationComplete(Future<Channel> f) { future.channel().close(); } }); assertFalse(clientSslHandler.handshakeFuture().await().isSuccess()); assertFalse(serverSslHandler.handshakeFuture().await().isSuccess()); Object error = errorQueue.take(); assertThat(error, Matchers.instanceOf(DecoderException.class)); assertThat(((Throwable) error).getCause(), Matchers.<Throwable>instanceOf(SSLException.class)); Object terminal = errorQueue.take(); assertSame(terminalEvent, terminal); assertNull(errorQueue.poll(1, TimeUnit.MILLISECONDS)); } finally { if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); } } }
handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java
/* * Copyright 2013 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelId; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalServerChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.CodecException; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.UnsupportedMessageTypeException; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.util.AbstractReferenceCounted; import io.netty.util.IllegalReferenceCountException; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.ImmediateEventExecutor; import io.netty.util.concurrent.ImmediateExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.PlatformDependent; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Test; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.ClosedChannelException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLProtocolException; import javax.net.ssl.X509ExtendedTrustManager; import static io.netty.buffer.Unpooled.wrappedBuffer; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; public class SslHandlerTest { @Test(timeout = 5000) public void testNonApplicationDataFailureFailsQueuedWrites() throws NoSuchAlgorithmException, InterruptedException { final CountDownLatch writeLatch = new CountDownLatch(1); final Queue<ChannelPromise> writesToFail = new ConcurrentLinkedQueue<ChannelPromise>(); SSLEngine engine = newClientModeSSLEngine(); SslHandler handler = new SslHandler(engine) { @Override public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); writeLatch.countDown(); } }; EmbeddedChannel ch = new EmbeddedChannel(new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof ByteBuf) { if (((ByteBuf) msg).isReadable()) { writesToFail.add(promise); } else { promise.setSuccess(); } } ReferenceCountUtil.release(msg); } }, handler); try { final CountDownLatch writeCauseLatch = new CountDownLatch(1); final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>(); ch.write(Unpooled.wrappedBuffer(new byte[]{1})).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { failureRef.compareAndSet(null, future.cause()); writeCauseLatch.countDown(); } }); writeLatch.await(); // Simulate failing the SslHandler non-application writes after there are applications writes queued. ChannelPromise promiseToFail; while ((promiseToFail = writesToFail.poll()) != null) { promiseToFail.setFailure(new RuntimeException("fake exception")); } writeCauseLatch.await(); Throwable writeCause = failureRef.get(); assertNotNull(writeCause); assertThat(writeCause, is(CoreMatchers.<Throwable>instanceOf(SSLException.class))); Throwable cause = handler.handshakeFuture().cause(); assertNotNull(cause); assertThat(cause, is(CoreMatchers.<Throwable>instanceOf(SSLException.class))); } finally { assertFalse(ch.finishAndReleaseAll()); } } @Test public void testNoSslHandshakeEventWhenNoHandshake() throws Exception { final AtomicBoolean inActive = new AtomicBoolean(false); SSLEngine engine = SSLContext.getDefault().createSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel( DefaultChannelId.newInstance(), false, false, new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Not forward the event to the SslHandler but just close the Channel. ctx.close(); } }, new SslHandler(engine) { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // We want to override what Channel.isActive() will return as otherwise it will // return true and so trigger an handshake. inActive.set(true); super.handlerAdded(ctx); inActive.set(false); } }, new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { throw (Exception) ((SslHandshakeCompletionEvent) evt).cause(); } } }) { @Override public boolean isActive() { return !inActive.get() && super.isActive(); } }; ch.register(); assertFalse(ch.finishAndReleaseAll()); } @Test(expected = SslHandshakeTimeoutException.class, timeout = 3000) public void testClientHandshakeTimeout() throws Exception { testHandshakeTimeout(true); } @Test(expected = SslHandshakeTimeoutException.class, timeout = 3000) public void testServerHandshakeTimeout() throws Exception { testHandshakeTimeout(false); } private static SSLEngine newServerModeSSLEngine() throws NoSuchAlgorithmException { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); // Set the mode before we try to do the handshake as otherwise it may throw an IllegalStateException. // See: // - https://docs.oracle.com/javase/10/docs/api/javax/net/ssl/SSLEngine.html#beginHandshake() // - http://mail.openjdk.java.net/pipermail/security-dev/2018-July/017715.html engine.setUseClientMode(false); return engine; } private static SSLEngine newClientModeSSLEngine() throws NoSuchAlgorithmException { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); // Set the mode before we try to do the handshake as otherwise it may throw an IllegalStateException. // See: // - https://docs.oracle.com/javase/10/docs/api/javax/net/ssl/SSLEngine.html#beginHandshake() // - http://mail.openjdk.java.net/pipermail/security-dev/2018-July/017715.html engine.setUseClientMode(true); return engine; } private static void testHandshakeTimeout(boolean client) throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(client); SslHandler handler = new SslHandler(engine); handler.setHandshakeTimeoutMillis(1); EmbeddedChannel ch = new EmbeddedChannel(handler); try { while (!handler.handshakeFuture().isDone()) { Thread.sleep(10); // We need to run all pending tasks as the handshake timeout is scheduled on the EventLoop. ch.runPendingTasks(); } handler.handshakeFuture().syncUninterruptibly(); } finally { ch.finishAndReleaseAll(); } } @Test(timeout = 5000L) public void testHandshakeAndClosePromiseFailedOnRemoval() throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); SslHandler handler = new SslHandler(engine); final AtomicReference<Throwable> handshakeRef = new AtomicReference<Throwable>(); final AtomicReference<Throwable> closeRef = new AtomicReference<Throwable>(); EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslHandshakeCompletionEvent) { handshakeRef.set(((SslHandshakeCompletionEvent) evt).cause()); } else if (evt instanceof SslCloseCompletionEvent) { closeRef.set(((SslCloseCompletionEvent) evt).cause()); } } }); assertFalse(handler.handshakeFuture().isDone()); assertFalse(handler.sslCloseFuture().isDone()); ch.pipeline().remove(handler); try { while (!handler.handshakeFuture().isDone() || handshakeRef.get() == null || !handler.sslCloseFuture().isDone() || closeRef.get() == null) { Thread.sleep(10); // Continue running all pending tasks until we notified for everything. ch.runPendingTasks(); } assertSame(handler.handshakeFuture().cause(), handshakeRef.get()); assertSame(handler.sslCloseFuture().cause(), closeRef.get()); } finally { ch.finishAndReleaseAll(); } } @Test public void testTruncatedPacket() throws Exception { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); // Push the first part of a 5-byte handshake message. ch.writeInbound(wrappedBuffer(new byte[]{22, 3, 1, 0, 5})); // Should decode nothing yet. assertThat(ch.readInbound(), is(nullValue())); try { // Push the second part of the 5-byte handshake message. ch.writeInbound(wrappedBuffer(new byte[]{2, 0, 0, 1, 0})); fail(); } catch (DecoderException e) { // Be sure we cleanup the channel and release any pending messages that may have been generated because // of an alert. // See https://github.com/netty/netty/issues/6057. ch.finishAndReleaseAll(); // The pushed message is invalid, so it should raise an exception if it decoded the message correctly. assertThat(e.getCause(), is(instanceOf(SSLProtocolException.class))); } } @Test public void testNonByteBufWriteIsReleased() throws Exception { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); AbstractReferenceCounted referenceCounted = new AbstractReferenceCounted() { @Override public ReferenceCounted touch(Object hint) { return this; } @Override protected void deallocate() { } }; try { ch.write(referenceCounted).get(); fail(); } catch (ExecutionException e) { assertThat(e.getCause(), is(instanceOf(UnsupportedMessageTypeException.class))); } assertEquals(0, referenceCounted.refCnt()); assertTrue(ch.finishAndReleaseAll()); } @Test(expected = UnsupportedMessageTypeException.class) public void testNonByteBufNotPassThrough() throws Exception { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); try { ch.writeOutbound(new Object()); } finally { ch.finishAndReleaseAll(); } } @Test public void testIncompleteWriteDoesNotCompletePromisePrematurely() throws NoSuchAlgorithmException { SSLEngine engine = newServerModeSSLEngine(); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); ChannelPromise promise = ch.newPromise(); ByteBuf buf = Unpooled.buffer(10).writeZero(10); ch.writeAndFlush(buf, promise); assertFalse(promise.isDone()); assertTrue(ch.finishAndReleaseAll()); assertTrue(promise.isDone()); assertThat(promise.cause(), is(instanceOf(SSLException.class))); } @Test public void testReleaseSslEngine() throws Exception { assumeTrue(OpenSsl.isAvailable()); SelfSignedCertificate cert = new SelfSignedCertificate(); try { SslContext sslContext = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()) .sslProvider(SslProvider.OPENSSL) .build(); try { assertEquals(1, ((ReferenceCounted) sslContext).refCnt()); SSLEngine sslEngine = sslContext.newEngine(ByteBufAllocator.DEFAULT); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(sslEngine)); assertEquals(2, ((ReferenceCounted) sslContext).refCnt()); assertEquals(1, ((ReferenceCounted) sslEngine).refCnt()); assertTrue(ch.finishAndReleaseAll()); ch.close().syncUninterruptibly(); assertEquals(1, ((ReferenceCounted) sslContext).refCnt()); assertEquals(0, ((ReferenceCounted) sslEngine).refCnt()); } finally { ReferenceCountUtil.release(sslContext); } } finally { cert.delete(); } } private static final class TlsReadTest extends ChannelOutboundHandlerAdapter { private volatile boolean readIssued; @Override public void read(ChannelHandlerContext ctx) throws Exception { readIssued = true; super.read(ctx); } public void test(final boolean dropChannelActive) throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); EmbeddedChannel ch = new EmbeddedChannel(false, false, this, new SslHandler(engine), new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (!dropChannelActive) { ctx.fireChannelActive(); } } } ); ch.config().setAutoRead(false); assertFalse(ch.config().isAutoRead()); ch.register(); assertTrue(readIssued); readIssued = false; assertTrue(ch.writeOutbound(Unpooled.EMPTY_BUFFER)); assertTrue(readIssued); assertTrue(ch.finishAndReleaseAll()); } } @Test public void testIssueReadAfterActiveWriteFlush() throws Exception { // the handshake is initiated by channelActive new TlsReadTest().test(false); } @Test public void testIssueReadAfterWriteFlushActive() throws Exception { // the handshake is initiated by flush new TlsReadTest().test(true); } @Test(timeout = 30000) public void testRemoval() throws Exception { NioEventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; try { final Promise<Void> clientPromise = group.next().newPromise(); Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(newHandler(SslContextBuilder.forClient().trustManager( InsecureTrustManagerFactory.INSTANCE).build(), clientPromise)); SelfSignedCertificate ssc = new SelfSignedCertificate(); final Promise<Void> serverPromise = group.next().newPromise(); ServerBootstrap serverBootstrap = new ServerBootstrap() .group(group, group) .channel(NioServerSocketChannel.class) .childHandler(newHandler(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(), serverPromise)); sc = serverBootstrap.bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); cc = bootstrap.connect(sc.localAddress()).syncUninterruptibly().channel(); serverPromise.syncUninterruptibly(); clientPromise.syncUninterruptibly(); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); } } private static ChannelHandler newHandler(final SslContext sslCtx, final Promise<Void> promise) { return new ChannelInitializer() { @Override protected void initChannel(final Channel ch) { final SslHandler sslHandler = sslCtx.newHandler(ch.alloc()); sslHandler.setHandshakeTimeoutMillis(1000); ch.pipeline().addFirst(sslHandler); sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) { ch.pipeline().remove(sslHandler); // Schedule the close so removal has time to propagate exception if any. ch.eventLoop().execute(new Runnable() { @Override public void run() { ch.close(); } }); } }); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof CodecException) { cause = cause.getCause(); } if (cause instanceof IllegalReferenceCountException) { promise.setFailure(cause); } } @Override public void channelInactive(ChannelHandlerContext ctx) { promise.trySuccess(null); } }); } }; } @Test public void testCloseFutureNotified() throws Exception { SSLEngine engine = newServerModeSSLEngine(); SslHandler handler = new SslHandler(engine); EmbeddedChannel ch = new EmbeddedChannel(handler); ch.close(); // When the channel is closed the SslHandler will write an empty buffer to the channel. ByteBuf buf = ch.readOutbound(); assertFalse(buf.isReadable()); buf.release(); assertFalse(ch.finishAndReleaseAll()); assertTrue(handler.handshakeFuture().cause() instanceof ClosedChannelException); assertTrue(handler.sslCloseFuture().cause() instanceof ClosedChannelException); } @Test(timeout = 5000) public void testEventsFired() throws Exception { SSLEngine engine = newServerModeSSLEngine(); final BlockingQueue<SslCompletionEvent> events = new LinkedBlockingQueue<SslCompletionEvent>(); EmbeddedChannel channel = new EmbeddedChannel(new SslHandler(engine), new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslCompletionEvent) { events.add((SslCompletionEvent) evt); } } }); assertTrue(events.isEmpty()); assertTrue(channel.finishAndReleaseAll()); SslCompletionEvent evt = events.take(); assertTrue(evt instanceof SslHandshakeCompletionEvent); assertTrue(evt.cause() instanceof ClosedChannelException); evt = events.take(); assertTrue(evt instanceof SslCloseCompletionEvent); assertTrue(evt.cause() instanceof ClosedChannelException); assertTrue(events.isEmpty()); } @Test(timeout = 5000) public void testHandshakeFailBeforeWritePromise() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); final CountDownLatch latch = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); final BlockingQueue<Object> events = new LinkedBlockingQueue<Object>(); Channel serverChannel = null; Channel clientChannel = null; EventLoopGroup group = new DefaultEventLoopGroup(); try { ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) { ByteBuf buf = ctx.alloc().buffer(10); buf.writeZero(buf.capacity()); ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { events.add(future); latch.countDown(); } }); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslCompletionEvent) { events.add(evt); latch.countDown(); latch2.countDown(); } } }); } }); Bootstrap cb = new Bootstrap(); cb.group(group) .channel(LocalChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) { ByteBuf buf = ctx.alloc().buffer(1000); buf.writeZero(buf.capacity()); ctx.writeAndFlush(buf); } }); } }); serverChannel = sb.bind(new LocalAddress("SslHandlerTest")).sync().channel(); clientChannel = cb.connect(serverChannel.localAddress()).sync().channel(); latch.await(); SslCompletionEvent evt = (SslCompletionEvent) events.take(); assertTrue(evt instanceof SslHandshakeCompletionEvent); assertThat(evt.cause(), is(instanceOf(SSLException.class))); ChannelFuture future = (ChannelFuture) events.take(); assertThat(future.cause(), is(instanceOf(SSLException.class))); serverChannel.close().sync(); serverChannel = null; clientChannel.close().sync(); clientChannel = null; latch2.await(); evt = (SslCompletionEvent) events.take(); assertTrue(evt instanceof SslCloseCompletionEvent); assertThat(evt.cause(), is(instanceOf(ClosedChannelException.class))); assertTrue(events.isEmpty()); } finally { if (serverChannel != null) { serverChannel.close(); } if (clientChannel != null) { clientChannel.close(); } group.shutdownGracefully(); } } @Test public void writingReadOnlyBufferDoesNotBreakAggregation() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final CountDownLatch serverReceiveLatch = new CountDownLatch(1); try { final int expectedBytes = 11; sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { private int readBytes; @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { readBytes += msg.readableBytes(); if (readBytes >= expectedBytes) { serverReceiveLatch.countDown(); } } }); } }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); cc = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc())); } }).connect(sc.localAddress()).syncUninterruptibly().channel(); // We first write a ReadOnlyBuffer because SslHandler will attempt to take the first buffer and append to it // until there is no room, or the aggregation size threshold is exceeded. We want to verify that we don't // throw when a ReadOnlyBuffer is used and just verify that we don't aggregate in this case. ByteBuf firstBuffer = Unpooled.buffer(10); firstBuffer.writeByte(0); firstBuffer = firstBuffer.asReadOnly(); ByteBuf secondBuffer = Unpooled.buffer(10); secondBuffer.writeZero(secondBuffer.capacity()); cc.write(firstBuffer); cc.writeAndFlush(secondBuffer).syncUninterruptibly(); serverReceiveLatch.countDown(); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslServerCtx); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 10000) public void testCloseOnHandshakeFailure() throws Exception { final SelfSignedCertificate ssc = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.key(), ssc.cert()).build(); final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(new SelfSignedCertificate().cert()) .build(); EventLoopGroup group = new NioEventLoopGroup(1); Channel sc = null; Channel cc = null; try { LocalAddress address = new LocalAddress(getClass().getSimpleName() + ".testCloseOnHandshakeFailure"); ServerBootstrap sb = new ServerBootstrap() .group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); } }); sc = sb.bind(address).syncUninterruptibly().channel(); final AtomicReference<SslHandler> sslHandlerRef = new AtomicReference<SslHandler>(); Bootstrap b = new Bootstrap() .group(group) .channel(LocalChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { SslHandler handler = sslClientCtx.newHandler(ch.alloc()); // We propagate the SslHandler via an AtomicReference to the outer-scope as using // pipeline.get(...) may return null if the pipeline was teared down by the time we call it. // This will happen if the channel was closed in the meantime. sslHandlerRef.set(handler); ch.pipeline().addLast(handler); } }); cc = b.connect(sc.localAddress()).syncUninterruptibly().channel(); SslHandler handler = sslHandlerRef.get(); handler.handshakeFuture().awaitUninterruptibly(); assertFalse(handler.handshakeFuture().isSuccess()); cc.closeFuture().syncUninterruptibly(); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslServerCtx); ReferenceCountUtil.release(sslClientCtx); } } @Test public void testOutboundClosedAfterChannelInactive() throws Exception { SslContext context = SslContextBuilder.forClient().build(); SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT); EmbeddedChannel channel = new EmbeddedChannel(); assertFalse(channel.finish()); channel.pipeline().addLast(new SslHandler(engine)); assertFalse(engine.isOutboundDone()); channel.close().syncUninterruptibly(); assertTrue(engine.isOutboundDone()); } @Test(timeout = 10000) public void testHandshakeFailedByWriteBeforeChannelActive() throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .protocols(SslUtils.PROTOCOL_SSL_V3) .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final CountDownLatch activeLatch = new CountDownLatch(1); final AtomicReference<AssertionError> errorRef = new AtomicReference<AssertionError>(); final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); cc = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof AssertionError) { errorRef.set((AssertionError) cause); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { activeLatch.countDown(); } }); } }).connect(sc.localAddress()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // Write something to trigger the handshake before fireChannelActive is called. future.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); } }).syncUninterruptibly().channel(); // Ensure there is no AssertionError thrown by having the handshake failed by the writeAndFlush(...) before // channelActive(...) was called. Let's first wait for the activeLatch countdown to happen and after this // check if we saw and AssertionError (even if we timed out waiting). activeLatch.await(5, TimeUnit.SECONDS); AssertionError error = errorRef.get(); if (error != null) { throw error; } assertThat(sslHandler.handshakeFuture().await().cause(), CoreMatchers.<Throwable>instanceOf(SSLException.class)); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 10000) public void testHandshakeTimeoutFlushStartsHandshake() throws Exception { testHandshakeTimeout0(false); } @Test(timeout = 10000) public void testHandshakeTimeoutStartTLS() throws Exception { testHandshakeTimeout0(true); } private static void testHandshakeTimeout0(final boolean startTls) throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .startTls(true) .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); sslHandler.setHandshakeTimeout(500, TimeUnit.MILLISECONDS); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslHandler); if (startTls) { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 })); } }); } } }).connect(sc.localAddress()); if (!startTls) { future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // Write something to trigger the handshake before fireChannelActive is called. future.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); } }); } cc = future.syncUninterruptibly().channel(); Throwable cause = sslHandler.handshakeFuture().await().cause(); assertThat(cause, CoreMatchers.<Throwable>instanceOf(SSLException.class)); assertThat(cause.getMessage(), containsString("timed out")); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test public void testHandshakeWithExecutorThatExecuteDirecty() throws Exception { testHandshakeWithExecutor(new Executor() { @Override public void execute(Runnable command) { command.run(); } }); } @Test public void testHandshakeWithImmediateExecutor() throws Exception { testHandshakeWithExecutor(ImmediateExecutor.INSTANCE); } @Test public void testHandshakeWithImmediateEventExecutor() throws Exception { testHandshakeWithExecutor(ImmediateEventExecutor.INSTANCE); } @Test public void testHandshakeWithExecutor() throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); try { testHandshakeWithExecutor(executorService); } finally { executorService.shutdown(); } } private static void testHandshakeWithExecutor(Executor executor) throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, executor); final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, executor); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(serverSslHandler) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); } }).connect(sc.localAddress()); cc = future.syncUninterruptibly().channel(); assertTrue(clientSslHandler.handshakeFuture().await().isSuccess()); assertTrue(serverSslHandler.handshakeFuture().await().isSuccess()); } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test public void testClientHandshakeTimeoutBecauseExecutorNotExecute() throws Exception { testHandshakeTimeoutBecauseExecutorNotExecute(true); } @Test public void testServerHandshakeTimeoutBecauseExecutorNotExecute() throws Exception { testHandshakeTimeoutBecauseExecutorNotExecute(false); } private static void testHandshakeTimeoutBecauseExecutorNotExecute(final boolean client) throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.JDK).build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, new Executor() { @Override public void execute(Runnable command) { if (!client) { command.run(); } // Do nothing to simulate slow execution. } }); if (client) { clientSslHandler.setHandshakeTimeout(100, TimeUnit.MILLISECONDS); } final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, new Executor() { @Override public void execute(Runnable command) { if (client) { command.run(); } // Do nothing to simulate slow execution. } }); if (!client) { serverSslHandler.setHandshakeTimeout(100, TimeUnit.MILLISECONDS); } try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(serverSslHandler) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); } }).connect(sc.localAddress()); cc = future.syncUninterruptibly().channel(); if (client) { Throwable cause = clientSslHandler.handshakeFuture().await().cause(); assertThat(cause, CoreMatchers.<Throwable>instanceOf(SSLException.class)); assertThat(cause.getMessage(), containsString("timed out")); assertFalse(serverSslHandler.handshakeFuture().await().isSuccess()); } else { Throwable cause = serverSslHandler.handshakeFuture().await().cause(); assertThat(cause, CoreMatchers.<Throwable>instanceOf(SSLException.class)); assertThat(cause.getMessage(), containsString("timed out")); assertFalse(clientSslHandler.handshakeFuture().await().isSuccess()); } } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv12() throws Throwable { testSessionTickets(SslUtils.PROTOCOL_TLS_V1_2, true); } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv13() throws Throwable { assumeTrue(OpenSsl.isTlsv13Supported()); testSessionTickets(SslUtils.PROTOCOL_TLS_V1_3, true); } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv12AndNoKey() throws Throwable { assumeTrue(OpenSsl.isBoringSSL()); testSessionTickets(SslUtils.PROTOCOL_TLS_V1_2, false); } @Test(timeout = 5000L) public void testSessionTicketsWithTLSv13AndNoKey() throws Throwable { assumeTrue(OpenSsl.isTlsv13Supported()); testSessionTickets(SslUtils.PROTOCOL_TLS_V1_3, false); } private static void testSessionTickets(String protocol, boolean withKey) throws Throwable { assumeTrue(OpenSsl.isAvailable()); final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(SslProvider.OPENSSL) .protocols(protocol) .build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.OPENSSL) .protocols(protocol) .build(); if (withKey) { OpenSslSessionTicketKey key = new OpenSslSessionTicketKey(new byte[OpenSslSessionTicketKey.NAME_SIZE], new byte[OpenSslSessionTicketKey.HMAC_KEY_SIZE], new byte[OpenSslSessionTicketKey.AES_KEY_SIZE]); ((OpenSslSessionContext) sslClientCtx.sessionContext()).setTicketKeys(key); ((OpenSslSessionContext) sslServerCtx.sessionContext()).setTicketKeys(key); } else { ((OpenSslSessionContext) sslClientCtx.sessionContext()).setTicketKeys(); ((OpenSslSessionContext) sslServerCtx.sessionContext()).setTicketKeys(); } EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; Channel cc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>(); final byte[] bytes = new byte[96]; PlatformDependent.threadLocalRandom().nextBytes(bytes); try { sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(serverSslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslHandshakeCompletionEvent) { ctx.writeAndFlush(Unpooled.wrappedBuffer(bytes)); } } }); } }) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); ch.pipeline().addLast(new ByteToMessageDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (in.readableBytes() == bytes.length) { queue.add(in.readBytes(bytes.length)); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { queue.add(cause); } }); } }).connect(sc.localAddress()); cc = future.syncUninterruptibly().channel(); assertTrue(clientSslHandler.handshakeFuture().await().isSuccess()); assertTrue(serverSslHandler.handshakeFuture().await().isSuccess()); Object obj = queue.take(); if (obj instanceof ByteBuf) { ByteBuf buffer = (ByteBuf) obj; ByteBuf expected = Unpooled.wrappedBuffer(bytes); try { assertEquals(expected, buffer); } finally { expected.release(); } } else { throw (Throwable) obj; } } finally { if (cc != null) { cc.close().syncUninterruptibly(); } if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); ReferenceCountUtil.release(sslClientCtx); } } @Test(timeout = 10000L) public void testHandshakeFailureOnlyFireExceptionOnce() throws Exception { final SslContext sslClientCtx = SslContextBuilder.forClient() .trustManager(new X509ExtendedTrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { failVerification(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { failVerification(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { failVerification(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { failVerification(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { failVerification(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { failVerification(); } @Override public X509Certificate[] getAcceptedIssuers() { return EmptyArrays.EMPTY_X509_CERTIFICATES; } private void failVerification() throws CertificateException { throw new CertificateException(); } }) .sslProvider(SslProvider.JDK).build(); final SelfSignedCertificate cert = new SelfSignedCertificate(); final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()) .sslProvider(SslProvider.JDK).build(); EventLoopGroup group = new NioEventLoopGroup(); Channel sc = null; final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT); try { final Object terminalEvent = new Object(); final BlockingQueue<Object> errorQueue = new LinkedBlockingQueue<Object>(); sc = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(serverSslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) { errorQueue.add(cause); } @Override public void channelInactive(ChannelHandlerContext ctx) { errorQueue.add(terminalEvent); } }); } }) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); final ChannelFuture future = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientSslHandler); } }).connect(sc.localAddress()); future.syncUninterruptibly(); clientSslHandler.handshakeFuture().addListener(new FutureListener<Channel>() { @Override public void operationComplete(Future<Channel> f) { future.channel().close(); } }); assertFalse(clientSslHandler.handshakeFuture().await().isSuccess()); assertFalse(serverSslHandler.handshakeFuture().await().isSuccess()); Object error = errorQueue.take(); assertThat(error, Matchers.instanceOf(DecoderException.class)); assertThat(((Throwable) error).getCause(), Matchers.<Throwable>instanceOf(SSLException.class)); Object terminal = errorQueue.take(); assertSame(terminalEvent, terminal); assertNull(errorQueue.poll(1, TimeUnit.MILLISECONDS)); } finally { if (sc != null) { sc.close().syncUninterruptibly(); } group.shutdownGracefully(); } } }
Do not require BoringSSL for testSessionTicketsWithTLSv12AndNoKey (#10301) Motivation: `SslHandlerTest.testSessionTicketsWithTLSv12AndNoKey` does not require BoringSSL and works with OpenSSL as well. Modifications: - Remove assume statement that expected BoringSSL; Result: Test works for any implementation of `OPENSSL` provider.
handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java
Do not require BoringSSL for testSessionTicketsWithTLSv12AndNoKey (#10301)
Java
apache-2.0
33421e2a0d92e65b163d3de36b54209803d3043f
0
nus-ncl/services-in-one,nus-ncl/services-in-one
package sg.ncl.adapter.deterlab; import org.apache.commons.lang3.RandomStringUtils; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.springframework.http.*;; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import sg.ncl.adapter.deterlab.data.jpa.DeterLabProjectRepository; import sg.ncl.adapter.deterlab.data.jpa.DeterLabUserRepository; import sg.ncl.adapter.deterlab.dtos.entities.DeterLabProjectEntity; import sg.ncl.adapter.deterlab.dtos.entities.DeterLabUserEntity; import sg.ncl.adapter.deterlab.exceptions.*; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; /** * @author Tran Ly Vu */ public class AdapterDeterLabTest { @Rule public MockitoRule mockito = MockitoJUnit.rule(); @Rule public ExpectedException exception = ExpectedException.none(); @Mock private DeterLabUserRepository deterLabUserRepository; @Mock private DeterLabProjectRepository deterLabProjectRepository; @Mock private ConnectionProperties properties; @Mock private RestTemplate restTemplate; @Mock ResponseEntity response; private AdapterDeterLab adapterDeterLab; @Before public void setUp(){ assertThat(mockingDetails(deterLabUserRepository).isMock()).isTrue(); assertThat(mockingDetails(properties).isMock()).isTrue(); assertThat(mockingDetails(restTemplate).isMock()).isTrue(); adapterDeterLab=new AdapterDeterLab(deterLabUserRepository, deterLabProjectRepository, properties,restTemplate); } //no exception thrown @Test public void joinProjectNewUsersTest1() { JSONObject myobject = new JSONObject(); String stubUid = RandomStringUtils.randomAlphanumeric(8); myobject.put("msg", "user is created"); myobject.put("uid", stubUid); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual = adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void joinProjectNewUsersTest2(){ JSONObject myobject = new JSONObject(); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))). thenThrow(new ResourceAccessException("")); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw AdapterDeterLabOperationFailedException @Test public void joinProjectNewUsersTest3() { JSONObject myobject = new JSONObject(); myobject.put("msg", "user not found"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw JSONException @Test public void joinProjectNewUsersTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "user not found"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw EmailAlreadyExistsException @Test public void joinProjectNewUsersTest5() { JSONObject myobject = new JSONObject(); String stubUid = RandomStringUtils.randomAlphanumeric(8); myobject.put("msg", "email address in use"); exception.expect(EmailAlreadyExistsException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw InvalidPasswordException @Test public void joinProjectNewUsersTest6() { JSONObject myobject = new JSONObject(); myobject.put("msg", "invalid password"); exception.expect(InvalidPasswordException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //no Exception thrown @Test public void applyProjectNewUsersTest1() { JSONObject myobject = new JSONObject(); String stubUid = RandomStringUtils.randomAlphanumeric(8); myobject.put("msg", "user is created"); myobject.put("uid", stubUid); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual = adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void applyProjectNewUsersTest2() { JSONObject myobject = new JSONObject(); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new AdapterDeterLabConnectionFailedException()); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } //throw AdapterDeterLabOperationFailedException @Test public void applyProjectNewUsersTest3() { JSONObject myobject = new JSONObject(); myobject.put("msg", "user is not created"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } //throw JSONException @Test public void applyProjectNewUsersTest4() { JSONObject myobject = new JSONObject(); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } // throw InvalidPasswordException @Test public void applyProjectNewUsersTest5() { JSONObject myobject = new JSONObject(); myobject.put("msg", "invalid password"); exception.expect(InvalidPasswordException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } //no exception thrown @Test public void applyProjectTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void applyProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException("")); adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); } //throw AdapterDeterLabOperationFailedException @Test public void applyProjectTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users fail"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); } //throw JSONException @Test public void applyProjectTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users fail"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); } //no exception thrown @Test public void joinProjectTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void joinProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException("")); adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); } //thrown AdapterDeterLabOperationFailedException @Test public void joinProjectTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users failure"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); } //throw JSONException @Test public void joinProjectTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users success"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); } //no exception thrown @Test public void updateCredentialsTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "password change success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } //throw AdapterDeterLabConnectionFailedException @Test public void updateCredentialsTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "password change success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException("")); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } //throw CredentialsUpdateException @Test public void updateCredentialsTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "password change failure"); exception.expect(CredentialsUpdateException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } //throw JSONException @Test public void updateCredentialsTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "password change success"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } @Test public void saveDeterUserIdMappingTest() { String deterUserId = "test1"; String nclUserId = "test2"; adapterDeterLab.saveDeterUserIdMapping(deterUserId, nclUserId); verify(deterLabUserRepository,times(1)).save(any(DeterLabUserEntity.class)); } //throw UserNotFoundException @Test public void getDeterUserIdByNclUserIdTest1(){ String nclUserId = "test"; exception.expect(UserNotFoundException.class); when(deterLabUserRepository.findByNclUserId(nclUserId)).thenReturn(null); String actual=adapterDeterLab.getDeterUserIdByNclUserId(nclUserId ); verify(deterLabUserRepository,times(1)).findByNclUserId(nclUserId); } //no exception thrown @Test public void getDeterUserIdByNclUserIdTest2(){ DeterLabUserEntity deterLabUserEntity=new DeterLabUserEntity(); deterLabUserEntity.setDeterUserId("test1"); String expected= deterLabUserEntity.getDeterUserId(); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(deterLabUserEntity); String actual=adapterDeterLab.getDeterUserIdByNclUserId(""); verify(deterLabUserRepository,times(1)).findByNclUserId(anyString()); assertEquals(expected,actual); } @Test public void saveDeterProjectIdTest() { String deterProjectId = "test1"; String nclTeamId = "test2"; adapterDeterLab.saveDeterProjectId(deterProjectId, nclTeamId); verify(deterLabProjectRepository,times(1)).save(any(DeterLabProjectEntity.class)); } @Test public void getDeterProjectIdByNclTeamIdTestException() { String nclTeamId = "test"; exception.expect(TeamNotFoundException.class); when(deterLabProjectRepository.findByNclTeamId(nclTeamId)).thenReturn(null); adapterDeterLab.getDeterProjectIdByNclTeamId(nclTeamId); verify(deterLabProjectRepository,times(1)).findByNclTeamId(nclTeamId); } @Test public void getDeterProjectIdByNclTeamIdTestGood(){ DeterLabProjectEntity deterLabProjectEntity = new DeterLabProjectEntity(); deterLabProjectEntity.setDeterProjectId("test1"); String expected = deterLabProjectEntity.getDeterProjectId(); when(deterLabProjectRepository.findByNclTeamId(anyString())).thenReturn(deterLabProjectEntity); String actual = adapterDeterLab.getDeterProjectIdByNclTeamId(""); verify(deterLabProjectRepository,times(1)).findByNclTeamId(anyString()); assertEquals(expected,actual); } //no exception thrown @Test public void createExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw AdapterDeterLabConnectionFailedException @Test public void createExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw NSFileParseException @Test public void createExperimentTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create fail ns file error"); exception.expect(NSFileParseException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw ExperimentNameAlreadyExistsException @Test public void createExperimentTest4(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create fail exp name already in use"); exception.expect(ExperimentNameAlreadyExistsException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw JSONException @Test public void createExperimentTest5() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create fail"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(properties.getCreateExperiment()).thenReturn(""); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void startExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment start success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual= adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void startExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw ExperimentStartException() @Test public void startExperimentTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment start fail"); exception.expect(ExperimentStartException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw AdapterDeterLabConnectionFailedException @Test public void startExperimentTest4(){ JSONObject myobject = new JSONObject(); myobject.put("msg", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void stopExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("status", "swapped"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual= adapterDeterLab.stopExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).stopExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.getString("status"),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void stopExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.stopExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).stopExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void deleteExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("status", "no experiment found"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual= adapterDeterLab.deleteExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).deleteExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.getString("status"),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void deleteExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("status", "no experiment found"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab. deleteExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).deleteExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw ExperimentDeleteException @Test public void deleteExperimentTest3() { JSONObject myobject = new JSONObject(); myobject.put("status", "experiment found"); exception.expect(ExperimentDeleteException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.deleteExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).deleteExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void getExperimentStatusTest1() { JSONObject myobject = new JSONObject(); myobject.put("status", "test string"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual= adapterDeterLab.getExperimentStatus("teamName", "experimentName"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getExpStatus(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.toString(),actual); } //throw Exception @Test public void getExperimentStatusTest2() { JSONObject myobject = new JSONObject(); myobject.put("status", "no experiment found"); // exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); String expected="{\"status\": \"error\"}"; String actual=adapterDeterLab.getExperimentStatus("teamName", "experimentName"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getExpStatus(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(expected,actual); } //throw IllegalArgumentException @Test public void processJoinRequestTest1() { JSONObject myobject = new JSONObject(); myobject.put("action", "approve"); exception.expect(IllegalArgumentException.class); String actual= adapterDeterLab.processJoinRequest(myobject.toString()); } //"action" is "approve" and throw AdapterDeterLabConnectionFailedException @Test public void processJoinRequestTest2() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); } //"action" is "approve" and throw AdapterDeterLabOperationFailedException @Test public void processJoinRequestTest3() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); myobject.put("msg", "process join request not OK"); exception.expect( AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); } //"action" is "approve" and throw JSONException @Test public void processJoinRequestTest4() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); myobject.put("msg", "process join request OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); } //"action" is "approve" and no exception thrown @Test public void processJoinRequestTest5() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); myobject.put("msg", "process join OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); assertEquals(myobject .toString(),actual); } //"action" is not "approve" and throw AdapterDeterLabConnectionFailedException @Test public void processJoinRequestTest6() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); } //"action" is not "approve" and throw AdapterDeterLabOperationFailedException @Test public void processJoinRequestTest7() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); myobject.put("msg", "process join request not OK"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); } //"action" is not "approve" and throw JSONException @Test public void processJoinRequestTest8() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); myobject.put("msg", "process join request OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); } //"action" is not "approve" and no exception thrown @Test public void processJoinRequestTest9() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); myobject.put("msg", "process join request OK"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void approveProjectTest1(){ JSONObject myobject = new JSONObject(); myobject.put("pid", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.approveProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); } //throw AdapterDeterLabOperationFailedException @Test public void approveProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "approve project not OK"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.approveProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); } //throw JSONException @Test public void approveProjectTest3() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "approve project OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.approveProject(""); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); } //no exception thrown @Test public void approveProjectTest4() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "approve project OK"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.approveProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void rejectProjectTest1(){ JSONObject myobject = new JSONObject(); myobject.put("pid", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.rejectProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); } //throw AdapterDeterLabOperationFailedException @Test public void rejectProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "reject project not OK"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.rejectProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); } //throw JSONException @Test public void rejectProjectTest3() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "reject project OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.rejectProject(""); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); } //no exception thrown @Test public void rejectProject4() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "reject project OK"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.rejectProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); assertEquals(myobject.toString(),actual); } @Test public void loginSuccess() throws Exception { JSONObject myobject = new JSONObject(); myobject.put("msg", "user is logged in"); when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } @Test public void loginFail() throws Exception { JSONObject myobject = new JSONObject(); myobject.put("msg", "user is logged in error"); when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); exception.expect(AdapterDeterLabOperationFailedException.class); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } @Test public void loginAdapterDeterlabConnectionException() throws Exception { when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))). thenThrow(new RestClientException("")); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); exception.expect(AdapterDeterLabConnectionFailedException.class); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } @Test public void loginJSONException() throws Exception { when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); when(response.getBody()).thenReturn(""); when(response.getBody().toString()).thenReturn(""); exception.expect(JSONException.class); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } //throw AdapterDeterLabConnectionFailedException @Test public void getTopoThumbnailTest() { JSONObject myobject = new JSONObject(); myobject.put("thumbnail", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); adapterDeterLab.getTopologyThumbnail(myobject.toString()); } }
adapter-deterlab/src/test/java/sg/ncl/adapter/deterlab/AdapterDeterLabTest.java
package sg.ncl.adapter.deterlab; import org.apache.commons.lang3.RandomStringUtils; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.springframework.http.*;; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import sg.ncl.adapter.deterlab.data.jpa.DeterLabProjectRepository; import sg.ncl.adapter.deterlab.data.jpa.DeterLabUserRepository; import sg.ncl.adapter.deterlab.dtos.entities.DeterLabProjectEntity; import sg.ncl.adapter.deterlab.dtos.entities.DeterLabUserEntity; import sg.ncl.adapter.deterlab.exceptions.*; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; /** * @author Tran Ly Vu */ public class AdapterDeterLabTest { @Rule public MockitoRule mockito = MockitoJUnit.rule(); @Rule public ExpectedException exception = ExpectedException.none(); @Mock private DeterLabUserRepository deterLabUserRepository; @Mock private DeterLabProjectRepository deterLabProjectRepository; @Mock private ConnectionProperties properties; @Mock private RestTemplate restTemplate; @Mock ResponseEntity response; private AdapterDeterLab adapterDeterLab; @Before public void setUp(){ assertThat(mockingDetails(deterLabUserRepository).isMock()).isTrue(); assertThat(mockingDetails(properties).isMock()).isTrue(); assertThat(mockingDetails(restTemplate).isMock()).isTrue(); adapterDeterLab=new AdapterDeterLab(deterLabUserRepository, deterLabProjectRepository, properties,restTemplate); } //no exception thrown @Test public void joinProjectNewUsersTest1() { JSONObject myobject = new JSONObject(); String stubUid = RandomStringUtils.randomAlphanumeric(8); myobject.put("msg", "user is created"); myobject.put("uid", stubUid); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual = adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void joinProjectNewUsersTest2(){ JSONObject myobject = new JSONObject(); exception.expect(ResourceAccessException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))). thenThrow(new ResourceAccessException("")); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw AdapterDeterLabOperationFailedException @Test public void joinProjectNewUsersTest3() { JSONObject myobject = new JSONObject(); myobject.put("msg", "user not found"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw JSONException @Test public void joinProjectNewUsersTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "user not found"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw EmailAlreadyExistsException @Test public void joinProjectNewUsersTest5() { JSONObject myobject = new JSONObject(); String stubUid = RandomStringUtils.randomAlphanumeric(8); myobject.put("msg", "email address in use"); exception.expect(EmailAlreadyExistsException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //throw InvalidPasswordException @Test public void joinProjectNewUsersTest6() { JSONObject myobject = new JSONObject(); myobject.put("msg", "invalid password"); exception.expect(InvalidPasswordException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); } //no Exception thrown @Test public void applyProjectNewUsersTest1() { JSONObject myobject = new JSONObject(); String stubUid = RandomStringUtils.randomAlphanumeric(8); myobject.put("msg", "user is created"); myobject.put("uid", stubUid); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual = adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void applyProjectNewUsersTest2() { JSONObject myobject = new JSONObject(); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new AdapterDeterLabConnectionFailedException()); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } //throw AdapterDeterLabOperationFailedException @Test public void applyProjectNewUsersTest3() { JSONObject myobject = new JSONObject(); myobject.put("msg", "user is not created"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } //throw JSONException @Test public void applyProjectNewUsersTest4() { JSONObject myobject = new JSONObject(); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } // throw InvalidPasswordException @Test public void applyProjectNewUsersTest5() { JSONObject myobject = new JSONObject(); myobject.put("msg", "invalid password"); exception.expect(InvalidPasswordException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.applyProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProjectNewUsers(); } //no exception thrown @Test public void applyProjectTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void applyProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException("")); adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); } //throw AdapterDeterLabOperationFailedException @Test public void applyProjectTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users fail"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); } //throw JSONException @Test public void applyProjectTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users fail"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); } //no exception thrown @Test public void joinProjectTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void joinProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException("")); adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); } //thrown AdapterDeterLabOperationFailedException @Test public void joinProjectTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users failure"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); } //throw JSONException @Test public void joinProjectTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "join project request existing users success"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); } //no exception thrown @Test public void updateCredentialsTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "password change success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } //throw AdapterDeterLabConnectionFailedException @Test public void updateCredentialsTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "password change success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException("")); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } //throw CredentialsUpdateException @Test public void updateCredentialsTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "password change failure"); exception.expect(CredentialsUpdateException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } //throw JSONException @Test public void updateCredentialsTest4() { JSONObject myobject = new JSONObject(); myobject.put("msg", "password change success"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); adapterDeterLab.updateCredentials(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getUpdateCredentials(); } @Test public void saveDeterUserIdMappingTest() { String deterUserId = "test1"; String nclUserId = "test2"; adapterDeterLab.saveDeterUserIdMapping(deterUserId, nclUserId); verify(deterLabUserRepository,times(1)).save(any(DeterLabUserEntity.class)); } //throw UserNotFoundException @Test public void getDeterUserIdByNclUserIdTest1(){ String nclUserId = "test"; exception.expect(UserNotFoundException.class); when(deterLabUserRepository.findByNclUserId(nclUserId)).thenReturn(null); String actual=adapterDeterLab.getDeterUserIdByNclUserId(nclUserId ); verify(deterLabUserRepository,times(1)).findByNclUserId(nclUserId); } //no exception thrown @Test public void getDeterUserIdByNclUserIdTest2(){ DeterLabUserEntity deterLabUserEntity=new DeterLabUserEntity(); deterLabUserEntity.setDeterUserId("test1"); String expected= deterLabUserEntity.getDeterUserId(); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(deterLabUserEntity); String actual=adapterDeterLab.getDeterUserIdByNclUserId(""); verify(deterLabUserRepository,times(1)).findByNclUserId(anyString()); assertEquals(expected,actual); } @Test public void saveDeterProjectIdTest() { String deterProjectId = "test1"; String nclTeamId = "test2"; adapterDeterLab.saveDeterProjectId(deterProjectId, nclTeamId); verify(deterLabProjectRepository,times(1)).save(any(DeterLabProjectEntity.class)); } @Test public void getDeterProjectIdByNclTeamIdTestException() { String nclTeamId = "test"; exception.expect(TeamNotFoundException.class); when(deterLabProjectRepository.findByNclTeamId(nclTeamId)).thenReturn(null); adapterDeterLab.getDeterProjectIdByNclTeamId(nclTeamId); verify(deterLabProjectRepository,times(1)).findByNclTeamId(nclTeamId); } @Test public void getDeterProjectIdByNclTeamIdTestGood(){ DeterLabProjectEntity deterLabProjectEntity = new DeterLabProjectEntity(); deterLabProjectEntity.setDeterProjectId("test1"); String expected = deterLabProjectEntity.getDeterProjectId(); when(deterLabProjectRepository.findByNclTeamId(anyString())).thenReturn(deterLabProjectEntity); String actual = adapterDeterLab.getDeterProjectIdByNclTeamId(""); verify(deterLabProjectRepository,times(1)).findByNclTeamId(anyString()); assertEquals(expected,actual); } //no exception thrown @Test public void createExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw AdapterDeterLabConnectionFailedException @Test public void createExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw NSFileParseException @Test public void createExperimentTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create fail ns file error"); exception.expect(NSFileParseException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw ExperimentNameAlreadyExistsException @Test public void createExperimentTest4(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create fail exp name already in use"); exception.expect(ExperimentNameAlreadyExistsException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw JSONException @Test public void createExperimentTest5() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create fail"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(properties.getCreateExperiment()).thenReturn(""); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.createExperiment(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getCreateExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void startExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment start success"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual= adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void startExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw ExperimentStartException() @Test public void startExperimentTest3(){ JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment start fail"); exception.expect(ExperimentStartException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw AdapterDeterLabConnectionFailedException @Test public void startExperimentTest4(){ JSONObject myobject = new JSONObject(); myobject.put("msg", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.startExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).startExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void stopExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("status", "swapped"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual= adapterDeterLab.stopExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).stopExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.getString("status"),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void stopExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "experiment create success"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.stopExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).stopExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void deleteExperimentTest1() { JSONObject myobject = new JSONObject(); myobject.put("status", "no experiment found"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual= adapterDeterLab.deleteExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).deleteExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.getString("status"),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void deleteExperimentTest2() { JSONObject myobject = new JSONObject(); myobject.put("status", "no experiment found"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab. deleteExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).deleteExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //throw ExperimentDeleteException @Test public void deleteExperimentTest3() { JSONObject myobject = new JSONObject(); myobject.put("status", "experiment found"); exception.expect(ExperimentDeleteException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); String actual=adapterDeterLab.deleteExperiment("teamName", "experimentName", "nclUserId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).deleteExperiment(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); } //no exception thrown @Test public void getExperimentStatusTest1() { JSONObject myobject = new JSONObject(); myobject.put("status", "test string"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual= adapterDeterLab.getExperimentStatus("teamName", "experimentName"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getExpStatus(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(myobject.toString(),actual); } //throw Exception @Test public void getExperimentStatusTest2() { JSONObject myobject = new JSONObject(); myobject.put("status", "no experiment found"); // exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RuntimeException()); String expected="{\"status\": \"error\"}"; String actual=adapterDeterLab.getExperimentStatus("teamName", "experimentName"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getExpStatus(); verify(properties,times(1)).getIp(); verify(properties,times(1)).getPort(); assertEquals(expected,actual); } //throw IllegalArgumentException @Test public void processJoinRequestTest1() { JSONObject myobject = new JSONObject(); myobject.put("action", "approve"); exception.expect(IllegalArgumentException.class); String actual= adapterDeterLab.processJoinRequest(myobject.toString()); } //"action" is "approve" and throw AdapterDeterLabConnectionFailedException @Test public void processJoinRequestTest2() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); } //"action" is "approve" and throw AdapterDeterLabOperationFailedException @Test public void processJoinRequestTest3() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); myobject.put("msg", "process join request not OK"); exception.expect( AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); } //"action" is "approve" and throw JSONException @Test public void processJoinRequestTest4() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); myobject.put("msg", "process join request OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); } //"action" is "approve" and no exception thrown @Test public void processJoinRequestTest5() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "approve"); myobject.put("msg", "process join OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveJoinRequest(); assertEquals(myobject .toString(),actual); } //"action" is not "approve" and throw AdapterDeterLabConnectionFailedException @Test public void processJoinRequestTest6() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); } //"action" is not "approve" and throw AdapterDeterLabOperationFailedException @Test public void processJoinRequestTest7() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); myobject.put("msg", "process join request not OK"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); } //"action" is not "approve" and throw JSONException @Test public void processJoinRequestTest8() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); myobject.put("msg", "process join request OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(""); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); } //"action" is not "approve" and no exception thrown @Test public void processJoinRequestTest9() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("approverUid", ""); myobject.put("uid", ""); myobject.put("gid", ""); myobject.put("action", "reject"); myobject.put("msg", "process join request OK"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.processJoinRequest(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectJoinRequest(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void approveProjectTest1(){ JSONObject myobject = new JSONObject(); myobject.put("pid", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.approveProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); } //throw AdapterDeterLabOperationFailedException @Test public void approveProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "approve project not OK"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.approveProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); } //throw JSONException @Test public void approveProjectTest3() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "approve project OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.approveProject(""); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); } //no exception thrown @Test public void approveProjectTest4() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "approve project OK"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.approveProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApproveProject(); assertEquals(myobject.toString(),actual); } //throw AdapterDeterLabConnectionFailedException @Test public void rejectProjectTest1(){ JSONObject myobject = new JSONObject(); myobject.put("pid", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); String actual=adapterDeterLab.rejectProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); } //throw AdapterDeterLabOperationFailedException @Test public void rejectProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "reject project not OK"); exception.expect(AdapterDeterLabOperationFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.rejectProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); } //throw JSONException @Test public void rejectProjectTest3() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "reject project OK"); exception.expect(JSONException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.rejectProject(""); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); } //no exception thrown @Test public void rejectProject4() { JSONObject myobject = new JSONObject(); myobject.put("pid", ""); myobject.put("msg", "reject project OK"); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); String actual=adapterDeterLab.rejectProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getRejectProject(); assertEquals(myobject.toString(),actual); } @Test public void loginSuccess() throws Exception { JSONObject myobject = new JSONObject(); myobject.put("msg", "user is logged in"); when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } @Test public void loginFail() throws Exception { JSONObject myobject = new JSONObject(); myobject.put("msg", "user is logged in error"); when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenReturn(response); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); when(response.getBody()).thenReturn(myobject.toString()); when(response.getBody().toString()).thenReturn(myobject.toString()); exception.expect(AdapterDeterLabOperationFailedException.class); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } @Test public void loginAdapterDeterlabConnectionException() throws Exception { when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))). thenThrow(new RestClientException("")); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); exception.expect(AdapterDeterLabConnectionFailedException.class); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } @Test public void loginJSONException() throws Exception { when(properties.isEnabled()).thenReturn(true); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response); when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity()); when(response.getBody()).thenReturn(""); when(response.getBody().toString()).thenReturn(""); exception.expect(JSONException.class); adapterDeterLab.login("userId", "password"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).login(); } //throw AdapterDeterLabConnectionFailedException @Test public void getTopoThumbnailTest() { JSONObject myobject = new JSONObject(); myobject.put("thumbnail", ""); exception.expect(AdapterDeterLabConnectionFailedException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))) .thenThrow(new RestClientException("")); adapterDeterLab.getTopologyThumbnail(myobject.toString()); } }
DEV-812 Fix one failed test in AdapterDeterLabTest
adapter-deterlab/src/test/java/sg/ncl/adapter/deterlab/AdapterDeterLabTest.java
DEV-812 Fix one failed test in AdapterDeterLabTest
Java
apache-2.0
73a95cd22c808521c0faabaf1ac88f746f5277f3
0
xiaojinzi123/Component,xiaojinzi123/Component,xiaojinzi123/Component
package com.xiaojinzi.componentdemo.view; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.xiaojinzi.base.ModuleConfig; import com.xiaojinzi.base.router.AppApi; import com.xiaojinzi.component.impl.Router; import com.xiaojinzi.component.impl.application.ModuleManager; import com.xiaojinzi.componentdemo.R; /** * 启动界面 */ public class MainAct extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_act); getSupportActionBar().setTitle("组件化方案:(路由、服务、生命周期)"); } public void loadAppModule(View v) { ModuleManager.getInstance().register(ModuleConfig.App.NAME); } public void unloadAppModule(View v) { ModuleManager.getInstance().unregister(ModuleConfig.App.NAME); } public void loadUserModule(View v) { ModuleManager.getInstance().register(ModuleConfig.User.NAME); } public void unloadUserModule(View v) { ModuleManager.getInstance().unregister(ModuleConfig.User.NAME); } public void loadHelpModule(View v) { ModuleManager.getInstance().register(ModuleConfig.Help.NAME); } public void unloadHelpModule(View v) { ModuleManager.getInstance().unregister(ModuleConfig.Help.NAME); } public void loadModule1Module(View v) { ModuleManager.getInstance().register(ModuleConfig.Module1.NAME); } public void unloadModule1Module(View v) { ModuleManager.getInstance().unregister(ModuleConfig.Module1.NAME); } public void loadModule2Module(View v) { ModuleManager.getInstance().register(ModuleConfig.Module2.NAME); } public void unloadModule2Module(View v) { ModuleManager.getInstance().unregister(ModuleConfig.Module2.NAME); } public void testRouter(View view) { Router.withApi(AppApi.class).goToTestRouter( () -> Toast.makeText(MainAct.this, "跳转后的提示", Toast.LENGTH_SHORT).show() ); } public void testRouterForFragment(View view) { Fragment fragment = Router.with("component1.fragment").navigate(); if (fragment == null) { Toast.makeText(this, "没有找到 'component1.fragment' 对应的 Fragment", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "找到了 'component1.fragment' 对应的 Fragment::" + fragment, Toast.LENGTH_SHORT).show(); } } public void testWebRouter(View view) { Router .with(this) .host(ModuleConfig.Help.NAME) .path(ModuleConfig.Help.TEST_WEB_ROUTER) .requestCode(123) .forward(); } public void testQuality(View view) { Router.withApi(AppApi.class) .goToTestQuality() .subscribe(); } public void testService(View view) { Router .with(this) .host(ModuleConfig.App.NAME) .path(ModuleConfig.App.TEST_SERVICE) .forward(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 123 && resultCode == RESULT_OK) { Toast.makeText(this, "返回数据啦", Toast.LENGTH_SHORT).show(); } } }
app/src/main/java/com/xiaojinzi/componentdemo/view/MainAct.java
package com.xiaojinzi.componentdemo.view; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.xiaojinzi.base.ModuleConfig; import com.xiaojinzi.base.router.AppApi; import com.xiaojinzi.component.impl.Router; import com.xiaojinzi.component.impl.RxRouter; import com.xiaojinzi.component.impl.application.ModuleManager; import com.xiaojinzi.componentdemo.R; /** * 启动界面 */ public class MainAct extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_act); getSupportActionBar().setTitle("组件化方案:(路由、服务、生命周期)"); } public void loadAppModule(View v) { ModuleManager.getInstance().register(ModuleConfig.App.NAME); } public void unloadAppModule(View v) { ModuleManager.getInstance().unregister(ModuleConfig.App.NAME); } public void loadUserModule(View v) { ModuleManager.getInstance().register(ModuleConfig.User.NAME); } public void unloadUserModule(View v) { ModuleManager.getInstance().unregister(ModuleConfig.User.NAME); } public void loadHelpModule(View v) { ModuleManager.getInstance().register(ModuleConfig.Help.NAME); } public void unloadHelpModule(View v) { ModuleManager.getInstance().unregister(ModuleConfig.Help.NAME); } public void loadModule1Module(View v) { ModuleManager.getInstance().register(ModuleConfig.Module1.NAME); } public void unloadModule1Module(View v) { ModuleManager.getInstance().unregister(ModuleConfig.Module1.NAME); } public void loadModule2Module(View v) { ModuleManager.getInstance().register(ModuleConfig.Module2.NAME); } public void unloadModule2Module(View v) { ModuleManager.getInstance().unregister(ModuleConfig.Module2.NAME); } public void testRouter(View view) { Router.withApi(AppApi.class).goToTestRouter( () -> Toast.makeText(MainAct.this, "跳转后的提示", Toast.LENGTH_SHORT).show() ); } public void testRouterForFragment(View view) { Fragment fragment = Router.with("component1.fragment").navigate(); if (fragment == null) { Toast.makeText(this, "没有找到 'component1.fragment' 对应的 Fragment", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "找到了 'component1.fragment' 对应的 Fragment::" + fragment, Toast.LENGTH_SHORT).show(); } } public void testWebRouter(View view) { Router .with(this) .host(ModuleConfig.Help.NAME) .path(ModuleConfig.Help.TEST_WEB_ROUTER) .forward(); } public void testQuality(View view) { Router.withApi(AppApi.class) .goToTestQuality() .subscribe(); } public void testService(View view) { Router .with(this) .host(ModuleConfig.App.NAME) .path(ModuleConfig.App.TEST_SERVICE) .forward(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 123 && resultCode == RESULT_OK) { Toast.makeText(this, "返回数据啦", Toast.LENGTH_SHORT).show(); } } }
修复跳转拿 ActivityResult 之后, 普通跳转如果填了 requestCode, 也会走跳转拿 ActivityResult 的过程. 框架是否帮助拿 ActivityResult 不应该是 requestCode 有值和有预埋的 Fragment 为条件.
app/src/main/java/com/xiaojinzi/componentdemo/view/MainAct.java
修复跳转拿 ActivityResult 之后, 普通跳转如果填了 requestCode, 也会走跳转拿 ActivityResult 的过程. 框架是否帮助拿 ActivityResult 不应该是 requestCode 有值和有预埋的 Fragment 为条件.
Java
apache-2.0
4561e6c4f9dd6d0c0b3710da695624a55531b640
0
Taskana/taskana,Taskana/taskana,Taskana/taskana,Taskana/taskana,Taskana/taskana
package pro.taskana.common.rest; /** Collection of Url to Controller mappings. */ public final class RestEndpoints { public static final String API_V1 = "/api/v1/"; public static final String URL_VERSION = API_V1 + "version"; public static final String URL_DOMAIN = API_V1 + "domains"; public static final String URL_CURRENT_USER = API_V1 + "current-user-info"; public static final String URL_ACCESS_ID = API_V1 + "access-ids"; public static final String URL_ACCESS_ID_GROUPS = API_V1 + "access-ids/groups"; public static final String URL_CLASSIFICATIONS = API_V1 + "classifications"; public static final String URL_CLASSIFICATIONS_ID = API_V1 + "classifications/{classificationId}"; public static final String URL_CLASSIFICATION_DEFINITIONS = API_V1 + "classification-definitions"; public static final String URL_CLASSIFICATION_CATEGORIES = API_V1 + "classification-categories"; public static final String URL_CLASSIFICATION_TYPES = API_V1 + "classification-types"; public static final String URL_CLASSIFICATION_CATEGORIES_BY_TYPES = API_V1 + "classifications-by-type"; public static final String URL_WORKBASKET_ACCESS_ITEMS = API_V1 + "workbasket-access-items"; public static final String URL_WORKBASKET = API_V1 + "workbaskets"; public static final String URL_WORKBASKET_DEFINITIONS = API_V1 + "workbasket-definitions"; public static final String URL_WORKBASKET_ID = API_V1 + "workbaskets/{workbasketId}"; public static final String URL_WORKBASKET_ID_ACCESS_ITEMS = API_V1 + "workbaskets/{workbasketId}/workbasketAccessItems"; public static final String URL_WORKBASKET_ID_DISTRIBUTION = API_V1 + "workbaskets/{workbasketId}/distribution-targets"; public static final String URL_TASKS = API_V1 + "tasks"; public static final String URL_TASKS_ID = API_V1 + "tasks/{taskId}"; public static final String URL_TASKS_ID_CLAIM = API_V1 + "tasks/{taskId}/claim"; public static final String URL_TASKS_ID_SELECT_AND_CLAIM = API_V1 + "tasks/select-and-claim"; public static final String URL_TASKS_ID_COMPLETE = API_V1 + "tasks/{taskId}/complete"; public static final String URL_TASKS_ID_TRANSFER_WORKBASKET_ID = API_V1 + "tasks/{taskId}/transfer/{workbasketId}"; public static final String URL_TASK_COMMENTS = API_V1 + "tasks/{taskId}/comments"; public static final String URL_TASK_COMMENT = API_V1 + "tasks/comments/{taskCommentId}"; public static final String URL_MONITOR = API_V1 + "monitor"; public static final String URL_MONITOR_TASKS_STATUS = API_V1 + "monitor/tasks-status-report"; public static final String URL_MONITOR_TASKS_WORKBASKET = API_V1 + "monitor/tasks-workbasket-report"; public static final String URL_MONITOR_TASKS_WORKBASKET_PLANNED = API_V1 + "monitor/tasks-workbasket-planned-date-report"; public static final String URL_MONITOR_TASKS_CLASSIFICATION = API_V1 + "monitor/tasks-classification-report"; public static final String URL_MONITOR_TIMESTAMP = API_V1 + "monitor/timestamp-report"; public static final String URL_HISTORY_ENABLED = API_V1 + "history-provider-enabled"; public static final String URL_HISTORY_EVENTS = API_V1 + "task-history-event"; public static final String URL_HISTORY_EVENTS_ID = "/{historyEventId}"; private RestEndpoints() {} }
rest/taskana-rest-spring/src/main/java/pro/taskana/common/rest/RestEndpoints.java
package pro.taskana.common.rest; /** Collection of Url to Controller mappings. */ public final class RestEndpoints { public static final String API_V1 = "/api/v1/"; public static final String URL_VERSION = API_V1 + "version"; public static final String URL_DOMAIN = API_V1 + "domains"; public static final String URL_CURRENT_USER = API_V1 + "current-user-info"; public static final String URL_ACCESS_ID = API_V1 + "access-ids"; public static final String URL_ACCESS_ID_GROUPS = URL_ACCESS_ID + "/groups"; public static final String URL_CLASSIFICATIONS = API_V1 + "classifications"; public static final String URL_CLASSIFICATIONS_ID = URL_CLASSIFICATIONS + "/{classificationId}"; public static final String URL_CLASSIFICATION_DEFINITIONS = API_V1 + "classification-definitions"; public static final String URL_CLASSIFICATION_CATEGORIES = API_V1 + "classification-categories"; public static final String URL_CLASSIFICATION_TYPES = API_V1 + "classification-types"; public static final String URL_CLASSIFICATION_CATEGORIES_BY_TYPES = API_V1 + "classifications-by-type"; public static final String URL_WORKBASKET_ACCESS_ITEMS = API_V1 + "workbasket-access-items"; public static final String URL_WORKBASKET = API_V1 + "workbaskets"; public static final String URL_WORKBASKET_DEFINITIONS = API_V1 + "workbasket-definitions"; public static final String URL_WORKBASKET_ID = URL_WORKBASKET + "/{workbasketId}"; public static final String URL_WORKBASKET_ID_ACCESS_ITEMS = URL_WORKBASKET_ID + "/workbasketAccessItems"; public static final String URL_WORKBASKET_ID_DISTRIBUTION = URL_WORKBASKET_ID + "/distribution-targets"; public static final String URL_TASKS = API_V1 + "tasks"; public static final String URL_TASKS_ID = URL_TASKS + "/{taskId}"; public static final String URL_TASKS_ID_CLAIM = URL_TASKS_ID + "/claim"; public static final String URL_TASKS_ID_SELECT_AND_CLAIM = URL_TASKS + "/select-and-claim"; public static final String URL_TASKS_ID_COMPLETE = URL_TASKS_ID + "/complete"; public static final String URL_TASKS_ID_TRANSFER_WORKBASKET_ID = URL_TASKS_ID + "/transfer/{workbasketId}"; public static final String URL_TASK_COMMENTS = URL_TASKS_ID + "/comments"; public static final String URL_TASK_COMMENT = URL_TASKS + "/comments/{taskCommentId}"; public static final String URL_MONITOR = API_V1 + "monitor"; public static final String URL_MONITOR_TASKS_STATUS = URL_MONITOR + "/tasks-status-report"; public static final String URL_MONITOR_TASKS_WORKBASKET = URL_MONITOR + "/tasks-workbasket-report"; public static final String URL_MONITOR_TASKS_WORKBASKET_PLANNED = URL_MONITOR + "/tasks-workbasket-planned-date-report"; public static final String URL_MONITOR_TASKS_CLASSIFICATION = URL_MONITOR + "/tasks-classification-report"; public static final String URL_MONITOR_TIMESTAMP = URL_MONITOR + "/timestamp-report"; public static final String URL_HISTORY_ENABLED = API_V1 + "history-provider-enabled"; public static final String URL_HISTORY_EVENTS = API_V1 + "task-history-event"; public static final String URL_HISTORY_EVENTS_ID = "/{historyEventId}"; private RestEndpoints() {} }
TSK-1430: expand strings to increase readability
rest/taskana-rest-spring/src/main/java/pro/taskana/common/rest/RestEndpoints.java
TSK-1430: expand strings to increase readability
Java
bsd-2-clause
c7e3564a0105ad0a07d509b3b2b80b95bfa2c321
0
justinsb/dnsjava
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.io.*; import java.text.*; import java.lang.reflect.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A generic DNS resource record. The specific record types extend this class. * A record contains a name, type, class, and rdata. * * @author Brian Wellington */ public abstract class Record implements Cloneable, Comparable { protected Name name; protected int type, dclass; protected int ttl; private boolean empty; private static final Record [] knownRecords = new Record[256]; private static final Class [] emptyClassArray = new Class[0]; private static final Object [] emptyObjectArray = new Object[0]; private static final DecimalFormat byteFormat = new DecimalFormat(); static { byteFormat.setMinimumIntegerDigits(3); } protected Record() {} Record(Name name, int type, int dclass, int ttl) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); this.name = name; this.type = type; this.dclass = dclass; this.ttl = ttl; } private static final Record getTypedObject(int type) { if (type < 0 || type > knownRecords.length) return UNKRecord.getMember(); if (knownRecords[type] != null) return knownRecords[type]; try { String s = Record.class.getName(); /* * Remove "Record" from the end and construct the new * class name. */ Class c = Class.forName(s.substring(0, s.length() - 6) + Type.string(type) + "Record"); Method m = c.getDeclaredMethod("getMember", emptyClassArray); knownRecords[type] = (Record) m.invoke(null, emptyObjectArray); } catch (ClassNotFoundException e) { /* This is normal; do nothing */ } catch (InvocationTargetException e) { if (Options.check("verbose")) System.err.println(e); } catch (NoSuchMethodException e) { if (Options.check("verbose")) System.err.println(e); } catch (IllegalAccessException e) { if (Options.check("verbose")) System.err.println(e); } if (knownRecords[type] == null) knownRecords[type] = UNKRecord.getMember(); return knownRecords[type]; } /** * Converts the type-specific RR to wire format - must be overriden */ abstract Record rrFromWire(Name name, int type, int dclass, int ttl, int length, DataByteInputStream in) throws IOException; private static Record newRecord(Name name, int type, int dclass, int ttl, int length, DataByteInputStream in) throws IOException { Record rec; int recstart; rec = getTypedObject(type); if (in == null) recstart = 0; else recstart = in.getPos(); rec = rec.rrFromWire(name, type, dclass, ttl, length, in); if (in == null) { rec.empty = true; } if (in != null && in.getPos() - recstart != length) throw new IOException("Invalid record length"); return rec; } /** * Creates a new record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param length The length of the record's data. * @param data The rdata of the record, in uncompressed DNS wire format. Only * the first length bytes are used. */ public static Record newRecord(Name name, int type, int dclass, int ttl, int length, byte [] data) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); DataByteInputStream dbs; if (data != null) dbs = new DataByteInputStream(data); else dbs = null; try { return newRecord(name, type, dclass, ttl, length, dbs); } catch (IOException e) { return null; } } /** * Creates a new record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param data The complete rdata of the record, in uncompressed DNS wire * format. */ public static Record newRecord(Name name, int type, int dclass, int ttl, byte [] data) { return newRecord(name, type, dclass, ttl, data.length, data); } /** * Creates a new empty record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass, int ttl) { return newRecord(name, type, dclass, ttl, 0, (byte []) null); } /** * Creates a new empty record, with the given parameters. This method is * designed to create records that will be added to the QUERY section * of a message. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass) { return newRecord(name, type, dclass, 0, 0, (byte []) null); } static Record fromWire(DataByteInputStream in, int section) throws IOException { int type, dclass; int ttl; int length; Name name; Record rec; int start; start = in.getPos(); name = new Name(in); type = in.readUnsignedShort(); dclass = in.readUnsignedShort(); if (section == Section.QUESTION) return newRecord(name, type, dclass); ttl = in.readInt(); length = in.readUnsignedShort(); if (length == 0) return newRecord(name, type, dclass, ttl); rec = newRecord(name, type, dclass, ttl, length, in); return rec; } /** * Builds a Record from DNS uncompressed wire format. */ public static Record fromWire(byte [] b, int section) throws IOException { DataByteInputStream in = new DataByteInputStream(b); return fromWire(in, section); } void toWire(DataByteOutputStream out, int section, Compression c) { int start = out.getPos(); name.toWire(out, c); out.writeShort(type); out.writeShort(dclass); if (section == Section.QUESTION) return; out.writeInt(ttl); int lengthPosition = out.getPos(); out.writeShort(0); /* until we know better */ if (!empty) rrToWire(out, c, false); out.writeShortAt(out.getPos() - lengthPosition - 2, lengthPosition); } /** * Converts a Record into DNS uncompressed wire format. */ public byte [] toWire(int section) { DataByteOutputStream out = new DataByteOutputStream(); toWire(out, section, null); return out.toByteArray(); } void toWireCanonical(DataByteOutputStream out) { name.toWireCanonical(out); out.writeShort(type); out.writeShort(dclass); out.writeInt(ttl); int lengthPosition = out.getPos(); out.writeShort(0); /* until we know better */ rrToWire(out, null, true); out.writeShortAt(out.getPos() - lengthPosition - 2, lengthPosition); } /** * Converts a Record into canonical DNS uncompressed wire format (all names are * converted to lowercase). */ public byte [] toWireCanonical() { DataByteOutputStream out = new DataByteOutputStream(); toWireCanonical(out); return out.toByteArray(); } /** * Converts the rdata in a Record into canonical DNS uncompressed wire format * (all names are converted to lowercase). */ public byte [] rdataToWireCanonical() { DataByteOutputStream out = new DataByteOutputStream(); rrToWire(out, null, true); return out.toByteArray(); } public abstract String rdataToString(); /** * Converts a Record into a String representation */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(name); if (sb.length() < 8) sb.append("\t"); if (sb.length() < 16) sb.append("\t"); sb.append("\t"); if (Options.check("BINDTTL")) sb.append(TTL.format(ttl)); else sb.append((long)ttl & 0xFFFFFFFFL); sb.append("\t"); if (dclass != DClass.IN || !Options.check("noPrintIN")) { sb.append(DClass.string(dclass)); sb.append("\t"); } sb.append(Type.string(type)); if (!empty) { sb.append("\t"); sb.append(rdataToString()); } return sb.toString(); } /** * Converts the text format of an RR to the internal format - must be overriden */ abstract Record rdataFromString(Name name, int dclass, int ttl, Tokenizer st, Name origin) throws IOException; /** * Returns a concatenation of the remaining strings from a Tokenizer, * or throws an IOException. */ protected static String remainingStrings(Tokenizer st) throws IOException { StringBuffer sb = null; while (true) { Tokenizer.Token t = st.get(); if (!t.isString()) break; if (sb == null) sb = new StringBuffer(); sb.append(t.value); } st.unget(); if (sb == null) return null; return sb.toString(); } /** * Converts a String into a byte array. */ protected static byte [] byteArrayFromString(String s) throws TextParseException { byte [] array = s.getBytes(); boolean escaped = false; boolean hasEscapes = false; for (int i = 0; i < array.length; i++) { if (array[i] == '\\') { hasEscapes = true; break; } } if (!hasEscapes) return array; ByteArrayOutputStream os = new ByteArrayOutputStream(); int digits = 0; int intval = 0; for (int i = 0; i < array.length; i++) { byte b = array[i]; if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw new TextParseException ("bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); os.write(b); escaped = false; } else if (array[i] == '\\') { escaped = true; digits = 0; intval = 0; } else os.write(array[i]); } if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); return os.toByteArray(); } /** * Converts a byte array into a String. */ protected static String byteArrayToString(byte [] array, boolean quote) { StringBuffer sb = new StringBuffer(); if (quote) sb.append('"'); for (int i = 0; i < array.length; i++) { short b = (short)(array[i] & 0xFF); if (b < 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == ';' || b == '\\') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } if (quote) sb.append('"'); return sb.toString(); } /** * Builds a new Record from its textual representation * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param st A tokenizer containing the textual representation of the rdata. * @param origin The default origin to be appended to relative domain names. * @return The new record * @throws IOException The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, int ttl, Tokenizer st, Name origin) throws IOException { Record rec; if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); Tokenizer.Token t = st.get(); if (t.type == Tokenizer.IDENTIFIER && t.value.equals("\\#")) { int length = st.getUInt16(); String s = remainingStrings(st); byte [] data = base16.fromString(s); if (length != data.length) throw st.exception("invalid unknown RR encoding: " + "length mismatch"); DataByteInputStream in = new DataByteInputStream(data); return newRecord(name, type, dclass, ttl, length, in); } st.unget(); rec = getTypedObject(type); rec = rec.rdataFromString(name, dclass, ttl, st, origin); t = st.get(); if (t.type != Tokenizer.EOL && t.type != Tokenizer.EOF) { throw st.exception("unexpected tokens at end of record"); } return rec; } /** * Builds a new Record from its textual representation * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param s The textual representation of the rdata. * @param origin The default origin to be appended to relative domain names. * @return The new record * @throws IOException The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, int ttl, String s, Name origin) throws IOException { return fromString(name, type, dclass, ttl, new Tokenizer(s), origin); } /** * Returns the record's name * @see Name */ public Name getName() { return name; } /** * Returns the record's type * @see Type */ public int getType() { return type; } /** * Returns the type of RRset that this record would belong to. For all types * except SIGRecord, this is equivalent to getType(). * @return The type of record, if not SIGRecord. If the type is SIGRecord, * the type covered is returned. * @see Type * @see RRset * @see SIGRecord */ public int getRRsetType() { if (type == Type.SIG) { SIGRecord sig = (SIGRecord) this; return sig.getTypeCovered(); } return type; } /** * Returns the record's class */ public int getDClass() { return dclass; } /** * Returns the record's TTL */ public int getTTL() { return ttl; } /** * Converts the type-specific RR to wire format - must be overriden */ abstract void rrToWire(DataByteOutputStream out, Compression c, boolean canonical); /** * Determines if two Records are identical */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Record)) return false; Record r = (Record) arg; if (type != r.type || dclass != r.dclass || !name.equals(r.name)) return false; byte [] array1 = rdataToWireCanonical(); byte [] array2 = r.rdataToWireCanonical(); return Arrays.equals(array1, array2); } /** * Generates a hash code based on the Record's data */ public int hashCode() { byte [] array = toWireCanonical(); return array.hashCode(); } private Record cloneRecord() { try { return (Record) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(); } } /** * Creates a new record identical to the current record, but with a different * name. This is most useful for replacing the name of a wildcard record. */ public Record withName(Name name) { if (!name.isAbsolute()) throw new RelativeNameException(name); Record rec = cloneRecord(); rec.name = name; return rec; } /** * Creates a new record identical to the current record, but with a different * class and ttl. This is most useful for dynamic update. */ Record withDClass(int dclass, int ttl) { Record rec = cloneRecord(); rec.dclass = dclass; rec.ttl = ttl; return rec; } /** * Compares this Record to another Object. * @param o The Object to be compared. * @return The value 0 if the argument is a record equivalent to this record; * a value less than 0 if the argument is less than this record in the * canonical ordering, and a value greater than 0 if the argument is greater * than this record in the canonical ordering. The canonical ordering * is defined to compare by name, class, type, and rdata. * @throws ClassCastException if the argument is not a Record. */ public int compareTo(Object o) { Record arg = (Record) o; if (this == arg) return (0); int n = name.compareTo(arg.name); if (n != 0) return (n); n = dclass - arg.dclass; if (n != 0) return (n); n = type - arg.type; if (n != 0) return (n); byte [] rdata1 = rdataToWireCanonical(); byte [] rdata2 = arg.rdataToWireCanonical(); for (int i = 0; i < rdata1.length && i < rdata2.length; i++) { n = (rdata1[i] & 0xFF) - (rdata2[i] & 0xFF); if (n != 0) return (n); } return (rdata1.length - rdata2.length); } /** * Returns the name for which additional data processing should be done * for this record. This can be used both for building responses and * parsing responses. * @return The name to used for additional data processing, or null if this * record type does not require additional data processing. */ public Name getAdditionalName() { return null; } }
org/xbill/DNS/Record.java
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.io.*; import java.text.*; import java.lang.reflect.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A generic DNS resource record. The specific record types extend this class. * A record contains a name, type, class, and rdata. * * @author Brian Wellington */ public abstract class Record implements Cloneable, Comparable { protected Name name; protected int type, dclass; protected int ttl; private boolean empty; private static final Record [] knownRecords = new Record[256]; private static final Class [] emptyClassArray = new Class[0]; private static final Object [] emptyObjectArray = new Object[0]; private static final DecimalFormat byteFormat = new DecimalFormat(); static { byteFormat.setMinimumIntegerDigits(3); } protected Record() {} Record(Name name, int type, int dclass, int ttl) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); this.name = name; this.type = type; this.dclass = dclass; this.ttl = ttl; } private static final Record getTypedObject(int type) { if (type < 0 || type > knownRecords.length) return UNKRecord.getMember(); if (knownRecords[type] != null) return knownRecords[type]; try { String s = Record.class.getName(); /* * Remove "Record" from the end and construct the new * class name. */ Class c = Class.forName(s.substring(0, s.length() - 6) + Type.string(type) + "Record"); Method m = c.getDeclaredMethod("getMember", emptyClassArray); knownRecords[type] = (Record) m.invoke(null, emptyObjectArray); } catch (ClassNotFoundException e) { /* This is normal; do nothing */ } catch (InvocationTargetException e) { if (Options.check("verbose")) System.err.println(e); } catch (NoSuchMethodException e) { if (Options.check("verbose")) System.err.println(e); } catch (IllegalAccessException e) { if (Options.check("verbose")) System.err.println(e); } if (knownRecords[type] == null) knownRecords[type] = UNKRecord.getMember(); return knownRecords[type]; } /** * Converts the type-specific RR to wire format - must be overriden */ abstract Record rrFromWire(Name name, int type, int dclass, int ttl, int length, DataByteInputStream in) throws IOException; private static Record newRecord(Name name, int type, int dclass, int ttl, int length, DataByteInputStream in) throws IOException { Record rec; int recstart; rec = getTypedObject(type); if (in == null) recstart = 0; else recstart = in.getPos(); rec = rec.rrFromWire(name, type, dclass, ttl, length, in); if (in == null) { rec.empty = true; } if (in != null && in.getPos() - recstart != length) throw new IOException("Invalid record length"); return rec; } /** * Creates a new record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param length The length of the record's data. * @param data The rdata of the record, in uncompressed DNS wire format. Only * the first length bytes are used. */ public static Record newRecord(Name name, int type, int dclass, int ttl, int length, byte [] data) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); DataByteInputStream dbs; if (data != null) dbs = new DataByteInputStream(data); else dbs = null; try { return newRecord(name, type, dclass, ttl, length, dbs); } catch (IOException e) { return null; } } /** * Creates a new record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param data The complete rdata of the record, in uncompressed DNS wire * format. */ public static Record newRecord(Name name, int type, int dclass, int ttl, byte [] data) { return newRecord(name, type, dclass, ttl, data.length, data); } /** * Creates a new empty record, with the given parameters. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass, int ttl) { return newRecord(name, type, dclass, ttl, 0, (byte []) null); } /** * Creates a new empty record, with the given parameters. This method is * designed to create records that will be added to the QUERY section * of a message. * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass) { return newRecord(name, type, dclass, 0, 0, (byte []) null); } static Record fromWire(DataByteInputStream in, int section) throws IOException { int type, dclass; int ttl; int length; Name name; Record rec; int start; start = in.getPos(); name = new Name(in); type = in.readUnsignedShort(); dclass = in.readUnsignedShort(); if (section == Section.QUESTION) return newRecord(name, type, dclass); ttl = in.readInt(); length = in.readUnsignedShort(); if (length == 0) return newRecord(name, type, dclass, ttl); rec = newRecord(name, type, dclass, ttl, length, in); return rec; } /** * Builds a Record from DNS uncompressed wire format. */ public static Record fromWire(byte [] b, int section) throws IOException { DataByteInputStream in = new DataByteInputStream(b); return fromWire(in, section); } void toWire(DataByteOutputStream out, int section, Compression c) { int start = out.getPos(); name.toWire(out, c); out.writeShort(type); out.writeShort(dclass); if (section == Section.QUESTION) return; out.writeInt(ttl); int lengthPosition = out.getPos(); out.writeShort(0); /* until we know better */ if (!empty) rrToWire(out, c, false); out.writeShortAt(out.getPos() - lengthPosition - 2, lengthPosition); } /** * Converts a Record into DNS uncompressed wire format. */ public byte [] toWire(int section) { DataByteOutputStream out = new DataByteOutputStream(); toWire(out, section, null); return out.toByteArray(); } void toWireCanonical(DataByteOutputStream out) { name.toWireCanonical(out); out.writeShort(type); out.writeShort(dclass); out.writeInt(ttl); int lengthPosition = out.getPos(); out.writeShort(0); /* until we know better */ rrToWire(out, null, true); out.writeShortAt(out.getPos() - lengthPosition - 2, lengthPosition); } /** * Converts a Record into canonical DNS uncompressed wire format (all names are * converted to lowercase). */ public byte [] toWireCanonical() { DataByteOutputStream out = new DataByteOutputStream(); toWireCanonical(out); return out.toByteArray(); } /** * Converts the rdata in a Record into canonical DNS uncompressed wire format * (all names are converted to lowercase). */ public byte [] rdataToWireCanonical() { DataByteOutputStream out = new DataByteOutputStream(); rrToWire(out, null, true); return out.toByteArray(); } public abstract String rdataToString(); /** * Converts a Record into a String representation */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(name); if (sb.length() < 8) sb.append("\t"); if (sb.length() < 16) sb.append("\t"); sb.append("\t"); if (Options.check("BINDTTL")) sb.append(TTL.format(ttl)); else sb.append((long)ttl & 0xFFFFFFFFL); sb.append("\t"); if (dclass != DClass.IN || !Options.check("noPrintIN")) { sb.append(DClass.string(dclass)); sb.append("\t"); } sb.append(Type.string(type)); if (!empty) { sb.append("\t"); sb.append(rdataToString()); } return sb.toString(); } /** * Converts the text format of an RR to the internal format - must be overriden */ abstract Record rdataFromString(Name name, int dclass, int ttl, Tokenizer st, Name origin) throws IOException; /** * Returns a concatenation of the remaining strings from a Tokenizer, * or throws an IOException. */ protected static String remainingStrings(Tokenizer st) throws IOException { StringBuffer sb = null; while (true) { Tokenizer.Token t = st.get(); if (!t.isString()) break; if (sb == null) sb = new StringBuffer(); sb.append(t.value); } st.unget(); if (sb == null) return null; return sb.toString(); } /** * Converts a String into a byte array. */ protected static byte [] byteArrayFromString(String s) throws TextParseException { byte [] array = s.getBytes(); boolean escaped = false; boolean hasEscapes = false; for (int i = 0; i < array.length; i++) { if (array[i] == '\\') { hasEscapes = true; break; } } if (!hasEscapes) return array; ByteArrayOutputStream os = new ByteArrayOutputStream(); int digits = 0; int intval = 0; for (int i = 0; i < array.length; i++) { byte b = array[i]; if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw new TextParseException ("bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); os.write(b); escaped = false; } else if (array[i] == '\\') { escaped = true; digits = 0; intval = 0; } else os.write(array[i]); } if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); return os.toByteArray(); } /** * Converts a byte array into a String. */ protected static String byteArrayToString(byte [] array, boolean quote) { StringBuffer sb = new StringBuffer(); if (quote) sb.append('"'); for (int i = 0; i < array.length; i++) { short b = (short)(array[i] & 0xFF); if (b < 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == ';' || b == '\\') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } if (quote) sb.append('"'); return sb.toString(); } /** * Builds a new Record from its textual representation * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param st A tokenizer containing the textual representation of the rdata. * @param origin The default origin to be appended to relative domain names. * @return The new record * @throws IOException The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, int ttl, Tokenizer st, Name origin) throws IOException { Record rec; if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); Tokenizer.Token t = st.get(); if (t.type == Tokenizer.IDENTIFIER && t.value.equals("\\#")) { int length = st.getUInt16(); String s = remainingStrings(st); byte [] data = base16.fromString(s); if (length != data.length) throw st.exception("invalid unknown RR encoding: " + "length mismatch"); DataByteInputStream in = new DataByteInputStream(data); return newRecord(name, type, dclass, ttl, length, in); } st.unget(); rec = getTypedObject(type); rec = rec.rdataFromString(name, dclass, ttl, st, origin); t = st.get(); if (t.type != Tokenizer.EOL && t.type != Tokenizer.EOF) { throw st.exception("unexpected tokens at end of record"); } return rec; } /** * Builds a new Record from its textual representation * @param name The owner name of the record. * @param type The record's type. * @param dclass The record's class. * @param ttl The record's time to live. * @param s The textual representation of the rdata. * @param origin The default origin to be appended to relative domain names. * @return The new record * @throws IOException The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, int ttl, String s, Name origin) throws IOException { return fromString(name, type, dclass, ttl, new Tokenizer(s), origin); } /** * Returns the record's name * @see Name */ public Name getName() { return name; } /** * Returns the record's type * @see Type */ public int getType() { return type; } /** * Returns the type of RRset that this record would belong to. For all types * except SIGRecord, this is equivalent to getType(). * @return The type of record, if not SIGRecord. If the type is SIGRecord, * the type covered is returned. * @see Type * @see RRset * @see SIGRecord */ public int getRRsetType() { if (type == Type.SIG) { SIGRecord sig = (SIGRecord) this; return sig.getTypeCovered(); } return type; } /** * Returns the record's class */ public int getDClass() { return dclass; } /** * Returns the record's TTL */ public int getTTL() { return ttl; } /** * Converts the type-specific RR to wire format - must be overriden */ abstract void rrToWire(DataByteOutputStream out, Compression c, boolean canonical); /** * Determines if two Records are identical */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Record)) return false; Record r = (Record) arg; if (type != r.type || dclass != r.dclass || !name.equals(r.name)) return false; byte [] array1 = rdataToWireCanonical(); byte [] array2 = r.rdataToWireCanonical(); return Arrays.equals(array1, array2); } /** * Generates a hash code based on the Record's data */ public int hashCode() { byte [] array = toWireCanonical(); return array.hashCode(); } private Record cloneRecord() { try { return (Record) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(); } } /** * Creates a new record identical to the current record, but with a different * name. This is most useful for replacing the name of a wildcard record. */ public Record withName(Name name) { if (!name.isAbsolute()) throw new RelativeNameException(name); Record rec = cloneRecord(); rec.name = name; return rec; } /** * Creates a new record identical to the current record, but with a different * class and ttl. This is most useful for dynamic update. */ Record withDClass(int dclass, int ttl) { Record rec = cloneRecord(); rec.dclass = dclass; rec.ttl = 0; return rec; } /** * Compares this Record to another Object. * @param o The Object to be compared. * @return The value 0 if the argument is a record equivalent to this record; * a value less than 0 if the argument is less than this record in the * canonical ordering, and a value greater than 0 if the argument is greater * than this record in the canonical ordering. The canonical ordering * is defined to compare by name, class, type, and rdata. * @throws ClassCastException if the argument is not a Record. */ public int compareTo(Object o) { Record arg = (Record) o; if (this == arg) return (0); int n = name.compareTo(arg.name); if (n != 0) return (n); n = dclass - arg.dclass; if (n != 0) return (n); n = type - arg.type; if (n != 0) return (n); byte [] rdata1 = rdataToWireCanonical(); byte [] rdata2 = arg.rdataToWireCanonical(); for (int i = 0; i < rdata1.length && i < rdata2.length; i++) { n = (rdata1[i] & 0xFF) - (rdata2[i] & 0xFF); if (n != 0) return (n); } return (rdata1.length - rdata2.length); } /** * Returns the name for which additional data processing should be done * for this record. This can be used both for building responses and * parsing responses. * @return The name to used for additional data processing, or null if this * record type does not require additional data processing. */ public Name getAdditionalName() { return null; } }
typo git-svn-id: fcb33a7ee5ec38b96370833547f088a4e742b712@1082 c76caeb1-94fd-44dd-870f-0c9d92034fc1
org/xbill/DNS/Record.java
typo
Java
bsd-3-clause
49293c3147d1cbb930f73618b77cdd819699b9e8
0
nyholku/purejavacomm,gchauvet/purejavacomm,gchauvet/purejavacomm,nyholku/purejavacomm,nyholku/purejavacomm
/* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm; // FIXME no mechanism to warn about duplicate port names import static jtermios.JTermios.*; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class CommPortIdentifier { public static final int PORT_SERIAL = 1; public static final int PORT_PARALLEL = 2; private static volatile Object m_Mutex = new Object(); private volatile String m_PortName; private volatile int m_PortType; private volatile CommPort m_CommPort; private volatile CommDriver m_Driver; private volatile static Hashtable<String, CommPortIdentifier> m_PortIdentifiers = new Hashtable<String, CommPortIdentifier>(); private volatile static Hashtable<CommPort, CommPortIdentifier> m_OpenPorts = new Hashtable<CommPort, CommPortIdentifier>(); private volatile static Hashtable<CommPortIdentifier, String> m_Owners = new Hashtable<CommPortIdentifier, String>(); private volatile Hashtable<CommPortIdentifier, List<CommPortOwnershipListener>> m_OwnerShipListeners = new Hashtable<CommPortIdentifier, List<CommPortOwnershipListener>>(); /** * This has not been tested at all */ public static void addPortName(String portName, int portType, CommDriver driver) { synchronized (m_Mutex) { m_PortIdentifiers.put(portName, new CommPortIdentifier(portName, portType, driver)); } } private CommPortIdentifier(String name, int portType, CommDriver driver) { m_PortName = name; m_PortType = portType; m_Driver = driver; } public static CommPortIdentifier getPortIdentifier(String portName) throws NoSuchPortException { synchronized (m_Mutex) { boolean ENUMERATE = false; for (CommPortIdentifier portid : m_OpenPorts.values()) if (portid.getName().equals(portName)) return portid; if (ENUMERATE) { // enumerating ports takes time, lets see if we can avoid it Enumeration e = getPortIdentifiers(); while (e.hasMoreElements()) { CommPortIdentifier portid = (CommPortIdentifier) e.nextElement(); if (portid.getName().equals(portName)) return portid; } } else { CommPortIdentifier portid = m_PortIdentifiers.get(portName); if (portid != null) return portid; // check if we can open a port with the given name int fd = jtermios.JTermios.open(portName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd != -1) { // yep, it exists, so close it and create a port id object for it // FIXME this does not detect if the port name is invalid device name // but is valid and existing filename jtermios.JTermios.close(fd); return new CommPortIdentifier(portName, PORT_SERIAL, null); } if (errno() == EBUSY) // exists but busy, cannot throw anything here, so return a port if for it return new CommPortIdentifier(portName, PORT_SERIAL, null); } throw new NoSuchPortException(); } } public static CommPortIdentifier getPortIdentifier(CommPort port) throws NoSuchPortException { synchronized (m_Mutex) { CommPortIdentifier portid = m_OpenPorts.get(port); if (portid == null) throw new NoSuchPortException(); return portid; } } public CommPort open(String appname, int timeout) throws PortInUseException { synchronized (m_Mutex) { long t0 = System.currentTimeMillis(); String owner = m_Owners.get(m_PortName); if (owner != null) { fireOwnershipEvent(CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED); try { while (System.currentTimeMillis() - t0 < timeout) { m_Mutex.wait(5); if (!isCurrentlyOwned()) break; } } catch (InterruptedException ie) { // can't throw it, can't swallow it, try to propagate it Thread.currentThread().interrupt(); } } if (isCurrentlyOwned()) throw new PortInUseException(); CommPortIdentifier info = m_PortIdentifiers.get(m_PortName); CommPort port; if (info != null) port = info.m_Driver.getCommPort(m_PortName, info.m_PortType); else port = new PureJavaSerialPort(m_PortName, timeout); // FIXME timeout here is not used m_OpenPorts.put(port, this); m_Owners.put(this, appname); fireOwnershipEvent(CommPortOwnershipListener.PORT_OWNED); return port; } } /* package */ static void close(CommPort port) { synchronized (m_Mutex) { CommPortIdentifier portid = m_OpenPorts.remove(port); if (portid != null) { portid.fireOwnershipEvent(CommPortOwnershipListener.PORT_UNOWNED); m_Owners.remove(portid); } } } public CommPort open(java.io.FileDescriptor fd) throws UnsupportedCommOperationException { throw new UnsupportedCommOperationException(); } public String getName() { return m_PortName; } public int getPortType() { return m_PortType; } public static Enumeration getPortIdentifiers() { synchronized (m_Mutex) { return new Enumeration() { List<CommPortIdentifier> m_PortIDs; { // insert the 'addPortName' ports to the dynamic port list m_PortIDs = new LinkedList<CommPortIdentifier>(); for (CommPortIdentifier portid : m_PortIdentifiers.values()) m_PortIDs.add(portid); // and now add the PureSerialPorts List<String> pureports = getPortList(); if (pureports != null) for (String name : pureports) m_PortIDs.add(new CommPortIdentifier(name, PORT_SERIAL, null)); } Iterator<CommPortIdentifier> m_Iterator = m_PortIDs.iterator(); public boolean hasMoreElements() { return m_Iterator != null ? m_Iterator.hasNext() : false; } public Object nextElement() { return m_Iterator.next(); }; }; } } public String getCurrentOwner() { synchronized (m_Mutex) { return m_Owners.get(this); } } public boolean isCurrentlyOwned() { return getCurrentOwner() != null; } public void addPortOwnershipListener(CommPortOwnershipListener listener) { synchronized (m_Mutex) { List<CommPortOwnershipListener> list = m_OwnerShipListeners.get(this); if (list == null) { list = new LinkedList<CommPortOwnershipListener>(); m_OwnerShipListeners.put(this, list); } list.add(listener); } } public void removePortOwnershipListener(CommPortOwnershipListener listener) { synchronized (m_Mutex) { List<CommPortOwnershipListener> list = m_OwnerShipListeners.get(this); if (list == null) return; list.remove(listener); if (list.isEmpty()) m_OwnerShipListeners.remove(list); } } private void fireOwnershipEvent(int type) { synchronized (m_Mutex) { List<CommPortOwnershipListener> list = m_OwnerShipListeners.get(this); if (list == null) return; for (CommPortOwnershipListener listener : list) listener.ownershipChange(type); } } }
src/purejavacomm/CommPortIdentifier.java
/* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm; // FIXME no mechanism to warn about duplicate port names import static jtermios.JTermios.*; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class CommPortIdentifier { public static final int PORT_SERIAL = 1; public static final int PORT_PARALLEL = 2; private static volatile Object m_Mutex = new Object(); private volatile String m_PortName; private volatile int m_PortType; private volatile CommPort m_CommPort; private volatile CommDriver m_Driver; private volatile static Hashtable<String, CommPortIdentifier> m_PortIdentifiers = new Hashtable<String, CommPortIdentifier>(); private volatile static Hashtable<CommPort, CommPortIdentifier> m_OpenPorts = new Hashtable<CommPort, CommPortIdentifier>(); private volatile static Hashtable<CommPortIdentifier, String> m_Owners = new Hashtable<CommPortIdentifier, String>(); private volatile Hashtable<CommPortIdentifier, List<CommPortOwnershipListener>> m_OwnerShipListeners = new Hashtable<CommPortIdentifier, List<CommPortOwnershipListener>>(); /** * This has not been tested at all */ public static void addPortName(String portName, int portType, CommDriver driver) { synchronized (m_Mutex) { m_PortIdentifiers.put(portName, new CommPortIdentifier(portName, portType, driver)); } } private CommPortIdentifier(String name, int portType, CommDriver driver) { m_PortName = name; m_PortType = portType; m_Driver = driver; } public static CommPortIdentifier getPortIdentifier(String portName) throws NoSuchPortException { synchronized (m_Mutex) { boolean ENUMERATE = false; for (CommPortIdentifier portid : m_OpenPorts.values()) if (portid.getName().equals(portName)) return portid; if (ENUMERATE) { // enumerating ports takes time, lets see if we can avoid it Enumeration e = getPortIdentifiers(); while (e.hasMoreElements()) { CommPortIdentifier portid = (CommPortIdentifier) e.nextElement(); if (portid.getName().equals(portName)) return portid; } } else { CommPortIdentifier portid = m_PortIdentifiers.get(portName); if (portid != null) return portid; // check if we can open a port with the given name int fd = jtermios.JTermios.open(portName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd != -1) { // yep, it exists, so close it and create a port id object for it // FIXME this does not detect if the port name is invalid device name // but is valid and existing filename jtermios.JTermios.close(fd); return new CommPortIdentifier(portName, PORT_SERIAL, null); } if (errno() == EBUSY) // exists but busy, cannot throw anything here, so return a port if for it return new CommPortIdentifier(portName, PORT_SERIAL, null); } throw new NoSuchPortException(); } } public static CommPortIdentifier getPortIdentifier(CommPort port) throws NoSuchPortException { synchronized (m_Mutex) { CommPortIdentifier portid = m_OpenPorts.get(port); if (portid == null) throw new NoSuchPortException(); return portid; } } public CommPort open(String appname, int timeout) throws PortInUseException { synchronized (m_Mutex) { long t0 = System.currentTimeMillis(); String owner = m_Owners.get(m_PortName); if (owner != null) { fireOwnershipEvent(CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED); try { while (System.currentTimeMillis() - t0 < timeout) { m_Mutex.wait(5); if (!isCurrentlyOwned()) break; } } catch (InterruptedException ie) { // can't throw it, can't swallow it, try to propagate it Thread.currentThread().interrupt(); } } if (isCurrentlyOwned()) throw new PortInUseException(); CommPortIdentifier info = m_PortIdentifiers.get(m_PortName); CommPort port; if (info != null) port = info.m_Driver.getCommPort(m_PortName, info.m_PortType); else port = new PureJavaSerialPort(m_PortName, timeout); // FIXME timeout here is not used m_OpenPorts.put(port, this); m_Owners.put(this, appname); fireOwnershipEvent(CommPortOwnershipListener.PORT_OWNED); return port; } } /* package */ static void close(CommPort port) { synchronized (m_Mutex) { m_Owners.remove(port.name); CommPortIdentifier portid = m_OpenPorts.remove(port); if (portid != null) portid.fireOwnershipEvent(CommPortOwnershipListener.PORT_UNOWNED); } } public CommPort open(java.io.FileDescriptor fd) throws UnsupportedCommOperationException { throw new UnsupportedCommOperationException(); } public String getName() { return m_PortName; } public int getPortType() { return m_PortType; } public static Enumeration getPortIdentifiers() { synchronized (m_Mutex) { return new Enumeration() { List<CommPortIdentifier> m_PortIDs; { // insert the 'addPortName' ports to the dynamic port list m_PortIDs = new LinkedList<CommPortIdentifier>(); for (CommPortIdentifier portid : m_PortIdentifiers.values()) m_PortIDs.add(portid); // and now add the PureSerialPorts List<String> pureports = getPortList(); if (pureports != null) for (String name : pureports) m_PortIDs.add(new CommPortIdentifier(name, PORT_SERIAL, null)); } Iterator<CommPortIdentifier> m_Iterator = m_PortIDs.iterator(); public boolean hasMoreElements() { return m_Iterator != null ? m_Iterator.hasNext() : false; } public Object nextElement() { return m_Iterator.next(); }; }; } } public String getCurrentOwner() { synchronized (m_Mutex) { return m_Owners.get(this); } } public boolean isCurrentlyOwned() { return getCurrentOwner() != null; } public void addPortOwnershipListener(CommPortOwnershipListener listener) { synchronized (m_Mutex) { List<CommPortOwnershipListener> list = m_OwnerShipListeners.get(this); if (list == null) { list = new LinkedList<CommPortOwnershipListener>(); m_OwnerShipListeners.put(this, list); } list.add(listener); } } public void removePortOwnershipListener(CommPortOwnershipListener listener) { synchronized (m_Mutex) { List<CommPortOwnershipListener> list = m_OwnerShipListeners.get(this); if (list == null) return; list.remove(listener); if (list.isEmpty()) m_OwnerShipListeners.remove(list); } } private void fireOwnershipEvent(int type) { synchronized (m_Mutex) { List<CommPortOwnershipListener> list = m_OwnerShipListeners.get(this); if (list == null) return; for (CommPortOwnershipListener listener : list) listener.ownershipChange(type); } } }
Fixed a bug in close that failed to remove the portid from m_Owners
src/purejavacomm/CommPortIdentifier.java
Fixed a bug in close that failed to remove the portid from m_Owners
Java
bsd-3-clause
840f4d3b2b7743d9d237e2b16dcceafc004d779f
0
Nilhcem/FakeSMTP,Synchro/FakeSMTP,serakkkk/FakeSMTP,CIResearchGroup/FakeSMTP,junlapong/FakeSMTP,junlapong/FakeSMTP
package com.nilhcem.fakesmtp.gui; import com.nilhcem.fakesmtp.core.ArgsHandler; import com.nilhcem.fakesmtp.core.Configuration; import com.nilhcem.fakesmtp.core.exception.UncaughtExceptionHandler; import com.nilhcem.fakesmtp.gui.listeners.MainWindowListener; import com.nilhcem.fakesmtp.model.UIModel; import com.nilhcem.fakesmtp.server.SMTPServerHandler; import org.slf4j.LoggerFactory; import javax.swing.JFrame; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.io.IOException; /** * Provides the main window of the application. * * @author Nilhcem * @since 1.0 */ public final class MainFrame { private final JFrame mainFrame = new JFrame(Configuration.INSTANCE.get("application.title")); private final MenuBar menu = new MenuBar(this); private final MainPanel panel = new MainPanel(menu); /** * Creates the main window and makes it visible. * <p> * First, assigns the main panel to the default uncaught exception handler to display exceptions in this panel.<br><br> * Before creating the main window, the application will have to set some elements, such as: * </p> * <ul> * <li>The minimum and default size;</li> * <li>The menu bar and the main panel;</li> * <li>An icon image;</li> * <li>A shutdown hook to stop the server, once the main window is closed.</li> * </ul><br> * <p> * The icon of the application is a modified version from the one provided in "{@code WebAppers.com}" * <i>(Creative Commons Attribution 3.0 License)</i>. * </p> */ public MainFrame() { ((UncaughtExceptionHandler) Thread.getDefaultUncaughtExceptionHandler()).setParentComponent(panel.get()); Dimension frameSize = new Dimension(Integer.parseInt(Configuration.INSTANCE.get("application.min.width")), Integer.parseInt(Configuration.INSTANCE.get("application.min.height"))); Image iconImage = Toolkit.getDefaultToolkit().getImage( getClass().getResource(Configuration.INSTANCE.get("application.icon.path"))); MainWindowListener windowListener = new MainWindowListener(this); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.addWindowStateListener(windowListener); // used for TrayIcon mainFrame.setSize(frameSize); mainFrame.setMinimumSize(frameSize); mainFrame.setJMenuBar(menu.get()); mainFrame.getContentPane().add(panel.get()); mainFrame.setLocationRelativeTo(null); // Center main frame mainFrame.setIconImage(iconImage); // Add shutdown hook to stop server if enabled Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { SMTPServerHandler.INSTANCE.stopServer(); } }); // Restore last saved smtp port (if not overridden by the user) String smtpPort = ArgsHandler.INSTANCE.getPort(); if (smtpPort == null) { smtpPort = Configuration.INSTANCE.get("smtp.default.port"); } panel.getPortText().setText(smtpPort); // Restore last emails directory (if not overridden by the user) String emailsDir = ArgsHandler.INSTANCE.getOutputDirectory(); if (emailsDir == null) { emailsDir = Configuration.INSTANCE.get("emails.default.dir"); } if (emailsDir != null && !emailsDir.isEmpty()) { panel.getSaveMsgTextField().get().setText(emailsDir); UIModel.INSTANCE.setSavePath(emailsDir); } mainFrame.setVisible(true); } public void close() { // Save configuration Configuration.INSTANCE.set("smtp.default.port", panel.getPortText().get().getText()); Configuration.INSTANCE.set("emails.default.dir", panel.getSaveMsgTextField().get().getText()); try { Configuration.INSTANCE.saveToUserProfile(); } catch (IOException ex) { LoggerFactory.getLogger(MainFrame.class).error("Could not save configuration", ex); } // Check for SMTP server running and stop it if (SMTPServerHandler.INSTANCE.getSmtpServer().isRunning()) { SMTPServerHandler.INSTANCE.getSmtpServer().stop(); } mainFrame.dispose(); System.exit(0); } }
src/main/java/com/nilhcem/fakesmtp/gui/MainFrame.java
package com.nilhcem.fakesmtp.gui; import com.nilhcem.fakesmtp.core.ArgsHandler; import com.nilhcem.fakesmtp.core.Configuration; import com.nilhcem.fakesmtp.core.exception.UncaughtExceptionHandler; import com.nilhcem.fakesmtp.gui.listeners.MainWindowListener; import com.nilhcem.fakesmtp.model.UIModel; import com.nilhcem.fakesmtp.server.SMTPServerHandler; import org.slf4j.LoggerFactory; import javax.swing.JFrame; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.io.IOException; /** * Provides the main window of the application. * * @author Nilhcem * @since 1.0 */ public final class MainFrame { private final JFrame mainFrame = new JFrame(Configuration.INSTANCE.get("application.title")); private final MenuBar menu = new MenuBar(this); private final MainPanel panel = new MainPanel(menu); /** * Creates the main window and makes it visible. * <p> * First, assigns the main panel to the default uncaught exception handler to display exceptions in this panel.<br><br> * Before creating the main window, the application will have to set some elements, such as: * </p> * <ul> * <li>The minimum and default size;</li> * <li>The menu bar and the main panel;</li> * <li>An icon image;</li> * <li>A shutdown hook to stop the server, once the main window is closed.</li> * </ul><br> * <p> * The icon of the application is a modified version from the one provided in "{@code WebAppers.com}" * <i>(Creative Commons Attribution 3.0 License)</i>. * </p> */ public MainFrame() { ((UncaughtExceptionHandler) Thread.getDefaultUncaughtExceptionHandler()).setParentComponent(panel.get()); Dimension frameSize = new Dimension(Integer.parseInt(Configuration.INSTANCE.get("application.min.width")), Integer.parseInt(Configuration.INSTANCE.get("application.min.height"))); Image iconImage = Toolkit.getDefaultToolkit().getImage( getClass().getResource(Configuration.INSTANCE.get("application.icon.path"))); MainWindowListener windowListener = new MainWindowListener(this); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.addWindowStateListener(windowListener); // for catching windowClosing event mainFrame.setSize(frameSize); mainFrame.setMinimumSize(frameSize); mainFrame.setJMenuBar(menu.get()); mainFrame.getContentPane().add(panel.get()); mainFrame.setLocationRelativeTo(null); // Center main frame mainFrame.setIconImage(iconImage); // Add shutdown hook to stop server if enabled Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { SMTPServerHandler.INSTANCE.stopServer(); } }); // Restore last saved smtp port (if not overridden by the user) String smtpPort = ArgsHandler.INSTANCE.getPort(); if (smtpPort == null) { smtpPort = Configuration.INSTANCE.get("smtp.default.port"); } panel.getPortText().setText(smtpPort); // Restore last emails directory (if not overridden by the user) String emailsDir = ArgsHandler.INSTANCE.getOutputDirectory(); if (emailsDir == null) { emailsDir = Configuration.INSTANCE.get("emails.default.dir"); } if (emailsDir != null && !emailsDir.isEmpty()) { panel.getSaveMsgTextField().get().setText(emailsDir); UIModel.INSTANCE.setSavePath(emailsDir); } mainFrame.setVisible(true); } public void close() { // Save configuration Configuration.INSTANCE.set("smtp.default.port", panel.getPortText().get().getText()); Configuration.INSTANCE.set("emails.default.dir", panel.getSaveMsgTextField().get().getText()); try { Configuration.INSTANCE.saveToUserProfile(); } catch (IOException ex) { LoggerFactory.getLogger(MainFrame.class).error("Could not save configuration", ex); } // Check for SMTP server running and stop it if (SMTPServerHandler.INSTANCE.getSmtpServer().isRunning()) { SMTPServerHandler.INSTANCE.getSmtpServer().stop(); } mainFrame.dispose(); System.exit(0); } }
Corrected a comment in MainFrame.java
src/main/java/com/nilhcem/fakesmtp/gui/MainFrame.java
Corrected a comment in MainFrame.java
Java
bsd-3-clause
eb39676132832300ccba42c2ad045e793b59e0ab
0
UoLCompSoc/ld32,UoLCompSoc/ld32,UoLCompSoc/ld32
package uk.org.ulcompsoc.ld32; import java.util.ArrayList; import java.util.List; import uk.org.ulcompsoc.ld32.CircleMap.RingSegment; import uk.org.ulcompsoc.ld32.audio.AudioName; import uk.org.ulcompsoc.ld32.audio.IAudioManagement; import uk.org.ulcompsoc.ld32.audio.SilentAudioManager; import uk.org.ulcompsoc.ld32.components.Atom; import uk.org.ulcompsoc.ld32.components.Damage; import uk.org.ulcompsoc.ld32.components.DeathAnimation; import uk.org.ulcompsoc.ld32.components.MapRenderable; import uk.org.ulcompsoc.ld32.components.MouseListener; import uk.org.ulcompsoc.ld32.components.Paddle; import uk.org.ulcompsoc.ld32.components.PaddleInputListener; import uk.org.ulcompsoc.ld32.components.PathFollower; import uk.org.ulcompsoc.ld32.components.Position; import uk.org.ulcompsoc.ld32.components.Renderable; import uk.org.ulcompsoc.ld32.components.Rotatable; import uk.org.ulcompsoc.ld32.components.SphericalBound; import uk.org.ulcompsoc.ld32.components.Tower; import uk.org.ulcompsoc.ld32.components.Velocity; import uk.org.ulcompsoc.ld32.components.Wallet; import uk.org.ulcompsoc.ld32.components.upgrades.Upgradable; import uk.org.ulcompsoc.ld32.mouse.EmptyTowerMouseListenerHandler; import uk.org.ulcompsoc.ld32.mouse.RegularTowerMouseListenerHandler; import uk.org.ulcompsoc.ld32.systems.AtomMovementSystem; import uk.org.ulcompsoc.ld32.systems.BasicFiringSystem; import uk.org.ulcompsoc.ld32.systems.DoomedSystem; import uk.org.ulcompsoc.ld32.systems.EnemySpawningSystem; import uk.org.ulcompsoc.ld32.systems.GUIRenderSystem; import uk.org.ulcompsoc.ld32.systems.MapRenderSystem; import uk.org.ulcompsoc.ld32.systems.MouseListenerSystem; import uk.org.ulcompsoc.ld32.systems.PaddleInputSystem; import uk.org.ulcompsoc.ld32.systems.PathFollowingSystem; import uk.org.ulcompsoc.ld32.systems.ProjectileLifeTimeSystem; import uk.org.ulcompsoc.ld32.systems.ProjectileMovementSystem; import uk.org.ulcompsoc.ld32.systems.RenderSystem; import uk.org.ulcompsoc.ld32.systems.SphericalCollisionSystem; import uk.org.ulcompsoc.ld32.systems.TowerSystem; import uk.org.ulcompsoc.ld32.systems.WalletRenderSystem; import uk.org.ulcompsoc.ld32.util.LDUtil; import uk.org.ulcompsoc.ld32.util.TextureManager; import uk.org.ulcompsoc.ld32.util.TextureName; import com.badlogic.ashley.core.Engine; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Animation.PlayMode; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Circle; public class LD32 extends ApplicationAdapter { private final Engine engine; private final OrthographicCamera camera; public static final TextureManager textureManager = new TextureManager(); // public static final IAudioManagement audioManager = new AudioManager(); public static final IAudioManagement audioManager = new SilentAudioManager(false); private final Entity paddle = new Entity(); private TextureRegion paddleSprite = null; private final Entity enemy = new Entity(); private final CircleMap map; private final Entity mapEntity = new Entity(); private final Entity tower = new Entity(); private ShapeRenderer shapeRenderer = null; private Batch spriteBatch = null; private Animation ballAnimation = null; public LD32() { super(); this.engine = new Engine(); this.camera = new OrthographicCamera(); this.map = new CircleMap(120.0f, 5); } @Override public void create() { this.camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // this.camera.position.set(Gdx.graphics.getWidth() / 2.0f, // Gdx.graphics.getHeight() / 2.0f, 0.0f); this.camera.position.set(0.0f, 0.0f, 0.0f); this.camera.zoom = 0.5f; this.shapeRenderer = new ShapeRenderer(); this.spriteBatch = new SpriteBatch(); textureManager.load(); audioManager.load(); audioManager.play(AudioName.ABSTRACTION); paddleSprite = new TextureRegion(textureManager.nameMap.get(TextureName.PADDLE)); final float paddleScale = 0.2f; final Renderable paddleRenderable = new Renderable(paddleSprite).setScale(paddleScale); paddle.add(paddleRenderable); final Position paddlePosition = Position.fromPolar(map.radius + paddleRenderable.getWidth(), 0.0f); paddle.add(paddlePosition); final int[] leftKeys = { Keys.LEFT, Keys.A }; final int[] rightKeys = { Keys.RIGHT, Keys.D }; final int[] fireKeys = { Keys.UP, Keys.SPACE }; paddle.add(new PaddleInputListener(leftKeys, rightKeys, fireKeys)); paddle.add(new SphericalBound(30f)); paddle.add(new Paddle()); paddle.add(new Wallet(0, 0, 0)); paddle.add(new Rotatable().matchPhi()); engine.addEntity(paddle); final RingSegment firstSegment = map.getFirstSegment(); enemy.add(Position.fromPolar(firstSegment.middleR, firstSegment.middlePhi)); enemy.add(new Renderable(Color.BLUE, 16.0f)); enemy.add(new PathFollower(firstSegment).continueToNull().killWhenDone()); // enemy.add(new Enemy()); // engine.addEntity(enemy); final Position towerPos = Position.fromPolar(map.radius, LDUtil.PI); final float towerScale = 0.25f; final Renderable towerRen = new Renderable(new TextureRegion( textureManager.nameMap.get(TextureName.BASIC_TOWER))).setScale(towerScale); tower.add(towerPos); tower.add(towerRen); tower.add(new Tower(new Upgradable())); tower.add(new Damage(Tower.DFLT_DMG)); tower.add(new Upgradable()); tower.add(new MouseListener(new RegularTowerMouseListenerHandler(engine), new Circle(towerPos.getX(), towerPos .getY(), towerRen.getHeight()))); tower.add(new SphericalBound(towerRen.getWidth() / 2.0f)); engine.addEntity(tower); engine.addEntity(makeAtom()); engine.addEntity(makeAtom()); // engine.addEntity(makeAtom()); float phi = 3 * (LDUtil.PI / 2.0f); for (int i = 0; i < 3; ++i) { engine.addEntity(makeEmptyTower(phi + i * (LDUtil.PI / 2.0f))); } mapEntity.add(Position.fromEuclidean(0.0f, 0.0f)); mapEntity.add(new MapRenderable(map)); engine.addEntity(mapEntity); engine.addSystem(new GUIRenderSystem(spriteBatch, camera, -100)); engine.addSystem(new EnemySpawningSystem(500, 1.0f, map)); engine.addSystem(new PaddleInputSystem(1000)); engine.addSystem(new MouseListenerSystem(2000, camera)); engine.addSystem(new PathFollowingSystem(5000)); engine.addSystem(new AtomMovementSystem(5500, new Circle(0, 0, map.radius))); engine.addSystem(new ProjectileMovementSystem(6000)); engine.addSystem(new BasicFiringSystem(6500)); engine.addSystem(new SphericalCollisionSystem(7500, new Circle(Gdx.graphics.getWidth() / 2, Gdx.graphics .getHeight() / 2, map.radius))); engine.addSystem(new ProjectileLifeTimeSystem(8000)); engine.addSystem(new TowerSystem(9000, paddle.getComponent(Wallet.class))); engine.addSystem(new MapRenderSystem(10000, shapeRenderer, camera)); engine.addSystem(new RenderSystem(20000, spriteBatch, shapeRenderer, camera)); engine.addSystem(new WalletRenderSystem(25000, spriteBatch, camera, Gdx.graphics.getWidth() * 0.9f, Gdx.graphics.getHeight() * 0.95f)); engine.addSystem(new DoomedSystem(100000, paddle)); // engine.addSystem(new PositionDebugSystem(50000, shapeRenderer)); // engine.addSystem(new BoundingDebugSystem(5000, shapeRenderer)); // engine.addSystem(new AtomMovementSystem(new // Circle(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2, // map.radius), 2)); } private List<Integer> frameCounts = new ArrayList<Integer>(); @Override public void render() { final float deltaTime = Gdx.graphics.getDeltaTime(); frameCounts.add(Gdx.graphics.getFramesPerSecond()); if (frameCounts.size() > 100) { int total = 0; for (int i : frameCounts) { total += i; } final float fps = (float) total / (float) frameCounts.size(); frameCounts.clear(); Gdx.app.log("FPS", "Average FPS: " + fps); } Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); engine.update(deltaTime); } @Override public void dispose() { super.dispose(); engine.removeAllEntities(); audioManager.dispose(); textureManager.dispose(); if (shapeRenderer != null) { shapeRenderer.dispose(); shapeRenderer = null; } if (spriteBatch != null) { spriteBatch.dispose(); spriteBatch = null; } } public Entity makeAtom() { if (ballAnimation == null) { ballAnimation = new Animation(0.15f, textureManager.animationRegionMap.get(TextureName.BALL_ANIM)); ballAnimation.setPlayMode(PlayMode.LOOP); } Entity e = new Entity(); Renderable r = new Renderable(ballAnimation).setScale(0.5f); e.add(Position.fromEuclidean(2.0f, 2.0f)); e.add(r); e.add(new SphericalBound(r.getWidth() / 2)); e.add(new Velocity(0.5f, 0.5f)); e.add(new Atom()); e.add(new DeathAnimation(ballAnimation)); e.add(new Rotatable().animateRotation(1.0f)); return e; } public Entity makeEmptyTower(float phi) { final Entity e = new Entity(); final Position towerPos = Position.fromPolar(map.radius, phi); final Renderable towerRen = new Renderable(new TextureRegion( textureManager.nameMap.get(TextureName.EMPTY_TOWER))).setScale(0.25f); e.add(towerPos); e.add(towerRen); e.add(new SphericalBound(towerRen.getWidth() / 2)); e.add(new MouseListener(new EmptyTowerMouseListenerHandler(engine, paddle), new Circle(towerPos.getX(), towerPos.getY(), towerRen.getHeight() * 0.95f))); return e; } }
core/src/uk/org/ulcompsoc/ld32/LD32.java
package uk.org.ulcompsoc.ld32; import java.util.ArrayList; import java.util.List; import uk.org.ulcompsoc.ld32.CircleMap.RingSegment; import uk.org.ulcompsoc.ld32.audio.AudioManager; import uk.org.ulcompsoc.ld32.audio.AudioName; import uk.org.ulcompsoc.ld32.audio.IAudioManagement; import uk.org.ulcompsoc.ld32.components.Atom; import uk.org.ulcompsoc.ld32.components.Damage; import uk.org.ulcompsoc.ld32.components.DeathAnimation; import uk.org.ulcompsoc.ld32.components.MapRenderable; import uk.org.ulcompsoc.ld32.components.MouseListener; import uk.org.ulcompsoc.ld32.components.Paddle; import uk.org.ulcompsoc.ld32.components.PaddleInputListener; import uk.org.ulcompsoc.ld32.components.PathFollower; import uk.org.ulcompsoc.ld32.components.Position; import uk.org.ulcompsoc.ld32.components.Renderable; import uk.org.ulcompsoc.ld32.components.Rotatable; import uk.org.ulcompsoc.ld32.components.SphericalBound; import uk.org.ulcompsoc.ld32.components.Tower; import uk.org.ulcompsoc.ld32.components.Velocity; import uk.org.ulcompsoc.ld32.components.Wallet; import uk.org.ulcompsoc.ld32.components.upgrades.Upgradable; import uk.org.ulcompsoc.ld32.mouse.EmptyTowerMouseListenerHandler; import uk.org.ulcompsoc.ld32.mouse.RegularTowerMouseListenerHandler; import uk.org.ulcompsoc.ld32.systems.AtomMovementSystem; import uk.org.ulcompsoc.ld32.systems.BasicFiringSystem; import uk.org.ulcompsoc.ld32.systems.DoomedSystem; import uk.org.ulcompsoc.ld32.systems.EnemySpawningSystem; import uk.org.ulcompsoc.ld32.systems.GUIRenderSystem; import uk.org.ulcompsoc.ld32.systems.MapRenderSystem; import uk.org.ulcompsoc.ld32.systems.MouseListenerSystem; import uk.org.ulcompsoc.ld32.systems.PaddleInputSystem; import uk.org.ulcompsoc.ld32.systems.PathFollowingSystem; import uk.org.ulcompsoc.ld32.systems.ProjectileLifeTimeSystem; import uk.org.ulcompsoc.ld32.systems.ProjectileMovementSystem; import uk.org.ulcompsoc.ld32.systems.RenderSystem; import uk.org.ulcompsoc.ld32.systems.SphericalCollisionSystem; import uk.org.ulcompsoc.ld32.systems.TowerSystem; import uk.org.ulcompsoc.ld32.systems.WalletRenderSystem; import uk.org.ulcompsoc.ld32.util.LDUtil; import uk.org.ulcompsoc.ld32.util.TextureManager; import uk.org.ulcompsoc.ld32.util.TextureName; import com.badlogic.ashley.core.Engine; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Animation.PlayMode; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Circle; public class LD32 extends ApplicationAdapter { private final Engine engine; private final OrthographicCamera camera; public static final TextureManager textureManager = new TextureManager(); public static final IAudioManagement audioManager = new AudioManager(); // public static final IAudioManagement audioManager = new // SilentAudioManager(false); private final Entity paddle = new Entity(); private TextureRegion paddleSprite = null; private final Entity enemy = new Entity(); private final CircleMap map; private final Entity mapEntity = new Entity(); private final Entity tower = new Entity(); private ShapeRenderer shapeRenderer = null; private Batch spriteBatch = null; private Animation ballAnimation = null; public LD32() { super(); this.engine = new Engine(); this.camera = new OrthographicCamera(); this.map = new CircleMap(120.0f, 5); } @Override public void create() { this.camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // this.camera.position.set(Gdx.graphics.getWidth() / 2.0f, // Gdx.graphics.getHeight() / 2.0f, 0.0f); this.camera.position.set(0.0f, 0.0f, 0.0f); this.camera.zoom = 0.5f; this.shapeRenderer = new ShapeRenderer(); this.spriteBatch = new SpriteBatch(); textureManager.load(); audioManager.load(); audioManager.play(AudioName.ABSTRACTION); paddleSprite = new TextureRegion(textureManager.nameMap.get(TextureName.PADDLE)); final float paddleScale = 0.2f; final Renderable paddleRenderable = new Renderable(paddleSprite).setScale(paddleScale); paddle.add(paddleRenderable); final Position paddlePosition = Position.fromPolar(map.radius + paddleRenderable.getWidth(), 0.0f); paddle.add(paddlePosition); final int[] leftKeys = { Keys.LEFT, Keys.A }; final int[] rightKeys = { Keys.RIGHT, Keys.D }; final int[] fireKeys = { Keys.UP, Keys.SPACE }; paddle.add(new PaddleInputListener(leftKeys, rightKeys, fireKeys)); paddle.add(new SphericalBound(30f)); paddle.add(new Paddle()); paddle.add(new Wallet(0, 0, 0)); paddle.add(new Rotatable().matchPhi()); engine.addEntity(paddle); final RingSegment firstSegment = map.getFirstSegment(); enemy.add(Position.fromPolar(firstSegment.middleR, firstSegment.middlePhi)); enemy.add(new Renderable(Color.BLUE, 16.0f)); enemy.add(new PathFollower(firstSegment).continueToNull().killWhenDone()); // enemy.add(new Enemy()); // engine.addEntity(enemy); final Position towerPos = Position.fromPolar(map.radius, LDUtil.PI); final float towerScale = 0.25f; final Renderable towerRen = new Renderable(new TextureRegion( textureManager.nameMap.get(TextureName.BASIC_TOWER))).setScale(towerScale); tower.add(towerPos); tower.add(towerRen); tower.add(new Tower(new Upgradable())); tower.add(new Damage(Tower.DFLT_DMG)); tower.add(new Upgradable()); tower.add(new MouseListener(new RegularTowerMouseListenerHandler(engine), new Circle(towerPos.getX(), towerPos .getY(), towerRen.getHeight()))); tower.add(new SphericalBound(towerRen.getWidth() / 2.0f)); engine.addEntity(tower); engine.addEntity(makeAtom()); engine.addEntity(makeAtom()); // engine.addEntity(makeAtom()); float phi = 3 * (LDUtil.PI / 2.0f); for (int i = 0; i < 3; ++i) { engine.addEntity(makeEmptyTower(phi + i * (LDUtil.PI / 2.0f))); } mapEntity.add(Position.fromEuclidean(0.0f, 0.0f)); mapEntity.add(new MapRenderable(map)); engine.addEntity(mapEntity); engine.addSystem(new GUIRenderSystem(spriteBatch, camera, -100)); engine.addSystem(new EnemySpawningSystem(500, 1.0f, map)); engine.addSystem(new PaddleInputSystem(1000)); engine.addSystem(new MouseListenerSystem(2000, camera)); engine.addSystem(new PathFollowingSystem(5000)); engine.addSystem(new AtomMovementSystem(5500, new Circle(0, 0, map.radius))); engine.addSystem(new ProjectileMovementSystem(6000)); engine.addSystem(new BasicFiringSystem(6500)); engine.addSystem(new SphericalCollisionSystem(7500, new Circle(Gdx.graphics.getWidth() / 2, Gdx.graphics .getHeight() / 2, map.radius))); engine.addSystem(new ProjectileLifeTimeSystem(8000)); engine.addSystem(new TowerSystem(9000, paddle.getComponent(Wallet.class))); engine.addSystem(new MapRenderSystem(10000, shapeRenderer, camera)); engine.addSystem(new RenderSystem(20000, spriteBatch, shapeRenderer, camera)); engine.addSystem(new WalletRenderSystem(25000, spriteBatch, camera, Gdx.graphics.getWidth() * 0.9f, Gdx.graphics.getHeight() * 0.95f)); engine.addSystem(new DoomedSystem(100000, paddle)); // engine.addSystem(new PositionDebugSystem(50000, shapeRenderer)); // engine.addSystem(new BoundingDebugSystem(5000, shapeRenderer)); // engine.addSystem(new AtomMovementSystem(new // Circle(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2, // map.radius), 2)); } private List<Integer> frameCounts = new ArrayList<Integer>(); @Override public void render() { final float deltaTime = Gdx.graphics.getDeltaTime(); frameCounts.add(Gdx.graphics.getFramesPerSecond()); if (frameCounts.size() > 100) { int total = 0; for (int i : frameCounts) { total += i; } final float fps = (float) total / (float) frameCounts.size(); frameCounts.clear(); Gdx.app.log("FPS", "Average FPS: " + fps); } Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); engine.update(deltaTime); } @Override public void dispose() { super.dispose(); engine.removeAllEntities(); audioManager.dispose(); textureManager.dispose(); if (shapeRenderer != null) { shapeRenderer.dispose(); shapeRenderer = null; } if (spriteBatch != null) { spriteBatch.dispose(); spriteBatch = null; } } public Entity makeAtom() { if (ballAnimation == null) { ballAnimation = new Animation(0.15f, textureManager.animationRegionMap.get(TextureName.BALL_ANIM)); ballAnimation.setPlayMode(PlayMode.LOOP); } Entity e = new Entity(); Renderable r = new Renderable(ballAnimation).setScale(0.5f); e.add(Position.fromEuclidean(2.0f, 2.0f)); e.add(r); e.add(new SphericalBound(r.getWidth() / 2)); e.add(new Velocity(0.5f, 0.5f)); e.add(new Atom()); e.add(new DeathAnimation(ballAnimation)); e.add(new Rotatable().animateRotation(1.0f)); return e; } public Entity makeEmptyTower(float phi) { final Entity e = new Entity(); final Position towerPos = Position.fromPolar(map.radius, phi); final Renderable towerRen = new Renderable(new TextureRegion( textureManager.nameMap.get(TextureName.EMPTY_TOWER))).setScale(0.25f); e.add(towerPos); e.add(towerRen); e.add(new SphericalBound(towerRen.getWidth() / 2)); e.add(new MouseListener(new EmptyTowerMouseListenerHandler(engine, paddle), new Circle(towerPos.getX(), towerPos.getY(), towerRen.getHeight() * 0.95f))); return e; } }
Disable music before push
core/src/uk/org/ulcompsoc/ld32/LD32.java
Disable music before push
Java
mit
652794d805592aebdc3314181f2ce49ad1b37051
0
dpursehouse/reviewassistant,ReviewAssistant/reviewassistant,dpursehouse/reviewassistant,ReviewAssistant/reviewassistant
package com.github.nexception.reviewassistant; import com.github.nexception.reviewassistant.models.Calculation; import com.google.common.collect.Ordering; import com.google.gerrit.extensions.api.GerritApi; import com.google.gerrit.extensions.api.changes.ChangeApi; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Patch.ChangeType; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.server.account.AccountByEmailCache; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.config.PluginConfigFactory; import com.google.gerrit.server.events.PatchSetCreatedEvent; import com.google.gerrit.server.patch.PatchList; import com.google.gerrit.server.patch.PatchListCache; import com.google.gerrit.server.patch.PatchListEntry; import com.google.gerrit.server.patch.PatchListNotAvailableException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.eclipse.jgit.api.BlameCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.blame.BlameResult; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * A class for calculating recommended review time and * recommended reviewers. */ public class ReviewAssistant implements Runnable { private final AccountByEmailCache emailCache; private final AccountCache accountCache; private final Change change; private final PatchListCache patchListCache; private final PatchSet ps; private final Repository repo; private final RevCommit commit; private final GerritApi api; private final PluginConfigFactory cfg; private static final Logger log = LoggerFactory.getLogger(ReviewAssistant.class); public interface Factory { ReviewAssistant create(RevCommit commit, Change change, PatchSet ps, Repository repo); } @Inject public ReviewAssistant(final PatchListCache patchListCache, final AccountCache accountCache, final GerritApi api, final AccountByEmailCache emailCache, final PluginConfigFactory cfg, @Assisted final RevCommit commit, @Assisted final Change change, @Assisted final PatchSet ps, @Assisted final Repository repo) { this.commit = commit; this.change = change; this.ps = ps; this.patchListCache = patchListCache; this.repo = repo; this.accountCache = accountCache; this.emailCache = emailCache; this.cfg = cfg; this.api = api; } /** * Returns a Calculation object with all relevant information * regarding a review for a patch set. * @param event the event for a patch set * @return the Calculation object for a review */ public static Calculation calculate(PatchSetCreatedEvent event) { log.info("Received event: " + event.patchSet.revision); Calculation calculation = new Calculation(); calculation.commitId = event.patchSet.revision; calculation.totalReviewTime = calculateReviewTime(event); calculation.hours = calculateReviewTime(event) / 60; calculation.minutes = calculateReviewTime(event) % 60; calculation.sessions = calculateReviewSessions(calculateReviewTime(event)); calculation.sessionTime = 60; return calculation; } /** * Returns the total amount of time in minutes recommended for a review. * Adds all line insertions and deletions for a patch set and calculates * the amount of minutes needed. * This calculation is based on the optimum review rate of 5 LOC in 1 minute. * @param event the event for a patch set * @return the total amount of time recommended for a review */ private static int calculateReviewTime(PatchSetCreatedEvent event) { int lines = event.patchSet.sizeInsertions + Math.abs(event.patchSet.sizeDeletions); int minutes = (int) Math.ceil(lines / 5); if(minutes < 5) { minutes = 5; } return minutes; } /** * Returns the recommended amount of review sessions for a review. * Divides the total amount of review time up in 60 minute sessions. * @param minutes the total amount of time recommended for a review * @return the recommended amount of review sessions */ private static int calculateReviewSessions(int minutes) { int sessions = Math.round(minutes / 60); if (sessions < 1) { sessions = 1; } return sessions; } /** * Calculates blame data for a given file and commit. * @param commit the commit to base the blame command on * @param file the file for which to calculate blame data * @return BlameResult */ private BlameResult calculateBlame(RevCommit commit, PatchListEntry file) { BlameCommand blameCommand = new BlameCommand(repo); blameCommand.setStartCommit(commit); blameCommand.setFilePath(file.getNewName()); try { BlameResult blameResult = blameCommand.call(); blameResult.computeAll(); return blameResult; } catch (GitAPIException e) { log.error("Could not call blame command for commit {}", commit.getName(), e); } catch (IOException e) { log.error("Could not compute blame result for commit {}", commit.getName(), e); } return null; } /** * Calculates all reviewers based on a blame result. The result is a map of accounts and integers * where the integer represents the number of occurrences of the account in the commit history. * @param edits list of edited rows for a file * @param blameResult result from git blame for a specific file * @return a list of accounts and integers */ private List<Entry<Account, Integer>> getReviewers(List<Edit> edits, BlameResult blameResult) { Map<Account, Integer> blameData = new HashMap<>(); int maxReviewers = cfg.getGlobalPluginConfig("reviewassistant").getInt("reviewers", "reviewers", 3); for (Edit edit : edits) { for (int i = edit.getBeginA(); i < edit.getEndA(); i++) { RevCommit commit = blameResult.getSourceCommit(i); Set<Account.Id> idSet = emailCache.get(commit.getAuthorIdent().getEmailAddress()); for (Account.Id id : idSet) { Account account = accountCache.get(id).getAccount(); // Check if account is active and not owner of change if (account.isActive() && !change.getOwner().equals(account.getId())) { Integer count = blameData.get(account); if (count == null) { count = 1; } else { count = count.intValue() + 1; } blameData.put(account, count); } } } } List<Entry<Account, Integer>> topReviewers = Ordering.from(new Comparator<Entry<Account, Integer>>() { @Override public int compare(Entry<Account, Integer> itemOne, Entry<Account, Integer> itemTwo) { return itemOne.getValue() - itemTwo.getValue(); } }).greatestOf(blameData.entrySet(), maxReviewers); log.info("getReviewers found " + topReviewers.size() + " reviewers"); return topReviewers; } private void addReviewers(Change change, List<Entry<Account, Integer>> list) { try { ChangeApi api = this.api.changes().id(change.getChangeId()); for (Entry<Account, Integer> entry : list) { api.addReviewer(entry.getKey().getId().toString()); log.info(entry.getKey() + " was added to this change"); } } catch (Exception e) { log.error("Could not add reviewers"); } } @Override public void run() { PatchList patchList; try { patchList = patchListCache.get(change, ps); } catch (PatchListNotAvailableException e) { log.error("Patchlist is not available for {}", change.getKey(), e); return; } if (commit.getParentCount() != 1) { log.error("No merge/initial"); return; } List<Entry<Account, Integer>> reviewers = new LinkedList<>(); for (PatchListEntry entry : patchList.getPatches()) { /* * Only git blame at the moment. If other methods are used in the future, * other change types might be required. */ if (entry.getChangeType() == ChangeType.MODIFIED || entry.getChangeType() == ChangeType.DELETED) { BlameResult blameResult = calculateBlame(commit.getParent(0), entry); if (blameResult != null) { List<Edit> edits = entry.getEdits(); reviewers.addAll(getReviewers(edits, blameResult)); for (int i = 0; i < reviewers.size(); i++) { log.info("Candidate " + (i + 1) + ": " + reviewers.get(i).getKey().getPreferredEmail() + ", blame score: " + reviewers.get(i).getValue()); } } else { log.error("calculateBlame returned null for commit {}", commit); } } } addReviewers(change, reviewers); } }
src/main/java/com/github/nexception/reviewassistant/ReviewAssistant.java
package com.github.nexception.reviewassistant; import com.github.nexception.reviewassistant.models.Calculation; import com.google.common.collect.Ordering; import com.google.gerrit.extensions.api.changes.AddReviewerInput; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Patch.ChangeType; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.server.account.AccountByEmailCache; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.change.ChangeResource; import com.google.gerrit.server.change.ChangesCollection; import com.google.gerrit.server.config.PluginConfigFactory; import com.google.gerrit.server.events.PatchSetCreatedEvent; import com.google.gerrit.server.patch.PatchList; import com.google.gerrit.server.patch.PatchListCache; import com.google.gerrit.server.patch.PatchListEntry; import com.google.gerrit.server.patch.PatchListNotAvailableException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.eclipse.jgit.api.BlameCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.blame.BlameResult; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * A class for calculating recommended review time and * recommended reviewers. */ public class ReviewAssistant implements Runnable { private final AccountByEmailCache emailCache; private final AccountCache accountCache; private final Change change; private final PatchListCache patchListCache; private final PatchSet ps; private final Repository repo; private final RevCommit commit; private final ChangesCollection changes; private final PluginConfigFactory cfg; private static final Logger log = LoggerFactory.getLogger(ReviewAssistant.class); public interface Factory { ReviewAssistant create(RevCommit commit, Change change, PatchSet ps, Repository repo); } @Inject public ReviewAssistant(final PatchListCache patchListCache, final AccountCache accountCache, final ChangesCollection changes, final AccountByEmailCache emailCache, final PluginConfigFactory cfg, @Assisted final RevCommit commit, @Assisted final Change change, @Assisted final PatchSet ps, @Assisted final Repository repo) { this.commit = commit; this.change = change; this.ps = ps; this.patchListCache = patchListCache; this.repo = repo; this.accountCache = accountCache; this.emailCache = emailCache; this.cfg = cfg; this.changes = changes; } /** * Returns a Calculation object with all relevant information * regarding a review for a patch set. * @param event the event for a patch set * @return the Calculation object for a review */ public static Calculation calculate(PatchSetCreatedEvent event) { log.info("Received event: " + event.patchSet.revision); Calculation calculation = new Calculation(); calculation.commitId = event.patchSet.revision; calculation.totalReviewTime = calculateReviewTime(event); calculation.hours = calculateReviewTime(event) / 60; calculation.minutes = calculateReviewTime(event) % 60; calculation.sessions = calculateReviewSessions(calculateReviewTime(event)); calculation.sessionTime = 60; return calculation; } /** * Returns the total amount of time in minutes recommended for a review. * Adds all line insertions and deletions for a patch set and calculates * the amount of minutes needed. * This calculation is based on the optimum review rate of 5 LOC in 1 minute. * @param event the event for a patch set * @return the total amount of time recommended for a review */ private static int calculateReviewTime(PatchSetCreatedEvent event) { int lines = event.patchSet.sizeInsertions + Math.abs(event.patchSet.sizeDeletions); int minutes = (int) Math.ceil(lines / 5); if(minutes < 5) { minutes = 5; } return minutes; } /** * Returns the recommended amount of review sessions for a review. * Divides the total amount of review time up in 60 minute sessions. * @param minutes the total amount of time recommended for a review * @return the recommended amount of review sessions */ private static int calculateReviewSessions(int minutes) { int sessions = Math.round(minutes / 60); if (sessions < 1) { sessions = 1; } return sessions; } /** * Calculates blame data for a given file and commit. * @param commit the commit to base the blame command on * @param file the file for which to calculate blame data * @return BlameResult */ private BlameResult calculateBlame(RevCommit commit, PatchListEntry file) { BlameCommand blameCommand = new BlameCommand(repo); blameCommand.setStartCommit(commit); blameCommand.setFilePath(file.getNewName()); try { BlameResult blameResult = blameCommand.call(); blameResult.computeAll(); return blameResult; } catch (GitAPIException e) { log.error("Could not call blame command for commit {}", commit.getName(), e); } catch (IOException e) { log.error("Could not compute blame result for commit {}", commit.getName(), e); } return null; } /** * Calculates all reviewers based on a blame result. The result is a map of accounts and integers * where the integer represents the number of occurrences of the account in the commit history. * @param edits list of edited rows for a file * @param blameResult result from git blame for a specific file * @return a list of accounts and integers */ private List<Entry<Account, Integer>> getReviewers(List<Edit> edits, BlameResult blameResult) { Map<Account, Integer> blameData = new HashMap<>(); int maxReviewers = cfg.getGlobalPluginConfig("reviewassistant").getInt("reviewers", "reviewers", 3); for (Edit edit : edits) { for (int i = edit.getBeginA(); i < edit.getEndA(); i++) { RevCommit commit = blameResult.getSourceCommit(i); Set<Account.Id> idSet = emailCache.get(commit.getAuthorIdent().getEmailAddress()); for (Account.Id id : idSet) { Account account = accountCache.get(id).getAccount(); // Check if account is active and not owner of change if (account.isActive() && !change.getOwner().equals(account.getId())) { Integer count = blameData.get(account); if (count == null) { count = 1; } else { count = count.intValue() + 1; } blameData.put(account, count); } } } } List<Entry<Account, Integer>> topReviewers = Ordering.from(new Comparator<Entry<Account, Integer>>() { @Override public int compare(Entry<Account, Integer> itemOne, Entry<Account, Integer> itemTwo) { return itemOne.getValue() - itemTwo.getValue(); } }).greatestOf(blameData.entrySet(), maxReviewers); log.info("getReviewers found " + topReviewers.size() + " reviewers"); return topReviewers; } private void addReviewers(Change change, List<Entry<Account, Integer>> list) { try { // ChangeResource changeResource = changes.parse(change.getId()); // AddReviewerInput input = new AddReviewerInput(); for (Entry<Account, Integer> entry : list) { log.info(entry.getKey() + " was added to this change"); } } catch (Exception e) { log.error("Could not add reviewers"); } } @Override public void run() { PatchList patchList; try { patchList = patchListCache.get(change, ps); } catch (PatchListNotAvailableException e) { log.error("Patchlist is not available for {}", change.getKey(), e); return; } if (commit.getParentCount() != 1) { log.error("No merge/initial"); return; } List<Entry<Account, Integer>> reviewers = new LinkedList<>(); for (PatchListEntry entry : patchList.getPatches()) { /* * Only git blame at the moment. If other methods are used in the future, * other change types might be required. */ if (entry.getChangeType() == ChangeType.MODIFIED || entry.getChangeType() == ChangeType.DELETED) { BlameResult blameResult = calculateBlame(commit.getParent(0), entry); if (blameResult != null) { List<Edit> edits = entry.getEdits(); reviewers.addAll(getReviewers(edits, blameResult)); for (int i = 0; i < reviewers.size(); i++) { log.info("Candidate " + (i + 1) + ": " + reviewers.get(i).getKey().getPreferredEmail() + ", blame score: " + reviewers.get(i).getValue()); } } else { log.error("calculateBlame returned null for commit {}", commit); } } } addReviewers(change, reviewers); } }
Auto add reviewer Change-Id: I3057e7d7e654ae1d7cb9cf865c0dbc8566e0b739
src/main/java/com/github/nexception/reviewassistant/ReviewAssistant.java
Auto add reviewer
Java
mit
36c1c891390a3e7307f4189089c857f09e8595d6
0
hpe-idol/find,hpautonomy/find,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,hpe-idol/java-powerpoint-report,hpe-idol/find,hpe-idol/java-powerpoint-report,hpautonomy/find,hpe-idol/find
package com.autonomy.abc.keywords; import com.autonomy.abc.config.ABCTestBase; import com.autonomy.abc.config.ApplicationType; import com.autonomy.abc.config.TestConfig; import com.autonomy.abc.selenium.menubar.NavBarTabId; import com.autonomy.abc.selenium.menubar.NotificationsDropDown; import com.autonomy.abc.selenium.menubar.SideNavBar; import com.autonomy.abc.selenium.page.AppBody; import com.autonomy.abc.selenium.page.keywords.CreateNewKeywordsPage; import com.autonomy.abc.selenium.page.keywords.KeywordsPage; import com.autonomy.abc.selenium.page.search.SearchPage; import org.apache.commons.lang.StringUtils; import org.apache.xpath.operations.Bool; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.MalformedURLException; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; public class KeywordsPageAndWizardITCase extends ABCTestBase { public KeywordsPageAndWizardITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) { super(config, browser, appType, platform); } private KeywordsPage keywordsPage; private CreateNewKeywordsPage createKeywordsPage; private SearchPage searchPage; private NotificationsDropDown notifications; @Before public void setUp() throws MalformedURLException { try { Thread.sleep(1000); //TODO TAKE THIS OUT!!! } catch (InterruptedException e) { System.out.println("Thread sleep in setUp went horribly wrong"); } navBar.switchPage(NavBarTabId.KEYWORDS); navBar.loadOrFadeWait(); keywordsPage = body.getKeywordsPage(); } //Passes @Test public void testCreateNewKeywordsButtonAndCancel() { assertThat("Create new keywords button is not visible", keywordsPage.createNewKeywordsButton().isDisplayed()); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); assertThat("Create new keywords button should not be visible", !keywordsPage.createNewKeywordsButton().isDisplayed()); assertThat("Create Synonyms button should be visible", createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).isDisplayed()); assertThat("Create Blacklisted button should be visible", createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).isDisplayed()); assertThat("Cancel button be visible", createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).isDisplayed()); assertThat("Continue button should be visible", createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).isDisplayed()); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); assertThat("Create new keywords button should be visible", keywordsPage.createNewKeywordsButton().isDisplayed()); } //Passes @Test public void testNavigateSynonymsWizard() throws InterruptedException { try { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Continue button should be disabled until a keywords type is selected", keywordsPage.isAttributePresent(createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE), "disabled")); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); assertThat("Synonym type not set active", createKeywordsPage.getFirstChild(createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM)).getAttribute("class").contains("progressive-disclosure-selection")); assertThat("Continue button should be enabled", !createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).getAttribute("class").contains("disabled")); assertThat("languages select should be visible", createKeywordsPage.languagesSelectBox().isDisplayed()); /*createKeywordsPage.selectLanguage("French"); assertEquals("French", createKeywordsPage.languagesSelectBox().getText()); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled"));*/ (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonymsTextBox().clear(); assertThat("Finish button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertThat("Add synonyms button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.addSynonymsButton(), "disabled")); createKeywordsPage.addSynonymsTextBox().sendKeys("horse"); assertThat("Finish button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addSynonymsButton().click(); assertThat("Finish button should be disabled until more than one synonym is added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("stuff pony things"); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(4, createKeywordsPage.countKeywords()); createKeywordsPage.finishWizardButton().click(); createKeywordsPage.loadOrFadeWait(); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); //searchPage.selectLanguage("French", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); new WebDriverWait(getDriver(), 8).until(ExpectedConditions.visibilityOf(searchPage.docLogo())); final List<String> searchTerms = searchPage.getSearchTermsList(); assertThat("Synonym group does not contain 'stuff', 'horse', 'pony' and 'things'", searchTerms.containsAll(Arrays.asList("stuff", "horse", "pony", "things"))); new SideNavBar(getDriver()).getTab(NavBarTabId.KEYWORDS).click(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); //keywordsPage.selectLanguage("French"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); assertThat("synonym horse is not displayed", keywordsPage.leadSynonym("horse").isDisplayed()); final List<String> synonymGroup = keywordsPage.getSynonymGroupSynonyms("horse"); assertThat("Synonym group does not contain 'stuff', 'horse', 'pony' and 'things'", synonymGroup.containsAll(Arrays.asList("stuff", "horse", "pony", "things"))); } finally { new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.deleteAllSynonyms(); //TODO Fails here } } //Passed @Test public void testWizardCancelButtonsWorksAfterClickingTheNavBarToggleButton() { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); topNavBar.sideBarToggle(); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); assertThat("Cancel button does not work after clicking the toggle button", keywordsPage.createNewKeywordsButton().isDisplayed()); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); topNavBar.sideBarToggle(); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); assertThat("Cancel button does not work after clicking the toggle button", keywordsPage.createNewKeywordsButton().isDisplayed()); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); //Not sure why these were repeated //keywordsPage.createNewKeywordsButton().click(); //createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); topNavBar.sideBarToggle(); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); assertThat("Cancel button does not work after clicking the toggle button", keywordsPage.createNewKeywordsButton().isDisplayed()); } //Passed @Test public void testNavigateBlacklistedWizard() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Continue button should be disabled until a keywords type is selected", createKeywordsPage.isAttributePresent(createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE), "disabled")); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); assertThat("Blacklisted type not set active", createKeywordsPage.getFirstChild(createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST)).getAttribute("class").contains("progressive-disclosure-selection")); assertThat("Continue button should be enabled", !createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).getAttribute("class").contains("disabled")); assertThat("Wizard did not navigate to languages page", createKeywordsPage.languagesSelectBox().isDisplayed()); //createKeywordsPage.selectLanguage("Swahili"); //assertEquals("Swahili", createKeywordsPage.languagesSelectBox().getText()); //createKeywordsPage.selectLanguage("English"); //assertEquals("English", createKeywordsPage.languagesSelectBox().getText()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertThat("Wizard did not navigate to blacklist page", createKeywordsPage.addBlacklistedTextBox().isDisplayed()); createKeywordsPage.addBlacklistedTextBox().clear(); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTextBox().sendKeys("danger"); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addBlacklistTermsButton().click(); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addBlacklistedTextBox().sendKeys("warning beware scary"); createKeywordsPage.addBlacklistTermsButton().click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(4, createKeywordsPage.countKeywords()); createKeywordsPage.finishWizardButton().click(); createKeywordsPage.loadOrFadeWait(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); final List<String> blacklistTerms = keywordsPage.getBlacklistedTerms(); createKeywordsPage.loadOrFadeWait(); assertThat("blacklist terms not all displayed", blacklistTerms.containsAll(Arrays.asList("danger", "warning", "beware", "scary"))); assertThat("too many blacklist terms", blacklistTerms.size() == 4); } //Passed @Test public void testKeywordsFilter() throws InterruptedException { final WebDriverWait wait = new WebDriverWait(getDriver(), 5); keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("dog hound canine", "English"); searchPage = body.getSearchPage(); wait.until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); assertThat("New keyword not searched for", searchPage.searchTitle().getText().contains("dog")); assertThat("New keyword not searched for", searchPage.searchTitle().getText().contains("hound")); assertThat("New keyword not searched for", searchPage.searchTitle().getText().contains("canine")); new SideNavBar(getDriver()).getTab(NavBarTabId.KEYWORDS).click(); wait.until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.selectLanguage("English"); assertThat("Synonym group dog not visible", keywordsPage.getSynonymGroupSynonyms("dog").containsAll(Arrays.asList("hound", "canine"))); assertThat("Synonym group hound not visible", keywordsPage.getSynonymGroupSynonyms("hound").containsAll(Arrays.asList("dog", "canine"))); assertThat("Synonym group canine not visible", keywordsPage.getSynonymGroupSynonyms("canine").containsAll(Arrays.asList("dog", "hound"))); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("illegal", "English"); assertThat("Blacklisted term 'illegal' not visible", keywordsPage.getBlacklistedTerms().contains("illegal")); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertThat("Blacklist terms are still visible", keywordsPage.getBlacklistedTerms().size() == 0); assertThat("A synonym list on row 2 is not visible", keywordsPage.synonymList(1).isDisplayed()); assertThat("Synonym group dog not visible", keywordsPage.getSynonymGroupSynonyms("dog").containsAll(Arrays.asList("hound", "canine"))); assertThat("Synonym group hound not visible", keywordsPage.getSynonymGroupSynonyms("hound").containsAll(Arrays.asList("dog", "canine"))); assertThat("Synonym group canine not visible", keywordsPage.getSynonymGroupSynonyms("canine").containsAll(Arrays.asList("dog", "hound"))); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); assertThat("Blacklisted term 'illegal' not visible", keywordsPage.getBlacklistedTerms().contains("illegal")); assertEquals("There should not be a a synonym list on row 2", 0, keywordsPage.countSynonymLists()); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); assertThat("A synonym list should be visible on row 2", keywordsPage.synonymList(1).isDisplayed()); assertThat("Synonym group dog not visible", keywordsPage.getSynonymGroupSynonyms("dog").containsAll(Arrays.asList("hound", "canine"))); assertThat("Synonym group hound not visible", keywordsPage.getSynonymGroupSynonyms("hound").containsAll(Arrays.asList("dog", "canine"))); assertThat("Synonym group canine not visible", keywordsPage.getSynonymGroupSynonyms("canine").containsAll(Arrays.asList("dog", "hound"))); assertThat("Blacklist term illegal is not visible", keywordsPage.getBlacklistedTerms().contains("illegal")); } //Passed @Test public void testDeleteKeywords() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("frog toad amphibian tadpole", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); assertThat("synonym group not fully created", keywordsPage.getSynonymGroupSynonyms("frog").containsAll(Arrays.asList("frog", "toad", "amphibian", "tadpole"))); assertEquals("Wrong number of synonym lists displayed", 4, keywordsPage.countSynonymLists()); assertEquals("Wrong number of synonyms in group frog", 4, keywordsPage.getSynonymGroupSynonyms("frog").size()); keywordsPage.deleteSynonym("amphibian", "toad"); assertEquals("Wrong number of synonym lists displayed", 3, keywordsPage.countSynonymLists()); assertEquals("Wrong number of synonyms in group toad", 3, keywordsPage.getSynonymGroupSynonyms("toad").size()); assertThat("the synonym amphibian should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("tadpole").contains("amphibian")); assertThat("the synonym amphibian should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("toad").contains("amphibian")); assertThat("the synonym amphibian should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("frog").contains("amphibian")); keywordsPage.deleteSynonym("frog", "frog"); assertEquals("Wrong number of synonym lists displayed", 2, keywordsPage.countSynonymLists()); assertEquals("Wrong number of synonyms in group toad", 2, keywordsPage.getSynonymGroupSynonyms("toad").size()); assertThat("the synonym frog should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("toad").contains("frog")); assertThat("the synonym frog should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("tadpole").contains("frog")); keywordsPage.deleteSynonym("tadpole", "toad"); assertEquals("Wrong number of synonym lists displayed", 0, keywordsPage.countSynonymLists()); } //Passed //The keyword 'wine' exists in two different synonym groups. Tests that deleting this keyword does not effect the other synonym group @Test public void testDeleteSynonymsFromOverlappingSynonymGroups() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("wine merlot shiraz bordeaux", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("wine red scarlet burgundy", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("English"); assertThat("synonym group not fully created", keywordsPage.getSynonymGroupSynonyms("red").containsAll(Arrays.asList("red", "scarlet", "wine", "burgundy"))); assertEquals(8, keywordsPage.countSynonymLists()); assertEquals(4, keywordsPage.getSynonymGroupSynonyms("burgundy").size()); assertEquals(4, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(2, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("bordeaux", "shiraz"); assertEquals(7, keywordsPage.countSynonymLists()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(4, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(2, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("burgundy", "red"); assertEquals(6, keywordsPage.countSynonymLists()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(2, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("wine", "red"); assertEquals(5, keywordsPage.countSynonymLists()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("shiraz", "wine"); assertEquals(4, keywordsPage.countSynonymLists()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("scarlet", "red"); assertEquals(2, keywordsPage.countSynonymLists()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("wine", "merlot"); assertEquals(0, keywordsPage.countSynonymLists()); } //Duplicate blacklisted terms are not allowed to be created within the same language @Test public void testCreateDuplicateBlacklist() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("fish", "English"); assertThat("Blacklist fish not visible", keywordsPage.getBlacklistedTerms().contains("fish")); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addBlacklistedTextBox().sendKeys("fish"); createKeywordsPage.addBlacklistTermsButton().click(); createKeywordsPage.loadOrFadeWait(); assertThat("Duplicate blacklist warning message not present", createKeywordsPage.getText().contains("The word \"fish\" is already blacklisted")); assertThat("Duplicate blacklist term should not be added", createKeywordsPage.countKeywords() == 0); assertThat("Finish button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addBlacklistedTextBox().clear(); createKeywordsPage.addBlacklistedTextBox().sendKeys("chips"); createKeywordsPage.addBlacklistTermsButton().click(); assertThat("Duplicate blacklist warning message has not disappeared", !createKeywordsPage.getText().contains("The word \"fish\" is already blacklisted")); assertThat("New blacklist term should be added", createKeywordsPage.countKeywords() == 1); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.deleteKeyword("chips"); assertThat("There should be no blacklist terms", createKeywordsPage.countKeywords() == 0); assertThat("Finish button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); assertThat("Cancel button redirects to wrong page", getDriver().getCurrentUrl().endsWith("keywords")); assertEquals("Wrong number of blacklisted terms", 1, keywordsPage.getBlacklistedTerms().size()); } //Whitespace of any form should not be added as a blacklisted term @Test public void testWhitespaceBlacklistTermsWizard() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTextBox().sendKeys(" "); createKeywordsPage.tryClickThenTryParentClick(createKeywordsPage.addBlacklistTermsButton()); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addBlacklistedTextBox().clear(); createKeywordsPage.addBlacklistedTextBox().click(); createKeywordsPage.addBlacklistedTextBox().sendKeys(Keys.RETURN); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addBlacklistedTextBox().sendKeys("\t"); createKeywordsPage.tryClickThenTryParentClick(createKeywordsPage.addBlacklistTermsButton()); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); } //Whitespace of any form should not be added as a synonym keyword @Test public void testWhitespaceSynonymsWizard() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms(" "); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().click(); createKeywordsPage.addSynonymsTextBox().sendKeys(Keys.RETURN); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addSynonyms("\t"); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addSynonyms("test"); createKeywordsPage.addSynonyms(" "); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 1); createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().click(); createKeywordsPage.addSynonymsTextBox().sendKeys(Keys.RETURN); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 1); createKeywordsPage.addSynonyms("\t"); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 1); } //Odd number of quotes or quotes with blank text should not be able to be added as a synonym keyword @Test public void testQuotesInSynonymsWizard() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("\""); assertEquals(0, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\"\""); assertEquals(0, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\" \""); assertEquals(0, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("test"); createKeywordsPage.addSynonyms("\""); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\"\""); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\" \""); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("terms \""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("Correct error message not showing", createKeywordsPage.getText().contains("Terms have an odd number of quotes, suggesting an unclosed phrase")); createKeywordsPage.addSynonyms("\"closed phrase\""); assertEquals(2, createKeywordsPage.countKeywords()); assertThat("Phrase not created", createKeywordsPage.getProspectiveKeywordsList().contains("closed phrase")); assertThat("Quotes unescaped", !createKeywordsPage.getProspectiveKeywordsList().contains("/")); } //Odd number of quotes or quotes with blank text should not be able to be added as a blacklisted term @Test public void testQuotesInBlacklistWizard() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTerms("\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\" \""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"d"); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("d\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("\"d\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("s\"d\"d"); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("test"); createKeywordsPage.addBlacklistedTerms("\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\" \""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"d"); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("d\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("\"d\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("s\"d\"d"); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); } @Ignore // This takes too long for a nightly test but is a useful test that need run periodically as the application has failed in the past with a large number of synonym groups. // Failure can present itself on other pages other than the KeywordsPage @Test public void testAddLotsOfSynonymGroups() throws IOException, InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); final List<String> groupsOfFiveSynonyms = keywordsPage.loadTextFileLineByLineIntoList("C://dev//res//100.txt"); for (final String synonymGroup : groupsOfFiveSynonyms) { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup(synonymGroup, "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); assertThat("Wrong number of synonym lists", keywordsPage.countSynonymLists() == groupsOfFiveSynonyms.indexOf(synonymGroup) + 1); } } //Whitespace, Odd number of quotes or quotes with blank text, boolean operators or proximity operators should not be able to added as keywords. This test checks they can't be added to existing synonyms on the Keywords Page @Test public void testAddingWhitespaceQuotesBooleansProximityOperatorsOnKeywordsPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("one two three", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); //keywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); keywordsPage.addSynonymToGroup("four", "one"); keywordsPage.waitForRefreshIconToDisappear(); assertThat("there should be four synonyms in a group", keywordsPage.getSynonymGroupSynonyms("two").contains("four")); assertEquals(4, keywordsPage.countSynonymLists()); keywordsPage.synonymGroupPlusButton("three").click(); keywordsPage.synonymGroupTextBox("three").clear(); keywordsPage.synonymGroupTickButton("three").click(); assertThat("add synonym box should still be displayed", keywordsPage.synonymGroupTextBox("three").isDisplayed()); keywordsPage.searchFilterTextBox().click(); assertThat("there should be four synonyms in a group", keywordsPage.getSynonymGroupSynonyms("two").contains("four")); assertEquals(4, keywordsPage.countSynonymLists()); for (final String badSynonym : Arrays.asList(" ", "\t", "\"", "NOT", "NEAR", "DNEAR", "XNEAR", "YNEAR", "NEAR123", "SENTENCE2", "PARAGRAPH3", "AND", "BEFORE", "AFTER", "WHEN", "SENTENCE", "PARAGRAPH", "OR", "WNEAR", "EOR", "NOTWHEN")) { keywordsPage.synonymGroupPlusButton("three").click(); keywordsPage.synonymGroupTextBox("three").clear(); keywordsPage.synonymGroupTextBox("three").sendKeys(badSynonym); keywordsPage.synonymGroupTickButton("three").click(); assertThat("add synonym box should still be displayed. Offending term is " + badSynonym, keywordsPage.synonymGroupTextBox("three").isDisplayed()); keywordsPage.loadOrFadeWait(); keywordsPage.searchFilterTextBox().click(); assertThat("there should be four synonyms in a group. Offending term is " + badSynonym, keywordsPage.getSynonymGroupSynonyms("one").size() == 4); assertEquals(4, keywordsPage.countSynonymLists()); } } //Phrases should be able to be added as synonyms from the keywords page @Test public void testPhrasesCanBeAddedAsSynonymsOnKeywordsPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("one two three", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("English"); keywordsPage.synonymGroupPlusButton("three").click(); keywordsPage.synonymGroupTextBox("three").clear(); keywordsPage.synonymGroupTextBox("three").sendKeys("four and five"); keywordsPage.synonymGroupTickButton("three").click(); Thread.sleep(5000); assertFalse("New Synonym Box is displayed",keywordsPage.synonymGroupTextBox("three").isDisplayed()); assertEquals(4, keywordsPage.countSynonymLists()); assertTrue(keywordsPage.getSynonymGroupSynonyms("three").contains("four and five")); } //Notification should drop down on creation of new keywords @Test public void testNotificationForCreatedBlacklistedTermAndSynonymGroup() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("orange", "English"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.PROMOTIONS); notifications = body.getNotifications(); topNavBar.notificationsDropdown(); assertThat(notifications.notificationNumber(1).getText(), containsString("Added \"orange\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("piano keyboard pianoforte", "English"); body.waitForGritterToClear(); topNavBar.notificationsDropdown(); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Created a new synonym group containing: keyboard, piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(2).getText().contains("Added \"orange\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); keywordsPage.loadOrFadeWait(); keywordsPage.deleteSynonym("keyboard", "piano"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.PROMOTIONS); topNavBar.notificationsDropdown(); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Updated a synonym group containing: piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(2).getText().contains("Created a new synonym group containing: keyboard, piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(3).getText().contains("Added \"orange\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); keywordsPage.selectLanguage("English"); keywordsPage.deleteBlacklistedTerm("orange"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.OVERVIEW); topNavBar.notificationsDropdown(); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Removed \"orange\" from the blacklist")); assertThat("Notification text incorrect", notifications.notificationNumber(2).getText().contains("Updated a synonym group containing: piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(3).getText().contains("Created a new synonym group containing: keyboard, piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(4).getText().contains("Added \"orange\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); } // This only tests the notifications dropdown and not the gritters @Test public void testHTMLEscapedInNotifications() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("<h1>Hi</h1>", "English"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.PROMOTIONS); topNavBar.notificationsDropdown(); notifications = body.getNotifications(); assertThat("Notification text incorrect, HTML not escaped", !notifications.notificationNumber(1).getText().contains("Added \"Hi\" to the blacklist")); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Added \"<h1>Hi</h1>\" to the blacklist")); //Pretty sure it wasn't... notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); } //Blacklisted terms can be created on the searchpage. This link has often broken @Test public void testCreateBlacklistedTermFromSearchPage() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("noir"); searchPage = body.getSearchPage(); //searchPage.selectLanguage("French", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); searchPage.loadOrFadeWait(); assertThat("No results for search noir", searchPage.docLogo().isDisplayed()); assertThat("No add to blacklist link displayed", searchPage.blacklistLink().isDisplayed()); assertThat("No create synonyms link displayed", searchPage.createSynonymsLink().isDisplayed()); searchPage.blacklistLink().click(); searchPage.loadOrFadeWait(); assertThat("link not directing to blacklist wizard", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("link not directing to blacklist wizard", createKeywordsPage.getText().contains("Select terms to blacklist")); assertEquals(1, createKeywordsPage.countKeywords()); //TODO Check this error assertThat("keywords list does not include term 'noir'", createKeywordsPage.getProspectiveKeywordsList().contains("noir")); createKeywordsPage.addBlacklistedTextBox().sendKeys("noir"); createKeywordsPage.addBlacklistTermsButton().click(); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'noir'", createKeywordsPage.getProspectiveKeywordsList().contains("noir")); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); assertThat("Blacklisted term not added", keywordsPage.getBlacklistedTerms().contains("noir")); } //There is a link to create synonym group from the search page that prepopulates the create synonyms wizard with the current search term. Often breaks. @Test public void testCreateSynonymGroupFromSearchPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("rouge"); searchPage = body.getSearchPage(); //searchPage.selectLanguage("French", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); assertThat("No results for search rouge", searchPage.docLogo().isDisplayed()); assertThat("No add to blacklist link displayed", searchPage.blacklistLink().isDisplayed()); assertThat("No create synonyms link displayed", searchPage.createSynonymsLink().isDisplayed()); searchPage.createSynonymsLink().click(); searchPage.loadOrFadeWait(); assertThat("link not directing to synonym group wizard", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("link not directing to synonym group wizard", createKeywordsPage.getText().contains("Select synonyms")); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'rouge'", createKeywordsPage.getProspectiveKeywordsList().contains("rouge")); assertThat("Finish button should be disabled until further synonyms added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addSynonymsTextBox().sendKeys("rouge"); createKeywordsPage.addSynonymsButton().click(); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'rouge'", createKeywordsPage.getProspectiveKeywordsList().contains("rouge")); assertThat("Finish button should be disabled until further synonyms added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().sendKeys("red"); createKeywordsPage.addSynonymsButton().click(); assertEquals(2, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'rouge'", createKeywordsPage.getProspectiveKeywordsList().contains("rouge")); assertThat("keywords list does not include term 'red'", createKeywordsPage.getProspectiveKeywordsList().contains("red")); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOf(keywordsPage.selectLanguageButton())); assertEquals("Blacklist has been created in the wrong language", "French", keywordsPage.getSelectedLanguage()); //keywordsPage.selectLanguage("French"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); assertThat("Synonym, group not added", keywordsPage.getSynonymGroupSynonyms("rouge").contains("red")); assertThat("Synonym, group not added", keywordsPage.getSynonymGroupSynonyms("red").contains("rouge")); assertEquals(2, keywordsPage.countSynonymLists()); } //There is a link to create synonym group from the search page that prepopulates the create synonyms wizard with the current multi term search. Often breaks. @Test public void testCreateSynonymGroupFromMultiTermSearchOnSearchPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("lodge dodge podge"); searchPage = body.getSearchPage(); //searchPage.selectLanguage("English", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); assertThat("No results for search", searchPage.docLogo().isDisplayed()); assertThat("No add to blacklist link displayed", searchPage.blacklistLink().isDisplayed()); assertThat("No create synonyms link displayed", searchPage.createSynonymsLink().isDisplayed()); searchPage.createSynonymsLink().click(); searchPage.loadOrFadeWait(); assertThat("link not directing to synonym group wizard", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("link not directing to synonym group wizard", createKeywordsPage.getText().contains("Select synonyms")); assertEquals(3, createKeywordsPage.countKeywords()); assertThat("Wrong prospective blacklisted terms added", createKeywordsPage.getProspectiveKeywordsList().containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); //keywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); assertThat("Synonym, group not complete", keywordsPage.getSynonymGroupSynonyms("lodge").containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertThat("Synonym, group not complete", keywordsPage.getSynonymGroupSynonyms("podge").containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertThat("Synonym, group not complete", keywordsPage.getSynonymGroupSynonyms("dodge").containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertEquals(3, keywordsPage.countSynonymLists()); } @Test public void testKeywordsSearchFilter() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("grizzly brownBear bigBear", "English"); //All keywords should be changed by the application to lowercase in all instances final List<String> synonymListBears = Arrays.asList("grizzly", "brownbear", "bigbear"); new WebDriverWait(getDriver(), 15).until(ExpectedConditions.visibilityOf(body.getSearchPage())); searchPage = body.getSearchPage(); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in title", searchPage.title().contains(synonym)); assertThat(synonym + " not included in 'You searched for' section", searchPage.youSearchedFor().contains(synonym)); assertThat(synonym + " synonym group not complete in'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertEquals("Wrong number of synonym lists displayed", 3, searchPage.countSynonymLists()); } new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("honeyBee bumbleBee buzzyBee", "English"); final List<String> synonymListBees = Arrays.asList("honeybee", "bumblebee", "buzzybee"); searchPage = body.getSearchPage(); for (final String synonym : synonymListBees) { assertThat(synonym + " not included in title", searchPage.title().contains(synonym)); //TODO assertThat(synonym + " not included in 'You searched for' section", searchPage.youSearchedFor().contains(synonym)); assertThat(synonym + " not included in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBees)); assertEquals(3, searchPage.countSynonymLists()); } new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.selectLanguage("English"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("zz"); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("buzz"); keywordsPage.loadOrFadeWait(); assertEquals(3, keywordsPage.countSynonymLists()); for (final String synonym : synonymListBees) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBees)); assertThat("synonym included in synonym group: " + synonym + " that should not be there", !keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("a"); keywordsPage.searchFilterTextBox().sendKeys(Keys.BACK_SPACE); keywordsPage.loadOrFadeWait(); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("Bear"); keywordsPage.loadOrFadeWait(); assertEquals(3, keywordsPage.countSynonymLists()); for (final String synonym : synonymListBears) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertThat("synonym included in synonym group: " + synonym + " that should not be there", !keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBees)); } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("a"); keywordsPage.searchFilterTextBox().sendKeys(Keys.BACK_SPACE); keywordsPage.loadOrFadeWait(); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } } @Test public void testSearchPageKeywords() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); List<String> synonymListBears = Arrays.asList("grizzly", "brownbear", "bigbear"); createKeywordsPage.createSynonymGroup(StringUtils.join(synonymListBears, ' '), "English"); searchPage = body.getSearchPage(); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in title", searchPage.title().contains(synonym)); assertThat(synonym + " not included in 'You searched for' section", searchPage.youSearchedFor().contains(synonym)); assertThat(synonym + " synonym group not complete in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertEquals(3, searchPage.countSynonymLists()); } searchPage.addSynonymToGroup("kodiak", "grizzly"); searchPage.loadOrFadeWait(); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertThat("kodiak not included in synonym group " + synonym, searchPage.getSynonymGroupSynonyms(synonym).contains("kodiak")); assertEquals(3, searchPage.countSynonymLists()); } searchPage.deleteSynonym("bigbear", "brownbear"); searchPage.loadOrFadeWait(); synonymListBears = Arrays.asList("grizzly", "brownbear"); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertThat("bigbear not deleted from group " + synonym, !searchPage.getSynonymGroupSynonyms(synonym).contains("bigbear")); assertThat("kodiak not included in synonym group " + synonym, searchPage.getSynonymGroupSynonyms(synonym).contains("kodiak")); assertEquals(2, searchPage.countSynonymLists()); } new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.selectLanguage("English"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertEquals(3, keywordsPage.countSynonymLists()); synonymListBears = Arrays.asList("grizzly", "brownbear", "kodiak"); for (final String synonym : synonymListBears) { assertThat(synonym + " group incomplete", keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertEquals(3, keywordsPage.getSynonymGroupSynonyms(synonym).size()); assertThat("bigbear not deleted from group " + synonym, !keywordsPage.getSynonymGroupSynonyms(synonym).contains("bigbear")); } } @Test public void testNoBlacklistLinkForBlacklistedSearch() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("wizard"); searchPage = body.getSearchPage(); //searchPage.selectLanguage("Arabic", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); searchPage.blacklistLink().click(); try { createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.finishWizardButton().click(); } catch (final NoSuchElementException e) { fail("blacklist link on search page has not navigated to the wizard"); } //new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOf(keywordsPage.selectLanguageButton())); //assertEquals("Blacklist has been created in the wrong language", "Arabic", keywordsPage.getSelectedLanguage()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); keywordsPage.loadOrFadeWait(); new WebDriverWait(getDriver(), 8).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); //keywordsPage.selectLanguage("Arabic"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); assertThat("Blacklisted term not created", keywordsPage.getBlacklistedTerms().contains("wizard")); topNavBar.search("wizard"); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); //searchPage.selectLanguage("Arabic", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); assertThat("'You searched for:' section incorrect", searchPage.youSearchedFor().contains("wizard")); assertThat("Keywords incorrect", searchPage.getBlacklistedTerms().contains("wizard")); assertThat("link to blacklist or create synonyms should not be present", !searchPage.getText().contains("You can create synonyms or blacklist these search terms")); //searchPage.selectLanguage("English", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); assertThat("Term should not be blacklisted in English", !searchPage.getText().contains("Any query terms were either blacklisted or stop words")); } @Test public void testSynonymGroupMembersSearchWholeGroup() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); final List<String> synonymListCars = Arrays.asList("car", "auto", "motor"); createKeywordsPage.createSynonymGroup(StringUtils.join(synonymListCars, ' '), "English"); searchPage = body.getSearchPage(); for (final String synonym : synonymListCars) { topNavBar.search(synonym); //searchPage.selectLanguage("Swahili", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); assertEquals(1, searchPage.countSynonymLists()); assertThat("Synonym group does not contain all its members", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListCars)); } } @Test public void testAddTwoSynonymsToSynonymGroupFromSearchPage() throws InterruptedException { try { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("house home dwelling abode", "English"); searchPage = body.getSearchPage(); topNavBar.search("house"); //searchPage.selectLanguage("English", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); assertEquals(1, searchPage.countSynonymLists()); assertThat("Synonym group does not contain all its members", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode"))); searchPage.addSynonymToGroup("lodging", "house"); searchPage.loadOrFadeWait(); assertThat("New synonym has not been added to the group", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "lodging"))); searchPage.addSynonymToGroup("residence", "house"); searchPage.loadOrFadeWait(); assertThat("New synonym has not been added to the group", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "lodging", "residence"))); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); assertThat("New synonym has not been added to the group", keywordsPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "lodging", "residence"))); keywordsPage.deleteAllSynonyms(); keywordsPage.loadOrFadeWait(); (new WebDriverWait(getDriver(),10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return keywordsPage.countSynonymLists() == 0; } }); assertEquals(0, keywordsPage.countSynonymLists()); //TODO Check why it's actually seeing two here - is this to do with the way I've changed countSynonymLists? } finally { getDriver().navigate().refresh(); } } @Test public void testRemoveTwoSynonymsFromSynonymGroupFromSearchPage() throws InterruptedException { try { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("house home dwelling abode residence", "English"); searchPage = body.getSearchPage(); topNavBar.search("house"); //searchPage.selectLanguage("English", getConfig().getType().getName()); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); assertEquals(1, searchPage.countSynonymLists()); assertThat("Synonym group does not contain all its members", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "residence"))); searchPage.deleteSynonym("residence", "house"); searchPage.loadOrFadeWait(); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("residence")); assertThat("Synonym has not been deleted", searchPage.getSynonymGroupSynonyms("house").contains("abode")); assertThat("More than one synonym deleted", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode"))); searchPage.deleteSynonym("abode", "house"); searchPage.loadOrFadeWait(); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("abode")); assertThat("More than one synonym deleted", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling"))); searchPage.deleteSynonym("dwelling", "house"); searchPage.loadOrFadeWait(); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("dwelling")); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("abode")); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("residence")); assertThat("More than one synonym deleted", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home"))); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); assertThat("Synonyms have not been removed from the group", keywordsPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "house"))); keywordsPage.deleteAllSynonyms(); keywordsPage.loadOrFadeWait(); //Thread.sleep(5000); //Wait for the synonyms to finish deleting //Wait until the synonyms are deleted (new WebDriverWait(getDriver(),10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return keywordsPage.countSynonymLists() == 0; } }); assertEquals(0, keywordsPage.countSynonymLists()); } finally { getDriver().navigate().refresh(); } } //This test passes but without language support probably shouldn't? @Test public void testOnlyLanguagesWithDocumentsAvailableOnSearchPage() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("Baku", "Azeri"); topNavBar.search("Baku"); searchPage = body.getSearchPage(); assertFalse(searchPage.getLanguageList().contains("Azeri")); } @Test public void testKeywordsLanguage() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("Atlanta", "Georgian"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("Tirana", "Albanian"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("Croatia Kroatia Hrvatska", "Croatian"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.selectLanguage("Georgian"); assertEquals(1, keywordsPage.getBlacklistedTerms().size()); assertEquals(0, keywordsPage.countSynonymLists()); keywordsPage.selectLanguage("Albanian"); assertEquals(1, keywordsPage.getBlacklistedTerms().size()); assertEquals(0, keywordsPage.countSynonymLists()); keywordsPage.selectLanguage("Croatian"); assertEquals(0, keywordsPage.getBlacklistedTerms().size()); assertEquals(3, keywordsPage.countSynonymLists()); } @Test public void testLanguageOfSearchPageKeywords() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("road rue strasse", "French"); topNavBar.search("Korea"); searchPage = body.getSearchPage(); searchPage.selectLanguage("Chinese", getConfig().getType().getName()); searchPage.createSynonymsLink().click(); searchPage.loadOrFadeWait(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.addSynonyms("한국"); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); topNavBar.search("Korea"); searchPage.selectLanguage("Chinese", getConfig().getType().getName()); assertEquals("wrong number of synonym lists displayed", 1, searchPage.countSynonymLists()); searchPage.selectLanguage("French", getConfig().getType().getName()); assertEquals("wrong number of synonym lists displayed", 0, searchPage.countSynonymLists()); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.selectLanguage("French"); assertThat("synonym assigned to wrong language", !keywordsPage.getText().contains("한국")); keywordsPage.selectLanguage("Chinese"); assertEquals("wrong number of synonym lists displayed", 2, keywordsPage.countSynonymLists()); assertThat("synonym not assigned to correct language", keywordsPage.getText().contains("한국")); } @Test public void testKeywordsCreationAndDeletionOnSecondWindow() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("double duo two pair couple", "Urdu"); navBar.switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); //keywordsPage.selectLanguage("Urdu"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for keywords yet"); keywordsPage.loadOrFadeWait(); final String url = getDriver().getCurrentUrl(); final List<String> browserHandles = keywordsPage.createAndListWindowHandles(); getDriver().switchTo().window(browserHandles.get(1)); getDriver().get(url); final KeywordsPage secondKeywordsPage = (new AppBody(getDriver())).getKeywordsPage(); assertEquals(5, secondKeywordsPage.countSynonymLists()); getDriver().switchTo().window(browserHandles.get(0)); keywordsPage = body.getKeywordsPage(); keywordsPage.loadOrFadeWait(); keywordsPage.deleteSynonym("couple", "two"); getDriver().switchTo().window(browserHandles.get(1)); assertEquals(4, secondKeywordsPage.countSynonymLists()); getDriver().switchTo().window(browserHandles.get(0)); keywordsPage = body.getKeywordsPage(); keywordsPage.loadOrFadeWait(); keywordsPage.deleteSynonym("pair", "duo"); getDriver().switchTo().window(browserHandles.get(1)); assertEquals(3, secondKeywordsPage.countSynonymLists()); } @Test public void testSynonymsNotCaseSensitive() { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("bear"); assertEquals(1, createKeywordsPage.countKeywords()); for (final String bearVariant : Arrays.asList("Bear", "beaR", "BEAR", "beAR", "BEar")) { createKeywordsPage.addSynonyms(bearVariant); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("bear not included as a keyword", createKeywordsPage.getProspectiveKeywordsList().contains("bear")); assertThat("correct error message not showing", createKeywordsPage.getText().contains(bearVariant + " is a case variant of bear, an existing keyword.")); //TODO } // disallows any adding of synonyms if disallowed synonym found createKeywordsPage.addSynonyms("Polar Bear"); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("bear not included as a keyword", createKeywordsPage.getProspectiveKeywordsList().contains("bear")); assertThat("correct error message not showing", createKeywordsPage.getText().contains("Bear is a case variant of bear, an existing keyword.")); //jam and jaM are case variants so none should be added createKeywordsPage.addSynonyms("jam jaM"); assertEquals(1, createKeywordsPage.countKeywords()); } @Test public void testSpinnerPresentOnLastSynonymWhilePenultimateSynonymSpinnerPresent() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("ying yang", "Korean"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); //keywordsPage.selectLanguage("Korean"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertEquals(2, keywordsPage.countSynonymLists()); keywordsPage.getSynonymIcon("ying", "yang").click(); if (keywordsPage.getSynonymIcon("ying", "yang").getAttribute("class").contains("fa-spin")) { assertThat("Spinner not present on last synonym", keywordsPage.getSynonymIcon("yang", "yang").getAttribute("class").contains("fa-spin")); } } @Test public void testBooleanTermsNotValidKeyword() { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("holder"); assertEquals(1, createKeywordsPage.countKeywords()); final List<String> booleanProximityOperators = Arrays.asList("NOT", "NEAR", "DNEAR", "SOUNDEX", "XNEAR", "YNEAR", "AND", "BEFORE", "AFTER", "WHEN", "SENTENCE", "PARAGRAPH", "OR", "WNEAR", "EOR", "NOTWHEN"); for (final String operator : booleanProximityOperators) { createKeywordsPage.addSynonyms(operator); assertThat("boolean operator \"" + operator + "\" should not be added as a synonym", !createKeywordsPage.getProspectiveKeywordsList().contains(operator)); assertThat("Correct error message not showing", createKeywordsPage.getText().contains(operator + " is a boolean or proximity operator. These are invalid")); //TODO assertEquals(1, createKeywordsPage.countKeywords()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); createKeywordsPage.loadOrFadeWait(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTerms("holder"); assertEquals(1, createKeywordsPage.countKeywords()); for (final String operator : booleanProximityOperators) { createKeywordsPage.addBlacklistedTerms(operator); assertThat("boolean operator \"" + operator + "\" should not be added as a synonym", !createKeywordsPage.getProspectiveKeywordsList().contains(operator)); assertThat("Correct error message not showing", createKeywordsPage.getText().contains(operator + " is a boolean or proximity operator. These are invalid")); assertEquals(1, createKeywordsPage.countKeywords()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); createKeywordsPage.loadOrFadeWait(); } @Test public void testAddKeywordsBoxOpenClickDelete() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("бір екі үш төрт бес", "Kazakh"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); //keywordsPage.selectLanguage("Kazakh"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for keywords yet"); keywordsPage.synonymGroupPlusButton("бір").click(); assertTrue(keywordsPage.synonymGroupTextBox("бір").isDisplayed()); keywordsPage.deleteSynonym("екі", "үш"); assertTrue(keywordsPage.synonymGroupTextBox("бір").isDisplayed()); } @Test public void testQuickSynonymDelete() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("string strong strang streng strung", "German"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.loadOrFadeWait(); //keywordsPage.selectLanguage("German"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for synonyms yet"); try { keywordsPage.scrollIntoViewAndClick(keywordsPage.getSynonymIcon("strong", "strung")); keywordsPage.scrollIntoViewAndClick(keywordsPage.getSynonymIcon("string", "strung")); } catch (final WebDriverException w) { fail("Unable to delete a synonym quickly"); } Thread.sleep(5000); assertEquals("Incorrect number of synonyms", 3, keywordsPage.countSynonymLists()); } @Test public void testAddingForbiddenKeywordsFromUrl() { String blacklistUrl = getConfig().getWebappUrl() + "/p/keywords/create/blacklisted/English/"; String synonymsUrl = getConfig().getWebappUrl() + "/p/keywords/create/synonyms/English/"; if (getConfig().getType().equals(ApplicationType.ON_PREM)) { blacklistUrl = getConfig().getWebappUrl() + "/p/keywords/create/blacklisted/englishUTF8/"; synonymsUrl = getConfig().getWebappUrl() + "/p/keywords/create/synonyms/englishUTF8/"; } for (final String forbidden : Arrays.asList("(", "\"", "OR")) { getDriver().get(blacklistUrl.concat(forbidden)); body.loadOrFadeWait(); createKeywordsPage = body.getCreateKeywordsPage(); assertFalse(forbidden + " is a forbidden keyword and should not be included in the prospective blacklist list", createKeywordsPage.getProspectiveKeywordsList().contains("(")); getDriver().get(synonymsUrl.concat(forbidden)); body.loadOrFadeWait(); createKeywordsPage = body.getCreateKeywordsPage(); assertFalse(forbidden + " is a forbidden keyword and should not be included in the prospective synonyms list", createKeywordsPage.getProspectiveKeywordsList().contains("(")); } } @Test public void testSynonymsDisplayedInAlphabeticalOrder() throws InterruptedException { keywordsPage.deleteAllSynonyms(); for (final String synonyms : Arrays.asList("aa ba ca da", "ab bb cb db", "dc cc bc ac", "ca ba da aa")) { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup(synonyms, "English"); searchPage = body.getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); final List<String> keywords = searchPage.getLeadSynonymsList(); for (int i = 0; i < keywords.size() - 1; i++) { assertTrue(keywords.get(i).compareTo(keywords.get(i + 1)) <= 0); } searchPage.loadOrFadeWait(); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); } keywordsPage.loadOrFadeWait(); keywordsPage = body.getKeywordsPage(); keywordsPage.searchFilterTextBox().sendKeys("cc"); final List<String> keywords = keywordsPage.getLeadSynonymsList(); for (int i = 0; i < keywords.size() - 1; i++) { assertTrue(keywords.get(i).compareTo(keywords.get(i + 1)) <= 0); } } @Test public void testBlacklistedKeywordsDisplayedInAlphabeticalOrder() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("aa ba ca da ab bb cb db", "English"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); final List<String> keywords = keywordsPage.getBlacklistedTerms(); assertEquals("Wrong number of blacklist items created", 8, keywords.size()); //TODO for (int i = 0; i < keywords.size() - 1; i++) { assertTrue(keywords.get(i).compareTo(keywords.get(i + 1)) <= 0); } } @Test public void testDeletingOfSynonymsAndBlacklistedTerms() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("aa ba ca da ab bb cb db", "English"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("ea es ed ef eg eh", "English"); searchPage = body.getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.deleteSynonym("es", "es"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("ea", "ea"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("eg", "eg"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("ed", "ed"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("ef", "ef"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("aa ba ca da ab bb cb db", "English"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage.createSynonymGroup("ea es ed ef eg eh", "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.deleteBlacklistedTerm("db"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteBlacklistedTerm("aa"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteBlacklistedTerm("da"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); } @Test public void testDoesDeletingSynonymDisableOtherSynonyms() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("ea es ed ef eg eh", "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage = body.getKeywordsPage(); final List<String> synonyms = Arrays.asList("ea", "es", "ed", "ef", "eg"); for (final String synonym : synonyms) { keywordsPage.getSynonymIcon(synonym, synonym).click(); assertEquals("Too many synonyms are disabled on synonym delete", 6 - synonyms.indexOf(synonym), keywordsPage.countDisabledKeywords()); Thread.sleep(3000); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); } } @Test public void testAllowKeywordStringsThatContainBooleansWithinThem() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("placeholder"); assertEquals(1, createKeywordsPage.getProspectiveKeywordsList().size()); final List<String> hiddenSearchOperators = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "NEARLY", "NEAR123LY", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED"); for (int i = 0; i < hiddenSearchOperators.size(); i++) { createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().sendKeys(hiddenSearchOperators.get(i)); createKeywordsPage.addSynonymsButton().click(); createKeywordsPage.loadOrFadeWait(); assertEquals(2 + i, createKeywordsPage.getProspectiveKeywordsList().size()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); keywordsPage.loadOrFadeWait(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); //createKeywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTerms("placeholder"); assertEquals(1, createKeywordsPage.getProspectiveKeywordsList().size()); for (int i = 0; i < hiddenSearchOperators.size(); i++) { createKeywordsPage.addBlacklistedTextBox().clear(); createKeywordsPage.addBlacklistedTextBox().sendKeys(hiddenSearchOperators.get(i)); createKeywordsPage.addBlacklistTermsButton().click(); createKeywordsPage.loadOrFadeWait(); assertEquals(2 + i, createKeywordsPage.getProspectiveKeywordsList().size()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); keywordsPage.loadOrFadeWait(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("place holder", "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); //keywordsPage.selectLanguage("English"); (LoggerFactory.getLogger(KeywordsPageAndWizardITCase.class)).warn("Cannot select language for blacklists yet"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); for (final String hiddenBooleansProximity : hiddenSearchOperators) { keywordsPage.addSynonymToGroup(hiddenBooleansProximity, "holder"); keywordsPage.loadOrFadeWait(); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym(hiddenBooleansProximity.toLowerCase())); } } }
src/test/java/com/autonomy/abc/keywords/KeywordsPageAndWizardITCase.java
package com.autonomy.abc.keywords; import com.autonomy.abc.config.ABCTestBase; import com.autonomy.abc.config.ApplicationType; import com.autonomy.abc.config.TestConfig; import com.autonomy.abc.selenium.menubar.NavBarTabId; import com.autonomy.abc.selenium.menubar.NotificationsDropDown; import com.autonomy.abc.selenium.menubar.SideNavBar; import com.autonomy.abc.selenium.page.AppBody; import com.autonomy.abc.selenium.page.keywords.CreateNewKeywordsPage; import com.autonomy.abc.selenium.page.keywords.KeywordsPage; import com.autonomy.abc.selenium.page.search.SearchPage; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.IOException; import java.net.MalformedURLException; import java.util.Arrays; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; public class KeywordsPageAndWizardITCase extends ABCTestBase { public KeywordsPageAndWizardITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) { super(config, browser, appType, platform); } private KeywordsPage keywordsPage; private CreateNewKeywordsPage createKeywordsPage; private SearchPage searchPage; private NotificationsDropDown notifications; @Before public void setUp() throws MalformedURLException { navBar.switchPage(NavBarTabId.KEYWORDS); navBar.loadOrFadeWait(); keywordsPage = body.getKeywordsPage(); } @Test public void testCreateNewKeywordsButtonAndCancel() { assertThat("Create new keywords button is not visible", keywordsPage.createNewKeywordsButton().isDisplayed()); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); assertThat("Create new keywords button should not be visible", !keywordsPage.createNewKeywordsButton().isDisplayed()); assertThat("Create Synonyms button should be visible", createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).isDisplayed()); assertThat("Create Blacklisted button should be visible", createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).isDisplayed()); assertThat("Cancel button be visible", createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).isDisplayed()); assertThat("Continue button should be visible", createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).isDisplayed()); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); assertThat("Create new keywords button should be visible", keywordsPage.createNewKeywordsButton().isDisplayed()); } @Test public void testNavigateSynonymsWizard() throws InterruptedException { try { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Continue button should be disabled until a keywords type is selected", keywordsPage.isAttributePresent(createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE), "disabled")); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); assertThat("Synonym type not set active", createKeywordsPage.getFirstChild(createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM)).getAttribute("class").contains("progressive-disclosure-selection")); assertThat("Continue button should be enabled", !createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).getAttribute("class").contains("disabled")); assertThat("languages select should be visible", createKeywordsPage.languagesSelectBox().isDisplayed()); createKeywordsPage.selectLanguage("French"); assertEquals("French", createKeywordsPage.languagesSelectBox().getText()); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addSynonymsTextBox().clear(); assertThat("Finish button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertThat("Add synonyms button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.addSynonymsButton(), "disabled")); createKeywordsPage.addSynonymsTextBox().sendKeys("horse"); assertThat("Finish button should be disabled until synonyms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addSynonymsButton().click(); assertThat("Finish button should be disabled until more than one synonym is added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("stuff pony things"); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(4, createKeywordsPage.countKeywords()); createKeywordsPage.finishWizardButton().click(); createKeywordsPage.loadOrFadeWait(); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); searchPage.selectLanguage("French", getConfig().getType().getName()); new WebDriverWait(getDriver(), 8).until(ExpectedConditions.visibilityOf(searchPage.docLogo())); final List<String> searchTerms = searchPage.getSearchTermsList(); assertThat("Synonym group does not contain 'stuff', 'horse', 'pony' and 'things'", searchTerms.containsAll(Arrays.asList("stuff", "horse", "pony", "things"))); new SideNavBar(getDriver()).getTab(NavBarTabId.KEYWORDS).click(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.selectLanguage("French"); assertThat("synonym horse is not displayed", keywordsPage.leadSynonym("horse").isDisplayed()); final List<String> synonymGroup = keywordsPage.getSynonymGroupSynonyms("horse"); assertThat("Synonym group does not contain 'stuff', 'horse', 'pony' and 'things'", synonymGroup.containsAll(Arrays.asList("stuff", "horse", "pony", "things"))); } finally { new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.deleteAllSynonyms(); } } @Test public void testWizardCancelButtonsWorksAfterClickingTheNavBarToggleButton() { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); topNavBar.sideBarToggle(); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); assertThat("Cancel button does not work after clicking the toggle button", keywordsPage.createNewKeywordsButton().isDisplayed()); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); topNavBar.sideBarToggle(); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); assertThat("Cancel button does not work after clicking the toggle button", keywordsPage.createNewKeywordsButton().isDisplayed()); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Not directed to wizard URL", getDriver().getCurrentUrl().contains("keywords/create")); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); topNavBar.sideBarToggle(); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); assertThat("Cancel button does not work after clicking the toggle button", keywordsPage.createNewKeywordsButton().isDisplayed()); } @Test public void testNavigateBlacklistedWizard() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("Continue button should be disabled until a keywords type is selected", createKeywordsPage.isAttributePresent(createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE), "disabled")); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); assertThat("Blacklisted type not set active", createKeywordsPage.getFirstChild(createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST)).getAttribute("class").contains("progressive-disclosure-selection")); assertThat("Continue button should be enabled", !createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).getAttribute("class").contains("disabled")); assertThat("Wizard did not navigate to languages page", createKeywordsPage.languagesSelectBox().isDisplayed()); createKeywordsPage.selectLanguage("Swahili"); assertEquals("Swahili", createKeywordsPage.languagesSelectBox().getText()); createKeywordsPage.selectLanguage("English"); assertEquals("English", createKeywordsPage.languagesSelectBox().getText()); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertThat("Wizard did not navigate to blacklist page", createKeywordsPage.addBlacklistedTextBox().isDisplayed()); createKeywordsPage.addBlacklistedTextBox().clear(); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTextBox().sendKeys("danger"); assertThat("Finish button should be disabled until blacklisted terms are added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addBlacklistTermsButton().click(); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addBlacklistedTextBox().sendKeys("warning beware scary"); createKeywordsPage.addBlacklistTermsButton().click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); assertEquals(4, createKeywordsPage.countKeywords()); createKeywordsPage.finishWizardButton().click(); createKeywordsPage.loadOrFadeWait(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); final List<String> blacklistTerms = keywordsPage.getBlacklistedTerms(); createKeywordsPage.loadOrFadeWait(); assertThat("blacklist terms not all displayed", blacklistTerms.containsAll(Arrays.asList("danger", "warning", "beware", "scary"))); assertThat("too many blacklist terms", blacklistTerms.size() == 4); } @Test public void testKeywordsFilter() throws InterruptedException { final WebDriverWait wait = new WebDriverWait(getDriver(), 5); keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("dog hound canine", "English"); searchPage = body.getSearchPage(); wait.until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); assertThat("New keyword not searched for", searchPage.searchTitle().getText().contains("dog")); assertThat("New keyword not searched for", searchPage.searchTitle().getText().contains("hound")); assertThat("New keyword not searched for", searchPage.searchTitle().getText().contains("canine")); new SideNavBar(getDriver()).getTab(NavBarTabId.KEYWORDS).click(); wait.until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.selectLanguage("English"); assertThat("Synonym group dog not visible", keywordsPage.getSynonymGroupSynonyms("dog").containsAll(Arrays.asList("hound", "canine"))); assertThat("Synonym group hound not visible", keywordsPage.getSynonymGroupSynonyms("hound").containsAll(Arrays.asList("dog", "canine"))); assertThat("Synonym group canine not visible", keywordsPage.getSynonymGroupSynonyms("canine").containsAll(Arrays.asList("dog", "hound"))); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("illegal", "English"); assertThat("Blacklisted term 'illegal' not visible", keywordsPage.getBlacklistedTerms().contains("illegal")); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertThat("Blacklist terms are still visible", keywordsPage.getBlacklistedTerms().size() == 0); assertThat("A synonym list on row 2 is not visible", keywordsPage.synonymList(1).isDisplayed()); assertThat("Synonym group dog not visible", keywordsPage.getSynonymGroupSynonyms("dog").containsAll(Arrays.asList("hound", "canine"))); assertThat("Synonym group hound not visible", keywordsPage.getSynonymGroupSynonyms("hound").containsAll(Arrays.asList("dog", "canine"))); assertThat("Synonym group canine not visible", keywordsPage.getSynonymGroupSynonyms("canine").containsAll(Arrays.asList("dog", "hound"))); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); assertThat("Blacklisted term 'illegal' not visible", keywordsPage.getBlacklistedTerms().contains("illegal")); assertEquals("There should not be a a synonym list on row 2", 0, keywordsPage.countSynonymLists()); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); assertThat("A synonym list should be visible on row 2", keywordsPage.synonymList(1).isDisplayed()); assertThat("Synonym group dog not visible", keywordsPage.getSynonymGroupSynonyms("dog").containsAll(Arrays.asList("hound", "canine"))); assertThat("Synonym group hound not visible", keywordsPage.getSynonymGroupSynonyms("hound").containsAll(Arrays.asList("dog", "canine"))); assertThat("Synonym group canine not visible", keywordsPage.getSynonymGroupSynonyms("canine").containsAll(Arrays.asList("dog", "hound"))); assertThat("Blacklist term illegal is not visible", keywordsPage.getBlacklistedTerms().contains("illegal")); } @Test public void testDeleteKeywords() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("frog toad amphibian tadpole", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); assertThat("synonym group not fully created", keywordsPage.getSynonymGroupSynonyms("frog").containsAll(Arrays.asList("frog", "toad", "amphibian", "tadpole"))); assertEquals("Wrong number of synonym lists displayed", 4, keywordsPage.countSynonymLists()); assertEquals("Wrong number of synonyms in group frog", 4, keywordsPage.getSynonymGroupSynonyms("frog").size()); keywordsPage.deleteSynonym("amphibian", "toad"); assertEquals("Wrong number of synonym lists displayed", 3, keywordsPage.countSynonymLists()); assertEquals("Wrong number of synonyms in group toad", 3, keywordsPage.getSynonymGroupSynonyms("toad").size()); assertThat("the synonym amphibian should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("tadpole").contains("amphibian")); assertThat("the synonym amphibian should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("toad").contains("amphibian")); assertThat("the synonym amphibian should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("frog").contains("amphibian")); keywordsPage.deleteSynonym("frog", "frog"); assertEquals("Wrong number of synonym lists displayed", 2, keywordsPage.countSynonymLists()); assertEquals("Wrong number of synonyms in group toad", 2, keywordsPage.getSynonymGroupSynonyms("toad").size()); assertThat("the synonym frog should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("toad").contains("frog")); assertThat("the synonym frog should be deleted from every synonym list", !keywordsPage.getSynonymGroupSynonyms("tadpole").contains("frog")); keywordsPage.deleteSynonym("tadpole", "toad"); assertEquals("Wrong number of synonym lists displayed", 0, keywordsPage.countSynonymLists()); } //The keyword 'wine' exists in two different synonym groups. Tests that deleting this keyword does not effect the other synonym group @Test public void testDeleteSynonymsFromOverlappingSynonymGroups() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("wine merlot shiraz bordeaux", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("wine red scarlet burgundy", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("English"); assertThat("synonym group not fully created", keywordsPage.getSynonymGroupSynonyms("red").containsAll(Arrays.asList("red", "scarlet", "wine", "burgundy"))); assertEquals(8, keywordsPage.countSynonymLists()); assertEquals(4, keywordsPage.getSynonymGroupSynonyms("burgundy").size()); assertEquals(4, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(2, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("bordeaux", "shiraz"); assertEquals(7, keywordsPage.countSynonymLists()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(4, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(2, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("burgundy", "red"); assertEquals(6, keywordsPage.countSynonymLists()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(2, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("wine", "red"); assertEquals(5, keywordsPage.countSynonymLists()); assertEquals(3, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("shiraz", "wine"); assertEquals(4, keywordsPage.countSynonymLists()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("scarlet").size()); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("scarlet", "red"); assertEquals(2, keywordsPage.countSynonymLists()); assertEquals(2, keywordsPage.getSynonymGroupSynonyms("merlot").size()); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym("wine")); keywordsPage.deleteSynonym("wine", "merlot"); assertEquals(0, keywordsPage.countSynonymLists()); } //Duplicate blacklisted terms are not allowed to be created within the same language @Test public void testCreateDuplicateBlacklist() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("fish", "English"); assertThat("Blacklist fish not visible", keywordsPage.getBlacklistedTerms().contains("fish")); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); assertThat("Finish button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addBlacklistedTextBox().sendKeys("fish"); createKeywordsPage.addBlacklistTermsButton().click(); createKeywordsPage.loadOrFadeWait(); assertThat("Duplicate blacklist warning message not present", createKeywordsPage.getText().contains("The word \"fish\" is already blacklisted")); assertThat("Duplicate blacklist term should not be added", createKeywordsPage.countKeywords() == 0); assertThat("Finish button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addBlacklistedTextBox().clear(); createKeywordsPage.addBlacklistedTextBox().sendKeys("chips"); createKeywordsPage.addBlacklistTermsButton().click(); assertThat("Duplicate blacklist warning message has not disappeared", !createKeywordsPage.getText().contains("The word \"fish\" is already blacklisted")); assertThat("New blacklist term should be added", createKeywordsPage.countKeywords() == 1); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.deleteKeyword("chips"); assertThat("There should be no blacklist terms", createKeywordsPage.countKeywords() == 0); assertThat("Finish button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); assertThat("Cancel button redirects to wrong page", getDriver().getCurrentUrl().endsWith("keywords")); assertEquals("Wrong number of blacklisted terms", 1, keywordsPage.getBlacklistedTerms().size()); } //Whitespace of any form should not be added as a blacklisted term @Test public void testWhitespaceBlacklistTermsWizard() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTextBox().sendKeys(" "); createKeywordsPage.tryClickThenTryParentClick(createKeywordsPage.addBlacklistTermsButton()); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addBlacklistedTextBox().clear(); createKeywordsPage.addBlacklistedTextBox().click(); createKeywordsPage.addBlacklistedTextBox().sendKeys(Keys.RETURN); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addBlacklistedTextBox().sendKeys("\t"); createKeywordsPage.tryClickThenTryParentClick(createKeywordsPage.addBlacklistTermsButton()); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); } //Whitespace of any form should not be added as a synonym keyword @Test public void testWhitespaceSynonymsWizard() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms(" "); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().click(); createKeywordsPage.addSynonymsTextBox().sendKeys(Keys.RETURN); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addSynonyms("\t"); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 0); createKeywordsPage.addSynonyms("test"); createKeywordsPage.addSynonyms(" "); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 1); createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().click(); createKeywordsPage.addSynonymsTextBox().sendKeys(Keys.RETURN); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 1); createKeywordsPage.addSynonyms("\t"); assertThat("Whitespace should not be added as a blacklist term", createKeywordsPage.countKeywords() == 1); } //Odd number of quotes or quotes with blank text should not be able to be added as a synonym keyword @Test public void testQuotesInSynonymsWizard() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("\""); assertEquals(0, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\"\""); assertEquals(0, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\" \""); assertEquals(0, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("test"); createKeywordsPage.addSynonyms("\""); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\"\""); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("\" \""); assertEquals(1, createKeywordsPage.countKeywords()); createKeywordsPage.addSynonyms("terms \""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("Correct error message not showing", createKeywordsPage.getText().contains("Terms have an odd number of quotes, suggesting an unclosed phrase")); createKeywordsPage.addSynonyms("\"closed phrase\""); assertEquals(2, createKeywordsPage.countKeywords()); assertThat("Phrase not created", createKeywordsPage.getProspectiveKeywordsList().contains("closed phrase")); assertThat("Quotes unescaped", !createKeywordsPage.getProspectiveKeywordsList().contains("/")); } //Odd number of quotes or quotes with blank text should not be able to be added as a blacklisted term @Test public void testQuotesInBlacklistWizard() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTerms("\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\" \""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"d"); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("d\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("\"d\""); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("s\"d\"d"); assertEquals(0, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("test"); createKeywordsPage.addBlacklistedTerms("\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\" \""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("plus button should be disabled", createKeywordsPage.isAttributePresent(createKeywordsPage.addBlacklistTermsButton(), "disabled")); createKeywordsPage.addBlacklistedTerms("\"d"); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("d\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("\"d\""); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); createKeywordsPage.addBlacklistedTerms("s\"d\"d"); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("wrong/no error message", createKeywordsPage.getText().contains("Terms may not contain quotation marks")); } @Ignore // This takes too long for a nightly test but is a useful test that need run periodically as the application has failed in the past with a large number of synonym groups. // Failure can present itself on other pages other than the KeywordsPage @Test public void testAddLotsOfSynonymGroups() throws IOException, InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); final List<String> groupsOfFiveSynonyms = keywordsPage.loadTextFileLineByLineIntoList("C://dev//res//100.txt"); for (final String synonymGroup : groupsOfFiveSynonyms) { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup(synonymGroup, "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); assertThat("Wrong number of synonym lists", keywordsPage.countSynonymLists() == groupsOfFiveSynonyms.indexOf(synonymGroup) + 1); } } //Whitespace, Odd number of quotes or quotes with blank text, boolean operators or proximity operators should not be able to added as keywords. This test checks they can't be added to existing synonyms on the Keywords Page @Test public void testAddingWhitespaceQuotesBooleansProximityOperatorsOnKeywordsPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("one two three", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("English"); keywordsPage.addSynonymToGroup("four", "one"); keywordsPage.waitForRefreshIconToDisappear(); assertThat("there should be four synonyms in a group", keywordsPage.getSynonymGroupSynonyms("two").contains("four")); assertEquals(4, keywordsPage.countSynonymLists()); keywordsPage.synonymGroupPlusButton("three").click(); keywordsPage.synonymGroupTextBox("three").clear(); keywordsPage.synonymGroupTickButton("three").click(); assertThat("add synonym box should still be displayed", keywordsPage.synonymGroupTextBox("three").isDisplayed()); keywordsPage.searchFilterTextBox().click(); assertThat("there should be four synonyms in a group", keywordsPage.getSynonymGroupSynonyms("two").contains("four")); assertEquals(4, keywordsPage.countSynonymLists()); for (final String badSynonym : Arrays.asList(" ", "\t", "\"", "NOT", "NEAR", "DNEAR", "XNEAR", "YNEAR", "NEAR123", "SENTENCE2", "PARAGRAPH3", "AND", "BEFORE", "AFTER", "WHEN", "SENTENCE", "PARAGRAPH", "OR", "WNEAR", "EOR", "NOTWHEN")) { keywordsPage.synonymGroupPlusButton("three").click(); keywordsPage.synonymGroupTextBox("three").clear(); keywordsPage.synonymGroupTextBox("three").sendKeys(badSynonym); keywordsPage.synonymGroupTickButton("three").click(); assertThat("add synonym box should still be displayed. Offending term is " + badSynonym, keywordsPage.synonymGroupTextBox("three").isDisplayed()); keywordsPage.loadOrFadeWait(); keywordsPage.searchFilterTextBox().click(); assertThat("there should be four synonyms in a group. Offending term is " + badSynonym, keywordsPage.getSynonymGroupSynonyms("one").size() == 4); assertEquals(4, keywordsPage.countSynonymLists()); } } //Phrases should be able to be added as synonyms from the keywords page @Test public void testPhrasesCanBeAddedAsSynonymsOnKeywordsPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("one two three", "English"); searchPage = body.getSearchPage(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("English"); keywordsPage.synonymGroupPlusButton("three").click(); keywordsPage.synonymGroupTextBox("three").clear(); keywordsPage.synonymGroupTextBox("three").sendKeys("four and five"); keywordsPage.synonymGroupTickButton("three").click(); Thread.sleep(5000); assertFalse(keywordsPage.synonymGroupTextBox("three").isDisplayed()); assertEquals(4, keywordsPage.countSynonymLists()); assertTrue(keywordsPage.getSynonymGroupSynonyms("three").contains("four and five")); } //Notification should drop down on creation of new keywords @Test public void testNotificationForCreatedBlacklistedTermAndSynonymGroup() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("orange", "English"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.PROMOTIONS); topNavBar.notificationsDropdown(); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Added \"orange\" to the blacklist")); notifications = body.getNotifications(); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("piano keyboard pianoforte", "English"); body.waitForGritterToClear(); topNavBar.notificationsDropdown(); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Created a new synonym group containing: keyboard, piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(2).getText().contains("Added \"orange\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); keywordsPage.loadOrFadeWait(); keywordsPage.deleteSynonym("keyboard", "piano"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.PROMOTIONS); topNavBar.notificationsDropdown(); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Updated a synonym group containing: piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(2).getText().contains("Created a new synonym group containing: keyboard, piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(3).getText().contains("Added \"orange\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); keywordsPage.selectLanguage("English"); keywordsPage.deleteBlacklistedTerm("orange"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.OVERVIEW); topNavBar.notificationsDropdown(); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Removed \"orange\" from the blacklist")); assertThat("Notification text incorrect", notifications.notificationNumber(2).getText().contains("Updated a synonym group containing: piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(3).getText().contains("Created a new synonym group containing: keyboard, piano, pianoforte")); assertThat("Notification text incorrect", notifications.notificationNumber(4).getText().contains("Added \"orange\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); } // This only tests the notifications dropdown and not the gritters @Test public void testHTMLEscapedInNotifications() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("<h1>Hi</h1>", "English"); body.waitForGritterToClear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.PROMOTIONS); topNavBar.notificationsDropdown(); notifications = body.getNotifications(); assertThat("Notification text incorrect, HTML not escaped", !notifications.notificationNumber(1).getText().contains("Added \"Hi\" to the blacklist")); assertThat("Notification text incorrect", notifications.notificationNumber(1).getText().contains("Added \"<h1>Hi</h1>\" to the blacklist")); notifications.notificationNumber(1).click(); assertThat("notification link has not directed back to the keywords page", getDriver().getCurrentUrl().contains("keyword")); } //Blacklisted terms can be created on the searchpage. This link has often broken @Test public void testCreateBlacklistedTermFromSearchPage() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("noir"); searchPage = body.getSearchPage(); searchPage.selectLanguage("French", getConfig().getType().getName()); searchPage.loadOrFadeWait(); assertThat("No results for search noir", searchPage.docLogo().isDisplayed()); assertThat("No add to blacklist link displayed", searchPage.blacklistLink().isDisplayed()); assertThat("No create synonyms link displayed", searchPage.createSynonymsLink().isDisplayed()); searchPage.blacklistLink().click(); searchPage.loadOrFadeWait(); assertThat("link not directing to blacklist wizard", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("link not directing to blacklist wizard", createKeywordsPage.getText().contains("Select terms to blacklist")); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'noir'", createKeywordsPage.getProspectiveKeywordsList().contains("noir")); createKeywordsPage.addBlacklistedTextBox().sendKeys("noir"); createKeywordsPage.addBlacklistTermsButton().click(); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'noir'", createKeywordsPage.getProspectiveKeywordsList().contains("noir")); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); assertThat("Blacklisted term not added", keywordsPage.getBlacklistedTerms().contains("noir")); } //There is a link to create synonym group from the search page that prepopulates the create synonyms wizard with the current search term. Often breaks. @Test public void testCreateSynonymGroupFromSearchPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("rouge"); searchPage = body.getSearchPage(); searchPage.selectLanguage("French", getConfig().getType().getName()); assertThat("No results for search rouge", searchPage.docLogo().isDisplayed()); assertThat("No add to blacklist link displayed", searchPage.blacklistLink().isDisplayed()); assertThat("No create synonyms link displayed", searchPage.createSynonymsLink().isDisplayed()); searchPage.createSynonymsLink().click(); searchPage.loadOrFadeWait(); assertThat("link not directing to synonym group wizard", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("link not directing to synonym group wizard", createKeywordsPage.getText().contains("Select synonyms")); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'rouge'", createKeywordsPage.getProspectiveKeywordsList().contains("rouge")); assertThat("Finish button should be disabled until further synonyms added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addSynonymsTextBox().sendKeys("rouge"); createKeywordsPage.addSynonymsButton().click(); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'rouge'", createKeywordsPage.getProspectiveKeywordsList().contains("rouge")); assertThat("Finish button should be disabled until further synonyms added", createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().sendKeys("red"); createKeywordsPage.addSynonymsButton().click(); assertEquals(2, createKeywordsPage.countKeywords()); assertThat("keywords list does not include term 'rouge'", createKeywordsPage.getProspectiveKeywordsList().contains("rouge")); assertThat("keywords list does not include term 'red'", createKeywordsPage.getProspectiveKeywordsList().contains("red")); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOf(keywordsPage.selectLanguageButton())); assertEquals("Blacklist has been created in the wrong language", "French", keywordsPage.getSelectedLanguage()); keywordsPage.selectLanguage("French"); assertThat("Synonym, group not added", keywordsPage.getSynonymGroupSynonyms("rouge").contains("red")); assertThat("Synonym, group not added", keywordsPage.getSynonymGroupSynonyms("red").contains("rouge")); assertEquals(2, keywordsPage.countSynonymLists()); } //There is a link to create synonym group from the search page that prepopulates the create synonyms wizard with the current multi term search. Often breaks. @Test public void testCreateSynonymGroupFromMultiTermSearchOnSearchPage() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("lodge dodge podge"); searchPage = body.getSearchPage(); searchPage.selectLanguage("English", getConfig().getType().getName()); assertThat("No results for search", searchPage.docLogo().isDisplayed()); assertThat("No add to blacklist link displayed", searchPage.blacklistLink().isDisplayed()); assertThat("No create synonyms link displayed", searchPage.createSynonymsLink().isDisplayed()); searchPage.createSynonymsLink().click(); searchPage.loadOrFadeWait(); assertThat("link not directing to synonym group wizard", getDriver().getCurrentUrl().contains("keywords/create")); createKeywordsPage = body.getCreateKeywordsPage(); assertThat("link not directing to synonym group wizard", createKeywordsPage.getText().contains("Select synonyms")); assertEquals(3, createKeywordsPage.countKeywords()); assertThat("Wrong prospective blacklisted terms added", createKeywordsPage.getProspectiveKeywordsList().containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertThat("Finish button should be enabled", !createKeywordsPage.isAttributePresent(createKeywordsPage.finishWizardButton(), "disabled")); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("English"); assertThat("Synonym, group not complete", keywordsPage.getSynonymGroupSynonyms("lodge").containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertThat("Synonym, group not complete", keywordsPage.getSynonymGroupSynonyms("podge").containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertThat("Synonym, group not complete", keywordsPage.getSynonymGroupSynonyms("dodge").containsAll(Arrays.asList("lodge", "dodge", "podge"))); assertEquals(3, keywordsPage.countSynonymLists()); } @Test public void testKeywordsSearchFilter() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("grizzly brownBear bigBear", "English"); //All keywords should be changed by the application to lowercase in all instances final List<String> synonymListBears = Arrays.asList("grizzly", "brownbear", "bigbear"); new WebDriverWait(getDriver(), 15).until(ExpectedConditions.visibilityOf(body.getSearchPage())); searchPage = body.getSearchPage(); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in title", searchPage.title().contains(synonym)); assertThat(synonym + " not included in 'You searched for' section", searchPage.youSearchedFor().contains(synonym)); assertThat(synonym + " synonym group not complete in'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertEquals("Wrong number of synonym lists displayed", 3, searchPage.countSynonymLists()); } new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("honeyBee bumbleBee buzzyBee", "English"); final List<String> synonymListBees = Arrays.asList("honeybee", "bumblebee", "buzzybee"); searchPage = body.getSearchPage(); for (final String synonym : synonymListBees) { assertThat(synonym + " not included in title", searchPage.title().contains(synonym)); assertThat(synonym + " not included in 'You searched for' section", searchPage.youSearchedFor().contains(synonym)); assertThat(synonym + " not included in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBees)); assertEquals(3, searchPage.countSynonymLists()); } new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.selectLanguage("English"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("zz"); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("buzz"); keywordsPage.loadOrFadeWait(); assertEquals(3, keywordsPage.countSynonymLists()); for (final String synonym : synonymListBees) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBees)); assertThat("synonym included in synonym group: " + synonym + " that should not be there", !keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("a"); keywordsPage.searchFilterTextBox().sendKeys(Keys.BACK_SPACE); keywordsPage.loadOrFadeWait(); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("Bear"); keywordsPage.loadOrFadeWait(); assertEquals(3, keywordsPage.countSynonymLists()); for (final String synonym : synonymListBears) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertThat("synonym included in synonym group: " + synonym + " that should not be there", !keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBees)); } keywordsPage.searchFilterTextBox().clear(); keywordsPage.searchFilterTextBox().sendKeys("a"); keywordsPage.searchFilterTextBox().sendKeys(Keys.BACK_SPACE); keywordsPage.loadOrFadeWait(); assertEquals(6, keywordsPage.countSynonymLists()); for (final List<String> synonymList : Arrays.asList(synonymListBears, synonymListBees)) { for (final String synonym : synonymList) { assertThat("synonym not included in synonym group: " + synonym, keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymList)); } } } @Test public void testSearchPageKeywords() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); List<String> synonymListBears = Arrays.asList("grizzly", "brownbear", "bigbear"); createKeywordsPage.createSynonymGroup(StringUtils.join(synonymListBears, ' '), "English"); searchPage = body.getSearchPage(); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in title", searchPage.title().contains(synonym)); assertThat(synonym + " not included in 'You searched for' section", searchPage.youSearchedFor().contains(synonym)); assertThat(synonym + " synonym group not complete in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertEquals(3, searchPage.countSynonymLists()); } searchPage.addSynonymToGroup("kodiak", "grizzly"); searchPage.loadOrFadeWait(); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertThat("kodiak not included in synonym group " + synonym, searchPage.getSynonymGroupSynonyms(synonym).contains("kodiak")); assertEquals(3, searchPage.countSynonymLists()); } searchPage.deleteSynonym("bigbear", "brownbear"); searchPage.loadOrFadeWait(); synonymListBears = Arrays.asList("grizzly", "brownbear"); for (final String synonym : synonymListBears) { assertThat(synonym + " not included in 'Keywords' section", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertThat("bigbear not deleted from group " + synonym, !searchPage.getSynonymGroupSynonyms(synonym).contains("bigbear")); assertThat("kodiak not included in synonym group " + synonym, searchPage.getSynonymGroupSynonyms(synonym).contains("kodiak")); assertEquals(2, searchPage.countSynonymLists()); } new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.selectLanguage("English"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertEquals(3, keywordsPage.countSynonymLists()); synonymListBears = Arrays.asList("grizzly", "brownbear", "kodiak"); for (final String synonym : synonymListBears) { assertThat(synonym + " group incomplete", keywordsPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListBears)); assertEquals(3, keywordsPage.getSynonymGroupSynonyms(synonym).size()); assertThat("bigbear not deleted from group " + synonym, !keywordsPage.getSynonymGroupSynonyms(synonym).contains("bigbear")); } } @Test public void testNoBlacklistLinkForBlacklistedSearch() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); topNavBar.search("wizard"); searchPage = body.getSearchPage(); searchPage.selectLanguage("Arabic", getConfig().getType().getName()); searchPage.blacklistLink().click(); try { createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.finishWizardButton().click(); } catch (final NoSuchElementException e) { fail("blacklist link on search page has not navigated to the wizard"); } new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOf(keywordsPage.selectLanguageButton())); assertEquals("Blacklist has been created in the wrong language", "Arabic", keywordsPage.getSelectedLanguage()); keywordsPage.loadOrFadeWait(); new WebDriverWait(getDriver(), 8).until(ExpectedConditions.visibilityOf(keywordsPage.createNewKeywordsButton())); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); keywordsPage.selectLanguage("Arabic"); assertThat("Blacklisted term not created", keywordsPage.getBlacklistedTerms().contains("wizard")); topNavBar.search("wizard"); new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); searchPage.selectLanguage("Arabic", getConfig().getType().getName()); assertThat("'You searched for:' section incorrect", searchPage.youSearchedFor().contains("wizard")); assertThat("Keywords incorrect", searchPage.getBlacklistedTerms().contains("wizard")); assertThat("link to blacklist or create synonyms should not be present", !searchPage.getText().contains("You can create synonyms or blacklist these search terms")); searchPage.selectLanguage("English", getConfig().getType().getName()); assertThat("Term should not be blacklisted in English", !searchPage.getText().contains("Any query terms were either blacklisted or stop words")); } @Test public void testSynonymGroupMembersSearchWholeGroup() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); final List<String> synonymListCars = Arrays.asList("car", "auto", "motor"); createKeywordsPage.createSynonymGroup(StringUtils.join(synonymListCars, ' '), "Swahili"); searchPage = body.getSearchPage(); for (final String synonym : synonymListCars) { topNavBar.search(synonym); searchPage.selectLanguage("Swahili", getConfig().getType().getName()); assertEquals(1, searchPage.countSynonymLists()); assertThat("Synonym group does not contain all its members", searchPage.getSynonymGroupSynonyms(synonym).containsAll(synonymListCars)); } } @Test public void testAddTwoSynonymsToSynonymGroupFromSearchPage() throws InterruptedException { try { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("house home dwelling abode", "English"); searchPage = body.getSearchPage(); topNavBar.search("house"); searchPage.selectLanguage("English", getConfig().getType().getName()); assertEquals(1, searchPage.countSynonymLists()); assertThat("Synonym group does not contain all its members", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode"))); searchPage.addSynonymToGroup("lodging", "house"); searchPage.loadOrFadeWait(); assertThat("New synonym has not been added to the group", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "lodging"))); searchPage.addSynonymToGroup("residence", "house"); searchPage.loadOrFadeWait(); assertThat("New synonym has not been added to the group", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "lodging", "residence"))); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); assertThat("New synonym has not been added to the group", keywordsPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "lodging", "residence"))); keywordsPage.deleteAllSynonyms(); keywordsPage.loadOrFadeWait(); assertEquals(0, keywordsPage.countSynonymLists()); } finally { getDriver().navigate().refresh(); } } @Test public void testRemoveTwoSynonymsFromSynonymGroupFromSearchPage() throws InterruptedException { try { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("house home dwelling abode residence", "English"); searchPage = body.getSearchPage(); topNavBar.search("house"); searchPage.selectLanguage("English", getConfig().getType().getName()); assertEquals(1, searchPage.countSynonymLists()); assertThat("Synonym group does not contain all its members", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode", "residence"))); searchPage.deleteSynonym("residence", "house"); searchPage.loadOrFadeWait(); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("residence")); assertThat("Synonym has not been deleted", searchPage.getSynonymGroupSynonyms("house").contains("abode")); assertThat("More than one synonym deleted", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling", "abode"))); searchPage.deleteSynonym("abode", "house"); searchPage.loadOrFadeWait(); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("abode")); assertThat("More than one synonym deleted", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "dwelling"))); searchPage.deleteSynonym("dwelling", "house"); searchPage.loadOrFadeWait(); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("dwelling")); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("abode")); assertThat("Synonym has not been deleted", !searchPage.getSynonymGroupSynonyms("house").contains("residence")); assertThat("More than one synonym deleted", searchPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home"))); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); assertThat("Synonyms have not been removed from the group", keywordsPage.getSynonymGroupSynonyms("house").containsAll(Arrays.asList("home", "house"))); keywordsPage.deleteAllSynonyms(); keywordsPage.loadOrFadeWait(); assertEquals(0, keywordsPage.countSynonymLists()); } finally { getDriver().navigate().refresh(); } } @Test public void testOnlyLanguagesWithDocumentsAvailableOnSearchPage() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("Baku", "Azeri"); topNavBar.search("Baku"); searchPage = body.getSearchPage(); assertFalse(searchPage.getLanguageList().contains("Azeri")); } @Test public void testKeywordsLanguage() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("Atlanta", "Georgian"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("Tirana", "Albanian"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("Croatia Kroatia Hrvatska", "Croatian"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.selectLanguage("Georgian"); assertEquals(1, keywordsPage.getBlacklistedTerms().size()); assertEquals(0, keywordsPage.countSynonymLists()); keywordsPage.selectLanguage("Albanian"); assertEquals(1, keywordsPage.getBlacklistedTerms().size()); assertEquals(0, keywordsPage.countSynonymLists()); keywordsPage.selectLanguage("Croatian"); assertEquals(0, keywordsPage.getBlacklistedTerms().size()); assertEquals(3, keywordsPage.countSynonymLists()); } @Test public void testLanguageOfSearchPageKeywords() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("road rue strasse", "French"); topNavBar.search("Korea"); searchPage = body.getSearchPage(); searchPage.selectLanguage("Chinese", getConfig().getType().getName()); searchPage.createSynonymsLink().click(); searchPage.loadOrFadeWait(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.addSynonyms("한국"); createKeywordsPage.finishWizardButton().click(); new WebDriverWait(getDriver(), 5).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); topNavBar.search("Korea"); searchPage.selectLanguage("Chinese", getConfig().getType().getName()); assertEquals("wrong number of synonym lists displayed", 1, searchPage.countSynonymLists()); searchPage.selectLanguage("French", getConfig().getType().getName()); assertEquals("wrong number of synonym lists displayed", 0, searchPage.countSynonymLists()); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.selectLanguage("French"); assertThat("synonym assigned to wrong language", !keywordsPage.getText().contains("한국")); keywordsPage.selectLanguage("Chinese"); assertEquals("wrong number of synonym lists displayed", 2, keywordsPage.countSynonymLists()); assertThat("synonym not assigned to correct language", keywordsPage.getText().contains("한국")); } @Test public void testKeywordsCreationAndDeletionOnSecondWindow() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("double duo two pair couple", "Urdu"); navBar.switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("Urdu"); keywordsPage.loadOrFadeWait(); final String url = getDriver().getCurrentUrl(); final List<String> browserHandles = keywordsPage.createAndListWindowHandles(); getDriver().switchTo().window(browserHandles.get(1)); getDriver().get(url); final KeywordsPage secondKeywordsPage = (new AppBody(getDriver())).getKeywordsPage(); assertEquals(5, secondKeywordsPage.countSynonymLists()); getDriver().switchTo().window(browserHandles.get(0)); keywordsPage = body.getKeywordsPage(); keywordsPage.loadOrFadeWait(); keywordsPage.deleteSynonym("couple", "two"); getDriver().switchTo().window(browserHandles.get(1)); assertEquals(4, secondKeywordsPage.countSynonymLists()); getDriver().switchTo().window(browserHandles.get(0)); keywordsPage = body.getKeywordsPage(); keywordsPage.loadOrFadeWait(); keywordsPage.deleteSynonym("pair", "duo"); getDriver().switchTo().window(browserHandles.get(1)); assertEquals(3, secondKeywordsPage.countSynonymLists()); } @Test public void testSynonymsNotCaseSensitive() { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("bear"); assertEquals(1, createKeywordsPage.countKeywords()); for (final String bearVariant : Arrays.asList("Bear", "beaR", "BEAR", "beAR", "BEar")) { createKeywordsPage.addSynonyms(bearVariant); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("bear not included as a keyword", createKeywordsPage.getProspectiveKeywordsList().contains("bear")); assertThat("correct error message not showing", createKeywordsPage.getText().contains(bearVariant + " is a case variant of bear, an existing keyword.")); } // disallows any adding of synonyms if disallowed synonym found createKeywordsPage.addSynonyms("Polar Bear"); assertEquals(1, createKeywordsPage.countKeywords()); assertThat("bear not included as a keyword", createKeywordsPage.getProspectiveKeywordsList().contains("bear")); assertThat("correct error message not showing", createKeywordsPage.getText().contains("Bear is a case variant of bear, an existing keyword.")); //jam and jaM are case variants so none should be added createKeywordsPage.addSynonyms("jam jaM"); assertEquals(1, createKeywordsPage.countKeywords()); } @Test public void testSpinnerPresentOnLastSynonymWhilePenultimateSynonymSpinnerPresent() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("ying yang", "Korean"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.selectLanguage("Korean"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); assertEquals(2, keywordsPage.countSynonymLists()); keywordsPage.getSynonymIcon("ying", "yang").click(); if (keywordsPage.getSynonymIcon("ying", "yang").getAttribute("class").contains("fa-spin")) { assertThat("Spinner not present on last synonym", keywordsPage.getSynonymIcon("yang", "yang").getAttribute("class").contains("fa-spin")); } } @Test public void testBooleanTermsNotValidKeyword() { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("holder"); assertEquals(1, createKeywordsPage.countKeywords()); final List<String> booleanProximityOperators = Arrays.asList("NOT", "NEAR", "DNEAR", "SOUNDEX", "XNEAR", "YNEAR", "AND", "BEFORE", "AFTER", "WHEN", "SENTENCE", "PARAGRAPH", "OR", "WNEAR", "EOR", "NOTWHEN"); for (final String operator : booleanProximityOperators) { createKeywordsPage.addSynonyms(operator); assertThat("boolean operator \"" + operator + "\" should not be added as a synonym", !createKeywordsPage.getProspectiveKeywordsList().contains(operator)); assertThat("Correct error message not showing", createKeywordsPage.getText().contains(operator + " is a boolean or proximity operator. These are invalid")); assertEquals(1, createKeywordsPage.countKeywords()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); createKeywordsPage.loadOrFadeWait(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTerms("holder"); assertEquals(1, createKeywordsPage.countKeywords()); for (final String operator : booleanProximityOperators) { createKeywordsPage.addBlacklistedTerms(operator); assertThat("boolean operator \"" + operator + "\" should not be added as a synonym", !createKeywordsPage.getProspectiveKeywordsList().contains(operator)); assertThat("Correct error message not showing", createKeywordsPage.getText().contains(operator + " is a boolean or proximity operator. These are invalid")); assertEquals(1, createKeywordsPage.countKeywords()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); createKeywordsPage.loadOrFadeWait(); } @Test public void testAddKeywordsBoxOpenClickDelete() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("бір екі үш төрт бес", "Kazakh"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.selectLanguage("Kazakh"); keywordsPage.synonymGroupPlusButton("бір").click(); assertTrue(keywordsPage.synonymGroupTextBox("бір").isDisplayed()); keywordsPage.deleteSynonym("екі", "үш"); assertTrue(keywordsPage.synonymGroupTextBox("бір").isDisplayed()); } @Test public void testQuickSynonymDelete() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("string strong strang streng strung", "German"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); keywordsPage.loadOrFadeWait(); keywordsPage.selectLanguage("German"); try { keywordsPage.scrollIntoViewAndClick(keywordsPage.getSynonymIcon("strong", "strung")); keywordsPage.scrollIntoViewAndClick(keywordsPage.getSynonymIcon("string", "strung")); } catch (final WebDriverException w) { fail("Unable to delete a synonym quickly"); } Thread.sleep(5000); assertEquals("Incorrect number of synonyms", 3, keywordsPage.countSynonymLists()); } @Test public void testAddingForbiddenKeywordsFromUrl() { String blacklistUrl = getConfig().getWebappUrl() + "/p/keywords/create/blacklisted/English/"; String synonymsUrl = getConfig().getWebappUrl() + "/p/keywords/create/synonyms/English/"; if (getConfig().getType().equals(ApplicationType.ON_PREM)) { blacklistUrl = getConfig().getWebappUrl() + "/p/keywords/create/blacklisted/englishUTF8/"; synonymsUrl = getConfig().getWebappUrl() + "/p/keywords/create/synonyms/englishUTF8/"; } for (final String forbidden : Arrays.asList("(", "\"", "OR")) { getDriver().get(blacklistUrl.concat(forbidden)); body.loadOrFadeWait(); createKeywordsPage = body.getCreateKeywordsPage(); assertFalse(forbidden + " is a forbidden keyword and should not be included in the prospective blacklist list", createKeywordsPage.getProspectiveKeywordsList().contains("(")); getDriver().get(synonymsUrl.concat(forbidden)); body.loadOrFadeWait(); createKeywordsPage = body.getCreateKeywordsPage(); assertFalse(forbidden + " is a forbidden keyword and should not be included in the prospective synonyms list", createKeywordsPage.getProspectiveKeywordsList().contains("(")); } } @Test public void testSynonymsDisplayedInAlphabeticalOrder() throws InterruptedException { keywordsPage.deleteAllSynonyms(); for (final String synonyms : Arrays.asList("aa ba ca da", "ab bb cb db", "dc cc bc ac", "ca ba da aa")) { keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup(synonyms, "English"); searchPage = body.getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); final List<String> keywords = searchPage.getLeadSynonymsList(); for (int i = 0; i < keywords.size() - 1; i++) { assertTrue(keywords.get(i).compareTo(keywords.get(i + 1)) <= 0); } searchPage.loadOrFadeWait(); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); } keywordsPage.loadOrFadeWait(); keywordsPage = body.getKeywordsPage(); keywordsPage.searchFilterTextBox().sendKeys("cc"); final List<String> keywords = keywordsPage.getLeadSynonymsList(); for (int i = 0; i < keywords.size() - 1; i++) { assertTrue(keywords.get(i).compareTo(keywords.get(i + 1)) <= 0); } } @Test public void testBlacklistedKeywordsDisplayedInAlphabeticalOrder() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("aa ba ca da ab bb cb db", "English"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.BLACKLIST); final List<String> keywords = keywordsPage.getBlacklistedTerms(); assertEquals("Wrong number of blacklist items created", 8, keywords.size()); for (int i = 0; i < keywords.size() - 1; i++) { assertTrue(keywords.get(i).compareTo(keywords.get(i + 1)) <= 0); } } @Test public void testDeletingOfSynonymsAndBlacklistedTerms() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("aa ba ca da ab bb cb db", "English"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("ea es ed ef eg eh", "English"); searchPage = body.getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.deleteSynonym("es", "es"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("ea", "ea"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("eg", "eg"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("ed", "ed"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteSynonym("ef", "ef"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createBlacklistedTerm("aa ba ca da ab bb cb db", "English"); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage.createSynonymGroup("ea es ed ef eg eh", "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.filterView(KeywordsPage.KeywordsFilter.ALL_TYPES); keywordsPage.deleteBlacklistedTerm("db"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteBlacklistedTerm("aa"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); keywordsPage.deleteBlacklistedTerm("da"); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); } @Test public void testDoesDeletingSynonymDisableOtherSynonyms() throws InterruptedException { keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("ea es ed ef eg eh", "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage = body.getKeywordsPage(); final List<String> synonyms = Arrays.asList("ea", "es", "ed", "ef", "eg"); for (final String synonym : synonyms) { keywordsPage.getSynonymIcon(synonym, synonym).click(); assertEquals("Too many synonyms are disabled on synonym delete", 6 - synonyms.indexOf(synonym), keywordsPage.countDisabledKeywords()); Thread.sleep(3000); assertFalse("some keywords are disabled after the last keyword delete", keywordsPage.areAnyKeywordsDisabled()); } } @Test public void testAllowKeywordStringsThatContainBooleansWithinThem() throws InterruptedException { keywordsPage.deleteAllSynonyms(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.SYNONYM).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addSynonyms("placeholder"); assertEquals(1, createKeywordsPage.getProspectiveKeywordsList().size()); final List<String> hiddenSearchOperators = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "NEARLY", "NEAR123LY", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED"); for (int i = 0; i < hiddenSearchOperators.size(); i++) { createKeywordsPage.addSynonymsTextBox().clear(); createKeywordsPage.addSynonymsTextBox().sendKeys(hiddenSearchOperators.get(i)); createKeywordsPage.addSynonymsButton().click(); createKeywordsPage.loadOrFadeWait(); assertEquals(2 + i, createKeywordsPage.getProspectiveKeywordsList().size()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); keywordsPage.loadOrFadeWait(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.keywordsType(CreateNewKeywordsPage.KeywordType.BLACKLIST).click(); createKeywordsPage.selectLanguage("English"); createKeywordsPage.continueWizardButton(CreateNewKeywordsPage.WizardStep.TYPE).click(); createKeywordsPage.loadOrFadeWait(); createKeywordsPage.addBlacklistedTerms("placeholder"); assertEquals(1, createKeywordsPage.getProspectiveKeywordsList().size()); for (int i = 0; i < hiddenSearchOperators.size(); i++) { createKeywordsPage.addBlacklistedTextBox().clear(); createKeywordsPage.addBlacklistedTextBox().sendKeys(hiddenSearchOperators.get(i)); createKeywordsPage.addBlacklistTermsButton().click(); createKeywordsPage.loadOrFadeWait(); assertEquals(2 + i, createKeywordsPage.getProspectiveKeywordsList().size()); } createKeywordsPage.cancelWizardButton(CreateNewKeywordsPage.WizardStep.TRIGGERS).click(); keywordsPage.loadOrFadeWait(); keywordsPage.createNewKeywordsButton().click(); createKeywordsPage = body.getCreateKeywordsPage(); createKeywordsPage.createSynonymGroup("place holder", "English"); new SideNavBar(getDriver()).switchPage(NavBarTabId.KEYWORDS); keywordsPage.loadOrFadeWait(); keywordsPage.selectLanguage("English"); keywordsPage.filterView(KeywordsPage.KeywordsFilter.SYNONYMS); for (final String hiddenBooleansProximity : hiddenSearchOperators) { keywordsPage.addSynonymToGroup(hiddenBooleansProximity, "holder"); keywordsPage.loadOrFadeWait(); assertEquals(1, keywordsPage.countSynonymGroupsWithLeadSynonym(hiddenBooleansProximity.toLowerCase())); } } }
Fixed some of the Keyword Page (and related wizard)'s tests. Some still require fixing, others now fail where they're supposed to. [git-p4: depot-paths = "//depot/products/frontend/abc/master/": change = 1240082]
src/test/java/com/autonomy/abc/keywords/KeywordsPageAndWizardITCase.java
Fixed some of the Keyword Page (and related wizard)'s tests. Some still require fixing, others now fail where they're supposed to.
Java
mit
38c8203501255052993a87b39151d880e5aadce4
0
nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server
package fi.nls.oskari.map.view; import com.ibatis.sqlmap.client.SqlMapSession; import fi.nls.oskari.domain.Role; import fi.nls.oskari.domain.User; import fi.nls.oskari.domain.map.view.Bundle; import fi.nls.oskari.domain.map.view.View; import fi.nls.oskari.domain.map.view.ViewTypes; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.service.db.BaseIbatisService; import fi.nls.oskari.util.ConversionHelper; import fi.nls.oskari.util.PropertyUtil; import java.sql.SQLException; import java.util.*; public class ViewServiceIbatisImpl extends BaseIbatisService<Object> implements ViewService { private static final Logger LOG = LogFactory.getLogger(ViewServiceIbatisImpl.class); private static final String PROP_VIEW_DEFAULT = "view.default"; private static final String PROP_VIEW_DEFAULT_ROLES = "view.default.roles"; private final Map<String, Long> roleToDefaultViewId; private final String[] defaultViewRoles; private final long defaultViewId; public ViewServiceIbatisImpl() { // roles in preferred order which we use to resolve default view // view.default.roles=Admin, User, Guest defaultViewRoles = PropertyUtil.getCommaSeparatedList(PROP_VIEW_DEFAULT_ROLES); roleToDefaultViewId = initDefaultViewsByRole(defaultViewRoles); defaultViewId = initDefaultViewId(); } private Map<String, Long> initDefaultViewsByRole(String[] roles) { if (roles.length == 0) { return Collections.emptyMap(); } Map<String, Long> roleToDefaultViewId = new HashMap<>(); for (String role : roles) { String roleViewIdStr = PropertyUtil.get(PROP_VIEW_DEFAULT + "." + role); long roleViewId = ConversionHelper.getLong(roleViewIdStr, -1); if (roleViewId != -1) { roleToDefaultViewId.put(role, roleViewId); LOG.debug("Added default view", roleViewId, "for role", role); } else { LOG.info("Failed to set default view id for role", role, "property missing or value invalid"); } } return roleToDefaultViewId; } private long initDefaultViewId() { long property = ConversionHelper.getLong(PropertyUtil.get(PROP_VIEW_DEFAULT), -1); if (property != -1) { LOG.debug("Global default view id from properties:" , property); return property; } // use one from db if property doesn't exist or is invalid Long database = ((Long) queryForObject("View.get-default-view-id", ViewTypes.DEFAULT)); LOG.debug("Global default view id from database:" , database); return database; } @Override protected String getNameSpace() { return "View"; } public boolean hasPermissionToAlterView(final View view, final User user) { // uuids are much longer than 10 actually but check for atleast 10 if(user.getUuid() == null || user.getUuid().length() < 10) { LOG.debug("Users uuid is missing or invalid: ", user.getUuid()); // user doesn't have an uuid, he shouldn't have any published maps return false; } if(view == null) { LOG.debug("View is null"); // view with id not found return false; } if(user.isGuest()) { LOG.debug("User is default/guest user"); return false; } if(view.getCreator() != user.getId()) { // check current user id against view creator (is it the same user) LOG.debug("Users id:", user.getId(), "didn't match view creator:", view.getCreator()); return false; } return true; } public List<View> getViews(int page, int pagesize) { final Map<String, Object> params = new HashMap<String, Object>(); params.put("limit", pagesize); params.put("offset", (page -1) * pagesize); List<View> views = queryForList("View.paged-views", params); return views; } public View getViewWithConf(long viewId) { if (viewId < 1) return null; View view = queryForObject("View.view-with-conf-by-view-id", viewId); return view; } public View getViewWithConfByUuId(String uuId) { if (uuId == null) return null; LOG.debug("uuid != null --> view-with-conf-by-uuid"); View view = (View) queryForObject("View.view-with-conf-by-uuid", uuId); setBundlesForView(view); return view; } public View getViewWithConfByOldId(long oldId) { if (oldId < 1) return null; View view = queryForObject("View.view-with-conf-by-old-id", oldId); return view; } public View getViewWithConf(String viewName) { View view = (View) queryForObject("View.view-with-conf-by-view-name", viewName); return view; } public List<View> getViewsForUser(long userId) { List<View> views = queryForList("View.views-with-conf-by-user-id", userId); LOG.debug("Found", views.size(), "views for user", userId); return views; } private void setBundlesForView(View view) { if (view == null) { return; } long id = view.getId(); List<Bundle> bundles = queryForList("View.bundle-by-view-id", id); view.setBundles(bundles); } public long addView(View view) throws ViewException { SqlMapSession session = openSession(); try { view.setUuid(UUID.randomUUID().toString()); session.startTransaction(); Object ret = queryForObject("View.add-view", view); long id = ((Long) ret).longValue(); LOG.info("Inserted view with id", id); view.setId(id); for (Bundle bundle : view.getBundles()) { addBundleForView(view.getId(), bundle); } session.commitTransaction(); return id; } catch (Exception e) { throw new ViewException("Error adding a view ", e); } finally { endSession(session); } } public void updateAccessFlag(View view) { update("View.update-access", view); } public void deleteViewById(final long id) throws DeleteViewException { View view = queryForObject("View.view-with-conf-by-view-id", id); if(view == null) { throw new DeleteViewException("Couldn't find a view with id:" + id); } SqlMapSession session = openSession(); try { session.startTransaction(); session.delete("View.delete-bundle-by-view", id); session.delete("View.delete-view", id); session.commitTransaction(); } catch (Exception e) { throw new DeleteViewException("Error deleting a view with id:" + id, e); } finally { endSession(session); } } public void deleteViewByUserId(long userId) throws DeleteViewException { SqlMapSession session = openSession(); try { session.startTransaction(); delete("View.delete-view-by-user", userId); session.commitTransaction(); } catch (Exception e) { throw new DeleteViewException("Error deleting a view with user id:" + userId, e); } finally { endSession(session); } } public void resetUsersDefaultViews(long userId) { update("View.resetUsersDefaultViews", userId); } public void updateView(View view) { update("View.update", view); } public void updateViewUsage(View view) { update("View.updateUsage", view); } public void updatePublishedView(final View view) throws ViewException { SqlMapSession session = openSession(); long id = view.getId(); try { session.startTransaction(); updateView(view); delete("View.delete-bundle-by-view", id); for (Bundle bundle : view.getBundles()) { addBundleForView(view.getId(), bundle); } session.commitTransaction(); } catch (Exception e) { throw new ViewException("Error updating a view with id:" + id, e); } finally { endSession(session); } } public void addBundleForView(final long viewId, final Bundle bundle) throws SQLException { // TODO: maybe setup sequencenumber to last if not set? bundle.setViewId(viewId); queryForObject("View.add-bundle", bundle); LOG.debug("Added bundle to view", bundle.getName()); } public void updateBundleSettingsForView(final long viewId, final Bundle bundle) throws ViewException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("view_id", viewId); params.put("bundle_id", bundle.getBundleId()); params.put("seqno", bundle.getSeqNo()); params.put("startup", bundle.getStartup()); params.put("config", bundle.getConfig()); params.put("state", bundle.getState()); params.put("bundleinstance", bundle.getBundleinstance()); try { final int numUpdated = getSqlMapClient().update("View.update-bundle-settings-in-view", params); if(numUpdated == 0) { // not updated, bundle not found throw new ViewException("Failed to update - bundle not found in view?"); } } catch (Exception e) { throw new ViewException("Failed to update", e); } } public long getDefaultViewId() { return defaultViewId; } /** * Returns default view id for the user, based on user roles. Configured by properties: * * view.default=[global default view id that is used if role-based default view is not found] * view.default.roles=[comma-separated list of role names in descending order f.ex. Admin, User, Guest] * view.default.[role name]=[default view id for the role] * * If properties are not found, defaults to #getDefaultViewId() * @param user to get default view for * @return view id based on users roles */ public long getDefaultViewId(final User user) { if(user == null) { LOG.debug("Tried to get default view for <null> user"); return getDefaultViewId(); } else { final long personalizedId = getPersonalizedDefaultViewId(user); if(personalizedId != -1) { return personalizedId; } return getSystemDefaultViewId(user.getRoles()); } } public long getSystemDefaultViewId(Collection<Role> roles) { if (roles == null) { LOG.debug("Tried to get default view for <null> roles"); } else { // Check the roles in given order and return the first match for (String defaultViewRole : defaultViewRoles) { if (Role.hasRoleWithName(roles, defaultViewRole)) { Long rolesDefaultViewId = roleToDefaultViewId.get(defaultViewRole); if (rolesDefaultViewId != null) { LOG.debug("Default view found for role", defaultViewRole, ":", rolesDefaultViewId); return rolesDefaultViewId; } } } } LOG.debug("No role based default views matched user roles:", roles, ". Defaulting to global default."); return getDefaultViewId(); } /** * Returns the saved default view id for the user, if one exists * * @param user to get default view for * @return view id of a saved default view */ private long getPersonalizedDefaultViewId(final User user) { if (!user.isGuest() && user.getId() != -1) { Object queryResult = queryForObject("View.get-default-view-id-by-user-id", user.getId()); if (queryResult != null) { return (Long) queryResult; } } return -1; } public boolean isSystemDefaultView(final long id) { return roleToDefaultViewId.containsValue(id) || getDefaultViewId() == id; } /** * Returns default view id for given role name * @param roleName * @return */ public long getDefaultViewIdForRole(final String roleName) { Long rolesDefaultViewId = roleToDefaultViewId.get(roleName); return rolesDefaultViewId != null ? rolesDefaultViewId : defaultViewId; } }
service-map/src/main/java/fi/nls/oskari/map/view/ViewServiceIbatisImpl.java
package fi.nls.oskari.map.view; import com.ibatis.sqlmap.client.SqlMapSession; import fi.nls.oskari.domain.Role; import fi.nls.oskari.domain.User; import fi.nls.oskari.domain.map.view.Bundle; import fi.nls.oskari.domain.map.view.View; import fi.nls.oskari.domain.map.view.ViewTypes; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.service.db.BaseIbatisService; import fi.nls.oskari.util.ConversionHelper; import fi.nls.oskari.util.PropertyUtil; import java.sql.SQLException; import java.util.*; public class ViewServiceIbatisImpl extends BaseIbatisService<Object> implements ViewService { private static final Logger LOG = LogFactory.getLogger(ViewServiceIbatisImpl.class); private static final String PROP_VIEW_DEFAULT = "view.default"; private static final String PROP_VIEW_DEFAULT_ROLES = "view.default.roles"; private final Map<String, Long> roleToDefaultViewId; private final String[] defaultViewRoles; private final long defaultViewId; public ViewServiceIbatisImpl() { // roles in preferred order which we use to resolve default view // view.default.roles=Admin, User, Guest defaultViewRoles = PropertyUtil.getCommaSeparatedList(PROP_VIEW_DEFAULT_ROLES); roleToDefaultViewId = initDefaultViewsByRole(defaultViewRoles); defaultViewId = initDefaultViewId(); } private Map<String, Long> initDefaultViewsByRole(String[] roles) { if (roles.length == 0) { return Collections.emptyMap(); } Map<String, Long> roleToDefaultViewId = new HashMap<>(); for (String role : roles) { String roleViewIdStr = PropertyUtil.get(PROP_VIEW_DEFAULT + "." + role); long roleViewId = ConversionHelper.getLong(roleViewIdStr, -1); if (roleViewId != -1) { roleToDefaultViewId.put(role, roleViewId); LOG.debug("Added default view", roleViewId, "for role", role); } else { LOG.info("Failed to set default view id for role", role, "property missing or value invalid"); } } return roleToDefaultViewId; } private long initDefaultViewId() { long property = ConversionHelper.getLong(PropertyUtil.get(PROP_VIEW_DEFAULT), -1); if (property != -1) { LOG.debug("Global default view id from properties:" , property); return property; } // use one from db if property doesn't exist or is invalid Long database = ((Long) queryForObject("View.get-default-view-id", ViewTypes.DEFAULT)); LOG.debug("Global default view id from database:" , database); return database; } @Override protected String getNameSpace() { return "View"; } public boolean hasPermissionToAlterView(final View view, final User user) { // uuids are much longer than 10 actually but check for atleast 10 if(user.getUuid() == null || user.getUuid().length() < 10) { LOG.debug("Users uuid is missing or invalid: ", user.getUuid()); // user doesn't have an uuid, he shouldn't have any published maps return false; } if(view == null) { LOG.debug("View is null"); // view with id not found return false; } if(user.isGuest()) { LOG.debug("User is default/guest user"); return false; } if(view.getCreator() != user.getId()) { // check current user id against view creator (is it the same user) LOG.debug("Users id:", user.getId(), "didn't match view creator:", view.getCreator()); return false; } return true; } public List<View> getViews(int page, int pagesize) { final Map<String, Object> params = new HashMap<String, Object>(); params.put("limit", pagesize); params.put("offset", (page -1) * pagesize); List<View> views = queryForList("View.paged-views", params); return views; } public View getViewWithConf(long viewId) { if (viewId < 1) return null; View view = queryForObject("View.view-with-conf-by-view-id", viewId); return view; } public View getViewWithConfByUuId(String uuId) { if (uuId == null) return null; LOG.debug("uuid != null --> view-with-conf-by-uuid"); View view = (View) queryForObject("View.view-with-conf-by-uuid", uuId); setBundlesForView(view); return view; } public View getViewWithConfByOldId(long oldId) { if (oldId < 1) return null; View view = queryForObject("View.view-with-conf-by-old-id", oldId); return view; } public View getViewWithConf(String viewName) { View view = (View) queryForObject("View.view-with-conf-by-view-name", viewName); return view; } public List<View> getViewsForUser(long userId) { List<View> views = queryForList("View.views-with-conf-by-user-id", userId); LOG.debug("Found", views.size(), "views for user", userId); return views; } private void setBundlesForView(View view) { if (view == null) { return; } long id = view.getId(); List<Bundle> bundles = queryForList("View.bundle-by-view-id", id); view.setBundles(bundles); } public long addView(View view) throws ViewException { SqlMapSession session = openSession(); try { view.setUuid(UUID.randomUUID().toString()); session.startTransaction(); Object ret = queryForObject("View.add-view", view); long id = ((Long) ret).longValue(); LOG.info("Inserted view with id", id); view.setId(id); for (Bundle bundle : view.getBundles()) { addBundleForView(view.getId(), bundle); } session.commitTransaction(); return id; } catch (Exception e) { throw new ViewException("Error adding a view ", e); } finally { endSession(session); } } public void updateAccessFlag(View view) { update("View.update-access", view); } public void deleteViewById(final long id) throws DeleteViewException { View view = queryForObject("View.view-with-conf-by-view-id", id); if(view == null) { throw new DeleteViewException("Couldn't find a view with id:" + id); } SqlMapSession session = openSession(); try { session.startTransaction(); session.delete("View.delete-bundle-by-view", id); session.delete("View.delete-view", id); session.commitTransaction(); } catch (Exception e) { throw new DeleteViewException("Error deleting a view with id:" + id, e); } finally { endSession(session); } } public void deleteViewByUserId(long userId) throws DeleteViewException { SqlMapSession session = openSession(); try { session.startTransaction(); delete("View.delete-view-by-user", userId); session.commitTransaction(); } catch (Exception e) { throw new DeleteViewException("Error deleting a view with user id:" + userId, e); } finally { endSession(session); } } public void resetUsersDefaultViews(long userId) { update("View.resetUsersDefaultViews", userId); } public void updateView(View view) { update("View.update", view); } public void updateViewUsage(View view) { update("View.updateUsage", view); } public void updatePublishedView(final View view) throws ViewException { SqlMapSession session = openSession(); long id = view.getId(); try { session.startTransaction(); updateView(view); delete("View.delete-bundle-by-view", id); for (Bundle bundle : view.getBundles()) { addBundleForView(view.getId(), bundle); } session.commitTransaction(); } catch (Exception e) { throw new ViewException("Error updating a view with id:" + id, e); } finally { endSession(session); } } public void addBundleForView(final long viewId, final Bundle bundle) throws SQLException { // TODO: maybe setup sequencenumber to last if not set? bundle.setViewId(viewId); queryForObject("View.add-bundle", bundle); LOG.debug("Added bundle to view", bundle.getName()); } public void updateBundleSettingsForView(final long viewId, final Bundle bundle) throws ViewException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("view_id", viewId); params.put("bundle_id", bundle.getBundleId()); params.put("seqno", bundle.getSeqNo()); params.put("startup", bundle.getStartup()); params.put("config", bundle.getConfig()); params.put("state", bundle.getState()); params.put("bundleinstance", bundle.getBundleinstance()); try { final int numUpdated = getSqlMapClient().update("View.update-bundle-settings-in-view", params); if(numUpdated == 0) { // not updated, bundle not found throw new ViewException("Failed to update - bundle not found in view?"); } } catch (Exception e) { throw new ViewException("Failed to update", e); } } public long getDefaultViewId() { return defaultViewId; } /** * Returns default view id for the user, based on user roles. Configured by properties: * * view.default=[global default view id that is used if role-based default view is not found] * view.default.roles=[comma-separated list of role names in descending order f.ex. Admin, User, Guest] * view.default.[role name]=[default view id for the role] * * If properties are not found, defaults to #getDefaultViewId() * @param user to get default view for * @return view id based on users roles */ public long getDefaultViewId(final User user) { if(user == null) { LOG.debug("Tried to get default view for <null> user"); return getDefaultViewId(); } else { final long personalizedId = getPersonalizedDefaultViewId(user); if(personalizedId != -1) { return personalizedId; } return getSystemDefaultViewId(user.getRoles()); } } public long getSystemDefaultViewId(Collection<Role> roles) { if (roles == null) { LOG.debug("Tried to get default view for <null> roles"); } else { // Check the roles in given order and return the first match for (String defaultViewRole : defaultViewRoles) { if (Role.hasRoleWithName(roles, defaultViewRole)) { Long rolesDefaultViewId = roleToDefaultViewId.get(defaultViewRole); if (rolesDefaultViewId != null) { LOG.debug("Default view found for role", defaultViewRole, ":", rolesDefaultViewId); return rolesDefaultViewId; } } } } LOG.debug("No role based default views matched user roles:", roles, ". Defaulting to global default."); return getDefaultViewId(); } /** * Returns the saved default view id for the user, if one exists * * @param user to get default view for * @return view id of a saved default view */ private long getPersonalizedDefaultViewId(final User user) { if (!user.isGuest() && user.getId() != -1) { Object queryResult = queryForObject("View.get-default-view-id-by-user-id", user.getId()); if (queryResult != null) { return (Long) queryResult; } } return -1; } public boolean isSystemDefaultView(final long id) { return roleToDefaultViewId.containsValue(id) || getDefaultViewId() == id; } /** * Returns default view id for given role name * @param roleName * @return */ public long getDefaultViewIdForRole(final String roleName) { if(roleToDefaultViewId.containsKey(roleName)) { return roleToDefaultViewId.get(roleName); } return getDefaultViewId(); } }
Avoid double checking
service-map/src/main/java/fi/nls/oskari/map/view/ViewServiceIbatisImpl.java
Avoid double checking
Java
mit
4c4396d6c9356cc44868e4ee3298f6a010dcea35
0
lukehutch/fast-classpath-scanner,lukehutch/fast-classpath-scanner,classgraph/classgraph
/* * This file is part of ClassGraph. * * Author: Johno Crawford (johno@sulake.com) * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2016 Johno Crawford * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.classgraph.utils; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** A ThreadPoolExecutor that can be used in a try-with-resources block. */ public class AutoCloseableExecutorService extends ThreadPoolExecutor implements AutoCloseable { /** * A ThreadPoolExecutor that can be used in a try-with-resources block. * * @param numThreads * The number of threads to allocate. */ public AutoCloseableExecutorService(final int numThreads) { super(numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new SimpleThreadFactory("ClassGraph-worker-", true)); } /** Shut down thread pool on close(). */ @Override public void close() { try { // Prevent any new tasks being submitted shutdown(); } catch (Exception e) { } try { // Await termination of any running tasks awaitTermination(2500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } try { // Interrupt all the threads to terminate them, if awaitTermination() timed out shutdownNow(); } catch (final Exception e) { throw new RuntimeException("Exception shutting down ExecutorService: " + e); } } }
src/main/java/io/github/classgraph/utils/AutoCloseableExecutorService.java
/* * This file is part of ClassGraph. * * Author: Johno Crawford (johno@sulake.com) * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2016 Johno Crawford * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.classgraph.utils; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** A ThreadPoolExecutor that can be used in a try-with-resources block. */ public class AutoCloseableExecutorService extends ThreadPoolExecutor implements AutoCloseable { /** * A ThreadPoolExecutor that can be used in a try-with-resources block. * * @param numThreads * The number of threads to allocate. */ public AutoCloseableExecutorService(final int numThreads) { super(numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new SimpleThreadFactory("ClassGraph-worker-", true)); } /** Shut down thread pool on close(). */ @Override public void close() { try { shutdownNow(); } catch (final Exception e) { throw new RuntimeException("Exception shutting down ExecutorService: " + e); } } }
Cleaner thread shutdown
src/main/java/io/github/classgraph/utils/AutoCloseableExecutorService.java
Cleaner thread shutdown
Java
mit
002eca31e708df09d5bb5632b05c5bd87d7f4a94
0
gabriel-silva/MapaDeIgarassu
package iphan.pibex.igarassu.ifpe.edu.br.ui.other; import android.content.Context; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import iphan.pibex.igarassu.ifpe.edu.br.model.GoogleMapsModel; import iphan.pibex.igarassu.ifpe.edu.br.ui.dialog.InvokeProgressDialog; import iphan.pibex.igarassu.ifpe.edu.br.model.ConnectionFireBaseModel; import iphan.pibex.igarassu.ifpe.edu.br.util.DataBaseUtil; public class InvokeAddMarkerMapOther implements OnMapReadyCallback { private Context context; private DataBaseUtil dataBaseUtil; public InvokeAddMarkerMapOther(Context context) { this.context = context; dataBaseUtil = new DataBaseUtil(context); } public void onAddMarkerFirebase() { InvokeProgressDialog.progressDialogStart(context, "Aguarde", "Os pontos estão sendo carregados..."); //Exibindo janela de progresso ConnectionFireBaseModel.getReferenceFirebase() .child("locations") .addValueEventListener(new ValueEventListenerMarkerOther(this.dataBaseUtil)); } public void onAddMarkerSqlite(){ GoogleMapsModel.getMap().clear(); /*Limpando o mapa*/ this.dataBaseUtil.addMarkerSqlite(); } @Override public void onMapReady(GoogleMap googleMap) { onAddMarkerFirebase(); } }
app/src/main/java/iphan/pibex/igarassu/ifpe/edu/br/ui/other/InvokeAddMarkerMapOther.java
package iphan.pibex.igarassu.ifpe.edu.br.ui.other; import android.content.Context; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import iphan.pibex.igarassu.ifpe.edu.br.model.GoogleMapsModel; import iphan.pibex.igarassu.ifpe.edu.br.ui.dialog.InvokeProgressDialog; import iphan.pibex.igarassu.ifpe.edu.br.model.ConnectionFireBaseModel; import iphan.pibex.igarassu.ifpe.edu.br.util.DataBaseUtil; public class InvokeAddMarkerMapOther implements OnMapReadyCallback { private Context context; private DataBaseUtil dataBaseUtil; public InvokeAddMarkerMapOther(Context context) { this.context = context; dataBaseUtil = new DataBaseUtil(context); } public void onAddMarkerFirebase() { ConnectionFireBaseModel.getReferenceFirebase().onDisconnect(); InvokeProgressDialog.progressDialogStart(context, "Aguarde", "Os pontos estão sendo carregados..."); //Exibindo janela de progresso ConnectionFireBaseModel.getReferenceFirebase() .child("locations") .addValueEventListener(new ValueEventListenerMarkerOther(this.dataBaseUtil)); } public void onAddMarkerSqlite(){ GoogleMapsModel.getMap().clear(); /*Limpando o mapa*/ this.dataBaseUtil.addMarkerSqlite(); } @Override public void onMapReady(GoogleMap googleMap) { onAddMarkerFirebase(); } }
Update InvokeAddMarkerMapOther.java
app/src/main/java/iphan/pibex/igarassu/ifpe/edu/br/ui/other/InvokeAddMarkerMapOther.java
Update InvokeAddMarkerMapOther.java
Java
mit
a9cab4d50202c231a9c8f49547d0574289cca2b7
0
andereld/progark,andereld/progark
package com.mygdx.game; /** * Created by esso on 18.03.15. */ public class Constants { public static final int REGULAR_REQUEST_TIME = 5000; }
client/core/src/com/mygdx/game/Constants.java
package com.mygdx.game; /** * Created by esso on 18.03.15. */ public class Constants { public static final int REGULAR_REQUEST_TIME = 10000; }
Change request time to 5000 ms
client/core/src/com/mygdx/game/Constants.java
Change request time to 5000 ms
Java
epl-1.0
772492da0b37e9179bf6259d240f9114238dff05
0
forge/intellij-idea-plugin,forge/intellij-idea-plugin
/* * Copyright 2014 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.plugin.idea.action; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.vfs.VirtualFile; import org.jboss.forge.addon.ui.command.UICommand; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.plugin.idea.context.UIContextFactory; import org.jboss.forge.plugin.idea.service.ServiceHelper; import org.jboss.forge.plugin.idea.ui.CommandListPopup; /** * Creates a popup list and displays all the currently registered * {@link UICommand} instances * * @author <a href="mailto:ggastald@redhat.com">George Gastaldi</a> * @author Adam Wyłuda */ public class ShowCommandListAction extends AnAction { @Override public void actionPerformed(AnActionEvent event) { if (CommandListPopup.isActive()) { return; } VirtualFile[] files = event.getData(DataKeys.VIRTUAL_FILE_ARRAY); // If no file is selected, then set project directory as selection if (files == null || files.length == 0) { files = new VirtualFile[]{event.getData(DataKeys.PROJECT_FILE_DIRECTORY)}; } final VirtualFile[] selectedFiles = files; ServiceHelper.loadFurnaceAndRun(new Runnable() { @Override public void run() { UIContext uiContext = UIContextFactory.create(selectedFiles); CommandListPopup popup = new CommandListPopup(uiContext); popup.show(); } }); } }
src/main/java/org/jboss/forge/plugin/idea/action/ShowCommandListAction.java
/* * Copyright 2014 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.plugin.idea.action; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.vfs.VirtualFile; import org.jboss.forge.addon.ui.command.UICommand; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.plugin.idea.context.UIContextFactory; import org.jboss.forge.plugin.idea.service.ServiceHelper; import org.jboss.forge.plugin.idea.ui.CommandListPopup; /** * Creates a popup list and displays all the currently registered * {@link UICommand} instances * * @author <a href="mailto:ggastald@redhat.com">George Gastaldi</a> * @author Adam Wyłuda */ public class ShowCommandListAction extends AnAction { @Override public void actionPerformed(AnActionEvent event) { if (CommandListPopup.isActive()) { return; } final VirtualFile[] files = event.getData(DataKeys.VIRTUAL_FILE_ARRAY); ServiceHelper.loadFurnaceAndRun(new Runnable() { @Override public void run() { UIContext uiContext = UIContextFactory.create(files); CommandListPopup popup = new CommandListPopup(uiContext); popup.show(); } }); } }
Add project directory to UISelection when no file is selected in IDE
src/main/java/org/jboss/forge/plugin/idea/action/ShowCommandListAction.java
Add project directory to UISelection when no file is selected in IDE
Java
mpl-2.0
5095b73db9fe7f1552ef063e954f578ec55cdcca
0
yonadev/yona-app-android,yonadev/yona-app-android,yonadev/yona-app-android,yonadev/yona-app-android
/* * Copyright (c) 2016 Stichting Yona Foundation * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * */ package nu.yona.app.api.manager.network; import nu.yona.app.YonaApplication; import nu.yona.app.api.model.OTPVerficationCode; import nu.yona.app.api.model.PinResetDelay; import nu.yona.app.api.model.RegisterUser; import nu.yona.app.api.model.User; import nu.yona.app.listener.DataLoadListener; import nu.yona.app.utils.AppUtils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by kinnarvasa on 28/03/16. */ public class AuthenticateNetworkImpl extends BaseImpl { /** * Register user. * * @param url the url * @param password the password * @param object the object * @param isEditMode the is edit mode * @param listener the listener */ public void registerUser(String url, String password, RegisterUser object, boolean isEditMode, final DataLoadListener listener) { try { if (!isEditMode) { getRestApi().registerUser(password, localLanguage, object).enqueue(getUserCallBack(listener)); } else { getRestApi().updateRegisterUser(url, password, localLanguage, object).enqueue(getUserCallBack(listener)); } } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } public void registerUser(String url, String password, RegisterUser object, DataLoadListener listener) { try { getRestApi().registerUser(url, password, localLanguage, object).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Register user override. * * @param password Yona Password * @param object RegisterUser object * @param otp SMS * @param listener the listener */ public void registerUserOverride(String password, RegisterUser object, String otp, final DataLoadListener listener) { try { getRestApi().overrideRegisterUser(password, localLanguage, otp, object).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Gets user. * * @param url url from user object to get/update user * @param yonaPassword yona password * @param listener the listener */ public void getUser(String url, String yonaPassword, DataLoadListener listener) { try { getRestApi().getUser(url, yonaPassword, localLanguage).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Verify mobile number. * * @param password yona password * @param url url for verify mobile number * @param otp sms verification code * @param listener the listener */ public void verifyMobileNumber(String password, String url, OTPVerficationCode otp, final DataLoadListener listener) { try { getRestApi().verifyMobileNumber(url, password, localLanguage, otp).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Resend otp. * * @param url url to resend sms * @param password yona password * @param listener the listener */ public void resendOTP(String url, String password, final DataLoadListener listener) { try { getRestApi().resendOTP(url, password, localLanguage).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Request user override. * * @param mobileNumber Registering mobile number * @param listener the listener */ public void requestUserOverride(String mobileNumber, DataLoadListener listener) { try { getRestApi().requestUserOverride(localLanguage, mobileNumber).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Delete user. * * @param url the url * @param yonaPassword the yona password * @param listener the listener */ public void deleteUser(String url, String yonaPassword, DataLoadListener listener) { try { getRestApi().deleteUser(url, yonaPassword, localLanguage).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Do passcode reset. * * @param url : URL for passcode reset * @param yonaPassword : Yona password * @param listener the listener */ public void doPasscodeReset(String url, String yonaPassword, final DataLoadListener listener) { try { getRestApi().requestPinReset(url, yonaPassword, localLanguage).enqueue(new Callback<PinResetDelay>() { @Override public void onResponse(Call<PinResetDelay> call, Response<PinResetDelay> response) { if (response.code() < NetworkConstant.RESPONSE_STATUS) { listener.onDataLoad(response.body()); } else { onError(response, listener); } } @Override public void onFailure(Call<PinResetDelay> call, Throwable t) { onError(t, listener); } }); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Do verify pin. * * @param url URL for verify pin * @param otp SMS received value * @param listener the listener */ public void doVerifyPin(String url, String otp, final DataLoadListener listener) { try { getRestApi().verifyPin(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), localLanguage, new OTPVerficationCode(otp)).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Do clear pin. * * @param url URL for Verify Pin Reset */ public void doClearPin(String url) { try { getRestApi().clearPin(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), localLanguage).enqueue(getCall(new DataLoadListener() { @Override public void onDataLoad(Object result) { // Do nothing as we don't worry about this response. } @Override public void onError(Object errorMessage) { // Do nothing as we don't worry about this response. } })); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } private Callback<User> getUserCallBack(final DataLoadListener listener) { return new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.code() < NetworkConstant.RESPONSE_STATUS) { listener.onDataLoad(response.body()); } else { onError(response, listener); } } @Override public void onFailure(Call<User> call, Throwable t) { onError(t, listener); } }; } }
app/src/main/java/nu/yona/app/api/manager/network/AuthenticateNetworkImpl.java
/* * Copyright (c) 2016 Stichting Yona Foundation * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * */ package nu.yona.app.api.manager.network; import nu.yona.app.YonaApplication; import nu.yona.app.api.model.OTPVerficationCode; import nu.yona.app.api.model.PinResetDelay; import nu.yona.app.api.model.RegisterUser; import nu.yona.app.api.model.User; import nu.yona.app.listener.DataLoadListener; import nu.yona.app.utils.AppUtils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by kinnarvasa on 28/03/16. */ public class AuthenticateNetworkImpl extends BaseImpl { /** * Register user. * * @param url the url * @param password the password * @param object the object * @param isEditMode the is edit mode * @param listener the listener */ public void registerUser(String url, String password, RegisterUser object, boolean isEditMode, final DataLoadListener listener) { try { if (!isEditMode) { getRestApi().registerUser(password, localLanguage, object).enqueue(getUserCallBack(listener)); } else { getRestApi().updateRegisterUser(url, password, localLanguage, object).enqueue(getUserCallBack(listener)); } } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } public void registerUser(String url, String password, RegisterUser object, DataLoadListener listener) { try { getRestApi().registerUser(url, password, object).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Register user override. * * @param password Yona Password * @param object RegisterUser object * @param otp SMS * @param listener the listener */ public void registerUserOverride(String password, RegisterUser object, String otp, final DataLoadListener listener) { try { getRestApi().overrideRegisterUser(password, localLanguage, otp, object).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Gets user. * * @param url url from user object to get/update user * @param yonaPassword yona password * @param listener the listener */ public void getUser(String url, String yonaPassword, DataLoadListener listener) { try { getRestApi().getUser(url, yonaPassword, localLanguage).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Verify mobile number. * * @param password yona password * @param url url for verify mobile number * @param otp sms verification code * @param listener the listener */ public void verifyMobileNumber(String password, String url, OTPVerficationCode otp, final DataLoadListener listener) { try { getRestApi().verifyMobileNumber(url, password, localLanguage, otp).enqueue(getUserCallBack(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Resend otp. * * @param url url to resend sms * @param password yona password * @param listener the listener */ public void resendOTP(String url, String password, final DataLoadListener listener) { try { getRestApi().resendOTP(url, password, localLanguage).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Request user override. * * @param mobileNumber Registering mobile number * @param listener the listener */ public void requestUserOverride(String mobileNumber, DataLoadListener listener) { try { getRestApi().requestUserOverride(mobileNumber, localLanguage).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Delete user. * * @param url the url * @param yonaPassword the yona password * @param listener the listener */ public void deleteUser(String url, String yonaPassword, DataLoadListener listener) { try { getRestApi().deleteUser(url, yonaPassword, localLanguage).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Do passcode reset. * * @param url : URL for passcode reset * @param yonaPassword : Yona password * @param listener the listener */ public void doPasscodeReset(String url, String yonaPassword, final DataLoadListener listener) { try { getRestApi().requestPinReset(url, yonaPassword, localLanguage).enqueue(new Callback<PinResetDelay>() { @Override public void onResponse(Call<PinResetDelay> call, Response<PinResetDelay> response) { if (response.code() < NetworkConstant.RESPONSE_STATUS) { listener.onDataLoad(response.body()); } else { onError(response, listener); } } @Override public void onFailure(Call<PinResetDelay> call, Throwable t) { onError(t, listener); } }); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Do verify pin. * * @param url URL for verify pin * @param otp SMS received value * @param listener the listener */ public void doVerifyPin(String url, String otp, final DataLoadListener listener) { try { getRestApi().verifyPin(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), localLanguage, new OTPVerficationCode(otp)).enqueue(getCall(listener)); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } /** * Do clear pin. * * @param url URL for Verify Pin Reset */ public void doClearPin(String url) { try { getRestApi().clearPin(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), localLanguage).enqueue(getCall(new DataLoadListener() { @Override public void onDataLoad(Object result) { // Do nothing as we don't worry about this response. } @Override public void onError(Object errorMessage) { // Do nothing as we don't worry about this response. } })); } catch (Exception e) { AppUtils.throwException(AuthenticateNetworkImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } private Callback<User> getUserCallBack(final DataLoadListener listener) { return new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.code() < NetworkConstant.RESPONSE_STATUS) { listener.onDataLoad(response.body()); } else { onError(response, listener); } } @Override public void onFailure(Call<User> call, Throwable t) { onError(t, listener); } }; } }
Language translation argument changes Language translation argument changes Signed-off-by: Kinnar Vasa <7e1ed76899879a0d8732c30e94b9e94691b30172@mobiquityinc.com>
app/src/main/java/nu/yona/app/api/manager/network/AuthenticateNetworkImpl.java
Language translation argument changes
Java
lgpl-2.1
7f988e84161baa456b9d170e198342b7bf10f179
0
it-tavis/opencms-core,victos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,MenZil/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,alkacon/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,gallardo/opencms-core,gallardo/opencms-core,gallardo/opencms-core,serrapos/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,serrapos/opencms-core,victos/opencms-core,alkacon/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,victos/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,victos/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,MenZil/opencms-core
package com.opencms.template; /* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/template/Attic/CmsXmlTemplate.java,v $ * Date : $Date: 2001/01/02 16:46:01 $ * Version: $Revision: 1.45 $ * * Copyright (C) 2000 The OpenCms Group * * This File is part of OpenCms - * the Open Source Content Mananagement System * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.com * * You should have received a copy of the GNU General Public License * long with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.util.*; import java.io.*; import com.opencms.launcher.*; import com.opencms.file.*; import com.opencms.util.*; import com.opencms.core.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.servlet.http.*; /** * Template class for displaying the processed contents of hierachical XML template files * that can include other subtemplates. * * @author Alexander Lucas * @version $Revision: 1.45 $ $Date: 2001/01/02 16:46:01 $ */ public class CmsXmlTemplate implements I_CmsConstants, I_CmsXmlTemplate, I_CmsLogChannels { public static final String C_FRAME_SELECTOR = "cmsframe"; /** name of the special body element */ public final static String C_BODY_ELEMENT = "body"; /** Boolean for additional debug output control */ public final static boolean C_DEBUG = false; /** Error string to be inserted for corrupt subtemplates for guest user requests. */ private final static String C_ERRORTEXT = "ERROR!"; /** * Template cache for storing cacheable results of the subtemplates. */ protected static com.opencms.launcher.I_CmsTemplateCache m_cache = null; /** * For debugging purposes only. * Counts the number of re-uses od the instance of this class. */ private int counter = 0; /** * For debugging purposes only. * Increments the class variable <code>counter</code> and * prints out its new value.. * <P> * May be called from the template file using * <code>&lt;METHOD name="counter"&gt;</code>. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object the initiating XLM document. * @param userObj Hashtable with parameters. * @return Actual value of <code>counter</code>. */ public Integer counter(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { counter++; return new Integer(counter); } /** * Help method to print nice classnames in error messages * @return class name in [ClassName] format */ protected String getClassName() { String name = getClass().getName(); return "[" + name.substring(name.lastIndexOf(".") + 1) + "] "; } /** * Gets the content of a given template file and its subtemplates * with the given parameters. The default section in the template file * will be used. * <P> * Parameters are stored in a hashtable and can derive from * <UL> * <LI>Template file of the parent template</LI> * <LI>Body file clicked by the user</LI> * <LI>URL parameters</LI> * </UL> * Paramter names must be in "elementName.parameterName" format. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template * @param parameters Hashtable with all template class parameters. * @return Content of the template and all subtemplates. * @exception CmsException */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters) throws CmsException { return getContent(cms, templateFile, elementName, parameters, null); } /** * Gets the content of a defined section in a given template file and its subtemplates * with the given parameters. * * @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters) * @param cms CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { if(C_DEBUG && A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] getting content of element " + ((elementName==null)?"<root>":elementName)); A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] template file is: " + templateFile); A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] selected template section is: " + ((templateSelector==null)?"<default>":templateSelector)); } CmsXmlTemplateFile xmlTemplateDocument = getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); if(templateSelector==null || "".equals(templateSelector)) { templateSelector = (String)parameters.get(C_FRAME_SELECTOR); } return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector); } /** * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getFileUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return cms.getRequestContext().getFileUri().getBytes(); } /** * Gets the QueryString for CmsFrameTemplates. * <P> * This method can be called using <code>&lt;METHOD name="getCmsQueryString"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getFrameQueryString(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String query = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getQueryString(); String frame="", param=""; if (!tagcontent.equals("")) { if (!tagcontent.startsWith("&")) { if (tagcontent.indexOf(",")!=-1) { frame=tagcontent.substring(0,tagcontent.indexOf(",")); param=tagcontent.substring(tagcontent.indexOf(",")+1); } else { frame=tagcontent; } } else { param=tagcontent; } } StringBuffer encQuery = new StringBuffer(); boolean notfirst = false; if(query != null) { // Fine. A lasturl parameter was found in session or parameter hashtable. // Check, if the URL parameters of the last url have to be encoded. int asteriskIdx = query.indexOf("?"); if(asteriskIdx > -1 && (asteriskIdx < (query.length()-1))) { // In fact, there are URL parameters encQuery.append(query.substring(0, asteriskIdx + 1)); String queryString = query.substring(asteriskIdx + 1); StringTokenizer st = new StringTokenizer(queryString, "&"); while(st.hasMoreTokens()) { // Loop through all URL parameters String currToken = st.nextToken(); if(currToken != null && !"".equals(currToken)) { // Look for the "=" character to divide parameter name and value int idx = currToken.indexOf("="); if(notfirst) { encQuery.append("&"); } else { notfirst = true; } if(idx > -1) { // A parameter name/value pair was found. // Encode the parameter value and write back! String key = currToken.substring(0,idx); String value = (idx < (currToken.length()-1))?currToken.substring(idx+1):""; encQuery.append(key); encQuery.append("="); encQuery.append(Encoder.escape(value)); } else { // Something strange happened. // Maybe a parameter without "=" ? // Write back without encoding! encQuery.append(currToken); } } } query = encQuery.toString(); } } query=(query==null?"":query); if(!query.equals("")) { if (query.indexOf("cmsframe=")!=-1) { int start=query.indexOf("cmsframe="); int end=query.indexOf("&",start); String cmsframe=""; if (end!=-1) { cmsframe=query.substring(start+9,end); } else { cmsframe=query.substring(start+9); } if (!cmsframe.equals("plain")) { if (!frame.equals("")){ if (end!=-1) { query=query.substring(0,start+9)+frame+query.substring(end); } else { query=query.substring(0,start+9)+frame; } } else { if (end!=-1) { query=query.substring(0,start)+query.substring(end+1); } else { query=query.substring(0,start); } } } } else { if (!tagcontent.equals("")){ query=query+"&cmsframe="+frame; } } if (!query.equals("")) { query = "?" + query; } } else { if (!frame.equals("")){ query = "?cmsframe="+frame; } } if(!query.equals("")) { query=query+param; } else { query="?"+param.substring(param.indexOf("&")+1); } return query; } /** * Gets the target for a link. * <P> * This method can be called using <code>&lt;METHOD name="getCmsFrame"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getFrameTarget(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String target=""; String cmsframe=(String)((Hashtable)userObject).get("cmsframe"); cmsframe=(cmsframe==null?"":cmsframe); if (cmsframe.equals("plain")) { target=""; } else { if (tagcontent.equals("")) { target="target=_top"; } else { target="target="+tagcontent; } } return target; } /** * Gets the key that should be used to cache the results of * <EM>this</EM> template class. * <P> * Since our results may depend on the used template file, * the parameters and the requested body document, we must * build a complex key using this three arguments. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return key that can be used for caching */ public Object getKey(CmsObject cms, String templateFile, Hashtable parameters, String templateSelector) { //Vector v = new Vector(); CmsRequestContext reqContext = cms.getRequestContext(); //v.addElement(reqContext.currentProject().getName()); //v.addElement(reqContext.getUri()); //v.addElement(templateFile); //v.addElement(parameters); //v.addElement(templateSelector); //return v; String result = "" + reqContext.currentProject().getId() + ":" + reqContext.currentUser().getName() + reqContext.getUri() + templateFile; Enumeration keys = parameters.keys(); while(keys.hasMoreElements()) { String key = (String)keys.nextElement(); result = result + key + parameters.get(key); } result = result + templateSelector; return result; } /** * Reads in the template file and starts the XML parser for the expected * content type. * <P> * Every extending class using not CmsXmlTemplateFile as content type, * but any derived type should override this method. * * @param cms CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public CmsXmlTemplateFile getOwnTemplateFile(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { CmsXmlTemplateFile xmlTemplateDocument = new CmsXmlTemplateFile(cms, templateFile); return xmlTemplateDocument; } /** * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getPathUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String path=cms.getRequestContext().getUri(); path=path.substring(0,path.lastIndexOf("/")+1); path=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath()+path; return path.getBytes(); } /** * Inserts the correct servlet path title into the template. * <P> * This method can be called using <code>&lt;METHOD name="getTitle"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getQueryString(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String query = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getQueryString(); if(query != null && !"".equals(query)) { query = "?" + query; } return query; } /** * Get the IP address of the current request. * <P> * This method can be called using <code>&lt;METHOD name="getRequestIp"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public String getRequestIp(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getRemoteAddr(); } /** * Inserts the correct servlet path title into the template. * <P> * This method can be called using <code>&lt;METHOD name="getTitle"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getServletPath(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath() + "/"; } /** * Get the session id. If no session exists, a new one will be created. * <P> * This method can be called using <code>&lt;METHOD name="getSessionId"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public String getSessionId(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true).getId(); } /** * Inserts the correct stylesheet into the layout template. * <P> * This method can be called using <code>&lt;METHOD name="getStylesheet"&gt;</code> * in the template file. * <P> * When using this method follwing parameters should be defined * either in the page file or in the template file: * <ul> * <li><code>root.stylesheet-ie</code></li> * <li><code>root.stylesheet-ns</code></li> * </ul> * These parameters should contain the correct OpenCms path * for the Internet Explorer and Netscape Navigate * specific stylesheets. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public String getStylesheet(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { CmsXmlTemplateFile templateFile = (CmsXmlTemplateFile)doc; // Get the styles from the parameter hashtable String styleIE = null; String styleNS = null; if(templateFile.hasData("stylesheet-ie")) { styleIE = templateFile.getDataValue("stylesheet-ie"); } else if(templateFile.hasData("stylesheet")) { styleIE = templateFile.getDataValue("stylesheet"); } else { styleIE = ""; } if(templateFile.hasData("stylesheet-ns")) { styleNS = templateFile.getDataValue("stylesheet-ns"); } else if(templateFile.hasData("stylesheet")) { styleNS = templateFile.getDataValue("stylesheet"); } else { styleNS = ""; } HttpServletRequest orgReq = (HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest(); String servletPath = orgReq.getServletPath() + "/"; // Get the user's browser String browser = orgReq.getHeader("user-agent"); if(browser == null) { // the browser is unknown - return the ns-style return styleNS; } if(browser.indexOf("MSIE") >-1) { return servletPath + styleIE; } else { return servletPath + styleNS; } } /** * Find the corresponding template class to be loaded. * this should be defined in the template file of the parent * template and can be overwritten in the body file. * * @param elementName Element name of this template in our parent template. * @param doc CmsXmlTemplateFile object of our template file including a subtemplate. * @param parameters Hashtable with all template class parameters. * @return Name of the class that should generate the output for the included template file. */ protected String getTemplateClassName(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException { String result = null; if(parameters.containsKey(elementName + "._CLASS_")) { result = (String)parameters.get(elementName + "._CLASS_"); } else { if(doc.hasSubtemplateClass(elementName)) { result = doc.getSubtemplateClass(elementName); } else { // Fallback to "body" element if(parameters.containsKey("body._CLASS_")) { result = (String)parameters.get("body._CLASS_"); } } } return result; } /** * Find the corresponding template file to be loaded by the template class. * this should be defined in the template file of the parent * template and can be overwritten in the body file. * * @param elementName Element name of this template in our parent template. * @param doc CmsXmlTemplateFile object of our template file including a subtemplate. * @param parameters Hashtable with all template class parameters. * @return Name of the template file that should be included. */ protected String getTemplateFileName(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException { String result = null; if(parameters.containsKey(elementName + "._TEMPLATE_")) { result = (String)parameters.get(elementName + "._TEMPLATE_"); } else { if(doc.hasSubtemplateFilename(elementName)) { result = doc.getSubtemplateFilename(elementName); } else { // Fallback to "body" element if(parameters.containsKey("body._TEMPLATE_")) { result = (String)parameters.get("body._TEMPLATE_"); } } } //System.err.println("returning template file name for Element " + elementName + " in File " + doc + ": " + result); return result; } /** * Find the corresponding template selector to be activated. * This may be defined in the template file of the parent * template and can be overwritten in the body file. * * @param elementName Element name of this template in our parent template. * @param doc CmsXmlTemplateFile object of our template file including a subtemplate. * @param parameters Hashtable with all template class parameters. * @return Name of the class that should generate the output for the included template file. */ protected String getTemplateSelector(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException { if(parameters.containsKey(elementName + "._TEMPLATESELECTOR_")) { return (String)parameters.get(elementName + "._TEMPLATESELECTOR_"); } else if (doc.hasSubtemplateSelector(elementName)) { return doc.getSubtemplateSelector(elementName); } else { return null; } } /** * Inserts the correct document title into the template. * <P> * This method can be called using <code>&lt;METHOD name="getTitle"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getTitle(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String requestedUri = cms.getRequestContext().getUri(); String title = cms.readProperty(requestedUri, C_PROPERTY_TITLE); if(title == null) { title = ""; } return title; } /** * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return (((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath() + cms.getRequestContext().getUri()).getBytes(); } /** * Indicates if the results of this class are cacheable. * <P> * Checks if the templateCache is set and if all subtemplates * are cacheable. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { boolean cacheable; try { if (!cms.getRequestContext().currentProject().equals(cms.onlineProject())) { // never cache offline-resources return false; } else { if (templateSelector == null || "".equals(templateSelector)) { templateSelector = (String) parameters.get(C_FRAME_SELECTOR); } cacheable = ((m_cache != null) && subtemplatesCacheable(cms, templateFile, elementName, parameters, templateSelector)); if (C_DEBUG && A_OpenCms.isLogging()) { String errorMessage = getClassName() + "Template class " + getClass().getName() + " with file " + templateFile + " is "; if (cacheable) { errorMessage = errorMessage + "cacheable."; } else { errorMessage = errorMessage + "not cacheable."; } A_OpenCms.log(C_OPENCMS_DEBUG, errorMessage); } } } catch (CmsException exc) { // there was an exception => don't cache this res. cacheable = false; } return cacheable; } /** * Tests, if the template cache is setted. * @return <code>true</code> if setted, <code>false</code> otherwise. */ public final boolean isTemplateCacheSet() { return m_cache != null; } /** * For debugging purposes only. * Prints out all parameters. * <P> * May be called from the template file using * <code>&lt;METHOD name="parameters"&gt;</code>. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object the initiating XLM document. * @param userObj Hashtable with parameters. * @return Debugging information about all parameters. */ public String parameters(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) { Hashtable param = (Hashtable)userObject; Enumeration keys = param.keys(); String s = ""; while(keys.hasMoreElements()) { String key = (String)keys.nextElement(); s = s + "<B>" + key + "</B>: " + param.get(key) + "<BR>"; } s = s + "<B>" + tagcontent + "</B><BR>"; return s; } /** * Set the instance of template cache that should be used to store * cacheable results of the subtemplates. * If the template cache is not set, caching will be disabled. * @param c Template cache to be used. */ public final void setTemplateCache(I_CmsTemplateCache c) { m_cache = c; } /** * Indicates if a previous cached result should be reloaded. * <P> * <em>not implemented.</em> Returns always <code>false</code>. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <code>false</code> */ public boolean shouldReload(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Starts the processing of the given template file by calling the * <code>getProcessedTemplateContent()</code> method of the content defintition * of the corresponding content type. * <P> * Any exceptions thrown while processing the template will be caught, * printed and and thrown again. * * @param cms CmsObject Object for accessing system resources. * @param xmlTemplateDocument XML parsed document of the content type "XML template file" or * any derived content type. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return Content of the template and all subtemplates. * @exception CmsException */ protected byte[] startProcessing(CmsObject cms, CmsXmlTemplateFile xmlTemplateDocument, String elementName, Hashtable parameters, String templateSelector) throws CmsException { String result = null; // Try to process the template file try { result = xmlTemplateDocument.getProcessedTemplateContent(this, parameters, templateSelector); } catch(Throwable e) { // There were errors while generating output for this template. // Clear HTML cache and then throw exception again xmlTemplateDocument.removeFromFileCache(); if(isCacheable(cms, xmlTemplateDocument.getAbsoluteFilename(), elementName, parameters, templateSelector)) { m_cache.clearCache(getKey(cms, xmlTemplateDocument.getAbsoluteFilename(), parameters, templateSelector)); } if(e instanceof CmsException) { throw (CmsException)e; } else { // under normal cirumstances, this should not happen. // any exception should be caught earlier and replaced by // corresponding CmsExceptions. String errorMessage = "Exception while getting content for (sub)template " + elementName + ". " + e; if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); } throw new CmsException(errorMessage); } } return result.getBytes(); } /** * Checks if all subtemplates are cacheable. * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <code>true</code> if all subtemplates are cacheable, <code>false</code> otherwise. */ public boolean subtemplatesCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { boolean cacheable = true; CmsXmlTemplateFile doc = null; Vector subtemplates = null; try { doc = this.getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); doc.init(cms, templateFile); subtemplates = doc.getAllSubElements(templateSelector); } catch(Exception e) { System.err.println(e); return false; } int numSubtemplates = subtemplates.size(); for(int i=0; i<numSubtemplates; i++) { String elName = (String)subtemplates.elementAt(i); String className = null; String templateName = null; try { className = getTemplateClassName(elName, doc, parameters); templateName = getTemplateFileName(elName, doc, parameters); } catch(CmsException e) { // There was an error while reading the class name or template name // from the subtemplate. // So we cannot determine the cacheability. if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + "Could not determine cacheability of subelement " + elName + " in template file " + doc.getFilename() + ". There were missing datablocks."); } return false; } try { I_CmsTemplate templClass = (I_CmsTemplate)CmsTemplateClassManager.getClassInstance(cms, className); cacheable = cacheable && templClass.isCacheable(cms, templateName, elName, parameters, null); } catch(Exception e) { System.err.println("E: " + e); } } return cacheable; } /** * Handles any occurence of an <code>&lt;ELEMENT&gt;</code> tag. * <P> * Every XML template class should use CmsXmlTemplateFile as * the interface to the XML file. Since CmsXmlTemplateFile is * an extension of A_CmsXmlContent by the additional tag * <code>&lt;ELEMENT&gt;</code> this user method ist mandatory. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object templateElement(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { // Our own template file that wants to include a subelement CmsXmlTemplateFile templateFile = (CmsXmlTemplateFile)doc; // Indicates, if this is a request of a guest user. Needed for error outputs. boolean isAnonymousUser = cms.anonymousUser().equals(cms.getRequestContext().currentUser()); // First create a copy of the parameter hashtable Hashtable parameterHashtable = (Hashtable)((Hashtable)userObject).clone(); // Name of the template class that should be used to handle the subtemplate String templateClass = getTemplateClassName(tagcontent, templateFile, parameterHashtable); // Name of the subtemplate file. String templateFilename = getTemplateFileName(tagcontent, templateFile, parameterHashtable); // Name of the subtemplate template selector String templateSelector = getTemplateSelector(tagcontent, templateFile, parameterHashtable); // Results returned by the subtemplate class byte[] result = null; // Temporary object for loading the subtemplate class Object loadedObject = null; // subtemplate class to be used for the include I_CmsTemplate subTemplate = null; // Key for the cache Object subTemplateKey = null; // try to load the subtemplate class try { loadedObject = CmsTemplateClassManager.getClassInstance(cms, templateClass); } catch(CmsException e) { // There was an error. First remove the template file from the file cache templateFile.removeFromFileCache(); if(isAnonymousUser) { // The current user is the anonymous user return C_ERRORTEXT; } else { // The current user is a system user, so we throw the exception again. throw e; } } // Check if the loaded object is really an instance of an OpenCms template class if(! (loadedObject instanceof I_CmsTemplate)) { String errorMessage = "Class " + templateClass + " is no OpenCms template class."; if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsXmlTemplate] " + errorMessage); } throw new CmsException(errorMessage, CmsException.C_XML_NO_TEMPLATE_CLASS); } subTemplate = (I_CmsTemplate)loadedObject; // Template class is now loaded. Next try to read the parameters Vector parameterTags = null; parameterTags = templateFile.getParameterNames(tagcontent); if(parameterTags != null) { int numParameterTags = parameterTags.size(); for(int i=0; i< numParameterTags; i++) { String paramName = (String)parameterTags.elementAt(i); String paramValue = templateFile.getParameter(tagcontent, paramName); if(! parameterHashtable.containsKey(paramName)) { parameterHashtable.put(tagcontent + "." + paramName, paramValue); } } } // all parameters are now parsed. Finally give the own subelement name // as parameter // TODO: replace _ELEMENT_ by a constant parameterHashtable.put("_ELEMENT_", tagcontent); // Try to get the result from the cache if(subTemplate.isCacheable(cms, templateFilename, tagcontent, parameterHashtable, null)) { subTemplateKey = subTemplate.getKey(cms, templateFilename, parameterHashtable, null); if(m_cache.has(subTemplateKey) && (! subTemplate.shouldReload(cms, templateFilename, tagcontent, parameterHashtable, null))) { result = m_cache.get(subTemplateKey); } } // OK. let's call the subtemplate if(result == null) { try { result = subTemplate.getContent(cms, templateFilename, tagcontent, parameterHashtable, templateSelector); } catch (Exception e) { // Oh, oh.. // There were errors while getting the content of the subtemplate if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Could not generate output for template file \"" + templateFilename + "\" included as element \"" + tagcontent + "\"."); A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + e); } // The anonymous user gets an error String instead of an exception if(isAnonymousUser) { return C_ERRORTEXT; } else { if(e instanceof CmsException) { throw (CmsException)e; } else { e.printStackTrace(); throw new CmsException("Error while executing getContent for subtemplate \"" + tagcontent + "\". " + e); } } } // Store the results in the template cache, if cacheable if(subTemplate.isCacheable(cms, templateFilename, tagcontent, parameterHashtable, null)) { // we don't need to re-get the caching-key here since it already exists m_cache.put(subTemplateKey, result); } } return result; } /** * Help method that handles any occuring error by writing * an error message to the OpenCms logfile and throwing a * CmsException of the type "unknown". * @param errorMessage String with the error message to be printed. * @exception CmsException */ protected void throwException(String errorMessage) throws CmsException { throwException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION); } /** * Help method that handles any occuring error by writing * an error message to the OpenCms logfile and throwing a * CmsException of the given type. * @param errorMessage String with the error message to be printed. * @param type Type of the exception to be thrown. * @exception CmsException */ protected void throwException(String errorMessage, int type) throws CmsException { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); } throw new CmsException(errorMessage, type); } /** * Help method that handles any occuring error by writing * an error message to the OpenCms logfile and re-throwing a * caught exception. * @param errorMessage String with the error message to be printed. * @param e Exception to be re-thrown. * @exception CmsException */ protected void throwException(String errorMessage, Exception e) throws CmsException { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Exception: " + e); } if(e instanceof CmsException) { throw (CmsException)e; } else { throw new CmsException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION, e); } } }
src/com/opencms/template/CmsXmlTemplate.java
package com.opencms.template; /* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/template/Attic/CmsXmlTemplate.java,v $ * Date : $Date: 2000/12/22 17:31:21 $ * Version: $Revision: 1.44 $ * * Copyright (C) 2000 The OpenCms Group * * This File is part of OpenCms - * the Open Source Content Mananagement System * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.com * * You should have received a copy of the GNU General Public License * long with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.util.*; import java.io.*; import com.opencms.launcher.*; import com.opencms.file.*; import com.opencms.util.*; import com.opencms.core.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.servlet.http.*; /** * Template class for displaying the processed contents of hierachical XML template files * that can include other subtemplates. * * @author Alexander Lucas * @version $Revision: 1.44 $ $Date: 2000/12/22 17:31:21 $ */ public class CmsXmlTemplate implements I_CmsConstants, I_CmsXmlTemplate, I_CmsLogChannels { public static final String C_FRAME_SELECTOR = "cmsframe"; /** name of the special body element */ public final static String C_BODY_ELEMENT = "body"; /** Boolean for additional debug output control */ public final static boolean C_DEBUG = false; /** Error string to be inserted for corrupt subtemplates for guest user requests. */ private final static String C_ERRORTEXT = "ERROR!"; /** * Template cache for storing cacheable results of the subtemplates. */ protected static com.opencms.launcher.I_CmsTemplateCache m_cache = null; /** * For debugging purposes only. * Counts the number of re-uses od the instance of this class. */ private int counter = 0; /** * For debugging purposes only. * Increments the class variable <code>counter</code> and * prints out its new value.. * <P> * May be called from the template file using * <code>&lt;METHOD name="counter"&gt;</code>. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object the initiating XLM document. * @param userObj Hashtable with parameters. * @return Actual value of <code>counter</code>. */ public Integer counter(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { counter++; return new Integer(counter); } /** * Help method to print nice classnames in error messages * @return class name in [ClassName] format */ protected String getClassName() { String name = getClass().getName(); return "[" + name.substring(name.lastIndexOf(".") + 1) + "] "; } /** * Gets the content of a given template file and its subtemplates * with the given parameters. The default section in the template file * will be used. * <P> * Parameters are stored in a hashtable and can derive from * <UL> * <LI>Template file of the parent template</LI> * <LI>Body file clicked by the user</LI> * <LI>URL parameters</LI> * </UL> * Paramter names must be in "elementName.parameterName" format. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template * @param parameters Hashtable with all template class parameters. * @return Content of the template and all subtemplates. * @exception CmsException */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters) throws CmsException { return getContent(cms, templateFile, elementName, parameters, null); } /** * Gets the content of a defined section in a given template file and its subtemplates * with the given parameters. * * @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters) * @param cms CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { if(C_DEBUG && A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] getting content of element " + ((elementName==null)?"<root>":elementName)); A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] template file is: " + templateFile); A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] selected template section is: " + ((templateSelector==null)?"<default>":templateSelector)); } CmsXmlTemplateFile xmlTemplateDocument = getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); if(templateSelector==null || "".equals(templateSelector)) { templateSelector = (String)parameters.get(C_FRAME_SELECTOR); } return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector); } /** * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getFileUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return cms.getRequestContext().getFileUri().getBytes(); } /** * Gets the QueryString for CmsFrameTemplates. * <P> * This method can be called using <code>&lt;METHOD name="getCmsQueryString"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getFrameQueryString(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String query = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getQueryString(); String frame="", param=""; if (!tagcontent.equals("")) { if (!tagcontent.startsWith("&")) { if (tagcontent.indexOf(",")!=-1) { frame=tagcontent.substring(0,tagcontent.indexOf(",")); param=tagcontent.substring(tagcontent.indexOf(",")+1); } else { frame=tagcontent; } } else { param=tagcontent; } } StringBuffer encQuery = new StringBuffer(); boolean notfirst = false; if(query != null) { // Fine. A lasturl parameter was found in session or parameter hashtable. // Check, if the URL parameters of the last url have to be encoded. int asteriskIdx = query.indexOf("?"); if(asteriskIdx > -1 && (asteriskIdx < (query.length()-1))) { // In fact, there are URL parameters encQuery.append(query.substring(0, asteriskIdx + 1)); String queryString = query.substring(asteriskIdx + 1); StringTokenizer st = new StringTokenizer(queryString, "&"); while(st.hasMoreTokens()) { // Loop through all URL parameters String currToken = st.nextToken(); if(currToken != null && !"".equals(currToken)) { // Look for the "=" character to divide parameter name and value int idx = currToken.indexOf("="); if(notfirst) { encQuery.append("&"); } else { notfirst = true; } if(idx > -1) { // A parameter name/value pair was found. // Encode the parameter value and write back! String key = currToken.substring(0,idx); String value = (idx < (currToken.length()-1))?currToken.substring(idx+1):""; encQuery.append(key); encQuery.append("="); encQuery.append(Encoder.escape(value)); } else { // Something strange happened. // Maybe a parameter without "=" ? // Write back without encoding! encQuery.append(currToken); } } } query = encQuery.toString(); } } query=(query==null?"":query); if(!query.equals("")) { if (query.indexOf("cmsframe=")!=-1) { int start=query.indexOf("cmsframe="); int end=query.indexOf("&",start); String cmsframe=""; if (end!=-1) { cmsframe=query.substring(start+9,end); } else { cmsframe=query.substring(start+9); } if (!cmsframe.equals("plain")) { if (!frame.equals("")){ if (end!=-1) { query=query.substring(0,start+9)+frame+query.substring(end); } else { query=query.substring(0,start+9)+frame; } } else { if (end!=-1) { query=query.substring(0,start)+query.substring(end+1); } else { query=query.substring(0,start); } } } } else { if (!tagcontent.equals("")){ query=query+"&cmsframe="+frame; } } if (!query.equals("")) { query = "?" + query; } } else { if (!frame.equals("")){ query = "?cmsframe="+frame; } } if(!query.equals("")) { query=query+param; } else { query="?"+param.substring(param.indexOf("&")+1); } return query; } /** * Gets the target for a link. * <P> * This method can be called using <code>&lt;METHOD name="getCmsFrame"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getFrameTarget(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String target=""; String cmsframe=(String)((Hashtable)userObject).get("cmsframe"); cmsframe=(cmsframe==null?"":cmsframe); if (cmsframe.equals("plain")) { target=""; } else { if (tagcontent.equals("")) { target="target=_top"; } else { target="target="+tagcontent; } } return target; } /** * Gets the key that should be used to cache the results of * <EM>this</EM> template class. * <P> * Since our results may depend on the used template file, * the parameters and the requested body document, we must * build a complex key using this three arguments. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return key that can be used for caching */ public Object getKey(CmsObject cms, String templateFile, Hashtable parameters, String templateSelector) { //Vector v = new Vector(); CmsRequestContext reqContext = cms.getRequestContext(); //v.addElement(reqContext.currentProject().getName()); //v.addElement(reqContext.getUri()); //v.addElement(templateFile); //v.addElement(parameters); //v.addElement(templateSelector); //return v; String result = "" + reqContext.currentProject().getId() + ":" + reqContext.currentUser().getName() + reqContext.getUri() + templateFile; Enumeration keys = parameters.keys(); while(keys.hasMoreElements()) { String key = (String)keys.nextElement(); result = result + key + parameters.get(key); } result = result + templateSelector; return result; } /** * Reads in the template file and starts the XML parser for the expected * content type. * <P> * Every extending class using not CmsXmlTemplateFile as content type, * but any derived type should override this method. * * @param cms CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public CmsXmlTemplateFile getOwnTemplateFile(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { CmsXmlTemplateFile xmlTemplateDocument = new CmsXmlTemplateFile(cms, templateFile); return xmlTemplateDocument; } /** * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getPathUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String path=cms.getRequestContext().getUri(); path=path.substring(0,path.lastIndexOf("/")+1); path=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath()+path; return path.getBytes(); } /** * Inserts the correct servlet path title into the template. * <P> * This method can be called using <code>&lt;METHOD name="getTitle"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getQueryString(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String query = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getQueryString(); if(query != null && !"".equals(query)) { query = "?" + query; } return query; } /** * Get the IP address of the current request. * <P> * This method can be called using <code>&lt;METHOD name="getRequestIp"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public String getRequestIp(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getRemoteAddr(); } /** * Inserts the correct servlet path title into the template. * <P> * This method can be called using <code>&lt;METHOD name="getTitle"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getServletPath(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath() + "/"; } /** * Get the session id. If no session exists, a new one will be created. * <P> * This method can be called using <code>&lt;METHOD name="getSessionId"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public String getSessionId(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true).getId(); } /** * Inserts the correct stylesheet into the layout template. * <P> * This method can be called using <code>&lt;METHOD name="getStylesheet"&gt;</code> * in the template file. * <P> * When using this method follwing parameters should be defined * either in the page file or in the template file: * <ul> * <li><code>root.stylesheet-ie</code></li> * <li><code>root.stylesheet-ns</code></li> * </ul> * These parameters should contain the correct OpenCms path * for the Internet Explorer and Netscape Navigate * specific stylesheets. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public String getStylesheet(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { CmsXmlTemplateFile templateFile = (CmsXmlTemplateFile)doc; // Get the styles from the parameter hashtable String styleIE = null; String styleNS = null; if(templateFile.hasData("stylesheet-ie")) { styleIE = templateFile.getDataValue("stylesheet-ie"); } else if(templateFile.hasData("stylesheet")) { styleIE = templateFile.getDataValue("stylesheet"); } else { styleIE = ""; } if(templateFile.hasData("stylesheet-ns")) { styleNS = templateFile.getDataValue("stylesheet-ns"); } else if(templateFile.hasData("stylesheet")) { styleNS = templateFile.getDataValue("stylesheet"); } else { styleNS = ""; } HttpServletRequest orgReq = (HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest(); String servletPath = orgReq.getServletPath() + "/"; // Get the user's browser String browser = orgReq.getHeader("user-agent"); if(browser == null) { // the browser is unknown - return the ns-style return styleNS; } if(browser.indexOf("MSIE") >-1) { return servletPath + styleIE; } else { return servletPath + styleNS; } } /** * Find the corresponding template class to be loaded. * this should be defined in the template file of the parent * template and can be overwritten in the body file. * * @param elementName Element name of this template in our parent template. * @param doc CmsXmlTemplateFile object of our template file including a subtemplate. * @param parameters Hashtable with all template class parameters. * @return Name of the class that should generate the output for the included template file. */ protected String getTemplateClassName(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException { String result = null; if(parameters.containsKey(elementName + "._CLASS_")) { result = (String)parameters.get(elementName + "._CLASS_"); } else { if(doc.hasSubtemplateClass(elementName)) { result = doc.getSubtemplateClass(elementName); } else { // Fallback to "body" element if(parameters.containsKey("body._CLASS_")) { result = (String)parameters.get("body._CLASS_"); } } } return result; } /** * Find the corresponding template file to be loaded by the template class. * this should be defined in the template file of the parent * template and can be overwritten in the body file. * * @param elementName Element name of this template in our parent template. * @param doc CmsXmlTemplateFile object of our template file including a subtemplate. * @param parameters Hashtable with all template class parameters. * @return Name of the template file that should be included. */ protected String getTemplateFileName(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException { String result = null; if(parameters.containsKey(elementName + "._TEMPLATE_")) { result = (String)parameters.get(elementName + "._TEMPLATE_"); } else { if(doc.hasSubtemplateFilename(elementName)) { result = doc.getSubtemplateFilename(elementName); } else { // Fallback to "body" element if(parameters.containsKey("body._TEMPLATE_")) { result = (String)parameters.get("body._TEMPLATE_"); } } } //System.err.println("returning template file name for Element " + elementName + " in File " + doc + ": " + result); return result; } /** * Find the corresponding template selector to be activated. * This may be defined in the template file of the parent * template and can be overwritten in the body file. * * @param elementName Element name of this template in our parent template. * @param doc CmsXmlTemplateFile object of our template file including a subtemplate. * @param parameters Hashtable with all template class parameters. * @return Name of the class that should generate the output for the included template file. */ protected String getTemplateSelector(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException { if(parameters.containsKey(elementName + "._TEMPLATESELECTOR_")) { return (String)parameters.get(elementName + "._TEMPLATESELECTOR_"); } else if (doc.hasSubtemplateSelector(elementName)) { return doc.getSubtemplateSelector(elementName); } else { return null; } } /** * Inserts the correct document title into the template. * <P> * This method can be called using <code>&lt;METHOD name="getTitle"&gt;</code> * in the template file. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getTitle(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { String requestedUri = cms.getRequestContext().getUri(); String title = cms.readProperty(requestedUri, C_PROPERTY_TITLE); if(title == null) { title = ""; } return title; } /** * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object getUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { return (((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath() + cms.getRequestContext().getUri()).getBytes(); } /** * Indicates if the results of this class are cacheable. * <P> * Checks if the templateCache is set and if all subtemplates * are cacheable. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { boolean cacheable; try { if (!cms.getRequestContext().currentProject().equals(cms.onlineProject())) { // never cache offline-resources return false; } else { if (templateSelector == null || "".equals(templateSelector)) { templateSelector = (String) parameters.get(C_FRAME_SELECTOR); } cacheable = ((m_cache != null) && subtemplatesCacheable(cms, templateFile, elementName, parameters, templateSelector)); if (C_DEBUG && A_OpenCms.isLogging()) { String errorMessage = getClassName() + "Template class " + getClass().getName() + " with file " + templateFile + " is "; if (cacheable) { errorMessage = errorMessage + "cacheable."; } else { errorMessage = errorMessage + "not cacheable."; } A_OpenCms.log(C_OPENCMS_DEBUG, errorMessage); } } } catch (CmsException exc) { // there was an exception => don't cache this res. cacheable = false; } return cacheable; } /** * Tests, if the template cache is setted. * @return <code>true</code> if setted, <code>false</code> otherwise. */ public final boolean isTemplateCacheSet() { return m_cache != null; } /** * For debugging purposes only. * Prints out all parameters. * <P> * May be called from the template file using * <code>&lt;METHOD name="parameters"&gt;</code>. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object the initiating XLM document. * @param userObj Hashtable with parameters. * @return Debugging information about all parameters. */ public String parameters(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) { Hashtable param = (Hashtable)userObject; Enumeration keys = param.keys(); String s = ""; while(keys.hasMoreElements()) { String key = (String)keys.nextElement(); s = s + "<B>" + key + "</B>: " + param.get(key) + "<BR>"; } s = s + "<B>" + tagcontent + "</B><BR>"; return s; } /** * Set the instance of template cache that should be used to store * cacheable results of the subtemplates. * If the template cache is not set, caching will be disabled. * @param c Template cache to be used. */ public final void setTemplateCache(I_CmsTemplateCache c) { m_cache = c; } /** * Indicates if a previous cached result should be reloaded. * <P> * <em>not implemented.</em> Returns always <code>false</code>. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <code>false</code> */ public boolean shouldReload(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Starts the processing of the given template file by calling the * <code>getProcessedTemplateContent()</code> method of the content defintition * of the corresponding content type. * <P> * Any exceptions thrown while processing the template will be caught, * printed and and thrown again. * * @param cms CmsObject Object for accessing system resources. * @param xmlTemplateDocument XML parsed document of the content type "XML template file" or * any derived content type. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return Content of the template and all subtemplates. * @exception CmsException */ protected byte[] startProcessing(CmsObject cms, CmsXmlTemplateFile xmlTemplateDocument, String elementName, Hashtable parameters, String templateSelector) throws CmsException { String result = null; // Try to process the template file try { result = xmlTemplateDocument.getProcessedTemplateContent(this, parameters, templateSelector); } catch(Throwable e) { // There were errors while generating output for this template. // Clear HTML cache and then throw exception again xmlTemplateDocument.removeFromFileCache(); if(isCacheable(cms, xmlTemplateDocument.getAbsoluteFilename(), elementName, parameters, templateSelector)) { m_cache.clearCache(getKey(cms, xmlTemplateDocument.getAbsoluteFilename(), parameters, templateSelector)); } if(e instanceof CmsException) { throw (CmsException)e; } else { // under normal cirumstances, this should not happen. // any exception should be caught earlier and replaced by // corresponding CmsExceptions. String errorMessage = "Exception while getting content for (sub)template " + elementName + ". " + e; if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); } throw new CmsException(errorMessage); } } return result.getBytes(); } /** * Checks if all subtemplates are cacheable. * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <code>true</code> if all subtemplates are cacheable, <code>false</code> otherwise. */ public boolean subtemplatesCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { boolean cacheable = true; CmsXmlTemplateFile doc = null; Vector subtemplates = null; try { doc = this.getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); doc.init(cms, templateFile); subtemplates = doc.getAllSubElements(templateSelector); } catch(Exception e) { System.err.println(e); return false; } int numSubtemplates = subtemplates.size(); for(int i=0; i<numSubtemplates; i++) { String elName = (String)subtemplates.elementAt(i); String className = null; String templateName = null; try { className = getTemplateClassName(elName, doc, parameters); templateName = getTemplateFileName(elName, doc, parameters); } catch(CmsException e) { // There was an error while reading the class name or template name // from the subtemplate. // So we cannot determine the cacheability. if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_INFO, getClassName() + "Could not determine cacheability of subelement " + elName + " in template file " + doc.getFilename() + ". There were missing datablocks."); } return false; } try { I_CmsTemplate templClass = (I_CmsTemplate)CmsTemplateClassManager.getClassInstance(cms, className); cacheable = cacheable && templClass.isCacheable(cms, templateName, elName, parameters, null); } catch(Exception e) { System.err.println("E: " + e); } } return cacheable; } /** * Handles any occurence of an <code>&lt;ELEMENT&gt;</code> tag. * <P> * Every XML template class should use CmsXmlTemplateFile as * the interface to the XML file. Since CmsXmlTemplateFile is * an extension of A_CmsXmlContent by the additional tag * <code>&lt;ELEMENT&gt;</code> this user method ist mandatory. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document. * @param userObj Hashtable with parameters. * @return String or byte[] with the content of this subelement. * @exception CmsException */ public Object templateElement(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException { // Our own template file that wants to include a subelement CmsXmlTemplateFile templateFile = (CmsXmlTemplateFile)doc; // Indicates, if this is a request of a guest user. Needed for error outputs. boolean isAnonymousUser = cms.anonymousUser().equals(cms.getRequestContext().currentUser()); // First create a copy of the parameter hashtable Hashtable parameterHashtable = (Hashtable)((Hashtable)userObject).clone(); // Name of the template class that should be used to handle the subtemplate String templateClass = getTemplateClassName(tagcontent, templateFile, parameterHashtable); // Name of the subtemplate file. String templateFilename = getTemplateFileName(tagcontent, templateFile, parameterHashtable); // Name of the subtemplate template selector String templateSelector = getTemplateSelector(tagcontent, templateFile, parameterHashtable); // Results returned by the subtemplate class byte[] result = null; // Temporary object for loading the subtemplate class Object loadedObject = null; // subtemplate class to be used for the include I_CmsTemplate subTemplate = null; // Key for the cache Object subTemplateKey = null; // try to load the subtemplate class try { loadedObject = CmsTemplateClassManager.getClassInstance(cms, templateClass); } catch(CmsException e) { // There was an error. First remove the template file from the file cache templateFile.removeFromFileCache(); if(isAnonymousUser) { // The current user is the anonymous user return C_ERRORTEXT; } else { // The current user is a system user, so we throw the exception again. throw e; } } // Check if the loaded object is really an instance of an OpenCms template class if(! (loadedObject instanceof I_CmsTemplate)) { String errorMessage = "Class " + templateClass + " is no OpenCms template class."; if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsXmlTemplate] " + errorMessage); } throw new CmsException(errorMessage, CmsException.C_XML_NO_TEMPLATE_CLASS); } subTemplate = (I_CmsTemplate)loadedObject; // Template class is now loaded. Next try to read the parameters Vector parameterTags = null; parameterTags = templateFile.getParameterNames(tagcontent); if(parameterTags != null) { int numParameterTags = parameterTags.size(); for(int i=0; i< numParameterTags; i++) { String paramName = (String)parameterTags.elementAt(i); String paramValue = templateFile.getParameter(tagcontent, paramName); if(! parameterHashtable.containsKey(paramName)) { parameterHashtable.put(tagcontent + "." + paramName, paramValue); } } } // all parameters are now parsed. Finally give the own subelement name // as parameter // TODO: replace _ELEMENT_ by a constant parameterHashtable.put("_ELEMENT_", tagcontent); // OK. let's call the subtemplate if(result == null) { try { result = subTemplate.getContent(cms, templateFilename, tagcontent, parameterHashtable, templateSelector); } catch (Exception e) { // Oh, oh.. // There were errors while getting the content of the subtemplate if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Could not generate output for template file \"" + templateFilename + "\" included as element \"" + tagcontent + "\"."); A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + e); } // The anonymous user gets an error String instead of an exception if(isAnonymousUser) { return C_ERRORTEXT; } else { if(e instanceof CmsException) { throw (CmsException)e; } else { e.printStackTrace(); throw new CmsException("Error while executing getContent for subtemplate \"" + tagcontent + "\". " + e); } } } } // Store the results in the template cache, if cacheable if(subTemplate.isCacheable(cms, templateFilename, tagcontent, parameterHashtable, null)) { subTemplateKey = subTemplate.getKey(cms, templateFilename, parameterHashtable, null); if(subTemplate.isCacheable(cms, templateFilename, tagcontent, parameterHashtable, null) && m_cache.has(subTemplateKey) && (! subTemplate.shouldReload(cms, templateFilename, tagcontent, parameterHashtable, null))) { result = m_cache.get(subTemplateKey); } m_cache.put(subTemplateKey, result); } return result; } /** * Help method that handles any occuring error by writing * an error message to the OpenCms logfile and throwing a * CmsException of the type "unknown". * @param errorMessage String with the error message to be printed. * @exception CmsException */ protected void throwException(String errorMessage) throws CmsException { throwException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION); } /** * Help method that handles any occuring error by writing * an error message to the OpenCms logfile and throwing a * CmsException of the given type. * @param errorMessage String with the error message to be printed. * @param type Type of the exception to be thrown. * @exception CmsException */ protected void throwException(String errorMessage, int type) throws CmsException { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); } throw new CmsException(errorMessage, type); } /** * Help method that handles any occuring error by writing * an error message to the OpenCms logfile and re-throwing a * caught exception. * @param errorMessage String with the error message to be printed. * @param e Exception to be re-thrown. * @exception CmsException */ protected void throwException(String errorMessage, Exception e) throws CmsException { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Exception: " + e); } if(e instanceof CmsException) { throw (CmsException)e; } else { throw new CmsException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION, e); } } }
Fixed a bug with re-using cached subtemplates.
src/com/opencms/template/CmsXmlTemplate.java
Fixed a bug with re-using cached subtemplates.
Java
lgpl-2.1
1df7cac0f885e5321c6be3d17330021d1ad16944
0
sylkai/stash_cache
package com.geekeclectic.android.stashcache; import android.content.Context; import android.util.Log; import android.widget.Toast; 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.HashMap; import java.util.UUID; /** * Created by sylk on 1/22/2015. */ public class StashImporter { private static InputStream in; private static int DEFAULT = 1; private static HashMap<String, ArrayList<UUID>> threadMap; private static HashMap<String, ArrayList<UUID>> embellishmentMap; private boolean fileFormattedCorrectly; private boolean allNumbersFormatted; public static final String TAG = "StashImporter"; public StashImporter(InputStream input) { // mFilename = "stash_input.txt"; in = input; threadMap = new HashMap<String, ArrayList<UUID>>(); embellishmentMap = new HashMap<String, ArrayList<UUID>>(); fileFormattedCorrectly = true; allNumbersFormatted = true; } public int importStash(Context context) throws IOException { StashData stash = StashData.get(context); populateMaps(stash); BufferedReader reader = null; try { // open and read the file into a StringBuilder // InputStream in = am.open(mFilename); reader = new BufferedReader(new InputStreamReader(in)); Log.d(TAG, "Reader successfully opened."); String line = ""; // read in thread data; end of thread block is marked by *** and will break loop while ((line = reader.readLine()) != null && !line.equals("***")) { // store source and type information String source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } // iterate through to the end of the source/type block and create a new thread for each id while ((line = reader.readLine()) != null) { if (line.equals("***") || line.equals("---")) { break; } String id = line; String key; if (id.contains(" ")) { key = id.split("\\s")[0]; } else { key = id; } incrementOrAddThread(source, type, id, key, stash); } if (line.equals("***")) { break; } } // read in fabric data; end of the block is marked by *** and will break loop while ((line = reader.readLine()) != null && !line.equals("***")) { // skip a line if the current line marks the fabric delimiter --- if (line.equals("---")) { line = reader.readLine(); if (checkToContinue(line)) { break; } } String source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } String color = reader.readLine(); if (checkToContinue(color)) { break; } line = reader.readLine(); int count; Double height; Double width; if (checkToContinue(line)) { break; } else { try { count = Integer.parseInt(line); } catch (NumberFormatException e) { count = 0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { height = Double.parseDouble(line); } catch (NumberFormatException e) { height = 0.0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { width = Double.parseDouble(line); } catch (NumberFormatException e) { width = 0.0; allNumbersFormatted = false; } } createNewFabric(source, type, color, count, height, width, stash); } // read in embellishment data; end of the block is marked by *** and will break loop while ((line = reader.readLine()) != null && !line.equals("***")) { // store source and type information String source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } // iterate through to the end of the source/type block and create a new embellishment for each id while ((line = reader.readLine()) != null) { if (line.equals("***") || line.equals("---")) { break; } String id = line; incrementOrAddEmbellishment(source, type, id, stash); } if (line.equals("***")) { break; } } // read in pattern data; each pattern is separated by --- // if fabric provided in pattern (under pattern info, separated by *), create new fabric // check for existing threads/embellishments and create new if missing while ((line = reader.readLine()) != null) { // read in pattern information String title = line; String source = reader.readLine(); if (checkToContinue(source)) { break; } int width; int height; line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { width = Integer.parseInt(line); } catch (NumberFormatException e) { width = 0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { height = Integer.parseInt(line); } catch (NumberFormatException e) { height = 0; allNumbersFormatted = false; } } // create pattern StashPattern pattern = new StashPattern(); pattern.setPatternName(title); pattern.setSource(source); pattern.setHeight(height); pattern.setWidth(width); stash.addPattern(pattern); // move forward one line to skip the first * reader.readLine(); // if fabric is entered, create a new fabric if (!(line = reader.readLine()).equals("*")) { source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } String color = reader.readLine(); if (checkToContinue(color)) { break; } int count; Double fabric_height; Double fabric_width; line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { count = Integer.parseInt(line); } catch (NumberFormatException e) { count = 0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { fabric_height = Double.parseDouble(line); } catch (NumberFormatException e) { fabric_height = 0.0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { fabric_width = Double.parseDouble(line); } catch (NumberFormatException e) { fabric_width = 0.0; allNumbersFormatted = false; } } StashFabric fabric = createNewFabric(source, type, color, count, fabric_height, fabric_width, stash); pattern.setFabric(fabric); fabric.setUsedFor(pattern); reader.readLine(); } // if thread information is entered, check for thread in stash already and add it if not present while ((line = reader.readLine()) != null) { source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } while ((line = reader.readLine()) != null) { if (line.equals("*") || line.equals("-")) { break; } String id = line; String key; if (id.contains(" ")) { key = id.split("\\s")[0]; } else { key = id; } StashThread thread = findOrAddThread(source, type, id, key, stash); thread.usedInPattern(pattern); pattern.addThread(thread); } if (line == null || line.equals("*")) { break; } } // if embellishment information is entered, check for embellishment in stash already and add it if not present while ((line = reader.readLine()) != null) { source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } while ((line = reader.readLine()) != null && !line.equals("-")) { if (line.equals("*") || line.equals("---")) { break; } String id = line; StashEmbellishment embellishment = findOrAddEmbellishment(source, type, id, stash); embellishment.usedInPattern(pattern); pattern.addEmbellishment(embellishment); } if (line == null || line.equals("---")) { break; } } } } catch (FileNotFoundException e) { // ignore because it happens when program is opened for the first time } finally { if (reader != null) { reader.close(); } if (fileFormattedCorrectly && allNumbersFormatted) { return 0; } else if (fileFormattedCorrectly == false) { return 1; } else { return 2; } } } private StashThread createNewThread(String source, String type, String id, String key, StashData stash, boolean inStash) { StashThread thread = new StashThread(); thread.setSource(source); thread.setType(type); thread.setCode(id); if (inStash) { thread.setSkeinsOwned(DEFAULT); } stash.addThread(thread); if (threadMap.get(key) == null) { ArrayList<UUID> threadList = new ArrayList<UUID>(); threadList.add(thread.getId()); threadMap.put(key, threadList); } else { ArrayList<UUID> threadList = threadMap.get(key); threadList.add(thread.getId()); } return thread; } private StashFabric createNewFabric(String source, String type, String color, int count, Double height, Double width, StashData stash) { StashFabric fabric = new StashFabric(); fabric.setSource(source); fabric.setType(type); fabric.setColor(color); fabric.setCount(count); fabric.setHeight(height); fabric.setWidth(width); stash.addFabric(fabric); return fabric; } private StashEmbellishment createNewEmbellishment(String source, String type, String id, StashData stash, boolean inStash) { StashEmbellishment embellishment = new StashEmbellishment(); embellishment.setSource(source); embellishment.setType(type); embellishment.setCode(id); if (inStash) { embellishment.setNumberOwned(DEFAULT); } stash.addEmbellishment(embellishment); if (embellishmentMap.get(id) == null) { ArrayList<UUID> embellishmentList = new ArrayList<UUID>(); embellishmentList.add(embellishment.getId()); embellishmentMap.put(id, embellishmentList); } else { ArrayList<UUID> embellishmentList = embellishmentMap.get(id); embellishmentList.add(embellishment.getId()); } return embellishment; } private void incrementOrAddThread(String source, String type, String id, String key, StashData stash) { ArrayList<UUID> threadList = threadMap.get(key); StashThread thread; if (threadList != null) { for (UUID threadId : threadList) { thread = stash.getThread(threadId); if (isSameThread(thread, source, type, id, key)) { if (!key.equals(id) && key.equals(thread.getCode())) { thread.setCode(id); } thread.increaseOwnedQuantity(); return; } } createNewThread(source, type, id, key, stash, true); } else { createNewThread(source, type, id, key, stash, true); } } private StashThread findOrAddThread(String source, String type, String id, String key, StashData stash) { ArrayList<UUID> threadList = stash.getThreadList(); StashThread thread; for (int i = 0; i < threadList.size(); i++) { thread = stash.getThread(threadList.get(i)); if (isSameThread(thread, source, type, key, id)) { if (!key.equals(id) && key.equals(thread.getCode())) { thread.setCode(id); } return thread; } } thread = createNewThread(source, type, id, key, stash, false); return thread; } private void incrementOrAddEmbellishment(String source, String type, String id, StashData stash) { ArrayList<UUID> embellishmentList = embellishmentMap.get(id); StashEmbellishment embellishment; if (embellishmentList != null) { for (UUID embellishmentId : embellishmentList) { embellishment = stash.getEmbellishment(embellishmentId); if (embellishment.getSource().equals(source) && embellishment.getType().equals(type) && embellishment.getCode().equals(id)) { embellishment.increaseOwned(); return; } } createNewEmbellishment(source, type, id, stash, true); } else { createNewEmbellishment(source, type, id, stash, true); } } private StashEmbellishment findOrAddEmbellishment(String source, String type, String id, StashData stash) { ArrayList<UUID> embellishmentList = embellishmentMap.get(id); StashEmbellishment embellishment; if (embellishmentList != null) { for (UUID embellishmentId : embellishmentList) { embellishment = stash.getEmbellishment(embellishmentId); if (embellishment.getSource().equals(source) && embellishment.getType().equals(type) && embellishment.getCode().equals(id)) { return embellishment; } } embellishment = createNewEmbellishment(source, type, id, stash, false); } else { embellishment = createNewEmbellishment(source, type, id, stash, false); } return embellishment; } private boolean checkToContinue(String toCheck) { if (toCheck != null && !toCheck.equals("***") && !toCheck.equals("---") && !toCheck.equals("*") && !toCheck.equals("-")) { return false; } else { fileFormattedCorrectly = false; return true; } } private void populateMaps(StashData stash) { ArrayList<UUID> threadList = stash.getThreadList(); ArrayList<UUID> shortThreadList; for (UUID threadId : threadList) { StashThread thread = stash.getThread(threadId); shortThreadList = threadMap.get(thread.getCode()); if (shortThreadList == null) { shortThreadList = new ArrayList<UUID>(); } shortThreadList.add(threadId); threadMap.put(thread.getCode(), shortThreadList); } ArrayList<UUID> embellishmentList = stash.getEmbellishmentList(); ArrayList<UUID> shortEmbellishmentList; for (UUID embellishmentId : embellishmentList) { StashEmbellishment embellishment = stash.getEmbellishment(embellishmentId); shortEmbellishmentList = embellishmentMap.get(embellishment.getCode()); if (shortEmbellishmentList == null) { shortEmbellishmentList = new ArrayList<UUID>(); } shortEmbellishmentList.add(embellishmentId); embellishmentMap.put(embellishment.getCode(), shortEmbellishmentList); } } private boolean isSameThread(StashThread thread, String source, String type, String id, String key) { if (thread.getSource() != null && thread.getSource().equals(source)) { if (thread.getType() != null && thread.getType().equals(type)) { if (thread.getCode() != null && thread.getCode().equals(id)) { return true; } else if (thread.getCode() != null && (thread.getCode().split("\\s")[0].equals(id) || key.equals(thread.getCode()))) { return true; } } } return false; } }
StashCache/app/src/main/java/com/geekeclectic/android/stashcache/StashImporter.java
package com.geekeclectic.android.stashcache; import android.content.Context; import android.util.Log; import android.widget.Toast; 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.HashMap; import java.util.UUID; /** * Created by sylk on 1/22/2015. */ public class StashImporter { private static InputStream in; private static int DEFAULT = 1; private static HashMap<String, ArrayList<UUID>> threadMap; private static HashMap<String, ArrayList<UUID>> embellishmentMap; private boolean fileFormattedCorrectly; private boolean allNumbersFormatted; public static final String TAG = "StashImporter"; public StashImporter(InputStream input) { // mFilename = "stash_input.txt"; in = input; threadMap = new HashMap<String, ArrayList<UUID>>(); embellishmentMap = new HashMap<String, ArrayList<UUID>>(); fileFormattedCorrectly = true; allNumbersFormatted = true; } public int importStash(Context context) throws IOException { StashData stash = StashData.get(context); populateMaps(stash); BufferedReader reader = null; try { // open and read the file into a StringBuilder // InputStream in = am.open(mFilename); reader = new BufferedReader(new InputStreamReader(in)); Log.d(TAG, "Reader successfully opened."); String line = ""; // read in thread data; end of thread block is marked by *** and will break loop while ((line = reader.readLine()) != null && !line.equals("***")) { // store source and type information String source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } // iterate through to the end of the source/type block and create a new thread for each id while ((line = reader.readLine()) != null) { if (line.equals("***") || line.equals("---")) { break; } String id = line; incrementOrAddThread(source, type, id, stash); } if (line.equals("***")) { break; } } // read in fabric data; end of the block is marked by *** and will break loop while ((line = reader.readLine()) != null && !line.equals("***")) { // skip a line if the current line marks the fabric delimiter --- if (line.equals("---")) { line = reader.readLine(); if (checkToContinue(line)) { break; } } String source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } String color = reader.readLine(); if (checkToContinue(color)) { break; } line = reader.readLine(); int count; Double height; Double width; if (checkToContinue(line)) { break; } else { try { count = Integer.parseInt(line); } catch (NumberFormatException e) { count = 0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { height = Double.parseDouble(line); } catch (NumberFormatException e) { height = 0.0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { width = Double.parseDouble(line); } catch (NumberFormatException e) { width = 0.0; allNumbersFormatted = false; } } createNewFabric(source, type, color, count, height, width, stash); } // read in embellishment data; end of the block is marked by *** and will break loop while ((line = reader.readLine()) != null && !line.equals("***")) { // store source and type information String source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } // iterate through to the end of the source/type block and create a new embellishment for each id while ((line = reader.readLine()) != null) { if (line.equals("***") || line.equals("---")) { break; } String id = line; incrementOrAddEmbellishment(source, type, id, stash); } if (line.equals("***")) { break; } } // read in pattern data; each pattern is separated by --- // if fabric provided in pattern (under pattern info, separated by *), create new fabric // check for existing threads/embellishments and create new if missing while ((line = reader.readLine()) != null) { // read in pattern information String title = line; String source = reader.readLine(); if (checkToContinue(source)) { break; } int width; int height; line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { width = Integer.parseInt(line); } catch (NumberFormatException e) { width = 0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { height = Integer.parseInt(line); } catch (NumberFormatException e) { height = 0; allNumbersFormatted = false; } } // create pattern StashPattern pattern = new StashPattern(); pattern.setPatternName(title); pattern.setSource(source); pattern.setHeight(height); pattern.setWidth(width); stash.addPattern(pattern); // move forward one line to skip the first * reader.readLine(); // if fabric is entered, create a new fabric if (!(line = reader.readLine()).equals("*")) { source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } String color = reader.readLine(); if (checkToContinue(color)) { break; } int count; Double fabric_height; Double fabric_width; line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { count = Integer.parseInt(line); } catch (NumberFormatException e) { count = 0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { fabric_height = Double.parseDouble(line); } catch (NumberFormatException e) { fabric_height = 0.0; allNumbersFormatted = false; } } line = reader.readLine(); if (checkToContinue(line)) { break; } else { try { fabric_width = Double.parseDouble(line); } catch (NumberFormatException e) { fabric_width = 0.0; allNumbersFormatted = false; } } StashFabric fabric = createNewFabric(source, type, color, count, fabric_height, fabric_width, stash); pattern.setFabric(fabric); fabric.setUsedFor(pattern); reader.readLine(); } // if thread information is entered, check for thread in stash already and add it if not present while ((line = reader.readLine()) != null) { source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } while ((line = reader.readLine()) != null) { if (line.equals("*") || line.equals("-")) { break; } String id = line; StashThread thread = findOrAddThread(source, type, id, stash); thread.usedInPattern(pattern); pattern.addThread(thread); } if (line == null || line.equals("*")) { break; } } // if embellishment information is entered, check for embellishment in stash already and add it if not present while ((line = reader.readLine()) != null) { source = line; String type = reader.readLine(); if (checkToContinue(type)) { break; } while ((line = reader.readLine()) != null && !line.equals("-")) { if (line.equals("*") || line.equals("---")) { break; } String id = line; StashEmbellishment embellishment = findOrAddEmbellishment(source, type, id, stash); embellishment.usedInPattern(pattern); pattern.addEmbellishment(embellishment); } if (line == null || line.equals("---")) { break; } } } } catch (FileNotFoundException e) { // ignore because it happens when program is opened for the first time } finally { if (reader != null) { reader.close(); } if (fileFormattedCorrectly && allNumbersFormatted) { return 0; } else if (fileFormattedCorrectly == false) { return 1; } else { return 2; } } } private StashThread createNewThread(String source, String type, String id, StashData stash, boolean inStash) { StashThread thread = new StashThread(); thread.setSource(source); thread.setType(type); thread.setCode(id); if (inStash) { thread.setSkeinsOwned(DEFAULT); } stash.addThread(thread); if (threadMap.get(id) == null) { ArrayList<UUID> threadList = new ArrayList<UUID>(); threadList.add(thread.getId()); threadMap.put(id, threadList); } else { ArrayList<UUID> threadList = threadMap.get(id); threadList.add(thread.getId()); } return thread; } private StashFabric createNewFabric(String source, String type, String color, int count, Double height, Double width, StashData stash) { StashFabric fabric = new StashFabric(); fabric.setSource(source); fabric.setType(type); fabric.setColor(color); fabric.setCount(count); fabric.setHeight(height); fabric.setWidth(width); stash.addFabric(fabric); return fabric; } private StashEmbellishment createNewEmbellishment(String source, String type, String id, StashData stash, boolean inStash) { StashEmbellishment embellishment = new StashEmbellishment(); embellishment.setSource(source); embellishment.setType(type); embellishment.setCode(id); if (inStash) { embellishment.setNumberOwned(DEFAULT); } stash.addEmbellishment(embellishment); if (embellishmentMap.get(id) == null) { ArrayList<UUID> embellishmentList = new ArrayList<UUID>(); embellishmentList.add(embellishment.getId()); embellishmentMap.put(id, embellishmentList); } else { ArrayList<UUID> embellishmentList = embellishmentMap.get(id); embellishmentList.add(embellishment.getId()); } return embellishment; } private void incrementOrAddThread(String source, String type, String id, StashData stash) { ArrayList<UUID> threadList = threadMap.get(id); StashThread thread; if (threadList != null) { for (UUID threadId : threadList) { thread = stash.getThread(threadId); if (thread.getSource().equals(source) && thread.getType().equals(type) && thread.getCode().equals(id)) { thread.increaseOwnedQuantity(); return; } } createNewThread(source, type, id, stash, true); } else { createNewThread(source, type, id, stash, true); } } private StashThread findOrAddThread(String source, String type, String id, StashData stash) { ArrayList<UUID> threadList = stash.getThreadList(); StashThread thread; for (int i = 0; i < threadList.size(); i++) { thread = stash.getThread(threadList.get(i)); if (thread.getSource().equals(source) && thread.getType().equals(type) && thread.getCode().equals(id)) { return thread; } } thread = createNewThread(source, type, id, stash, false); return thread; } private void incrementOrAddEmbellishment(String source, String type, String id, StashData stash) { ArrayList<UUID> embellishmentList = embellishmentMap.get(id); StashEmbellishment embellishment; if (embellishmentList != null) { for (UUID embellishmentId : embellishmentList) { embellishment = stash.getEmbellishment(embellishmentId); if (embellishment.getSource().equals(source) && embellishment.getType().equals(type) && embellishment.getCode().equals(id)) { embellishment.increaseOwned(); return; } } createNewEmbellishment(source, type, id, stash, true); } else { createNewEmbellishment(source, type, id, stash, true); } } private StashEmbellishment findOrAddEmbellishment(String source, String type, String id, StashData stash) { ArrayList<UUID> embellishmentList = embellishmentMap.get(id); StashEmbellishment embellishment; if (embellishmentList != null) { for (UUID embellishmentId : embellishmentList) { embellishment = stash.getEmbellishment(embellishmentId); if (embellishment.getSource().equals(source) && embellishment.getType().equals(type) && embellishment.getCode().equals(id)) { return embellishment; } } embellishment = createNewEmbellishment(source, type, id, stash, false); } else { embellishment = createNewEmbellishment(source, type, id, stash, false); } return embellishment; } private boolean checkToContinue(String toCheck) { if (toCheck != null && !toCheck.equals("***") && !toCheck.equals("---") && !toCheck.equals("*") && !toCheck.equals("-")) { return false; } else { fileFormattedCorrectly = false; return true; } } private void populateMaps(StashData stash) { ArrayList<UUID> threadList = stash.getThreadList(); ArrayList<UUID> shortThreadList; for (UUID threadId : threadList) { StashThread thread = stash.getThread(threadId); shortThreadList = threadMap.get(thread.getCode()); if (shortThreadList == null) { shortThreadList = new ArrayList<UUID>(); } shortThreadList.add(threadId); threadMap.put(thread.getCode(), shortThreadList); } ArrayList<UUID> embellishmentList = stash.getEmbellishmentList(); ArrayList<UUID> shortEmbellishmentList; for (UUID embellishmentId : embellishmentList) { StashEmbellishment embellishment = stash.getEmbellishment(embellishmentId); shortEmbellishmentList = embellishmentMap.get(embellishment.getCode()); if (shortEmbellishmentList == null) { shortEmbellishmentList = new ArrayList<UUID>(); } shortEmbellishmentList.add(embellishmentId); embellishmentMap.put(embellishment.getCode(), shortEmbellishmentList); } } }
Changes made to accommodate matching number codes to number code + text as the same thread, and to preserve the number code + text additional information if it was entered somewhere in the import document. I need to decide if I am doing this for embellishments as well, or if the situation is less likely there and should therefore be ignored.
StashCache/app/src/main/java/com/geekeclectic/android/stashcache/StashImporter.java
Changes made to accommodate matching number codes to number code + text as the same thread, and to preserve the number code + text additional information if it was entered somewhere in the import document.
Java
lgpl-2.1
6ef4547548b66980ec5b81c9e0520630f3ed1c36
0
adamretter/exist,lcahlander/exist,lcahlander/exist,adamretter/exist,eXist-db/exist,lcahlander/exist,wolfgangmm/exist,wolfgangmm/exist,dizzzz/exist,dizzzz/exist,windauer/exist,adamretter/exist,dizzzz/exist,olvidalo/exist,ambs/exist,ambs/exist,ambs/exist,eXist-db/exist,dizzzz/exist,dizzzz/exist,lcahlander/exist,olvidalo/exist,lcahlander/exist,eXist-db/exist,windauer/exist,ambs/exist,wolfgangmm/exist,adamretter/exist,ambs/exist,eXist-db/exist,olvidalo/exist,adamretter/exist,wolfgangmm/exist,wolfgangmm/exist,windauer/exist,ambs/exist,windauer/exist,olvidalo/exist,dizzzz/exist,wolfgangmm/exist,windauer/exist,olvidalo/exist,eXist-db/exist,windauer/exist,lcahlander/exist,eXist-db/exist,adamretter/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2016 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.security.internal; import org.exist.EXistException; import org.exist.TestUtils; import org.exist.backup.Backup; import org.exist.backup.Restore; import org.exist.backup.restore.listener.RestoreListener; import org.exist.security.*; import org.exist.security.SecurityManager; import org.exist.security.internal.aider.GroupAider; import org.exist.security.internal.aider.UserAider; import org.exist.storage.BrokerPool; import org.exist.test.ExistXmldbEmbeddedServer; import org.exist.xmldb.UserManagementService; import org.junit.*; import org.w3c.dom.Node; import org.xml.sax.SAXException; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XMLResource; import org.xmldb.api.modules.XPathQueryService; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Observable; import static org.junit.Assert.assertEquals; public class BackupRestoreSecurityPrincipalsTest { private final static String BACKUP_FILE_PREFIX = "exist.BackupRestoreSecurityPrincipalsTest"; private final static String BACKUP_FILE_SUFFIX = ".backup.zip"; private final static String FRANK_USER = "frank"; private final static String JOE_USER = "joe"; private final static String JACK_USER = "jack"; @ClassRule public static ExistXmldbEmbeddedServer server = new ExistXmldbEmbeddedServer(false, true, true); /** * 1. With an empty database we create three * users: 'frank', 'joe', and 'jack'. * * 2. We create a backup of the database which contains * the three users from (1). * * 3. We destroy the database, restart the server, * and start again with a clean database. * * 4. With an (again) empty database we create two * users: 'frank', and 'jack'. * * 5. We then try and restore the database backup from (2), which * contains the original 'frank', 'joe', and 'jack' users. * * frank will have the same username and user id in the current * database and the backup we are trying to restore. * * joe does not exist in the current database, but his user id * in the backup will collide with that of jack in the current database. * * jack will have a different user id in the backup when compared to the current * database, however he will have the same username. * * We want to make sure that after the restore, all three users are present * that they have distinct and expected user ids and that any resources * that were owned by them are still correctly owner by them (and not some other user). */ @Test public void restoreConflictingUsername() throws PermissionDeniedException, EXistException, SAXException, ParserConfigurationException, IOException, URISyntaxException, XMLDBException, IllegalAccessException, ClassNotFoundException, InstantiationException { // creates a database with new users: 'frank(id=11)', 'joe(id=12)', and 'jack(id=13)' createInitialUsers(FRANK_USER, JOE_USER, JACK_USER); // create a backup of the database (which has the initial users) final Path backupFile = backupDatabase(); //reset database to empty server.restart(true); //create new users: 'frank(id=11)' and 'jack(id=12)' createInitialUsers(FRANK_USER, JACK_USER); final String accountQuery = "declare namespace c = 'http://exist-db.org/Configuration';\n" + "for $account in //c:account\n" + "return\n" + "<user id='{$account/@id}' name='{$account/c:name}'/>"; final XPathQueryService xqs = (XPathQueryService) server.getRoot().getService("XPathQueryService", "1.0"); final SecurityManagerImpl sm = (SecurityManagerImpl) BrokerPool.getInstance().getSecurityManager(); //check the current user accounts ResourceSet result = xqs.query(accountQuery); assertUser(RealmImpl.ADMIN_ACCOUNT_ID, SecurityManager.DBA_USER, ((XMLResource) result.getResource(0)).getContentAsDOM()); assertUser(RealmImpl.GUEST_ACCOUNT_ID, SecurityManager.GUEST_USER, ((XMLResource) result.getResource(1)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 1, "frank", ((XMLResource) result.getResource(2)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 2, "jack", ((XMLResource) result.getResource(3)).getContentAsDOM()); //check the last user id assertEquals(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 2, sm.getLastAccountId()); //last account id should be that of 'jack' //create a test collection and give everyone access final CollectionManagementService cms = (CollectionManagementService)server.getRoot().getService("CollectionManagementService", "1.0"); final Collection test = cms.createCollection("test"); final UserManagementService testUms = (UserManagementService)test.getService("UserManagementService", "1.0"); testUms.chmod("rwxrwxrwx"); //create and store a new document as 'frank' final Collection frankTest = DatabaseManager.getCollection("xmldb:exist:///db/test", FRANK_USER, FRANK_USER); final String FRANKS_DOCUMENT = "franks-document.xml"; final Resource frankDoc = frankTest.createResource(FRANKS_DOCUMENT, XMLResource.RESOURCE_TYPE); frankDoc.setContent("<hello>frank</hello>"); frankTest.storeResource(frankDoc); //create and store a new document as 'jack' final Collection jackTest = DatabaseManager.getCollection("xmldb:exist:///db/test", JACK_USER, JACK_USER); final String JACKS_DOCUMENT = "jacks-document.xml"; final Resource jackDoc = jackTest.createResource(JACKS_DOCUMENT, XMLResource.RESOURCE_TYPE); jackDoc.setContent("<hello>jack</hello>"); jackTest.storeResource(jackDoc); //restore the database backup final Restore restore = new Restore(); restore.restore(new NullRestoreListener(), "admin", "", null, backupFile, "xmldb:exist:///db"); //check the current user accounts after the restore result = xqs.query(accountQuery); assertUser(RealmImpl.ADMIN_ACCOUNT_ID, SecurityManager.DBA_USER, ((XMLResource) result.getResource(0)).getContentAsDOM()); assertUser(RealmImpl.GUEST_ACCOUNT_ID, SecurityManager.GUEST_USER, ((XMLResource) result.getResource(1)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 1, FRANK_USER, ((XMLResource) result.getResource(2)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 2, JACK_USER, ((XMLResource) result.getResource(3)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 3, JOE_USER, ((XMLResource) result.getResource(4)).getContentAsDOM()); //check the last user id after the restore assertEquals(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 3, sm.getLastAccountId()); //last account id should be that of 'joe' //check the owner of frank's document after restore final Resource fDoc = test.getResource(FRANKS_DOCUMENT); final Permission franksDocPermissions = testUms.getPermissions(fDoc); assertEquals(FRANK_USER, franksDocPermissions.getOwner().getName()); //check the owner of jack's document after restore final Resource jDoc = test.getResource(JACKS_DOCUMENT); final Permission jacksDocPermissions = testUms.getPermissions(jDoc); assertEquals(JACK_USER, jacksDocPermissions.getOwner().getName()); } /** * Creates initial database users. * * NOTE: The database must be in a clean initialised empty state. */ private void createInitialUsers(final String... usernames) throws PermissionDeniedException, XMLDBException, SAXException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { int lastAccountId = SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID; for (final String username : usernames) { createUser(username, username); assertEquals(++lastAccountId, getUser(username).getId()); } } /** * Backup the database. * * @return The path to the database backup. */ private Path backupDatabase() throws IOException, XMLDBException, SAXException { final Path backupFile = Files.createTempFile(BACKUP_FILE_PREFIX, BACKUP_FILE_SUFFIX); backupFile.toFile().deleteOnExit(); final Backup backup = new Backup(TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD, backupFile); backup.backup(false, null); return backupFile; } private void assertUser(final int userId, final String userName, final Node account) { assertEquals(userId, Integer.parseInt(account.getAttributes().getNamedItem("id").getNodeValue())); assertEquals(userName, account.getAttributes().getNamedItem("name").getNodeValue()); } private void createUser(final String username, final String password) throws XMLDBException, PermissionDeniedException { final UserManagementService ums = (UserManagementService) server.getRoot().getService("UserManagementService", "1.0"); final Account user = new UserAider(username); user.setPassword(password); //create the personal group final Group group = new GroupAider(username); group.setMetadataValue(EXistSchemaType.DESCRIPTION, "Personal group for " + username); group.addManager(ums.getAccount("admin")); ums.addGroup(group); //add the personal group as the primary group user.addGroup(username); //create the account ums.addAccount(user); //add the new account as a manager of their personal group ums.addGroupManager(username, group.getName()); } private Account getUser(final String username) throws XMLDBException { final UserManagementService ums = (UserManagementService) server.getRoot().getService("UserManagementService", "1.0"); return ums.getAccount(username); } private static class NullRestoreListener implements RestoreListener { @Override public void createCollection(final String collection) { } @Override public void restored(final String resource) { } @Override public void info(final String message) { } @Override public void warn(final String message) { } @Override public void error(final String message) { } @Override public String warningsAndErrorsAsString() { return null; } @Override public boolean hasProblems() { return false; } @Override public void setCurrentCollection(final String currentCollectionName) { } @Override public void setCurrentResource(final String currentResourceName) { } @Override public void restoreStarting() { } @Override public void restoreFinished() { } @Override public void observe(final Observable observable) { } @Override public void setCurrentBackup(final String currentBackup) { } @Override public void setNumberOfFiles(long nr) { } @Override public void incrementFileCounter() { } } }
test/src/org/exist/security/internal/BackupRestoreSecurityPrincipalsTest.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2016 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.security.internal; import org.exist.EXistException; import org.exist.TestUtils; import org.exist.backup.Backup; import org.exist.backup.Restore; import org.exist.backup.restore.listener.RestoreListener; import org.exist.security.*; import org.exist.security.SecurityManager; import org.exist.security.internal.aider.GroupAider; import org.exist.security.internal.aider.UserAider; import org.exist.storage.BrokerPool; import org.exist.test.ExistXmldbEmbeddedServer; import org.exist.xmldb.UserManagementService; import org.junit.*; import org.w3c.dom.Node; import org.xml.sax.SAXException; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XMLResource; import org.xmldb.api.modules.XPathQueryService; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Observable; import static org.junit.Assert.assertEquals; public class BackupRestoreSecurityPrincipalsTest { private final static String BACKUP_FILE_PREFIX = "exist.BackupRestoreSecurityPrincipalsTest"; private final static String BACKUP_FILE_SUFFIX = ".backup.zip"; private final static String FRANK_USER = "frank"; private final static String JOE_USER = "joe"; private final static String JACK_USER = "jack"; @ClassRule public static ExistXmldbEmbeddedServer server = new ExistXmldbEmbeddedServer(false, true, true); /** * 1. With an empty database we create three * users: 'frank', 'joe', and 'jack'. * * 2. We create a backup of the database which contains * the three users from (1). * * 3. We destroy the database, restart the server, * and start again with a clean database. * * 4. With an (again) empty database we create two * users: 'frank', and 'jack'. * * 5. We then try and restore the database backup from (2), which * contains the original 'frank', 'joe', and 'jack' users. * * frank will have the same username and user id in the current * database and the backup we are trying to restore. * * joe does not exist in the current database, but his user id * in the backup will collide with that of jack in the current database. * * jack will have a different user id in the backup when compared to the current * database, however he will have the same username. * * We want to make sure that after the restore, all three users are present * that they have distinct and expected user ids and that any resources * that were owned by them are still correctly owner by them (and not some other user). */ @Test public void restoreConflictingUsername() throws PermissionDeniedException, EXistException, SAXException, ParserConfigurationException, IOException, URISyntaxException, XMLDBException, IllegalAccessException, ClassNotFoundException, InstantiationException { // creates a database with new users: 'frank(id=11)', 'joe(id=12)', and 'jack(id=13)' createInitialUsers(FRANK_USER, JOE_USER, JACK_USER); // create a backup of the database (which has the initial users) final Path backupFile = backupDatabase(); //reset database to empty server.restart(true); //create new users: 'frank(id=11)' and 'jack(id=12)' createInitialUsers(FRANK_USER, JACK_USER); final String accountQuery = "declare namespace c = 'http://exist-db.org/Configuration';\n" + "for $account in //c:account\n" + "return\n" + "<user id='{$account/@id}' name='{$account/c:name}'/>"; final XPathQueryService xqs = (XPathQueryService) server.getRoot().getService("XPathQueryService", "1.0"); final SecurityManagerImpl sm = (SecurityManagerImpl) BrokerPool.getInstance().getSecurityManager(); //check the current user accounts ResourceSet result = xqs.query(accountQuery); assertUser(RealmImpl.ADMIN_ACCOUNT_ID, SecurityManager.DBA_USER, ((XMLResource) result.getResource(0)).getContentAsDOM()); assertUser(RealmImpl.GUEST_ACCOUNT_ID, SecurityManager.GUEST_USER, ((XMLResource) result.getResource(1)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 1, "frank", ((XMLResource) result.getResource(2)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 2, "jack", ((XMLResource) result.getResource(3)).getContentAsDOM()); //check the last user id assertEquals(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 2, sm.getLastAccountId()); //last account id should be that of 'jack' //create a test collection and give everyone access final CollectionManagementService cms = (CollectionManagementService)server.getRoot().getService("CollectionManagementService", "1.0"); final Collection test = cms.createCollection("test"); final UserManagementService testUms = (UserManagementService)test.getService("UserManagementService", "1.0"); testUms.chmod("rwxrwxrwx"); //create and store a new document as 'frank' final Collection frankTest = DatabaseManager.getCollection("xmldb:exist:///db/test", FRANK_USER, FRANK_USER); final String FRANKS_DOCUMENT = "franks-document.xml"; final Resource frankDoc = frankTest.createResource(FRANKS_DOCUMENT, XMLResource.RESOURCE_TYPE); frankDoc.setContent("<hello>frank</hello>"); frankTest.storeResource(frankDoc); //create and store a new document as 'jack' final Collection jackTest = DatabaseManager.getCollection("xmldb:exist:///db/test", JACK_USER, JACK_USER); final String JACKS_DOCUMENT = "jacks-document.xml"; final Resource jackDoc = jackTest.createResource(JACKS_DOCUMENT, XMLResource.RESOURCE_TYPE); jackDoc.setContent("<hello>jack</hello>"); jackTest.storeResource(jackDoc); //restore the database backup final Restore restore = new Restore(); restore.restore(new NullRestoreListener(), "admin", "", null, backupFile, "xmldb:exist:///db"); //check the current user accounts after the restore result = xqs.query(accountQuery); assertUser(RealmImpl.ADMIN_ACCOUNT_ID, SecurityManager.DBA_USER, ((XMLResource) result.getResource(0)).getContentAsDOM()); assertUser(RealmImpl.GUEST_ACCOUNT_ID, SecurityManager.GUEST_USER, ((XMLResource) result.getResource(1)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 1, FRANK_USER, ((XMLResource) result.getResource(2)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 2, JACK_USER, ((XMLResource) result.getResource(3)).getContentAsDOM()); assertUser(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 3, JOE_USER, ((XMLResource) result.getResource(4)).getContentAsDOM()); //check the last user id after the restore assertEquals(SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID + 3, sm.getLastAccountId()); //last account id should be that of 'joe' //check the owner of frank's document after restore final Resource fDoc = test.getResource(FRANKS_DOCUMENT); final Permission franksDocPermissions = testUms.getPermissions(fDoc); assertEquals(FRANK_USER, franksDocPermissions.getOwner().getName()); //check the owner of jack's document after restore final Resource jDoc = test.getResource(JACKS_DOCUMENT); final Permission jacksDocPermissions = testUms.getPermissions(jDoc); assertEquals(JACK_USER, jacksDocPermissions.getOwner().getName()); } /** * Creates initial database users. * * NOTE: The database must be in a clean initialised empty state. */ private void createInitialUsers(final String... usernames) throws PermissionDeniedException, XMLDBException, SAXException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { int lastAccountId = SecurityManagerImpl.INITIAL_LAST_ACCOUNT_ID; for (final String username : usernames) { createUser(username, username); assertEquals(++lastAccountId, getUser(username).getId()); } } /** * Backup the database. * * @return The path to the database backup. */ private Path backupDatabase() throws IOException, XMLDBException, SAXException { final Path backupFile = Files.createTempFile(BACKUP_FILE_PREFIX, BACKUP_FILE_SUFFIX); backupFile.toFile().deleteOnExit(); final Backup backup = new Backup(TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD, backupFile); backup.backup(false, null); return backupFile; } private void assertUser(final int userId, final String userName, final Node account) { assertEquals(userId, Integer.parseInt(account.getAttributes().getNamedItem("id").getNodeValue())); assertEquals(userName, account.getAttributes().getNamedItem("name").getNodeValue()); } private void createUser(final String username, final String password) throws XMLDBException, PermissionDeniedException { final UserManagementService ums = (UserManagementService) server.getRoot().getService("UserManagementService", "1.0"); final Account user = new UserAider(username); user.setPassword(password); //create the personal group final Group group = new GroupAider(username); group.setMetadataValue(EXistSchemaType.DESCRIPTION, "Personal group for " + username); group.addManager(ums.getAccount("admin")); ums.addGroup(group); //add the personal group as the primary group user.addGroup(username); //create the account ums.addAccount(user); //add the new account as a manager of their personal group ums.addGroupManager(username, group.getName()); } private Account getUser(final String username) throws XMLDBException { final UserManagementService ums = (UserManagementService) server.getRoot().getService("UserManagementService", "1.0"); return ums.getAccount(username); } private static class NullRestoreListener implements RestoreListener { @Override public void createCollection(final String collection) { } @Override public void restored(final String resource) { } @Override public void info(final String message) { } @Override public void warn(final String message) { } @Override public void error(final String message) { } @Override public String warningsAndErrorsAsString() { return null; } @Override public boolean hasProblems() { return false; } @Override public void setCurrentCollection(final String currentCollectionName) { } @Override public void setCurrentResource(final String currentResourceName) { } @Override public void restoreStarting() { } @Override public void restoreFinished() { } @Override public void observe(final Observable observable) { } @Override public void setCurrentBackup(final String currentBackup) { } } }
fix build
test/src/org/exist/security/internal/BackupRestoreSecurityPrincipalsTest.java
fix build
Java
unlicense
b1ad050cf323aa41c44b3873e898f21e91df6f8e
0
ioos/sos-injector
package com.axiomalaska.sos.xmlbuilder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.axiomalaska.phenomena.Phenomenon; import com.axiomalaska.sos.data.*; import com.axiomalaska.sos.tools.IdCreator; public class SensorRegisterSensorBuilder extends SosXmlBuilder { // --------------------------------------------------------------------------- // Private Data // --------------------------------------------------------------------------- private SosSensor sensor; private IdCreator idCreator; private SosStation station; // --------------------------------------------------------------------------- // Constructor // --------------------------------------------------------------------------- public SensorRegisterSensorBuilder(SosStation station, SosSensor sensor, IdCreator idCreator){ this.sensor = sensor; this.idCreator = idCreator; this.station = station; } // --------------------------------------------------------------------------- // Public Members // --------------------------------------------------------------------------- /** * Build the XML String */ public String build() { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element registerSensor = doc.createElement("RegisterSensor"); registerSensor.setAttribute("service", "SOS"); registerSensor.setAttribute("version", "1.0.0"); registerSensor.setAttribute("xmlns", "http://www.opengis.net/sos/1.0"); registerSensor.setAttribute("xmlns:swe", "http://www.opengis.net/swe/1.0.1"); registerSensor.setAttribute("xmlns:ows", "http://www.opengeospatial.net/ows"); registerSensor.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink"); registerSensor.setAttribute("xmlns:gml", "http://www.opengis.net/gml"); registerSensor.setAttribute("xmlns:ogc", "http://www.opengis.net/ogc"); registerSensor.setAttribute("xmlns:om", "http://www.opengis.net/om/1.0"); registerSensor.setAttribute("xmlns:sml", "http://www.opengis.net/sensorML/1.0.1"); registerSensor.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); registerSensor.setAttribute("xsi:schemaLocation", "http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosRegisterSensor.xsd http://www.opengis.net/om/1.0 http://schemas.opengis.net/om/1.0.0/extensions/observationSpecialization_override.xsd"); doc.appendChild(registerSensor); Element sensorDescription = doc.createElement("SensorDescription"); registerSensor.appendChild(sensorDescription); Element sensorML = doc.createElement("sml:SensorML"); sensorML.setAttribute("version", "1.0.1"); sensorDescription.appendChild(sensorML); Element member = doc.createElement("sml:member"); sensorML.appendChild(member); Element system = doc.createElement("sml:System"); member.appendChild(system); system.appendChild(createDescriptionNode(doc, station, sensor)); system.appendChild(createNameNode(doc, station, sensor)); system.appendChild(createIdentificationNode(doc)); system.appendChild(createParentProcedures(doc)); List<Phenomenon> phenomena = sensor.getPhenomena(); List<Phenomenon> filteredPhenomena = removeDuplicatePhenomena(phenomena); system.appendChild(createInputsNode(doc, filteredPhenomena)); // make sure that 'network-all' is listed as a network boolean hasNetworkAll = false; for (SosNetwork net : station.getNetworks()) { if (net.getId().toLowerCase().contains("all")) hasNetworkAll = true; } // add network-all as an offering if (!hasNetworkAll) { SosNetworkImp networkall = new SosNetworkImp(); networkall.setDescription("Includes all the sensors in the network"); networkall.setId("network-all"); List<SosNetwork> networks = station.getNetworks(); networks.add(networkall); system.appendChild(createOutputsNode(doc, phenomena, networks)); } else { system.appendChild(createOutputsNode(doc, phenomena, station.getNetworks())); } // system.appendChild(createOutputsNode(doc, filteredPhenomena)); registerSensor.appendChild(createObservationTemplate(doc)); String xmlString = getString(doc); return xmlString; } catch (Exception ex) { System.err.println(ex.getMessage()); } return null; } // --------------------------------------------------------------------------- // Private Members // --------------------------------------------------------------------------- /** * A station can have more than one phenomenon with the same id, but the depth * of the phenomenon must be different. * * @param phenomena - the list of phenomena to remove duplicates from * @return a list of phenomena with the duplicate phenomena id removed. */ private List<Phenomenon> removeDuplicatePhenomena(List<Phenomenon> phenomena) { List<Phenomenon> filteredPhenomena = new ArrayList<Phenomenon>(); Set<String> set = new HashSet<String>(); for(Phenomenon phenomenon : phenomena){ if(!set.contains(phenomenon.getId())){ filteredPhenomena.add(phenomenon); set.add(phenomenon.getId()); } } return filteredPhenomena; } /** * <ObservationTemplate> <om:Measurement> <om:samplingTime/> <om:procedure/> <om:observedProperty/> <om:featureOfInterest></om:featureOfInterest> <om:result xsi:type="gml:MeasureType" uom="" >0.0</om:result> </om:Measurement> </ObservationTemplate> */ private Node createObservationTemplate(Document doc) { Element observationTemplate = doc.createElement("ObservationTemplate"); Element measurement = doc.createElement("om:Measurement"); observationTemplate.appendChild(measurement); Element samplingTime = doc.createElement("om:samplingTime"); measurement.appendChild(samplingTime); Element procedure = doc.createElement("om:procedure"); measurement.appendChild(procedure); Element observedProperty = doc.createElement("om:observedProperty"); measurement.appendChild(observedProperty); Element featureOfInterest = doc.createElement("om:featureOfInterest"); measurement.appendChild(featureOfInterest); Element result = doc.createElement("om:result"); result.setAttribute("uom", ""); result.setAttribute("xsi:type", "gml:MeasureType"); result.appendChild(doc.createTextNode("0.0")); measurement.appendChild(result); return observationTemplate; } /** <sml:outputs> <sml:OutputList> <sml:output name="Air Temperature"> <swe:Quantity definition="http://mmisw.org/ont/cf/parameter/air_temperature"> <gml:metaDataProperty> <offering> <id>network-all</id> </offering> </gml:metaDataProperty> <swe:uom code="C"/> </swe:Quantity> </sml:output> </sml:OutputList> </sml:outputs> */ private Node createOutputsNode(Document doc, List<Phenomenon> phenomena) { Element outputs = doc.createElement("sml:outputs"); Element outputList = doc.createElement("sml:OutputList"); outputs.appendChild(outputList); for(Phenomenon phenomenon : phenomena){ Element output = doc.createElement("sml:output"); output.setAttribute("name", phenomenon.getName()); outputList.appendChild(output); Element quantity = doc.createElement("swe:Quantity"); quantity.setAttribute("definition", phenomenon.getId()); output.appendChild(quantity); Element metaDataProperty = doc.createElement("gml:metaDataProperty"); quantity.appendChild(metaDataProperty); Element offering = doc.createElement("offering"); metaDataProperty.appendChild(offering); Element id = doc.createElement("id"); id.appendChild(doc.createTextNode("network-all")); offering.appendChild(id); Element name = doc.createElement("name"); name.appendChild(doc.createTextNode("Includes all the sensors in the network")); offering.appendChild(name); String unitString = ""; if(phenomenon.getUnit() != null){ // toString generates strings w/ whitespace which is against the pattern symbol for UomSymbol, just remove them?? unitString = phenomenon.getUnit().toString().replaceAll("\\s+", ""); } Element uom = doc.createElement("swe:uom"); uom.setAttribute("code", unitString); quantity.appendChild(uom); } return outputs; } /** <sml:inputs> <sml:InputList> <sml:input name="Air Temperature"> <swe:ObservableProperty definition="http://mmisw.org/ont/cf/parameter/air_temperature"/> </sml:input> </sml:InputList> </sml:inputs> */ private Node createInputsNode(Document doc, List<Phenomenon> phenomena) { Element inputs = doc.createElement("sml:inputs"); Element inputList = doc.createElement("sml:InputList"); inputs.appendChild(inputList); for(Phenomenon phenomenon : phenomena){ Element input = doc.createElement("sml:input"); input.setAttribute("name", phenomenon.getName()); inputList.appendChild(input); Element observableProperty = doc.createElement("swe:ObservableProperty"); observableProperty.setAttribute("definition", phenomenon.getId()); input.appendChild(observableProperty); } return inputs; } /** * Produces the XML below <sml:identification> <sml:IdentifierList> <sml:identifier name="sensorID"> <sml:Term definition="http://mmisw.org/ont/ioos/definition/sensorID"> <sml:value>urn:ioos:sensor:aoos:pilotrock:airtemp</sml:value> </sml:Term> </sml:identifier> </sml:IdentifierList> </sml:identification> */ private Node createIdentificationNode(Document doc) { Element identification = doc.createElement("sml:identification"); Element identifierList = doc.createElement("sml:IdentifierList"); identification.appendChild(identifierList); Element identifier = doc.createElement("sml:identifier"); identifier.setAttribute("name", "sensorID"); identifierList.appendChild(identifier); Element term = doc.createElement("sml:Term"); term.setAttribute("definition", "http://mmisw.org/ont/ioos/definition/sensorID"); identifier.appendChild(term); Element value = doc.createElement("sml:value"); String procedureId = idCreator.createSensorId(station, sensor); value.appendChild(doc.createTextNode(procedureId)); term.appendChild(value); return identification; } /** * <gml:description>STATION DESCRIPTION</gml:description> */ private Node createDescriptionNode(Document doc, SosStation station, SosSensor sensor) { Element description = doc.createElement("gml:description"); description.appendChild(doc.createTextNode(station.getDescription() + ", " + sensor.getDescription())); return description; } /** * <gml:name>urn:ogc:object:feature:Sensor:IFGI:ifgi-sensor-90</gml:name> */ private Node createNameNode(Document doc, SosStation station, SosSensor sensor) { Element name = doc.createElement("gml:name"); name.appendChild(doc.createTextNode(idCreator.createSensorId(station, sensor))); return name; } /** * Produces the XML below <sml:capabilities name="parentProcedures"> <swe:SimpleDataRecord definition="urn:ogc:def:property:capabilities"> <gml:metaDataProperty xlink:title="urn:ogc:object:feature:Station:IFGI:ifgi-station-1" /> <gml:metaDataProperty xlink:title="urn:ogc:object:feature:Network:IFGI:ifgi-network-1" /> </swe:SimpleDataRecord> </sml:capabilities> */ private Node createParentProcedures(Document doc){ Element capabilities = doc.createElement("sml:capabilities"); capabilities.setAttribute("name", "parentProcedures"); Element simpleDataRecord = doc.createElement("swe:SimpleDataRecord"); simpleDataRecord.setAttribute("definition", "urn:ogc:def:property:capabilities"); capabilities.appendChild(simpleDataRecord); Element metaDataProperty = doc.createElement("gml:metaDataProperty"); metaDataProperty.setAttribute("xlink:title", idCreator.createStationId(station)); simpleDataRecord.appendChild(metaDataProperty); for(SosNetwork network : sensor.getNetworks()){ metaDataProperty = doc.createElement("gml:metaDataProperty"); metaDataProperty.setAttribute("xlink:title", idCreator.createNetworkId(network)); simpleDataRecord.appendChild(metaDataProperty); } return capabilities; } /** * Altered outputs node to include the actual networks listed for the station (rather than just network-all) * @param doc * @param filteredPhenomena * @param id * @param description * @return */ private Node createOutputsNode(Document doc, List<Phenomenon> filteredPhenomena, List<SosNetwork> networks) { Element outputs = doc.createElement("sml:outputs"); Element outputList = doc.createElement("sml:OutputList"); outputs.appendChild(outputList); for(Phenomenon phenomenon : filteredPhenomena){ Element output = doc.createElement("sml:output"); output.setAttribute("name", phenomenon.getName()); outputList.appendChild(output); Element quantity = doc.createElement("swe:Quantity"); quantity.setAttribute("definition", phenomenon.getId()); output.appendChild(quantity); for (SosNetwork network : networks) { Element metaDataProperty = doc.createElement("gml:metaDataProperty"); quantity.appendChild(metaDataProperty); Element offering = doc.createElement("offering"); metaDataProperty.appendChild(offering); Element idNode = doc.createElement("id"); idNode.appendChild(doc.createTextNode(network.getId())); offering.appendChild(idNode); Element name = doc.createElement("name"); name.appendChild(doc.createTextNode(network.getDescription())); offering.appendChild(name); } String unitString = ""; if(phenomenon.getUnit() != null){ // toString generates strings w/ whitespace which is against the pattern symbol for UomSymbol, just remove them?? unitString = phenomenon.getUnit().toString().replaceAll("\\s+", ""); } Element uom = doc.createElement("swe:uom"); uom.setAttribute("code", unitString); quantity.appendChild(uom); } return outputs; } }
src/main/java/com/axiomalaska/sos/xmlbuilder/SensorRegisterSensorBuilder.java
package com.axiomalaska.sos.xmlbuilder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.axiomalaska.phenomena.Phenomenon; import com.axiomalaska.sos.data.*; import com.axiomalaska.sos.tools.IdCreator; public class SensorRegisterSensorBuilder extends SosXmlBuilder { // --------------------------------------------------------------------------- // Private Data // --------------------------------------------------------------------------- private SosSensor sensor; private IdCreator idCreator; private SosStation station; // --------------------------------------------------------------------------- // Constructor // --------------------------------------------------------------------------- public SensorRegisterSensorBuilder(SosStation station, SosSensor sensor, IdCreator idCreator){ this.sensor = sensor; this.idCreator = idCreator; this.station = station; } // --------------------------------------------------------------------------- // Public Members // --------------------------------------------------------------------------- /** * Build the XML String */ public String build() { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element registerSensor = doc.createElement("RegisterSensor"); registerSensor.setAttribute("service", "SOS"); registerSensor.setAttribute("version", "1.0.0"); registerSensor.setAttribute("xmlns", "http://www.opengis.net/sos/1.0"); registerSensor.setAttribute("xmlns:swe", "http://www.opengis.net/swe/1.0.1"); registerSensor.setAttribute("xmlns:ows", "http://www.opengeospatial.net/ows"); registerSensor.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink"); registerSensor.setAttribute("xmlns:gml", "http://www.opengis.net/gml"); registerSensor.setAttribute("xmlns:ogc", "http://www.opengis.net/ogc"); registerSensor.setAttribute("xmlns:om", "http://www.opengis.net/om/1.0"); registerSensor.setAttribute("xmlns:sml", "http://www.opengis.net/sensorML/1.0.1"); registerSensor.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); registerSensor.setAttribute("xsi:schemaLocation", "http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosRegisterSensor.xsd http://www.opengis.net/om/1.0 http://schemas.opengis.net/om/1.0.0/extensions/observationSpecialization_override.xsd"); doc.appendChild(registerSensor); Element sensorDescription = doc.createElement("SensorDescription"); registerSensor.appendChild(sensorDescription); Element sensorML = doc.createElement("sml:SensorML"); sensorML.setAttribute("version", "1.0.1"); sensorDescription.appendChild(sensorML); Element member = doc.createElement("sml:member"); sensorML.appendChild(member); Element system = doc.createElement("sml:System"); member.appendChild(system); system.appendChild(createDescriptionNode(doc, station, sensor)); system.appendChild(createNameNode(doc, station, sensor)); system.appendChild(createIdentificationNode(doc)); system.appendChild(createParentProcedures(doc)); List<Phenomenon> phenomena = sensor.getPhenomena(); List<Phenomenon> filteredPhenomena = removeDuplicatePhenomena(phenomena); system.appendChild(createInputsNode(doc, filteredPhenomena)); // make sure that 'network-all' is listed as a network boolean hasNetworkAll = false; for (SosNetwork net : station.getNetworks()) { if (net.getId().toLowerCase().contains("all")) hasNetworkAll = true; } // add network-all as an offering if (!hasNetworkAll) { SosNetworkImp networkall = new SosNetworkImp(); networkall.setDescription("Includes all the sensors in the network"); networkall.setId("network-all"); List<SosNetwork> networks = station.getNetworks(); networks.add(networkall); system.appendChild(createOutputsNode(doc, phenomena, networks)); } else { system.appendChild(createOutputsNode(doc, phenomena, station.getNetworks())); } // system.appendChild(createOutputsNode(doc, filteredPhenomena)); registerSensor.appendChild(createObservationTemplate(doc)); String xmlString = getString(doc); return xmlString; } catch (Exception ex) { System.err.println(ex.getMessage()); } return null; } // --------------------------------------------------------------------------- // Private Members // --------------------------------------------------------------------------- /** * A station can have more than one phenomenon with the same id, but the depth * of the phenomenon must be different. * * @param phenomena - the list of phenomena to remove duplicates from * @return a list of phenomena with the duplicate phenomena id removed. */ private List<Phenomenon> removeDuplicatePhenomena(List<Phenomenon> phenomena) { List<Phenomenon> filteredPhenomena = new ArrayList<Phenomenon>(); Set<String> set = new HashSet<String>(); for(Phenomenon phenomenon : phenomena){ if(!set.contains(phenomenon.getId())){ filteredPhenomena.add(phenomenon); set.add(phenomenon.getId()); } } return filteredPhenomena; } /** * <ObservationTemplate> <om:Measurement> <om:samplingTime/> <om:procedure/> <om:observedProperty/> <om:featureOfInterest></om:featureOfInterest> <om:result xsi:type="gml:MeasureType" uom="" >0.0</om:result> </om:Measurement> </ObservationTemplate> */ private Node createObservationTemplate(Document doc) { Element observationTemplate = doc.createElement("ObservationTemplate"); Element measurement = doc.createElement("om:Measurement"); observationTemplate.appendChild(measurement); Element samplingTime = doc.createElement("om:samplingTime"); measurement.appendChild(samplingTime); Element procedure = doc.createElement("om:procedure"); measurement.appendChild(procedure); Element observedProperty = doc.createElement("om:observedProperty"); measurement.appendChild(observedProperty); Element featureOfInterest = doc.createElement("om:featureOfInterest"); measurement.appendChild(featureOfInterest); Element result = doc.createElement("om:result"); result.setAttribute("uom", ""); result.setAttribute("xsi:type", "gml:MeasureType"); result.appendChild(doc.createTextNode("0.0")); measurement.appendChild(result); return observationTemplate; } /** <sml:outputs> <sml:OutputList> <sml:output name="Air Temperature"> <swe:Quantity definition="http://mmisw.org/ont/cf/parameter/air_temperature"> <gml:metaDataProperty> <offering> <id>network-all</id> </offering> </gml:metaDataProperty> <swe:uom code="C"/> </swe:Quantity> </sml:output> </sml:OutputList> </sml:outputs> */ private Node createOutputsNode(Document doc, List<Phenomenon> phenomena) { Element outputs = doc.createElement("sml:outputs"); Element outputList = doc.createElement("sml:OutputList"); outputs.appendChild(outputList); for(Phenomenon phenomenon : phenomena){ Element output = doc.createElement("sml:output"); output.setAttribute("name", phenomenon.getName()); outputList.appendChild(output); Element quantity = doc.createElement("swe:Quantity"); quantity.setAttribute("definition", phenomenon.getId()); output.appendChild(quantity); Element metaDataProperty = doc.createElement("gml:metaDataProperty"); quantity.appendChild(metaDataProperty); Element offering = doc.createElement("offering"); metaDataProperty.appendChild(offering); Element id = doc.createElement("id"); id.appendChild(doc.createTextNode("network-all")); offering.appendChild(id); Element name = doc.createElement("name"); name.appendChild(doc.createTextNode("Includes all the sensors in the network")); offering.appendChild(name); String unitString = ""; if(phenomenon.getUnit() != null){ // toString generates strings w/ whitespace which is against the pattern symbol for UomSymbol, just remove them?? unitString = phenomenon.getUnit().toString().replaceAll("\\s+", ""); } Element uom = doc.createElement("swe:uom"); uom.setAttribute("code", unitString); quantity.appendChild(uom); } return outputs; } /** <sml:inputs> <sml:InputList> <sml:input name="Air Temperature"> <swe:ObservableProperty definition="http://mmisw.org/ont/cf/parameter/air_temperature"/> </sml:input> </sml:InputList> </sml:inputs> */ private Node createInputsNode(Document doc, List<Phenomenon> phenomena) { Element inputs = doc.createElement("sml:inputs"); Element inputList = doc.createElement("sml:InputList"); inputs.appendChild(inputList); for(Phenomenon phenomenon : phenomena){ Element input = doc.createElement("sml:input"); input.setAttribute("name", phenomenon.getName()); inputList.appendChild(input); Element observableProperty = doc.createElement("swe:ObservableProperty"); observableProperty.setAttribute("definition", phenomenon.getId()); input.appendChild(observableProperty); } return inputs; } /** * Produces the XML below <sml:identification> <sml:IdentifierList> <sml:identifier name="sensorID"> <sml:Term definition="http://mmisw.org/ont/ioos/definition/sensorID"> <sml:value>urn:ioos:sensor:aoos:pilotrock:airtemp</sml:value> </sml:Term> </sml:identifier> </sml:IdentifierList> </sml:identification> */ private Node createIdentificationNode(Document doc) { Element identification = doc.createElement("sml:identification"); Element identifierList = doc.createElement("sml:IdentifierList"); identification.appendChild(identifierList); Element identifier = doc.createElement("sml:identifier"); identifier.setAttribute("name", "sensorID"); identifierList.appendChild(identifier); Element term = doc.createElement("sml:Term"); term.setAttribute("definition", "http://mmisw.org/ont/ioos/definition/sensorID"); identifier.appendChild(term); Element value = doc.createElement("sml:value"); String procedureId = idCreator.createSensorId(station, sensor); value.appendChild(doc.createTextNode(procedureId)); term.appendChild(value); return identification; } /** * <gml:description>STATION DESCRIPTION</gml:description> */ private Node createDescriptionNode(Document doc, SosStation station, SosSensor sensor) { Element description = doc.createElement("gml:description"); description.appendChild(doc.createTextNode(station.getDescription() + ", " + sensor.getDescription())); return description; } /** * <gml:name>urn:ogc:object:feature:Sensor:IFGI:ifgi-sensor-90</gml:name> */ private Node createNameNode(Document doc, SosStation station, SosSensor sensor) { Element name = doc.createElement("gml:name"); name.appendChild(doc.createTextNode(idCreator.createSensorId(station, sensor))); return name; } /** * Produces the XML below <sml:capabilities name="parentProcedures"> <swe:SimpleDataRecord definition="urn:ogc:def:property:capabilities"> <gml:metaDataProperty xlink:title="urn:ogc:object:feature:Station:IFGI:ifgi-station-1" /> <gml:metaDataProperty xlink:title="urn:ogc:object:feature:Network:IFGI:ifgi-network-1" /> </swe:SimpleDataRecord> </sml:capabilities> */ private Node createParentProcedures(Document doc){ Element capabilities = doc.createElement("sml:capabilities"); capabilities.setAttribute("name", "parentProcedures"); Element simpleDataRecord = doc.createElement("swe:SimpleDataRecord"); simpleDataRecord.setAttribute("definition", "urn:ogc:def:property:capabilities"); capabilities.appendChild(simpleDataRecord); Element metaDataProperty = doc.createElement("gml:metaDataProperty"); metaDataProperty.setAttribute("xlink:title", idCreator.createStationId(station)); simpleDataRecord.appendChild(metaDataProperty); for(SosNetwork network : sensor.getNetworks()){ metaDataProperty = doc.createElement("gml:metaDataProperty"); metaDataProperty.setAttribute("xlink:title", idCreator.createNetworkId(network)); simpleDataRecord.appendChild(metaDataProperty); } return capabilities; } /** * Altered outputs node to include the actual networks listed for the station (rather than just network-all) * @param doc * @param filteredPhenomena * @param id * @param description * @return */ private Node createOutputsNode(Document doc, List<Phenomenon> filteredPhenomena, List<SosNetwork> networks) { Element outputs = doc.createElement("sml:outputs"); Element outputList = doc.createElement("sml:OutputList"); outputs.appendChild(outputList); for (SosNetwork network : networks) { for(Phenomenon phenomenon : filteredPhenomena){ Element output = doc.createElement("sml:output"); output.setAttribute("name", phenomenon.getName()); outputList.appendChild(output); Element quantity = doc.createElement("swe:Quantity"); quantity.setAttribute("definition", phenomenon.getId()); output.appendChild(quantity); Element metaDataProperty = doc.createElement("gml:metaDataProperty"); quantity.appendChild(metaDataProperty); Element offering = doc.createElement("offering"); metaDataProperty.appendChild(offering); Element idNode = doc.createElement("id"); idNode.appendChild(doc.createTextNode(network.getId())); offering.appendChild(idNode); Element name = doc.createElement("name"); name.appendChild(doc.createTextNode(network.getDescription())); offering.appendChild(name); String unitString = ""; if(phenomenon.getUnit() != null){ // toString generates strings w/ whitespace which is against the pattern symbol for UomSymbol, just remove them?? unitString = phenomenon.getUnit().toString().replaceAll("\\s+", ""); } Element uom = doc.createElement("swe:uom"); uom.setAttribute("code", unitString); quantity.appendChild(uom); } } return outputs; } }
changed sensor register builder to add sensors to multiple networks
src/main/java/com/axiomalaska/sos/xmlbuilder/SensorRegisterSensorBuilder.java
changed sensor register builder to add sensors to multiple networks
Java
apache-2.0
b181e437c8b928af6acb7d493d9cdc810b9fd5f7
0
sergeyltd/pilgrim-base,sergeyltd/pilgrim-base
package org.pilgrim.leetcode.y2021; import org.pilgrim.base.linkedlist.ReverseLinkedList.ListNode; /* Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. For example, the following two linked lists begin to intersect at node c1: It is guaranteed that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Example 1: Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 Output: Intersected at '8' Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. Example 2: Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 Output: Intersected at '2' Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 Output: No intersection Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. Constraints: The number of nodes of listA is in the m. The number of nodes of listB is in the n. 0 <= m, n <= 3 * 104 1 <= Node.val <= 105 0 <= skipA <= m 0 <= skipB <= n intersectVal is 0 if listA and listB do not intersect. intersectVal == listA[skipA + 1] == listB[skipB + 1] if listA and listB intersect. Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory?*/ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class IntersectionTwoLinkedLists { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode pA = headA; ListNode pB = headB; while (pA != pB) { pA = pA == null ? headB : pA.next; pB = pB == null ? headA : pB.next; } return pA; // Note: In the case lists do not intersect, the pointers for A and B // will still line up in the 2nd iteration, just that here won't be // a common node down the list and both will reach their respective ends // at the same time. So pA will be NULL in that case. } }
src/main/java/org/pilgrim/leetcode/y2021/IntersectionTwoLinkedLists.java
package org.pilgrim.leetcode.y2021; import org.pilgrim.base.linkedlist.ReverseLinkedList.ListNode; /* Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. For example, the following two linked lists begin to intersect at node c1: It is guaranteed that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Example 1: Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 Output: Intersected at '8' Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. Example 2: Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 Output: Intersected at '2' Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 Output: No intersection Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. Constraints: The number of nodes of listA is in the m. The number of nodes of listB is in the n. 0 <= m, n <= 3 * 104 1 <= Node.val <= 105 0 <= skipA <= m 0 <= skipB <= n intersectVal is 0 if listA and listB do not intersect. intersectVal == listA[skipA + 1] == listB[skipB + 1] if listA and listB intersect. Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory?*/ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class IntersectionTwoLinkedLists { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null){ return null; } int lengthA = len(headA); int lengthB = len(headB); if(lengthA > lengthB){ int diff = lengthA - lengthB; headA = shift(headA, diff); } else if(lengthA < lengthB){ int diff = lengthB - lengthA; headB = shift(headB, diff); } while(headA != null && headB != null){ System.out.println("a=" + headA.val); System.out.println("b=" + headB.val); if(headA == headB){ return headA; } headA = headA.next; headB = headB.next; } return null; } private static int len(ListNode node){ int length = 0; while(node != null){ node = node.next; length++; } System.out.println(length); return length; } private static ListNode shift(ListNode node, int d){ for(int i=0; i<d; i++){ node = node.next; } System.out.println(node.val); return node; } }
IntersectionTwoLinkedLists updated
src/main/java/org/pilgrim/leetcode/y2021/IntersectionTwoLinkedLists.java
IntersectionTwoLinkedLists updated
Java
apache-2.0
e1646b2b3dc9aac033ebefee476bcaf3ef34fd97
0
andy-goryachev/FxDock
// Copyright © 2016-2018 Andy Goryachev <andy@goryachev.com> package goryachev.fxdock.internal; import goryachev.common.util.CList; import goryachev.common.util.D; import goryachev.common.util.SStream; import goryachev.fx.FX; import goryachev.fxdock.FxDockFramework; import goryachev.fxdock.FxDockPane; import goryachev.fxdock.FxDockWindow; import java.util.List; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Window; /** * Docking Framework Tools. */ public class DockTools { private static boolean isEmpty(Node n) { if(n == null) { return true; } else if(n instanceof FxDockRootPane) { return isEmpty(((FxDockRootPane)n).getContent()); } else if(n instanceof FxDockBorderPane) { return false; } else if(n instanceof FxDockEmptyPane) { return true; } else if(n instanceof FxDockSplitPane) { return (((FxDockSplitPane)n).getPaneCount() == 0); } else if(n instanceof FxDockTabPane) { return (((FxDockTabPane)n).getTabCount() == 0); } return true; } public static void setParent(Node p, Node child) { ParentProperty prop = getParentProperty(child); if(prop != null) { Node oldp = prop.get(); if(oldp != null) { if(oldp == p) { D.print("same parent", p); // FIX ??? } else { int ix = indexInParent(child); if(ix >= 0) { replaceChild(oldp, ix, new DeletedPane()); } } } prop.set(p); } } private static ParentProperty getParentProperty(Node n) { if(n instanceof FxDockBorderPane) { return ((FxDockBorderPane)n).parent; } else if(n instanceof FxDockSplitPane) { return ((FxDockSplitPane)n).parent; } else if(n instanceof FxDockTabPane) { return ((FxDockTabPane)n).parent; } else if(n instanceof FxDockEmptyPane) { return ((FxDockEmptyPane)n).parent; } else if(n instanceof DeletedPane) { return null; } // return null; throw new Error("?" + n); } public static void remove(Node n) { Node p = getParent(n); remove(p, n); collapseEmptySpace(p); } private static void remove(Node parent, Node child) { if(parent instanceof FxDockTabPane) { ((FxDockTabPane)parent).removeTab(child); } else if(parent instanceof FxDockSplitPane) { ((FxDockSplitPane)parent).removePane(child); } else if(parent instanceof Pane) { ((Pane)parent).getChildren().remove(child); } else { throw new Error("?" + parent); } } public static Node getParent(Node n) { if(n instanceof FxDockBorderPane) { return ((FxDockBorderPane)n).parent.get(); } else if(n instanceof FxDockSplitPane) { return ((FxDockSplitPane)n).parent.get(); } else if(n instanceof FxDockTabPane) { return ((FxDockTabPane)n).parent.get(); } else if(n instanceof FxDockEmptyPane) { return ((FxDockEmptyPane)n).parent.get(); } return null; } public static FxDockWindow findWindow(double screenx, double screeny) { CList<FxDockWindow> list = null; List<FxDockWindow> ws = FxDockFramework.getWindows(); for(FxDockWindow w: ws) { if(w.isIconified()) { continue; } if(contains(w, screenx, screeny)) { if(list == null) { list = new CList<>(ws.size()); } list.add(w); } } if(list == null) { return null; } else { return FxDockFramework.findTopWindow(list); } } public static FxDockWindow getWindow(Node n) { if(n != null) { Scene sc = n.getScene(); if(sc != null) { Window w = sc.getWindow(); if(w instanceof FxDockWindow) { return (FxDockWindow)w; } } } return null; } // returns true if the window has been closed public static boolean closeWindowUnlessLast(Node n) { FxDockWindow w = getWindow(n); if(w != null) { if(FxDockFramework.getWindowCount() > 1) { w.discardSettings = true; w.close(); return true; } } return false; } /** for debugging or information purposes */ public static SStream saveLayout(Node n) { return FxDockSchema.saveLayoutPrivate(n); } public static boolean aboveDiagonal(double x, double y, double x0, double y0, double x1, double y1) { double liney = y0 + (y1 - y0) * (x - x0) / (x1 - x0); return y < liney; } public static boolean contains(Window w, double screenx, double screeny) { double x = w.getX(); if(screenx < x) { return false; } else if(screenx > (x + w.getWidth())) { return false; } double y = w.getY(); if(screeny < y) { return false; } else if(screeny > (y + w.getHeight())) { return false; } return true; } public static List<Pane> collectDividers(FxDockSplitPane sp) { CList<Pane> rv = new CList<>(); for(Node n: sp.lookupAll(".split-pane-divider")) { if(n instanceof Pane) { Pane p = (Pane)n; if(p.getParent() == sp) { rv.add(p); } } } return rv; } public static Node findDockElement(Node n, double screenx, double screeny) { if(n != null) { Point2D p = n.screenToLocal(screenx, screeny); if(n.contains(p)) { if(n instanceof FxDockPane) { return n; } else if(n instanceof FxDockEmptyPane) { return n; } else if(n instanceof FxDockSplitPane) { Node ch = findDockElement(((FxDockSplitPane)n).getPanes(), screenx, screeny); if(ch == null) { return n; } else { // on a divider return ch; } } else if(n instanceof FxDockTabPane) { FxDockTabPane t = (FxDockTabPane)n; return t.getSelectedTab(); } if(n instanceof Parent) { Node ch = findDockElement(((Parent)n).getChildrenUnmodifiable(), screenx, screeny); if(ch != null) { return ch; } } } } return null; } private static Node findDockElement(List<Node> ns, double screenx, double screeny) { for(Node ch: ns) { Node found = findDockElement(ch, screenx, screeny); if(found != null) { return found; } } return null; } private static void unlink(Node n) { Node p = getParent(n); if(p == null) { // ok } else if(p instanceof FxDockSplitPane) { // make sure an empty pane is left in place int ix = indexInParent(n); ((FxDockSplitPane)p).setPane(ix, new DeletedPane()); } else if(p instanceof FxDockTabPane) { // make sure an empty pane is left in place int ix = indexInParent(n); ((FxDockTabPane)p).setTab(ix, new DeletedPane()); } else if(p instanceof FxDockRootPane) { ((FxDockRootPane)p).setContent(new DeletedPane()); } else if(p instanceof DeletedPane) { // no problemo } else { throw new Error("?" + p); } } public static Node prepareToAdd(Node n) { if(n == null) { return new FxDockEmptyPane(); } else { // TODO this does not look right - use unlink before starting the move unlink(n); return n; } } private static Node makeSplit(Node client, Node old, Where where) { if(client == old) { old = new FxDockEmptyPane(); } // check if nested splits are not needed Node p = getParent(old); if(p instanceof FxDockSplitPane) { FxDockSplitPane sp = (FxDockSplitPane)p; if(sp.getOrientation() == Orientation.HORIZONTAL) { switch(where) { case LEFT: sp.addPane(0, client); return sp; case RIGHT: sp.addPane(client); return sp; } } else { switch(where) { case TOP: sp.addPane(0, client); return sp; case BOTTOM: sp.addPane(client); return sp; } } } switch(where) { case BOTTOM: return new FxDockSplitPane(Orientation.VERTICAL, old, client); case LEFT: return new FxDockSplitPane(Orientation.HORIZONTAL, client, old); case RIGHT: return new FxDockSplitPane(Orientation.HORIZONTAL, old, client); case TOP: return new FxDockSplitPane(Orientation.VERTICAL, client, old); case CENTER: default: throw new Error("?" + where); } } private static FxDockTabPane makeTab(Node old, Node client) { FxDockTabPane t = new FxDockTabPane(); t.addTab(old); t.addTab(client); t.select(client); return t; } public static int indexInParent(Node n) { Node p = getParent(n); if(p instanceof FxDockSplitPane) { return ((FxDockSplitPane)p).indexOfPane(n); } else if(p instanceof FxDockTabPane) { return ((FxDockTabPane)p).indexOfTab(n); } return -1; } /** replaces a child at the specified index in the parent */ private static void replaceChild(Node p, int index, Node newChild) { if(p instanceof FxDockSplitPane) { ((FxDockSplitPane)p).setPane(index, newChild); } else if(p instanceof FxDockTabPane) { ((FxDockTabPane)p).setTab(index, newChild); } else if(p instanceof FxDockRootPane) { ((FxDockRootPane)p).setContent(newChild); } else { throw new Error("?" + p); } } public static void collapseEmptySpace(Node parent) { if(parent instanceof FxDockSplitPane) { FxDockSplitPane p = (FxDockSplitPane)parent; // remove deleted panes for(int i=p.getPaneCount()-1; i>=0; --i) { Node n = p.getPane(i); if(n instanceof DeletedPane) { p.removePane(i); } } // combine empty panes boolean empty = false; int ct = 0; int index = -1; for(int i=p.getPaneCount()-1; i>=0; --i) { Node n = p.getPane(i); if(isEmpty(n)) { if(empty) { p.removePane(i); } else { empty = true; } } else { empty = false; index = i; ct++; } } if(ct < 2) { int ix = indexInParent(p); Node pp = getParent(p); switch(ct) { case 0: replaceChild(pp, ix, new DeletedPane()); collapseEmptySpace(pp); break; case 1: // no need to have split pane with a single pane Node n = p.getPane(index); replaceChild(pp, ix, n); break; } } } else if(parent instanceof FxDockTabPane) { FxDockTabPane p = (FxDockTabPane)parent; // remove deleted panes for(int i=p.getTabCount()-1; i>=0; --i) { Node n = p.getTab(i); if(n == null) { p.removeTab(i); } else if(n instanceof DeletedPane) { p.removeTab(i); } } // combine empty panes boolean empty = false; int ct = 0; int index = -1; for(int i=p.getTabCount()-1; i>=0; --i) { Node n = p.getTab(i); if(isEmpty(n)) { if(empty) { p.removeTab(i); } else { empty = true; } } else { empty = false; index = i; ct++; } } if(ct < 2) { int ix = indexInParent(p); Node p2 = getParent(p); switch(ct) { case 0: replaceChild(p2, ix, new DeletedPane()); collapseEmptySpace(p2); break; case 1: // no need to have tab pane with a single tab Node n = p.getTab(index); replaceChild(p2, ix, n); break; } } } else if(parent instanceof FxDockRootPane) { FxDockRootPane rp = (FxDockRootPane)parent; Node n = rp.getContent(); if(isEmpty(n)) { if(!closeWindowUnlessLast(parent)) { rp.setContent(null); } } } } private static boolean insertSplit(FxDockPane client, FxDockSplitPane sp, Object where) { if(where instanceof Where) { Orientation or = sp.getOrientation(); switch((Where)where) { case LEFT: if(or == Orientation.HORIZONTAL) { sp.addPane(0, client); return true; } break; case RIGHT: if(or == Orientation.HORIZONTAL) { sp.addPane(client); return true; } break; case TOP: if(or == Orientation.VERTICAL) { sp.addPane(0, client); return true; } break; case BOTTOM: if(or == Orientation.VERTICAL) { sp.addPane(client); return true; } break; } } return false; } public static void insertPane(FxDockPane client, Node target, Object where) { if(target instanceof FxDockRootPane) { FxDockRootPane rp = (FxDockRootPane)target; BeforeDrop b = new BeforeDrop(client, target); boolean makesplit = true; Node old = rp.getContent(); if(old instanceof FxDockSplitPane) { if(insertSplit(client, (FxDockSplitPane)old, where)) { makesplit = false; } } if(makesplit) { rp.setContent(makeSplit(client, old, (Where)where)); } collapseEmptySpace(b.clientParent); b.adjustSplits(); } else if(target instanceof FxDockPane) { // FIX throw new Error("replace with split or tab"); } else { // TODO throw new Error("?" + target); } } public static void moveToNewWindow(FxDockPane client, double screenx, double screeny) { Node p = getParent(client); double w = client.getWidth(); double h = client.getHeight(); FxDockWindow win = FxDockFramework.createWindow(); win.setContent(client); win.setX(screenx); win.setY(screeny); // moving window after show() seems to cause flicker double op = win.getOpacity(); win.setOpacity(0); FxDockFramework.open(win); // take into account window decorations // apparently, this is available only after show() Node n = win.getDockRootPane().getCenter(); Insets m = FX.getInsetsInWindow(win, n); // this may still cause flicker win.setX(screenx - m.getLeft()); win.setY(screeny - m.getTop()); win.setWidth(w + m.getLeft() + m.getRight()); win.setHeight(h + m.getTop() + m.getBottom()); win.setOpacity(op); collapseEmptySpace(p); } public static void moveToNewWindow(FxDockPane client) { Node p = getParent(client); Window clientWindow = getWindow(client); // TODO still not correct Insets m = getWindowInsets(clientWindow); Point2D pos = client.localToScreen(0, 0); FxDockWindow w = FxDockFramework.createWindow(); w.setContent(client); w.setX(pos.getX() - m.getLeft()); w.setY(pos.getY() - m.getTop()); w.setWidth(client.getWidth() + m.getRight() + m.getLeft()); w.setHeight(client.getHeight() + m.getTop() + m.getBottom()); FxDockFramework.open(w); collapseEmptySpace(p); } public static Insets getWindowInsets(Window w) { Scene s = w.getScene(); double left = s.getX(); double top = s.getY(); double right = w.getWidth() - s.getWidth() - left; double bottom = w.getHeight() - s.getHeight() - top; return new Insets(top, right, bottom, left); } public static void moveToSplit(FxDockPane client, FxDockSplitPane sp, int index) { BeforeDrop b = new BeforeDrop(client, sp); sp.addPane(index, client); collapseEmptySpace(b.clientParent); b.adjustSplits(); } private static void addToRootPane(FxDockPane client, FxDockRootPane rp, Where where) { Node old = rp.getContent(); switch(where) { case CENTER: if(old instanceof FxDockEmptyPane) { rp.setContent(client); } else { rp.setContent(makeTab(old, client)); } break; default: rp.setContent(makeSplit(client, old, where)); break; } } private static void addToTabPane(FxDockPane client, FxDockTabPane tp, int index, Where where) { switch(where) { case CENTER: tp.addTab(client); tp.select(client); break; default: Node p = getParent(tp); int ix = indexInParent(tp); Node sp = makeSplit(client, tp, where); if(p != sp) { replaceChild(p, ix, sp); } break; } } private static void addToSplitPane(FxDockPane client, Pane target, FxDockSplitPane sp, int index, Where where) { // determine index from where and sp orientation int ix; if(sp.getOrientation() == Orientation.HORIZONTAL) { switch(where) { case LEFT: ix = index; break; case RIGHT: ix = index+1; break; default: ix = -1; break; } } else { switch(where) { case BOTTOM: ix = index+1; break; case TOP: ix = index; break; default: ix = -1; break; } } if(ix < 0) { Node p = getParent(target); int ip = indexInParent(target); switch(where) { case CENTER: if(target instanceof FxDockEmptyPane) { sp.setPane(ip, client); } else { Node t = makeTab(target, client); replaceChild(p, ip, t); } break; default: Node n = makeSplit(client, target, where); replaceChild(p, ip, n); break; } } else { // simply insert another pane into this split pane sp.addPane(ix, client); } } /** moves client pane to new position, creating necessary splits or tabs */ public static void moveToPane(FxDockPane client, Pane target, Where where) { BeforeDrop b = new BeforeDrop(client, target); Node targetParent = getParent(target); if(targetParent instanceof FxDockSplitPane) { int targetIndex = indexInParent(target); addToSplitPane(client, target, (FxDockSplitPane)targetParent, targetIndex, where); } else if(targetParent instanceof FxDockTabPane) { int targetIndex = indexInParent(target); addToTabPane(client, (FxDockTabPane)targetParent, targetIndex, where); } else if(targetParent instanceof FxDockRootPane) { addToRootPane(client, (FxDockRootPane)targetParent, where); } else { throw new Error("?" + targetParent); } collapseEmptySpace(b.clientParent); b.adjustSplits(); } }
src/goryachev/fxdock/internal/DockTools.java
// Copyright © 2016-2018 Andy Goryachev <andy@goryachev.com> package goryachev.fxdock.internal; import goryachev.common.util.CList; import goryachev.common.util.D; import goryachev.common.util.SStream; import goryachev.fx.FX; import goryachev.fxdock.FxDockFramework; import goryachev.fxdock.FxDockPane; import goryachev.fxdock.FxDockWindow; import java.util.List; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Window; /** * Docking Framework Tools. */ public class DockTools { private static boolean isEmpty(Node n) { if(n == null) { return true; } else if(n instanceof FxDockRootPane) { return isEmpty(((FxDockRootPane)n).getContent()); } else if(n instanceof FxDockBorderPane) { return false; } else if(n instanceof FxDockEmptyPane) { return true; } else if(n instanceof FxDockSplitPane) { return (((FxDockSplitPane)n).getPaneCount() == 0); } else if(n instanceof FxDockTabPane) { return (((FxDockTabPane)n).getTabCount() == 0); } return true; } public static void setParent(Node p, Node child) { ParentProperty prop = getParentProperty(child); if(prop != null) { Node oldp = prop.get(); if(oldp != null) { if(oldp == p) { D.print("same parent", p); // FIX ??? } else { int ix = indexInParent(child); if(ix >= 0) { replaceChild(oldp, ix, new DeletedPane()); } } } prop.set(p); } } private static ParentProperty getParentProperty(Node n) { if(n instanceof FxDockBorderPane) { return ((FxDockBorderPane)n).parent; } else if(n instanceof FxDockSplitPane) { return ((FxDockSplitPane)n).parent; } else if(n instanceof FxDockTabPane) { return ((FxDockTabPane)n).parent; } else if(n instanceof FxDockEmptyPane) { return ((FxDockEmptyPane)n).parent; } else if(n instanceof DeletedPane) { return null; } // return null; throw new Error("?" + n); } public static void remove(Node n) { Node p = getParent(n); remove(p, n); collapseEmptySpace(p); } private static void remove(Node parent, Node child) { if(parent instanceof FxDockTabPane) { ((FxDockTabPane)parent).removeTab(child); } else if(parent instanceof FxDockSplitPane) { ((FxDockSplitPane)parent).removePane(child); } else if(parent instanceof Pane) { ((Pane)parent).getChildren().remove(child); } else { throw new Error("?" + parent); } } public static Node getParent(Node n) { if(n instanceof FxDockBorderPane) { return ((FxDockBorderPane)n).parent.get(); } else if(n instanceof FxDockSplitPane) { return ((FxDockSplitPane)n).parent.get(); } else if(n instanceof FxDockTabPane) { return ((FxDockTabPane)n).parent.get(); } else if(n instanceof FxDockEmptyPane) { return ((FxDockEmptyPane)n).parent.get(); } return null; } public static FxDockWindow findWindow(double screenx, double screeny) { CList<FxDockWindow> list = null; List<FxDockWindow> ws = FxDockFramework.getWindows(); for(FxDockWindow w: ws) { if(w.isIconified()) { continue; } if(contains(w, screenx, screeny)) { if(list == null) { list = new CList<>(ws.size()); } list.add(w); } } if(list == null) { return null; } else { return FxDockFramework.findTopWindow(list); } } public static FxDockWindow getWindow(Node n) { if(n != null) { Scene sc = n.getScene(); if(sc != null) { Window w = sc.getWindow(); if(w instanceof FxDockWindow) { return (FxDockWindow)w; } } } return null; } // returns true if the window has been closed public static boolean closeWindowUnlessLast(Node n) { FxDockWindow w = getWindow(n); if(w != null) { if(FxDockFramework.getWindowCount() > 1) { w.discardSettings = true; w.close(); return true; } } return false; } /** for debugging or information purposes */ public static SStream saveLayout(Node n) { return FxDockSchema.saveLayoutPrivate(n); } public static boolean aboveDiagonal(double x, double y, double x0, double y0, double x1, double y1) { double liney = y0 + (y1 - y0) * (x - x0) / (x1 - x0); return y < liney; } public static boolean contains(Window w, double screenx, double screeny) { double x = w.getX(); if(screenx < x) { return false; } else if(screenx > (x + w.getWidth())) { return false; } double y = w.getY(); if(screeny < y) { return false; } else if(screeny > (y + w.getHeight())) { return false; } return true; } public static List<Pane> collectDividers(FxDockSplitPane sp) { CList<Pane> rv = new CList<>(); for(Node n: sp.lookupAll(".split-pane-divider")) { if(n instanceof Pane) { Pane p = (Pane)n; if(p.getParent() == sp) { rv.add(p); } } } return rv; } public static Node findDockElement(Node n, double screenx, double screeny) { if(n != null) { Point2D p = n.screenToLocal(screenx, screeny); if(n.contains(p)) { if(n instanceof FxDockPane) { return n; } else if(n instanceof FxDockEmptyPane) { return n; } else if(n instanceof FxDockSplitPane) { Node ch = findDockElement(((FxDockSplitPane)n).getPanes(), screenx, screeny); if(ch == null) { return n; } else { // on a divider return ch; } } else if(n instanceof FxDockTabPane) { FxDockTabPane t = (FxDockTabPane)n; return t.getSelectedTab(); } if(n instanceof Parent) { Node ch = findDockElement(((Parent)n).getChildrenUnmodifiable(), screenx, screeny); if(ch != null) { return ch; } } } } return null; } private static Node findDockElement(List<Node> ns, double screenx, double screeny) { for(Node ch: ns) { Node found = findDockElement(ch, screenx, screeny); if(found != null) { return found; } } return null; } private static void unlink(Node n) { Node p = getParent(n); if(p == null) { // ok } else if(p instanceof FxDockSplitPane) { // make sure an empty pane is left in place int ix = indexInParent(n); ((FxDockSplitPane)p).setPane(ix, new DeletedPane()); } else if(p instanceof FxDockTabPane) { // make sure an empty pane is left in place int ix = indexInParent(n); ((FxDockTabPane)p).setTab(ix, new DeletedPane()); } else if(p instanceof FxDockRootPane) { ((FxDockRootPane)p).setContent(new DeletedPane()); } else if(p instanceof DeletedPane) { // no problemo } else { throw new Error("?" + p); } } public static Node prepareToAdd(Node n) { if(n == null) { return new FxDockEmptyPane(); } else { // TODO this does not look right - use unlink before starting the move unlink(n); return n; } } private static Node makeSplit(Node client, Node old, Where where) { if(client == old) { old = new FxDockEmptyPane(); } // check if nested splits are not needed Node p = getParent(old); if(p instanceof FxDockSplitPane) { FxDockSplitPane sp = (FxDockSplitPane)p; if(sp.getOrientation() == Orientation.HORIZONTAL) { switch(where) { case LEFT: sp.addPane(0, client); return sp; case RIGHT: sp.addPane(client); return sp; } } else { switch(where) { case TOP: sp.addPane(0, client); return sp; case BOTTOM: sp.addPane(client); return sp; } } } switch(where) { case BOTTOM: return new FxDockSplitPane(Orientation.VERTICAL, old, client); case LEFT: return new FxDockSplitPane(Orientation.HORIZONTAL, client, old); case RIGHT: return new FxDockSplitPane(Orientation.HORIZONTAL, old, client); case TOP: return new FxDockSplitPane(Orientation.VERTICAL, client, old); case CENTER: default: throw new Error("?" + where); } } private static FxDockTabPane makeTab(Node old, Node client) { FxDockTabPane t = new FxDockTabPane(); t.addTab(old); t.addTab(client); t.select(client); return t; } public static int indexInParent(Node n) { Node p = getParent(n); if(p instanceof FxDockSplitPane) { return ((FxDockSplitPane)p).indexOfPane(n); } else if(p instanceof FxDockTabPane) { return ((FxDockTabPane)p).indexOfTab(n); } return -1; } /** replaces a child at the specified index in the parent */ private static void replaceChild(Node p, int index, Node newChild) { if(p instanceof FxDockSplitPane) { ((FxDockSplitPane)p).setPane(index, newChild); } else if(p instanceof FxDockTabPane) { ((FxDockTabPane)p).setTab(index, newChild); } else if(p instanceof FxDockRootPane) { ((FxDockRootPane)p).setContent(newChild); } else { throw new Error("?" + p); } } public static void collapseEmptySpace(Node parent) { if(parent instanceof FxDockSplitPane) { FxDockSplitPane p = (FxDockSplitPane)parent; // remove deleted panes for(int i=p.getPaneCount()-1; i>=0; --i) { Node n = p.getPane(i); if(n instanceof DeletedPane) { p.removePane(i); } } // combine empty panes boolean empty = false; int ct = 0; int index = -1; for(int i=p.getPaneCount()-1; i>=0; --i) { Node n = p.getPane(i); if(isEmpty(n)) { if(empty) { p.removePane(i); } else { empty = true; } } else { empty = false; index = i; ct++; } } if(ct < 2) { int ix = indexInParent(p); Node pp = getParent(p); switch(ct) { case 0: replaceChild(pp, ix, new DeletedPane()); collapseEmptySpace(pp); break; case 1: // no need to have split pane with a single pane Node n = p.getPane(index); replaceChild(pp, ix, n); break; } } } else if(parent instanceof FxDockTabPane) { FxDockTabPane p = (FxDockTabPane)parent; // remove deleted panes for(int i=p.getTabCount()-1; i>=0; --i) { Node n = p.getTab(i); if(n == null) { p.removeTab(i); } else if(n instanceof DeletedPane) { p.removeTab(i); } } // combine empty panes boolean empty = false; int ct = 0; int index = -1; for(int i=p.getTabCount()-1; i>=0; --i) { Node n = p.getTab(i); if(isEmpty(n)) { if(empty) { p.removeTab(i); } else { empty = true; } } else { empty = false; index = i; ct++; } } if(ct < 2) { int ix = indexInParent(p); Node p2 = getParent(p); switch(ct) { case 0: replaceChild(p2, ix, new DeletedPane()); collapseEmptySpace(p2); break; case 1: // no need to have tab pane with a single tab Node n = p.getTab(index); replaceChild(p2, ix, n); break; } } } else if(parent instanceof FxDockRootPane) { FxDockRootPane rp = (FxDockRootPane)parent; Node n = rp.getContent(); if(isEmpty(n)) { if(!closeWindowUnlessLast(parent)) { rp.setContent(null); } } } } private static boolean insertSplit(FxDockPane client, FxDockSplitPane sp, Object where) { if(where instanceof Where) { Orientation or = sp.getOrientation(); switch((Where)where) { case LEFT: if(or == Orientation.HORIZONTAL) { sp.addPane(0, client); return true; } break; case RIGHT: if(or == Orientation.HORIZONTAL) { sp.addPane(client); return true; } break; case TOP: if(or == Orientation.VERTICAL) { sp.addPane(0, client); return true; } break; case BOTTOM: if(or == Orientation.VERTICAL) { sp.addPane(client); return true; } break; } } return false; } public static void insertPane(FxDockPane client, Node target, Object where) { if(target instanceof FxDockRootPane) { FxDockRootPane rp = (FxDockRootPane)target; BeforeDrop b = new BeforeDrop(client, target); boolean makesplit = true; Node old = rp.getContent(); if(old instanceof FxDockSplitPane) { if(insertSplit(client, (FxDockSplitPane)old, where)) { makesplit = false; } } if(makesplit) { rp.setContent(makeSplit(client, old, (Where)where)); } collapseEmptySpace(b.clientParent); b.adjustSplits(); } else if(target instanceof FxDockPane) { // FIX throw new Error("replace with split or tab"); } else { // TODO throw new Error("?" + target); } } public static void moveToNewWindow(FxDockPane client, double screenx, double screeny) { Node p = getParent(client); double w = client.getWidth(); double h = client.getHeight(); FxDockWindow win = FxDockFramework.createWindow(); win.setContent(client); win.setX(screenx); win.setY(screeny); // moving window after show() seems to cause flicker double op = win.getOpacity(); win.setOpacity(0); FxDockFramework.open(win); // take into account window decorations // apparently, this is available only after show() Node n = win.getDockRootPane().getCenter(); Insets m = FX.getInsetsInWindow(win, n); // this may still cause flicker win.setX(screenx - m.getLeft()); win.setY(screeny - m.getTop()); win.setWidth(w + m.getLeft() + m.getRight()); win.setHeight(h + m.getTop() + m.getBottom()); win.setOpacity(op); collapseEmptySpace(p); } public static void moveToNewWindow(FxDockPane client) { Node p = getParent(client); Window clientWindow = getWindow(client); // TODO still not correct Insets m = getWindowInsets(clientWindow); Point2D pos = client.localToScreen(0, 0); FxDockWindow w = FxDockFramework.createWindow(); w.setContent(client); w.setX(pos.getX() - m.getLeft()); w.setY(pos.getY() - m.getTop()); w.setWidth(client.getWidth() + m.getRight() + m.getLeft()); w.setHeight(client.getHeight() + m.getTop() + m.getBottom()); FxDockFramework.open(w); collapseEmptySpace(p); } public static Insets getWindowInsets(Window w) { Scene s = w.getScene(); double left = s.getX(); double top = s.getY(); double right = w.getWidth() - s.getWidth() - left; double bottom = w.getHeight() - s.getHeight() - top; return new Insets(top, right, bottom, left); } public static void moveToSplit(FxDockPane client, FxDockSplitPane sp, int index) { BeforeDrop b = new BeforeDrop(client, sp); sp.addPane(index, client); collapseEmptySpace(b.clientParent); b.adjustSplits(); } private static void addToRootPane(FxDockPane client, FxDockRootPane rp, Where where) { Node old = rp.getContent(); switch(where) { case CENTER: if(old instanceof FxDockEmptyPane) { rp.setContent(client); } else { rp.setContent(makeTab(old, client)); } break; default: rp.setContent(makeSplit(client, old, where)); break; } } private static void addToTabPane(FxDockPane client, FxDockTabPane tp, int index, Where where) { switch(where) { case CENTER: tp.addTab(client); tp.select(client); break; default: Node p = getParent(tp); int ix = indexInParent(tp); Node sp = makeSplit(client, tp, where); if(p != sp) { replaceChild(p, ix, sp); } break; } } private static void addToSplitPane(FxDockPane client, Pane target, FxDockSplitPane sp, int index, Where where) { // determine index from where and sp orientation int ix; if(sp.getOrientation() == Orientation.HORIZONTAL) { switch(where) { case LEFT: ix = 0; break; case RIGHT: ix = sp.getPaneCount() - 1; break; default: ix = -1; break; } } else { switch(where) { case BOTTOM: ix = sp.getPaneCount() - 1; break; case TOP: ix = 0; break; default: ix = -1; break; } } if(ix < 0) { Node p = getParent(target); int ip = indexInParent(target); switch(where) { case CENTER: if(target instanceof FxDockEmptyPane) { sp.setPane(ip, client); } else { Node t = makeTab(target, client); replaceChild(p, ip, t); } break; default: Node n = makeSplit(client, target, where); replaceChild(p, ip, n); break; } } else { // simply insert another pane into this split pane sp.addPane(ix, client); } } /** moves client pane to new position, creating necessary splits or tabs */ public static void moveToPane(FxDockPane client, Pane target, Where where) { BeforeDrop b = new BeforeDrop(client, target); Node targetParent = getParent(target); if(targetParent instanceof FxDockSplitPane) { int targetIndex = indexInParent(target); addToSplitPane(client, target, (FxDockSplitPane)targetParent, targetIndex, where); } else if(targetParent instanceof FxDockTabPane) { int targetIndex = indexInParent(target); addToTabPane(client, (FxDockTabPane)targetParent, targetIndex, where); } else if(targetParent instanceof FxDockRootPane) { addToRootPane(client, (FxDockRootPane)targetParent, where); } else { throw new Error("?" + targetParent); } collapseEmptySpace(b.clientParent); b.adjustSplits(); } }
Fix drag & and drop incorrect position
src/goryachev/fxdock/internal/DockTools.java
Fix drag & and drop incorrect position
Java
apache-2.0
876045f307376cf6eee7590fda61bb6497613f76
0
idea4bsd/idea4bsd,TangHao1987/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,signed/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,adedayo/intellij-community,da1z/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,ftomassetti/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,samthor/intellij-community,vvv1559/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,clumsy/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,slisson/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,ernestp/consulo,semonte/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,izonder/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,samthor/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,signed/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,samthor/intellij-community,ryano144/intellij-community,FHannes/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,supersven/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,semonte/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,semonte/intellij-community,da1z/intellij-community,holmes/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,da1z/intellij-community,asedunov/intellij-community,holmes/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,ernestp/consulo,da1z/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,izonder/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ernestp/consulo,robovm/robovm-studio,gnuhub/intellij-community,robovm/robovm-studio,dslomov/intellij-community,caot/intellij-community,petteyg/intellij-community,retomerz/intellij-community,caot/intellij-community,asedunov/intellij-community,ryano144/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,fnouama/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,robovm/robovm-studio,diorcety/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,consulo/consulo,fitermay/intellij-community,xfournet/intellij-community,blademainer/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ernestp/consulo,izonder/intellij-community,apixandru/intellij-community,consulo/consulo,ryano144/intellij-community,semonte/intellij-community,gnuhub/intellij-community,da1z/intellij-community,signed/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,izonder/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,signed/intellij-community,kool79/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,samthor/intellij-community,ryano144/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,kool79/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ryano144/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,amith01994/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,holmes/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,allotria/intellij-community,retomerz/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,slisson/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,kool79/intellij-community,joewalnes/idea-community,xfournet/intellij-community,petteyg/intellij-community,ryano144/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,izonder/intellij-community,signed/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,kool79/intellij-community,semonte/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,ernestp/consulo,wreckJ/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,signed/intellij-community,slisson/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ibinti/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,samthor/intellij-community,orekyuu/intellij-community,slisson/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,supersven/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,kdwink/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,consulo/consulo,kool79/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,SerCeMan/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,supersven/intellij-community,fitermay/intellij-community,signed/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,caot/intellij-community,supersven/intellij-community,amith01994/intellij-community,clumsy/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,allotria/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,kool79/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,vladmm/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,da1z/intellij-community,kool79/intellij-community,robovm/robovm-studio,supersven/intellij-community,ahb0327/intellij-community,da1z/intellij-community,caot/intellij-community,izonder/intellij-community,diorcety/intellij-community,consulo/consulo,mglukhikh/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,caot/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,jagguli/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,akosyakov/intellij-community,slisson/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,allotria/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,clumsy/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,da1z/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,xfournet/intellij-community,slisson/intellij-community,semonte/intellij-community,retomerz/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,xfournet/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,hurricup/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,kool79/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,signed/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,caot/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,caot/intellij-community,samthor/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,izonder/intellij-community,xfournet/intellij-community,supersven/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,joewalnes/idea-community,clumsy/intellij-community,da1z/intellij-community,signed/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,supersven/intellij-community,blademainer/intellij-community,kool79/intellij-community,joewalnes/idea-community,ryano144/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,asedunov/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ahb0327/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,semonte/intellij-community,samthor/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,caot/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,asedunov/intellij-community,retomerz/intellij-community,da1z/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,consulo/consulo,semonte/intellij-community,semonte/intellij-community,apixandru/intellij-community,retomerz/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,izonder/intellij-community,Lekanich/intellij-community,caot/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,adedayo/intellij-community,clumsy/intellij-community,jagguli/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,signed/intellij-community,vvv1559/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,caot/intellij-community,blademainer/intellij-community,xfournet/intellij-community,holmes/intellij-community,amith01994/intellij-community,allotria/intellij-community,FHannes/intellij-community,supersven/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,robovm/robovm-studio,kdwink/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,suncycheng/intellij-community,supersven/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,slisson/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,petteyg/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,kool79/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community
/* * Copyright (c) 2007, Your Corporation. All Rights Reserved. */ /** * created at Jan 3, 2002 * @author Jeka */ package com.intellij.compiler; import com.intellij.CommonBundle; import com.intellij.ProjectTopics; import com.intellij.compiler.impl.javaCompiler.BackendCompiler; import com.intellij.compiler.impl.javaCompiler.api.CompilerAPICompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseEmbeddedCompiler; import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler; import com.intellij.compiler.impl.javaCompiler.jikes.JikesCompiler; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.compiler.options.ExcludedEntriesConfiguration; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.ModuleListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.InputValidator; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import org.apache.oro.text.regex.*; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; @State( name = "CompilerConfiguration", storages = { @Storage(id = "default", file = "$PROJECT_FILE$") ,@Storage(id = "dir", file = "$PROJECT_CONFIG_DIR$/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED) } ) public class CompilerConfigurationImpl extends CompilerConfiguration implements PersistentStateComponent<Element>, ProjectComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.CompilerConfiguration"); @NonNls public static final String TESTS_EXTERNAL_COMPILER_HOME_PROPERTY_NAME = "tests.external.compiler.home"; public static final int DEPENDENCY_FORMAT_VERSION = 53; @SuppressWarnings({"WeakerAccess"}) public String DEFAULT_COMPILER; @NotNull private BackendCompiler myDefaultJavaCompiler; // extensions of the files considered as resource files private final List<Pattern> myRegexpResourcePaterns = new ArrayList<Pattern>(getDefaultRegexpPatterns()); // extensions of the files considered as resource files. If present, Overrides patterns in old regexp format stored in myRegexpResourcePaterns private final List<String> myWildcardPatterns = new ArrayList<String>(); private final List<Pair<Pattern, Pattern>> myCompiledPatterns = new ArrayList<Pair<Pattern, Pattern>>(); private final List<Pair<Pattern, Pattern>> myNegatedCompiledPatterns = new ArrayList<Pair<Pattern, Pattern>>(); private boolean myWildcardPatternsInitialized = false; private final Project myProject; private final ModuleManager myModuleManager; private final ExcludedEntriesConfiguration myExcludedEntriesConfiguration; private final Collection<BackendCompiler> myRegisteredCompilers = new ArrayList<BackendCompiler>(); private JavacCompiler JAVAC_EXTERNAL_BACKEND; private final Perl5Matcher myPatternMatcher = new Perl5Matcher(); { loadDefaultWildcardPatterns(); } private boolean myEnableAnnotationProcessors = false; private final Map<String, String> myProcessorsMap = new HashMap<String, String>(); // map: AnnotationProcessorName -> options private boolean myObtainProcessorsFromClasspath = true; private String myProcessorPath = ""; private final Set<Module> myExcludedModules = new HashSet<Module>(); private final Set<String> myExcludedModuleNames = new HashSet<String>(); public CompilerConfigurationImpl(Project project, ModuleManager moduleManager) { myProject = project; myModuleManager = moduleManager; myExcludedEntriesConfiguration = new ExcludedEntriesConfiguration(); Disposer.register(project, myExcludedEntriesConfiguration); project.getMessageBus().connect(project).subscribe(ProjectTopics.MODULES, new ModuleListener() { public void modulesRenamed(Project project, List<Module> modules) { } public void moduleRemoved(Project project, Module module) { } public void beforeModuleRemoved(Project project, Module module) { myExcludedModules.remove(module); myExcludedModuleNames.remove(module.getName()); } public void moduleAdded(Project project, Module module) { if (myExcludedModuleNames.remove(module.getName())) { myExcludedModules.add(module); } } }); } public Element getState() { try { @NonNls final Element e = new Element("state"); writeExternal(e); return e; } catch (WriteExternalException e1) { LOG.error(e1); return null; } } public void loadState(Element state) { try { readExternal(state); } catch (InvalidDataException e) { LOG.error(e); } } private void loadDefaultWildcardPatterns() { if (!myWildcardPatterns.isEmpty()) { removeWildcardPatterns(); } try { addWildcardResourcePattern("?*.properties"); addWildcardResourcePattern("?*.xml"); addWildcardResourcePattern("?*.gif"); addWildcardResourcePattern("?*.png"); addWildcardResourcePattern("?*.jpeg"); addWildcardResourcePattern("?*.jpg"); addWildcardResourcePattern("?*.html"); addWildcardResourcePattern("?*.dtd"); addWildcardResourcePattern("?*.tld"); addWildcardResourcePattern("?*.ftl"); } catch (MalformedPatternException e) { LOG.error(e); } } private static List<Pattern> getDefaultRegexpPatterns() { try { return Arrays.asList(compilePattern(".+\\.(properties|xml|html|dtd|tld)"), compilePattern(".+\\.(gif|png|jpeg|jpg)")); } catch (MalformedPatternException e) { LOG.error(e); } return Collections.emptyList(); } public static String getTestsExternalCompilerHome() { String compilerHome = System.getProperty(TESTS_EXTERNAL_COMPILER_HOME_PROPERTY_NAME, null); if (compilerHome == null) { if (SystemInfo.isMac) { compilerHome = new File(System.getProperty("java.home")).getAbsolutePath(); } else { compilerHome = new File(System.getProperty("java.home")).getParentFile().getAbsolutePath(); } } return compilerHome; } private static Pattern compilePattern(@NonNls String s) throws MalformedPatternException { try { final PatternCompiler compiler = new Perl5Compiler(); return SystemInfo.isFileSystemCaseSensitive? compiler.compile(s) : compiler.compile(s, Perl5Compiler.CASE_INSENSITIVE_MASK); } catch (org.apache.oro.text.regex.MalformedPatternException ex) { throw new MalformedPatternException(ex); } } public void disposeComponent() { } public void initComponent() { } public void projectClosed() { } public JavacCompiler getJavacCompiler() { if (JAVAC_EXTERNAL_BACKEND == null) { createCompilers(); } return JAVAC_EXTERNAL_BACKEND; } public void projectOpened() { createCompilers(); } private void createCompilers() { JAVAC_EXTERNAL_BACKEND = new JavacCompiler(myProject); myRegisteredCompilers.add(JAVAC_EXTERNAL_BACKEND); if (!ApplicationManager.getApplication().isUnitTestMode()) { final BackendCompiler JIKES_BACKEND = new JikesCompiler(myProject); myRegisteredCompilers.add(JIKES_BACKEND); if (EclipseCompiler.isInitialized()) { final EclipseCompiler eclipse = new EclipseCompiler(myProject); myRegisteredCompilers.add(eclipse); } if (ApplicationManagerEx.getApplicationEx().isInternal()) { try { final EclipseEmbeddedCompiler eclipseEmbedded = new EclipseEmbeddedCompiler(myProject); myRegisteredCompilers.add(eclipseEmbedded); } catch (NoClassDefFoundError e) { // eclipse jar must be not in the classpath } } if (ApplicationManagerEx.getApplicationEx().isInternal()) { try { CompilerAPICompiler inprocessJavaCompiler = new CompilerAPICompiler(myProject); myRegisteredCompilers.add(inprocessJavaCompiler); } catch (NoClassDefFoundError e) { // wrong JDK } } } myDefaultJavaCompiler = JAVAC_EXTERNAL_BACKEND; for (BackendCompiler compiler : myRegisteredCompilers) { if (compiler.getId().equals(DEFAULT_COMPILER)) { myDefaultJavaCompiler = compiler; break; } } DEFAULT_COMPILER = myDefaultJavaCompiler.getId(); } public Collection<BackendCompiler> getRegisteredJavaCompilers() { return myRegisteredCompilers; } public String[] getResourceFilePatterns() { return getWildcardPatterns(); } private String[] getRegexpPatterns() { String[] patterns = ArrayUtil.newStringArray(myRegexpResourcePaterns.size()); int index = 0; for (final Pattern myRegexpResourcePatern : myRegexpResourcePaterns) { patterns[index++] = myRegexpResourcePatern.getPattern(); } return patterns; } private String[] getWildcardPatterns() { return ArrayUtil.toStringArray(myWildcardPatterns); } public void addResourceFilePattern(String namePattern) throws MalformedPatternException { addWildcardResourcePattern(namePattern); } // need this method only for handling patterns in old regexp format private void addRegexpPattern(String namePattern) throws MalformedPatternException { Pattern pattern = compilePattern(namePattern); if (pattern != null) { myRegexpResourcePaterns.add(pattern); } } public ExcludedEntriesConfiguration getExcludedEntriesConfiguration() { return myExcludedEntriesConfiguration; } public boolean isExcludedFromCompilation(final VirtualFile virtualFile) { return myExcludedEntriesConfiguration.isExcluded(virtualFile); } @Override public boolean isResourceFile(VirtualFile virtualFile) { return isResourceFile(virtualFile.getName(), virtualFile.getParent()); } public boolean isAnnotationProcessorsEnabled() { return myEnableAnnotationProcessors; } public void setAnnotationProcessorsEnabled(boolean enableAnnotationProcessors) { myEnableAnnotationProcessors = enableAnnotationProcessors; } public boolean isObtainProcessorsFromClasspath() { return myObtainProcessorsFromClasspath; } public void setObtainProcessorsFromClasspath(boolean obtainProcessorsFromClasspath) { myObtainProcessorsFromClasspath = obtainProcessorsFromClasspath; } public String getProcessorPath() { return myProcessorPath; } public void setProcessorsPath(String processorsPath) { myProcessorPath = processorsPath; } public Map<String, String> getAnnotationProcessorsMap() { return Collections.unmodifiableMap(myProcessorsMap); } public void setAnnotationProcessorsMap(Map<String, String> map) { myProcessorsMap.clear(); myProcessorsMap.putAll(map); } public Set<Module> getExcludedModules() { return Collections.unmodifiableSet(myExcludedModules); } public void setExcludedModules(Collection<Module> modules) { myExcludedModules.clear(); myExcludedModuleNames.clear(); myExcludedModules.addAll(modules); } private void addWildcardResourcePattern(@NonNls final String wildcardPattern) throws MalformedPatternException { final Pair<Pattern, Pattern> pattern = convertToRegexp(wildcardPattern); if (pattern != null) { myWildcardPatterns.add(wildcardPattern); if (isPatternNegated(wildcardPattern)) { myNegatedCompiledPatterns.add(pattern); } else { myCompiledPatterns.add(pattern); } } } public void removeResourceFilePatterns() { removeWildcardPatterns(); } private void removeRegexpPatterns() { myRegexpResourcePaterns.clear(); } private void removeWildcardPatterns() { myWildcardPatterns.clear(); myCompiledPatterns.clear(); myNegatedCompiledPatterns.clear(); } private static Pair<Pattern, Pattern> convertToRegexp(String wildcardPattern) { if (isPatternNegated(wildcardPattern)) { wildcardPattern = wildcardPattern.substring(1); } wildcardPattern = FileUtil.toSystemIndependentName(wildcardPattern); String dirPattern = null; int slash = wildcardPattern.lastIndexOf('/'); if (slash >= 0) { dirPattern = wildcardPattern.substring(0, slash + 1); wildcardPattern = wildcardPattern.substring(slash + 1); if (!dirPattern.startsWith("/")) { dirPattern = "/" + dirPattern; } //now dirPattern starts and ends with '/' dirPattern = normalizeWildcards(dirPattern); dirPattern = StringUtil.replace(dirPattern, "/.*.*/", "(/.*)?/"); dirPattern = StringUtil.trimEnd(dirPattern, "/"); dirPattern = optimize(dirPattern); dirPattern = ".*" + dirPattern; } wildcardPattern = normalizeWildcards(wildcardPattern); wildcardPattern = optimize(wildcardPattern); final Pattern dirCompiled = dirPattern == null ? null : compilePattern(dirPattern); return Pair.create(compilePattern(wildcardPattern), dirCompiled); } private static String optimize(String wildcardPattern) { return wildcardPattern.replaceAll("(?:\\.\\*)+", ".*"); } private static String normalizeWildcards(String wildcardPattern) { wildcardPattern = StringUtil.replace(wildcardPattern, "\\!", "!"); wildcardPattern = StringUtil.replace(wildcardPattern, ".", "\\."); wildcardPattern = StringUtil.replace(wildcardPattern, "*?", ".+"); wildcardPattern = StringUtil.replace(wildcardPattern, "?*", ".+"); wildcardPattern = StringUtil.replace(wildcardPattern, "*", ".*"); wildcardPattern = StringUtil.replace(wildcardPattern, "?", "."); return wildcardPattern; } public static boolean isPatternNegated(String wildcardPattern) { return wildcardPattern.length() > 1 && wildcardPattern.charAt(0) == '!'; } public boolean isResourceFile(String name) { return isResourceFile(name, null); } private boolean matches(String s, Pattern p) { synchronized (myPatternMatcher) { try { return myPatternMatcher.matches(s, p); } catch (Exception e) { LOG.error("Exception matching file name \"" + s + "\" against the pattern \"" + p + "\"", e); return false; } } } private boolean isResourceFile(String name, @Nullable VirtualFile parent) { final Ref<String> parentRef = Ref.create(null); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < myCompiledPatterns.size(); i++) { if (matches(name, parent, parentRef, myCompiledPatterns.get(i))) { return true; } } if (myNegatedCompiledPatterns.isEmpty()) { return false; } //noinspection ForLoopReplaceableByForEach for (int i = 0; i < myNegatedCompiledPatterns.size(); i++) { if (matches(name, parent, parentRef, myNegatedCompiledPatterns.get(i))) { return false; } } return true; } private boolean matches(String name, VirtualFile parent, Ref<String> parentRef, Pair<Pattern, Pattern> pair) { if (!matches(name, pair.first)) { return false; } final Pattern dirPattern = pair.second; if (dirPattern == null || parent == null) { return true; } String parentPath = parentRef.get(); if (parentPath == null) { parentRef.set(parentPath = parent.getPath()); } return matches(parentPath, dirPattern); } // property names @NonNls private static final String EXCLUDE_FROM_COMPILE = "excludeFromCompile"; @NonNls private static final String RESOURCE_EXTENSIONS = "resourceExtensions"; @NonNls private static final String ANNOTATION_PROCESSING = "annotationProcessing"; @NonNls private static final String WILDCARD_RESOURCE_PATTERNS = "wildcardResourcePatterns"; @NonNls private static final String ENTRY = "entry"; @NonNls private static final String NAME = "name"; public void readExternal(Element parentNode) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, parentNode); Element node = parentNode.getChild(EXCLUDE_FROM_COMPILE); if (node != null) { myExcludedEntriesConfiguration.readExternal(node); } try { removeRegexpPatterns(); node = parentNode.getChild(RESOURCE_EXTENSIONS); if (node != null) { for (final Object o : node.getChildren(ENTRY)) { Element element = (Element)o; String pattern = element.getAttributeValue(NAME); if (pattern != null && !"".equals(pattern)) { addRegexpPattern(pattern); } } } removeWildcardPatterns(); node = parentNode.getChild(WILDCARD_RESOURCE_PATTERNS); if (node != null) { myWildcardPatternsInitialized = true; for (final Object o : node.getChildren(ENTRY)) { final Element element = (Element)o; String pattern = element.getAttributeValue(NAME); if (pattern != null && !"".equals(pattern)) { addWildcardResourcePattern(pattern); } } } } catch (MalformedPatternException e) { throw new InvalidDataException(e); } final Element annotationProcessingSettings = parentNode.getChild(ANNOTATION_PROCESSING); if (annotationProcessingSettings != null) { myEnableAnnotationProcessors = Boolean.valueOf(annotationProcessingSettings.getAttributeValue("enabled", "false")); myObtainProcessorsFromClasspath = Boolean.valueOf(annotationProcessingSettings.getAttributeValue("useClasspath", "true")); final StringBuilder pathBuilder = new StringBuilder(); for (Element pathElement : ((Collection<Element>)annotationProcessingSettings.getChildren("processorPath"))) { final String path = pathElement.getAttributeValue("value"); if (path != null) { if (pathBuilder.length() > 0) { pathBuilder.append(File.pathSeparator); } pathBuilder.append(path); } } myProcessorPath = pathBuilder.toString(); myProcessorsMap.clear(); for (Element processorChild : ((Collection<Element>)annotationProcessingSettings.getChildren("processor"))) { final String name = processorChild.getAttributeValue("name"); final String options = processorChild.getAttributeValue("options", ""); myProcessorsMap.put(name, options); } myExcludedModules.clear(); myExcludedModuleNames.clear(); final Collection<Element> excluded = (Collection<Element>)annotationProcessingSettings.getChildren("excludeModule"); if (excluded.size() > 0) { final Map<String, Module> moduleMap = new com.intellij.util.containers.HashMap<String, Module>(); for (Module module : myModuleManager.getModules()) { moduleMap.put(module.getName(), module); } for (Element moduleElement : excluded) { final String name = moduleElement.getAttributeValue("name"); if (name != null) { final Module module = moduleMap.get(name); if (module != null) { myExcludedModules.add(module); } else { myExcludedModuleNames.add(name); } } } } } } public void writeExternal(Element parentNode) throws WriteExternalException { DefaultJDOMExternalizer.writeExternal(this, parentNode); if(myExcludedEntriesConfiguration.getExcludeEntryDescriptions().length > 0) { Element newChild = new Element(EXCLUDE_FROM_COMPILE); myExcludedEntriesConfiguration.writeExternal(newChild); parentNode.addContent(newChild); } final Element newChild = new Element(RESOURCE_EXTENSIONS); for (final String pattern : getRegexpPatterns()) { final Element entry = new Element(ENTRY); entry.setAttribute(NAME, pattern); newChild.addContent(entry); } parentNode.addContent(newChild); if (myWildcardPatternsInitialized || !myWildcardPatterns.isEmpty()) { final Element wildcardPatterns = new Element(WILDCARD_RESOURCE_PATTERNS); for (final String wildcardPattern : myWildcardPatterns) { final Element entry = new Element(ENTRY); entry.setAttribute(NAME, wildcardPattern); wildcardPatterns.addContent(entry); } parentNode.addContent(wildcardPatterns); } final Element annotationProcessingSettings = new Element(ANNOTATION_PROCESSING); parentNode.addContent(annotationProcessingSettings); annotationProcessingSettings.setAttribute("enabled", String.valueOf(myEnableAnnotationProcessors)); annotationProcessingSettings.setAttribute("useClasspath", String.valueOf(myObtainProcessorsFromClasspath)); if (myProcessorPath.length() > 0) { final StringTokenizer tokenizer = new StringTokenizer(myProcessorPath, File.pathSeparator, false); while (tokenizer.hasMoreTokens()) { final String path = tokenizer.nextToken(); final Element pathElement = new Element("processorPath"); annotationProcessingSettings.addContent(pathElement); pathElement.setAttribute("value", path); } } for (Map.Entry<String, String> entry : myProcessorsMap.entrySet()) { final Element processor = new Element("processor"); annotationProcessingSettings.addContent(processor); processor.setAttribute("name", entry.getKey()); processor.setAttribute("options", entry.getValue()); } final List<Module> modules = new ArrayList<Module>(getExcludedModules()); Collections.sort(modules, new Comparator<Module>() { public int compare(Module o1, Module o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); for (Module module : modules) { final Element moduleElement = new Element("excludeModule"); annotationProcessingSettings.addContent(moduleElement); moduleElement.setAttribute("name", module.getName()); } } @NotNull @NonNls public String getComponentName() { return "CompilerConfiguration"; } public BackendCompiler getDefaultCompiler() { if (JAVAC_EXTERNAL_BACKEND == null) { createCompilers(); } return myDefaultJavaCompiler; } public void setDefaultCompiler(BackendCompiler defaultCompiler) { myDefaultJavaCompiler = defaultCompiler; DEFAULT_COMPILER = defaultCompiler.getId(); } public void convertPatterns() { if (!needPatternConversion()) { return; } try { boolean ok; try { ok = doConvertPatterns(); } catch (MalformedPatternException e) { ok = false; } if (!ok) { final String initialPatternString = patternsToString(getRegexpPatterns()); final String message = CompilerBundle.message( "message.resource.patterns.format.changed", ApplicationNamesInfo.getInstance().getProductName(), initialPatternString, CommonBundle.getOkButtonText(), CommonBundle.getCancelButtonText() ); final String wildcardPatterns = Messages.showInputDialog( myProject, message, CompilerBundle.message("pattern.conversion.dialog.title"), Messages.getWarningIcon(), initialPatternString, new InputValidator() { public boolean checkInput(String inputString) { return true; } public boolean canClose(String inputString) { final StringTokenizer tokenizer = new StringTokenizer(inputString, ";", false); StringBuilder malformedPatterns = new StringBuilder(); while (tokenizer.hasMoreTokens()) { String pattern = tokenizer.nextToken(); try { addWildcardResourcePattern(pattern); } catch (MalformedPatternException e) { malformedPatterns.append("\n\n"); malformedPatterns.append(pattern); malformedPatterns.append(": "); malformedPatterns.append(e.getMessage()); } } if (malformedPatterns.length() > 0) { Messages.showErrorDialog(CompilerBundle.message("error.bad.resource.patterns", malformedPatterns.toString()), CompilerBundle.message("bad.resource.patterns.dialog.title")); removeWildcardPatterns(); return false; } return true; } }); if (wildcardPatterns == null) { // cancel pressed loadDefaultWildcardPatterns(); } } } finally { myWildcardPatternsInitialized = true; } } private boolean needPatternConversion() { return !myWildcardPatternsInitialized && !myRegexpResourcePaterns.isEmpty(); } private boolean doConvertPatterns() throws MalformedPatternException { final String[] regexpPatterns = getRegexpPatterns(); final List<String> converted = new ArrayList<String>(); final Pattern multipleExtensionsPatternPattern = compilePattern("\\.\\+\\\\\\.\\((\\w+(?:\\|\\w+)*)\\)"); final Pattern singleExtensionPatternPattern = compilePattern("\\.\\+\\\\\\.(\\w+)"); final Perl5Matcher matcher = new Perl5Matcher(); for (final String regexpPattern : regexpPatterns) { //final Matcher multipleExtensionsMatcher = multipleExtensionsPatternPattern.matcher(regexpPattern); if (matcher.matches(regexpPattern, multipleExtensionsPatternPattern)) { final MatchResult match = matcher.getMatch(); final StringTokenizer tokenizer = new StringTokenizer(match.group(1), "|", false); while (tokenizer.hasMoreTokens()) { converted.add("?*." + tokenizer.nextToken()); } } else { //final Matcher singleExtensionMatcher = singleExtensionPatternPattern.matcher(regexpPattern); if (matcher.matches(regexpPattern, singleExtensionPatternPattern)) { final MatchResult match = matcher.getMatch(); converted.add("?*." + match.group(1)); } else { return false; } } } for (final String aConverted : converted) { addWildcardResourcePattern(aConverted); } return true; } private static String patternsToString(final String[] patterns) { final StringBuilder extensionsString = new StringBuilder(); for (int idx = 0; idx < patterns.length; idx++) { if (idx > 0) { extensionsString.append(";"); } extensionsString.append(patterns[idx]); } return extensionsString.toString(); } }
java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java
/* * Copyright (c) 2007, Your Corporation. All Rights Reserved. */ /** * created at Jan 3, 2002 * @author Jeka */ package com.intellij.compiler; import com.intellij.CommonBundle; import com.intellij.ProjectTopics; import com.intellij.compiler.impl.javaCompiler.BackendCompiler; import com.intellij.compiler.impl.javaCompiler.api.CompilerAPICompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseEmbeddedCompiler; import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler; import com.intellij.compiler.impl.javaCompiler.jikes.JikesCompiler; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.compiler.options.ExcludedEntriesConfiguration; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.ModuleListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.InputValidator; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import org.apache.oro.text.regex.*; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; @State( name = "CompilerConfiguration", storages = { @Storage(id = "default", file = "$PROJECT_FILE$") ,@Storage(id = "dir", file = "$PROJECT_CONFIG_DIR$/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED) } ) public class CompilerConfigurationImpl extends CompilerConfiguration implements PersistentStateComponent<Element>, ProjectComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.CompilerConfiguration"); @NonNls public static final String TESTS_EXTERNAL_COMPILER_HOME_PROPERTY_NAME = "tests.external.compiler.home"; public static final int DEPENDENCY_FORMAT_VERSION = 53; @SuppressWarnings({"WeakerAccess"}) public String DEFAULT_COMPILER; @NotNull private BackendCompiler myDefaultJavaCompiler; // extensions of the files considered as resource files private final List<Pattern> myRegexpResourcePaterns = new ArrayList<Pattern>(getDefaultRegexpPatterns()); // extensions of the files considered as resource files. If present, Overrides patterns in old regexp format stored in myRegexpResourcePaterns private final List<String> myWildcardPatterns = new ArrayList<String>(); private final List<Pair<Pattern, Pattern>> myCompiledPatterns = new ArrayList<Pair<Pattern, Pattern>>(); private final List<Pair<Pattern, Pattern>> myNegatedCompiledPatterns = new ArrayList<Pair<Pattern, Pattern>>(); private boolean myWildcardPatternsInitialized = false; private final Project myProject; private final ModuleManager myModuleManager; private final ExcludedEntriesConfiguration myExcludedEntriesConfiguration; private final Collection<BackendCompiler> myRegisteredCompilers = new ArrayList<BackendCompiler>(); private JavacCompiler JAVAC_EXTERNAL_BACKEND; private final Perl5Matcher myPatternMatcher = new Perl5Matcher(); { loadDefaultWildcardPatterns(); } private boolean myEnableAnnotationProcessors = false; private final Map<String, String> myProcessorsMap = new HashMap<String, String>(); // map: AnnotationProcessorName -> options private boolean myObtainProcessorsFromClasspath = true; private String myProcessorPath = ""; private final Set<Module> myExcludedModules = new HashSet<Module>(); private final Set<String> myExcludedModuleNames = new HashSet<String>(); public CompilerConfigurationImpl(Project project, ModuleManager moduleManager) { myProject = project; myModuleManager = moduleManager; myExcludedEntriesConfiguration = new ExcludedEntriesConfiguration(); Disposer.register(project, myExcludedEntriesConfiguration); project.getMessageBus().connect(project).subscribe(ProjectTopics.MODULES, new ModuleListener() { public void modulesRenamed(Project project, List<Module> modules) { } public void moduleRemoved(Project project, Module module) { } public void beforeModuleRemoved(Project project, Module module) { myExcludedModules.remove(module); myExcludedModuleNames.remove(module.getName()); } public void moduleAdded(Project project, Module module) { if (myExcludedModuleNames.remove(module.getName())) { myExcludedModules.add(module); } } }); } public Element getState() { try { @NonNls final Element e = new Element("state"); writeExternal(e); return e; } catch (WriteExternalException e1) { LOG.error(e1); return null; } } public void loadState(Element state) { try { readExternal(state); } catch (InvalidDataException e) { LOG.error(e); } } private void loadDefaultWildcardPatterns() { if (!myWildcardPatterns.isEmpty()) { removeWildcardPatterns(); } try { addWildcardResourcePattern("?*.properties"); addWildcardResourcePattern("?*.xml"); addWildcardResourcePattern("?*.gif"); addWildcardResourcePattern("?*.png"); addWildcardResourcePattern("?*.jpeg"); addWildcardResourcePattern("?*.jpg"); addWildcardResourcePattern("?*.html"); addWildcardResourcePattern("?*.dtd"); addWildcardResourcePattern("?*.tld"); addWildcardResourcePattern("?*.ftl"); } catch (MalformedPatternException e) { LOG.error(e); } } private static List<Pattern> getDefaultRegexpPatterns() { try { return Arrays.asList(compilePattern(".+\\.(properties|xml|html|dtd|tld)"), compilePattern(".+\\.(gif|png|jpeg|jpg)")); } catch (MalformedPatternException e) { LOG.error(e); } return Collections.emptyList(); } public static String getTestsExternalCompilerHome() { String compilerHome = System.getProperty(TESTS_EXTERNAL_COMPILER_HOME_PROPERTY_NAME, null); if (compilerHome == null) { if (SystemInfo.isMac) { compilerHome = new File(System.getProperty("java.home")).getAbsolutePath(); } else { compilerHome = new File(System.getProperty("java.home")).getParentFile().getAbsolutePath(); } } return compilerHome; } private static Pattern compilePattern(@NonNls String s) throws MalformedPatternException { try { final PatternCompiler compiler = new Perl5Compiler(); return SystemInfo.isFileSystemCaseSensitive? compiler.compile(s) : compiler.compile(s, Perl5Compiler.CASE_INSENSITIVE_MASK); } catch (org.apache.oro.text.regex.MalformedPatternException ex) { throw new MalformedPatternException(ex); } } public void disposeComponent() { } public void initComponent() { } public void projectClosed() { } public JavacCompiler getJavacCompiler() { if (JAVAC_EXTERNAL_BACKEND == null) { createCompilers(); } return JAVAC_EXTERNAL_BACKEND; } public void projectOpened() { createCompilers(); } private void createCompilers() { JAVAC_EXTERNAL_BACKEND = new JavacCompiler(myProject); myRegisteredCompilers.add(JAVAC_EXTERNAL_BACKEND); if (!ApplicationManager.getApplication().isUnitTestMode()) { final BackendCompiler JIKES_BACKEND = new JikesCompiler(myProject); myRegisteredCompilers.add(JIKES_BACKEND); if (EclipseCompiler.isInitialized()) { final EclipseCompiler eclipse = new EclipseCompiler(myProject); myRegisteredCompilers.add(eclipse); } if (ApplicationManagerEx.getApplicationEx().isInternal()) { try { final EclipseEmbeddedCompiler eclipseEmbedded = new EclipseEmbeddedCompiler(myProject); myRegisteredCompilers.add(eclipseEmbedded); } catch (NoClassDefFoundError e) { // eclipse jar must be not in the classpath } } if (ApplicationManagerEx.getApplicationEx().isInternal()) { try { CompilerAPICompiler inprocessJavaCompiler = new CompilerAPICompiler(myProject); myRegisteredCompilers.add(inprocessJavaCompiler); } catch (NoClassDefFoundError e) { // wrong JDK } } } myDefaultJavaCompiler = JAVAC_EXTERNAL_BACKEND; for (BackendCompiler compiler : myRegisteredCompilers) { if (compiler.getId().equals(DEFAULT_COMPILER)) { myDefaultJavaCompiler = compiler; break; } } DEFAULT_COMPILER = myDefaultJavaCompiler.getId(); } public Collection<BackendCompiler> getRegisteredJavaCompilers() { return myRegisteredCompilers; } public String[] getResourceFilePatterns() { return getWildcardPatterns(); } private String[] getRegexpPatterns() { String[] patterns = ArrayUtil.newStringArray(myRegexpResourcePaterns.size()); int index = 0; for (final Pattern myRegexpResourcePatern : myRegexpResourcePaterns) { patterns[index++] = myRegexpResourcePatern.getPattern(); } return patterns; } private String[] getWildcardPatterns() { return ArrayUtil.toStringArray(myWildcardPatterns); } public void addResourceFilePattern(String namePattern) throws MalformedPatternException { addWildcardResourcePattern(namePattern); } // need this method only for handling patterns in old regexp format private void addRegexpPattern(String namePattern) throws MalformedPatternException { Pattern pattern = compilePattern(namePattern); if (pattern != null) { myRegexpResourcePaterns.add(pattern); } } public ExcludedEntriesConfiguration getExcludedEntriesConfiguration() { return myExcludedEntriesConfiguration; } public boolean isExcludedFromCompilation(final VirtualFile virtualFile) { return myExcludedEntriesConfiguration.isExcluded(virtualFile); } @Override public boolean isResourceFile(VirtualFile virtualFile) { return isResourceFile(virtualFile.getName(), virtualFile.getParent()); } public boolean isAnnotationProcessorsEnabled() { return myEnableAnnotationProcessors; } public void setAnnotationProcessorsEnabled(boolean enableAnnotationProcessors) { myEnableAnnotationProcessors = enableAnnotationProcessors; } public boolean isObtainProcessorsFromClasspath() { return myObtainProcessorsFromClasspath; } public void setObtainProcessorsFromClasspath(boolean obtainProcessorsFromClasspath) { myObtainProcessorsFromClasspath = obtainProcessorsFromClasspath; } public String getProcessorPath() { return myProcessorPath; } public void setProcessorsPath(String processorsPath) { myProcessorPath = processorsPath; } public Map<String, String> getAnnotationProcessorsMap() { return Collections.unmodifiableMap(myProcessorsMap); } public void setAnnotationProcessorsMap(Map<String, String> map) { myProcessorsMap.clear(); myProcessorsMap.putAll(map); } public Set<Module> getExcludedModules() { return Collections.unmodifiableSet(myExcludedModules); } public void setExcludedModules(Collection<Module> modules) { myExcludedModules.clear(); myExcludedModuleNames.clear(); myExcludedModules.addAll(modules); } private void addWildcardResourcePattern(@NonNls final String wildcardPattern) throws MalformedPatternException { final Pair<Pattern, Pattern> pattern = convertToRegexp(wildcardPattern); if (pattern != null) { myWildcardPatterns.add(wildcardPattern); if (isPatternNegated(wildcardPattern)) { myNegatedCompiledPatterns.add(pattern); } else { myCompiledPatterns.add(pattern); } } } public void removeResourceFilePatterns() { removeWildcardPatterns(); } private void removeRegexpPatterns() { myRegexpResourcePaterns.clear(); } private void removeWildcardPatterns() { myWildcardPatterns.clear(); myCompiledPatterns.clear(); myNegatedCompiledPatterns.clear(); } private static Pair<Pattern, Pattern> convertToRegexp(String wildcardPattern) { if (isPatternNegated(wildcardPattern)) { wildcardPattern = wildcardPattern.substring(1); } wildcardPattern = FileUtil.toSystemIndependentName(wildcardPattern); String dirPattern = null; int slash = wildcardPattern.lastIndexOf('/'); if (slash >= 0) { dirPattern = wildcardPattern.substring(0, slash + 1); wildcardPattern = wildcardPattern.substring(slash + 1); if (!dirPattern.startsWith("/")) { dirPattern = "/" + dirPattern; } //now dirPattern starts and ends with '/' dirPattern = normalizeWildcards(dirPattern); dirPattern = StringUtil.replace(dirPattern, "/.*.*/", "(/.*)?/"); dirPattern = StringUtil.trimEnd(dirPattern, "/"); dirPattern = optimize(dirPattern); dirPattern = ".*" + dirPattern; } wildcardPattern = normalizeWildcards(wildcardPattern); wildcardPattern = optimize(wildcardPattern); final Pattern dirCompiled = dirPattern == null ? null : compilePattern(dirPattern); return Pair.create(compilePattern(wildcardPattern), dirCompiled); } private static String optimize(String wildcardPattern) { return wildcardPattern.replaceAll("(?:\\.\\*)+", ".*"); } private static String normalizeWildcards(String wildcardPattern) { wildcardPattern = StringUtil.replace(wildcardPattern, "\\!", "!"); wildcardPattern = StringUtil.replace(wildcardPattern, ".", "\\."); wildcardPattern = StringUtil.replace(wildcardPattern, "*?", ".+"); wildcardPattern = StringUtil.replace(wildcardPattern, "?*", ".+"); wildcardPattern = StringUtil.replace(wildcardPattern, "*", ".*"); wildcardPattern = StringUtil.replace(wildcardPattern, "?", "."); return wildcardPattern; } public static boolean isPatternNegated(String wildcardPattern) { return wildcardPattern.length() > 1 && wildcardPattern.charAt(0) == '!'; } public boolean isResourceFile(String name) { return isResourceFile(name, null); } private boolean matches(String s, Pattern p) { synchronized (myPatternMatcher) { try { return myPatternMatcher.matches(s, p); } catch (Exception e) { LOG.error("Exception matching file name \"" + s + "\" against the pattern \"" + p + "\"", e); return false; } } } private boolean isResourceFile(String name, @Nullable VirtualFile parent) { final Ref<String> parentRef = Ref.create(null); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < myCompiledPatterns.size(); i++) { if (matches(name, parent, parentRef, myCompiledPatterns.get(i))) { return true; } } if (myNegatedCompiledPatterns.isEmpty()) { return false; } //noinspection ForLoopReplaceableByForEach for (int i = 0; i < myNegatedCompiledPatterns.size(); i++) { if (matches(name, parent, parentRef, myNegatedCompiledPatterns.get(i))) { return false; } } return true; } private boolean matches(String name, VirtualFile parent, Ref<String> parentRef, Pair<Pattern, Pattern> pair) { if (!matches(name, pair.first)) { return false; } final Pattern dirPattern = pair.second; if (dirPattern == null || parent == null) { return true; } String parentPath = parentRef.get(); if (parentPath == null) { parentRef.set(parentPath = parent.getPath()); } return matches(parentPath, dirPattern); } // property names @NonNls private static final String EXCLUDE_FROM_COMPILE = "excludeFromCompile"; @NonNls private static final String RESOURCE_EXTENSIONS = "resourceExtensions"; @NonNls private static final String ANNOTATION_PROCESSING = "annotationProcessing"; @NonNls private static final String WILDCARD_RESOURCE_PATTERNS = "wildcardResourcePatterns"; @NonNls private static final String ENTRY = "entry"; @NonNls private static final String NAME = "name"; public void readExternal(Element parentNode) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, parentNode); Element node = parentNode.getChild(EXCLUDE_FROM_COMPILE); if (node != null) { myExcludedEntriesConfiguration.readExternal(node); } try { removeRegexpPatterns(); node = parentNode.getChild(RESOURCE_EXTENSIONS); if (node != null) { for (final Object o : node.getChildren(ENTRY)) { Element element = (Element)o; String pattern = element.getAttributeValue(NAME); if (pattern != null && !"".equals(pattern)) { addRegexpPattern(pattern); } } } removeWildcardPatterns(); node = parentNode.getChild(WILDCARD_RESOURCE_PATTERNS); if (node != null) { myWildcardPatternsInitialized = true; for (final Object o : node.getChildren(ENTRY)) { final Element element = (Element)o; String pattern = element.getAttributeValue(NAME); if (pattern != null && !"".equals(pattern)) { addWildcardResourcePattern(pattern); } } } } catch (MalformedPatternException e) { throw new InvalidDataException(e); } final Element annotationProcessingSettings = parentNode.getChild(ANNOTATION_PROCESSING); if (annotationProcessingSettings != null) { myEnableAnnotationProcessors = Boolean.valueOf(annotationProcessingSettings.getAttributeValue("enabled", "false")); myObtainProcessorsFromClasspath = Boolean.valueOf(annotationProcessingSettings.getAttributeValue("useClasspath", "true")); final StringBuilder pathBuilder = new StringBuilder(); for (Element pathElement : ((Collection<Element>)annotationProcessingSettings.getChildren("processorPath"))) { final String path = pathElement.getAttributeValue("value"); if (path != null) { if (pathBuilder.length() > 0) { pathBuilder.append(File.pathSeparator); } pathBuilder.append(path); } } myProcessorPath = pathBuilder.toString(); myProcessorPath = annotationProcessingSettings.getAttributeValue("processorPath", ""); myProcessorsMap.clear(); for (Element processorChild : ((Collection<Element>)annotationProcessingSettings.getChildren("processor"))) { final String name = processorChild.getAttributeValue("name"); final String options = processorChild.getAttributeValue("options", ""); myProcessorsMap.put(name, options); } myExcludedModules.clear(); myExcludedModuleNames.clear(); final Collection<Element> excluded = (Collection<Element>)annotationProcessingSettings.getChildren("excludeModule"); if (excluded.size() > 0) { final Map<String, Module> moduleMap = new com.intellij.util.containers.HashMap<String, Module>(); for (Module module : myModuleManager.getModules()) { moduleMap.put(module.getName(), module); } for (Element moduleElement : excluded) { final String name = moduleElement.getAttributeValue("name"); if (name != null) { final Module module = moduleMap.get(name); if (module != null) { myExcludedModules.add(module); } else { myExcludedModuleNames.add(name); } } } } } } public void writeExternal(Element parentNode) throws WriteExternalException { DefaultJDOMExternalizer.writeExternal(this, parentNode); if(myExcludedEntriesConfiguration.getExcludeEntryDescriptions().length > 0) { Element newChild = new Element(EXCLUDE_FROM_COMPILE); myExcludedEntriesConfiguration.writeExternal(newChild); parentNode.addContent(newChild); } final Element newChild = new Element(RESOURCE_EXTENSIONS); for (final String pattern : getRegexpPatterns()) { final Element entry = new Element(ENTRY); entry.setAttribute(NAME, pattern); newChild.addContent(entry); } parentNode.addContent(newChild); if (myWildcardPatternsInitialized || !myWildcardPatterns.isEmpty()) { final Element wildcardPatterns = new Element(WILDCARD_RESOURCE_PATTERNS); for (final String wildcardPattern : myWildcardPatterns) { final Element entry = new Element(ENTRY); entry.setAttribute(NAME, wildcardPattern); wildcardPatterns.addContent(entry); } parentNode.addContent(wildcardPatterns); } final Element annotationProcessingSettings = new Element(ANNOTATION_PROCESSING); parentNode.addContent(annotationProcessingSettings); annotationProcessingSettings.setAttribute("enabled", String.valueOf(myEnableAnnotationProcessors)); annotationProcessingSettings.setAttribute("useClasspath", String.valueOf(myObtainProcessorsFromClasspath)); if (myProcessorPath.length() > 0) { final StringTokenizer tokenizer = new StringTokenizer(myProcessorPath, File.pathSeparator, false); while (tokenizer.hasMoreTokens()) { final String path = tokenizer.nextToken(); final Element pathElement = new Element("processorPath"); annotationProcessingSettings.addContent(pathElement); pathElement.setAttribute("value", path); } } for (Map.Entry<String, String> entry : myProcessorsMap.entrySet()) { final Element processor = new Element("processor"); annotationProcessingSettings.addContent(processor); processor.setAttribute("name", entry.getKey()); processor.setAttribute("options", entry.getValue()); } final List<Module> modules = new ArrayList<Module>(getExcludedModules()); Collections.sort(modules, new Comparator<Module>() { public int compare(Module o1, Module o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); for (Module module : modules) { final Element moduleElement = new Element("excludeModule"); annotationProcessingSettings.addContent(moduleElement); moduleElement.setAttribute("name", module.getName()); } } @NotNull @NonNls public String getComponentName() { return "CompilerConfiguration"; } public BackendCompiler getDefaultCompiler() { if (JAVAC_EXTERNAL_BACKEND == null) { createCompilers(); } return myDefaultJavaCompiler; } public void setDefaultCompiler(BackendCompiler defaultCompiler) { myDefaultJavaCompiler = defaultCompiler; DEFAULT_COMPILER = defaultCompiler.getId(); } public void convertPatterns() { if (!needPatternConversion()) { return; } try { boolean ok; try { ok = doConvertPatterns(); } catch (MalformedPatternException e) { ok = false; } if (!ok) { final String initialPatternString = patternsToString(getRegexpPatterns()); final String message = CompilerBundle.message( "message.resource.patterns.format.changed", ApplicationNamesInfo.getInstance().getProductName(), initialPatternString, CommonBundle.getOkButtonText(), CommonBundle.getCancelButtonText() ); final String wildcardPatterns = Messages.showInputDialog( myProject, message, CompilerBundle.message("pattern.conversion.dialog.title"), Messages.getWarningIcon(), initialPatternString, new InputValidator() { public boolean checkInput(String inputString) { return true; } public boolean canClose(String inputString) { final StringTokenizer tokenizer = new StringTokenizer(inputString, ";", false); StringBuilder malformedPatterns = new StringBuilder(); while (tokenizer.hasMoreTokens()) { String pattern = tokenizer.nextToken(); try { addWildcardResourcePattern(pattern); } catch (MalformedPatternException e) { malformedPatterns.append("\n\n"); malformedPatterns.append(pattern); malformedPatterns.append(": "); malformedPatterns.append(e.getMessage()); } } if (malformedPatterns.length() > 0) { Messages.showErrorDialog(CompilerBundle.message("error.bad.resource.patterns", malformedPatterns.toString()), CompilerBundle.message("bad.resource.patterns.dialog.title")); removeWildcardPatterns(); return false; } return true; } }); if (wildcardPatterns == null) { // cancel pressed loadDefaultWildcardPatterns(); } } } finally { myWildcardPatternsInitialized = true; } } private boolean needPatternConversion() { return !myWildcardPatternsInitialized && !myRegexpResourcePaterns.isEmpty(); } private boolean doConvertPatterns() throws MalformedPatternException { final String[] regexpPatterns = getRegexpPatterns(); final List<String> converted = new ArrayList<String>(); final Pattern multipleExtensionsPatternPattern = compilePattern("\\.\\+\\\\\\.\\((\\w+(?:\\|\\w+)*)\\)"); final Pattern singleExtensionPatternPattern = compilePattern("\\.\\+\\\\\\.(\\w+)"); final Perl5Matcher matcher = new Perl5Matcher(); for (final String regexpPattern : regexpPatterns) { //final Matcher multipleExtensionsMatcher = multipleExtensionsPatternPattern.matcher(regexpPattern); if (matcher.matches(regexpPattern, multipleExtensionsPatternPattern)) { final MatchResult match = matcher.getMatch(); final StringTokenizer tokenizer = new StringTokenizer(match.group(1), "|", false); while (tokenizer.hasMoreTokens()) { converted.add("?*." + tokenizer.nextToken()); } } else { //final Matcher singleExtensionMatcher = singleExtensionPatternPattern.matcher(regexpPattern); if (matcher.matches(regexpPattern, singleExtensionPatternPattern)) { final MatchResult match = matcher.getMatch(); converted.add("?*." + match.group(1)); } else { return false; } } } for (final String aConverted : converted) { addWildcardResourcePattern(aConverted); } return true; } private static String patternsToString(final String[] patterns) { final StringBuilder extensionsString = new StringBuilder(); for (int idx = 0; idx < patterns.length; idx++) { if (idx > 0) { extensionsString.append(";"); } extensionsString.append(patterns[idx]); } return extensionsString.toString(); } }
fix processor path externalization
java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java
fix processor path externalization
Java
apache-2.0
8eddcc77fcfcca04e58baac9dd40d6ca4dda2706
0
crawlik/ezbake-platform-services,infochimps-forks/ezbake-platform-services,crawlik/ezbake-platform-services,crawlik/ezbake-platform-services,crawlik/ezbake-platform-services,infochimps-forks/ezbake-platform-services,infochimps-forks/ezbake-platform-services,crawlik/ezbake-platform-services,infochimps-forks/ezbake-platform-services,crawlik/ezbake-platform-services,infochimps-forks/ezbake-platform-services,infochimps-forks/ezbake-platform-services,crawlik/ezbake-platform-services,infochimps-forks/ezbake-platform-services,infochimps-forks/ezbake-platform-services,crawlik/ezbake-platform-services
/* Copyright (C) 2013-2014 Computer Sciences Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ezbake.security.impl.ua; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; import ezbake.security.api.ua.Community; import ezbake.security.api.ua.User; import ezbake.security.api.ua.UserAttributeService; import ezbake.security.api.ua.UserNotFoundException; import ezbake.security.service.sync.NoopRedisCache; import ezbake.security.service.sync.EzSecurityRedisCache; public class LDAPUAService implements UserAttributeService { public static final String LDAP_HOST = "ezbake.uaservice.ldap.host"; public static final String DEFAULT_LDAP_HOST = "localhost"; public static final String LDAP_PORT = "ezbake.uaservice.ldap.port"; public static final int DEFAULT_LDAP_PORT = 389; public static class LdapModule extends AbstractModule { private Properties ezConfiguration; public LdapModule(Properties ezConfiguration) { this.ezConfiguration = ezConfiguration; } @Override protected void configure() {} @Provides LdapConnection provideLdapConnection() { logger.info("connecting to ldap at {}:{}", getHost(), getPort()); LdapConnection connection = new LdapNetworkConnection(getHost(), getPort(), false); return connection; } private int getPort() { return Integer.valueOf(ezConfiguration.getProperty(LDAP_PORT, String.valueOf(DEFAULT_LDAP_PORT))); } private String getHost() { return ezConfiguration.getProperty(LDAP_HOST, DEFAULT_LDAP_HOST); } } private static final Logger logger = LoggerFactory.getLogger(LDAPUAService.class); protected final LdapConnection connection; private final NoopRedisCache cache; @Inject public LDAPUAService(Properties ezConfiguration, LdapConnection connection) { cache = new NoopRedisCache(); this.connection = connection; } @Override public boolean assertUserStrictFailure(String principal) { return assertUser(principal); } @Override public boolean assertUser(String principal) { try { getUserOrThrow(principal); } catch (UserNotFoundException e) { logger.debug("couldn't find user {}", principal, e); return false; } return true; } @Override public User getUser(String principal) throws UserNotFoundException { return getUserOrThrow(principal); } @Override public User getUserProfile(String principal) throws UserNotFoundException { User u = getUserOrThrow(principal); u.setCommunities(null); u.setAuthorizations(null); u.setProjects(null); return u; } @Override public Map<String, List<String>> getUserGroups(String principal) throws UserNotFoundException { User u = getUserOrThrow(principal); return u.getProjects(); } @Override public EzSecurityRedisCache getCache() { return this.cache; } //-------------------------------------------------------------------------------- private User getUserOrThrow(String principal) throws UserNotFoundException { try { logger.debug("looking up user {}", principal); maybeBind(); Dn userDnVal = userDn(principal); logger.trace("user {} is assumed to have dn {}", principal, userDnVal); Entry userEntry = connection.lookup(userDnVal); if (userEntry == null) { throw new UserNotFoundException("LDAP response for " + userDnVal + " empty"); } User user = userFromEntry(userEntry); user.setPrincipal(principal); logger.trace("found user: {}", user); return user; } catch (LdapException e) { throw new UserNotFoundException("Couldn't find " + principal, e); } } //-------------------------------------------------------------------------------- public void addToList(Collection<String> lst, Attribute attr) throws LdapInvalidAttributeValueException { logger.trace("adding {} to {}", attr, lst); while(attr.size() > 0) { String val = attr.getString(); lst.add(val); logger.trace("{}: {}", val, lst); attr.remove(val); } } private User userFromEntry(Entry userEntry) throws LdapException { User user = new User(); int emailCount = 0; for (Attribute attr : userEntry.getAttributes()) { logger.trace("considering attribute {}", attr); switch (attr.getUpId()) { case "givenName": user.setFirstName(attr.getString()); break; case "sn": user.setSurName(attr.getString()); break; case "uid": user.setUid(attr.getString()); break; case "ou": user.setCompany(attr.getString()); user.setOrganization(attr.getString()); user.getAuthorizations().setOrganization(attr.getString()); break; case "telephoneNumber": user.setPhoneNumber(attr.getString()); break; case "mail": user.getEmails().put(String.valueOf(emailCount++), attr.getString()); break; case "ezAuthLevel": user.getAuthorizations().setLevel(attr.getString()); break; case "ezGovernmentAuth": addToList(user.getAuthorizations().getAuths(), attr.clone()); break; case "ezCommunityAuth": addToList(user.getAuthorizations().getCommunityAuthorizations(), attr.clone()); break; case "ezCountryOfCitizenship": user.getAuthorizations().setCitizenship(attr.getString()); break; case "ezGroupAndProject": addToProjects(user.getProjects(), attr.clone()); break; case "ezCommunityName": user.getCommunities().addAll(communitiesFromAttr(attr.clone())); break; case "ezAffiliation": addToList(user.getAffiliations(), attr.clone()); break; }; } user.setName(user.getFirstName() + " " + user.getSurName()); return user; } //-------------------------------------------------------------------------------- private List<Community> communitiesFromAttr(Attribute attr) throws LdapException { List<Community> communities = new ArrayList<>(); logger.trace("getting communities: {}", attr); while(attr.size() > 0) { String val = attr.getString(); communities.add(communityFromName(val)); logger.trace("{}: {}", val, communities); attr.remove(val); } return communities; } private Community communityFromName(String name) throws LdapException { Community result = new Community(); Dn communityDnVal = communityDn(name); logger.trace("looking up community with dn {}", communityDnVal); Entry communityEntry = connection.lookup(communityDnVal); for (Attribute attr : communityEntry.getAttributes()) { logger.trace("considering attribute {}", attr); switch (attr.getUpId()) { case "ezCommunityName": result.setCommunityName(attr.getString()); break; case "ezCommunityType": result.setCommunityType(attr.getString()); break; case "ou": result.setOrganization(attr.getString()); break; case "ezTopic": addToList(result.getTopics(), attr.clone()); break; case "ezRegion": addToList(result.getRegions(), attr.clone()); break; case "ezGroupMemberOf": addToList(result.getGroups(), attr.clone()); break; case "ezCommunityFlag": result.getFlags().put(flagFrom(attr.getString()),boolFrom(attr.getString())); break; } } return result; } private List<String> groupsFromType(String type) throws LdapException { List<String> result = new ArrayList<>(); Dn groupTypeDnVal = groupTypeDn(type); logger.trace("looking up group type with dn {}", groupTypeDnVal); Entry typeEntry = connection.lookup(groupTypeDnVal); for (Attribute attr : typeEntry.getAttributes()) { logger.trace("considering attribute {}", attr); switch (attr.getUpId()) { case "ezGroupMemberOf": addToList(result, attr.clone()); break; } } return result; } //-------------------------------------------------------------------------------- private void addToProjects(Map<String,List<String>> groups, Attribute attr) throws LdapInvalidAttributeValueException { logger.trace("adding {} to {}", attr, groups); while(attr.size() > 0) { String groupAndProject = attr.getString(); String groupName = groupFrom(groupAndProject); String projectName = projectFrom(groupAndProject); logger.trace("decomposed {} to {} -> {}. adding to {}", groupAndProject, groupName, projectName, groups); List<String> projects = groups.get(groupName); if (projects == null) { projects = new ArrayList<>(); groups.put(groupName, projects); } projects.add(projectName); attr.remove(groupAndProject); } } //-------------------------------------------------------------------------------- private Boolean boolFrom(String val) { return new Boolean(val.split("=")[1]); } private String flagFrom(String val) { return val.split("=")[0]; } private String groupFrom(String groupAndProject) { return groupAndProject.split(":")[0]; } private String projectFrom(String groupAndProject) { return groupAndProject.split(":")[1]; } //-------------------------------------------------------------------------------- private Dn communityDn(String name) throws LdapInvalidDnException { return baseDn().add(new Rdn("cn","ezbake")).add(new Rdn("cn","communities")).add(new Rdn("cn", name)); } private Dn groupTypeDn(String type) throws LdapInvalidDnException { return baseDn().add(new Rdn("cn","ezbake")).add(new Rdn("cn","grouptypes")).add(new Rdn("cn", type)); } private Dn userDn(String principal) throws LdapInvalidDnException { return new Dn(principal.split(",")); } //-------------------------------------------------------------------------------- protected Dn baseDn() throws LdapInvalidDnException { // This simply takes the domain components of the hostname and // infers the LDAP layout from it. It's presumptuous but // flexible enough to work with the SRP as it's // configured. I'm going to leave this protected to allow base // classes to do it more flexibly if needed. String hostname = null; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { String msg = "localhost unknown. highly unexpected."; logger.error(msg, ex); throw new RuntimeException(msg, ex); } String[] hostElements = hostname.split("\\."); logger.trace("got {} components for hostname {}", hostElements.length, hostname); Dn result = new Dn(); // domain elements (all except first) in reverse order for (int i = hostElements.length - 1; i >= 1; i--) { String elem = hostElements[i]; logger.trace("adding element {}", elem); result = result.add(new Rdn("dc", elem)); } logger.trace("baseDn: {}", result); return result; } //-------------------------------------------------------------------------------- private void maybeBind() throws LdapException { if (!connection.isAuthenticated()) { logger.debug("binding to ldap."); connection.bind(); } } }
security/common/ua/src/main/java/ezbake/security/impl/ua/LDAPUAService.java
/* Copyright (C) 2013-2014 Computer Sciences Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ezbake.security.impl.ua; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; import ezbake.security.api.ua.Community; import ezbake.security.api.ua.User; import ezbake.security.api.ua.UserAttributeService; import ezbake.security.api.ua.UserNotFoundException; import ezbake.security.service.sync.NoopRedisCache; import ezbake.security.service.sync.EzSecurityRedisCache; public class LDAPUAService implements UserAttributeService { public static final String LDAP_HOST = "ezbake.uaservice.ldap.host"; public static final String DEFAULT_LDAP_HOST = "localhost"; public static final String LDAP_PORT = "ezbake.uaservice.ldap.port"; public static final int DEFAULT_LDAP_PORT = 389; public static class LdapModule extends AbstractModule { private Properties ezConfiguration; public LdapModule(Properties ezConfiguration) { this.ezConfiguration = ezConfiguration; } @Override protected void configure() {} @Provides LdapConnection provideLdapConnection() { logger.info("connecting to ldap at {}:{}", getHost(), getPort()); LdapConnection connection = new LdapNetworkConnection(getHost(), getPort(), false); return connection; } private int getPort() { return Integer.valueOf(ezConfiguration.getProperty(LDAP_PORT, String.valueOf(DEFAULT_LDAP_PORT))); } private String getHost() { return ezConfiguration.getProperty(LDAP_HOST, DEFAULT_LDAP_HOST); } } private static final Logger logger = LoggerFactory.getLogger(LDAPUAService.class); protected final LdapConnection connection; private final NoopRedisCache cache; @Inject public LDAPUAService(Properties ezConfiguration, LdapConnection connection) { cache = new NoopRedisCache(); this.connection = connection; } @Override public boolean assertUserStrictFailure(String principal) { return assertUser(principal); } @Override public boolean assertUser(String principal) { try { getUserOrThrow(principal); } catch (UserNotFoundException e) { logger.debug("couldn't find user {}", principal, e); return false; } return true; } @Override public User getUser(String principal) throws UserNotFoundException { return getUserOrThrow(principal); } @Override public User getUserProfile(String principal) throws UserNotFoundException { User u = getUserOrThrow(principal); u.setCommunities(null); u.setAuthorizations(null); u.setProjects(null); return u; } @Override public Map<String, List<String>> getUserGroups(String principal) throws UserNotFoundException { User u = getUserOrThrow(principal); return u.getProjects(); } @Override public EzSecurityRedisCache getCache() { return this.cache; } //-------------------------------------------------------------------------------- private User getUserOrThrow(String principal) throws UserNotFoundException { try { maybeBind(); Dn userDnVal = userDn(principal); logger.debug("looking up user with dn {}", userDnVal); Entry userEntry = connection.lookup(userDnVal); if (userEntry == null) { throw new UserNotFoundException("LDAP response for " + userDnVal + " empty"); } User user = userFromEntry(userEntry); user.setPrincipal(principal); return user; } catch (LdapException e) { throw new UserNotFoundException("Couldn't find " + principal, e); } } //-------------------------------------------------------------------------------- public void addToList(Collection<String> lst, Attribute attr) throws LdapInvalidAttributeValueException { logger.trace("adding {} to {}", attr, lst); while(attr.size() > 0) { String val = attr.getString(); lst.add(val); logger.trace("{}: {}", val, lst); attr.remove(val); } } private User userFromEntry(Entry userEntry) throws LdapException { User user = new User(); int emailCount = 0; for (Attribute attr : userEntry.getAttributes()) { logger.trace("considering attribute {}", attr); switch (attr.getUpId()) { case "givenName": user.setFirstName(attr.getString()); break; case "sn": user.setSurName(attr.getString()); break; case "uid": user.setUid(attr.getString()); break; case "ou": user.setCompany(attr.getString()); user.setOrganization(attr.getString()); user.getAuthorizations().setOrganization(attr.getString()); break; case "telephoneNumber": user.setPhoneNumber(attr.getString()); break; case "mail": user.getEmails().put(String.valueOf(emailCount++), attr.getString()); break; case "ezAuthLevel": user.getAuthorizations().setLevel(attr.getString()); break; case "ezGovernmentAuth": addToList(user.getAuthorizations().getAuths(), attr.clone()); break; case "ezCommunityAuth": addToList(user.getAuthorizations().getCommunityAuthorizations(), attr.clone()); break; case "ezCountryOfCitizenship": user.getAuthorizations().setCitizenship(attr.getString()); break; case "ezGroupAndProject": addToProjects(user.getProjects(), attr.clone()); break; case "ezCommunityName": user.getCommunities().addAll(communitiesFromAttr(attr.clone())); break; case "ezAffiliation": addToList(user.getAffiliations(), attr.clone()); break; }; } user.setName(user.getFirstName() + " " + user.getSurName()); return user; } //-------------------------------------------------------------------------------- private List<Community> communitiesFromAttr(Attribute attr) throws LdapException { List<Community> communities = new ArrayList<>(); logger.trace("getting communities: {}", attr); while(attr.size() > 0) { String val = attr.getString(); communities.add(communityFromName(val)); logger.trace("{}: {}", val, communities); attr.remove(val); } return communities; } private Community communityFromName(String name) throws LdapException { Community result = new Community(); Dn communityDnVal = communityDn(name); logger.trace("looking up community with dn {}", communityDnVal); Entry communityEntry = connection.lookup(communityDnVal); for (Attribute attr : communityEntry.getAttributes()) { logger.trace("considering attribute {}", attr); switch (attr.getUpId()) { case "ezCommunityName": result.setCommunityName(attr.getString()); break; case "ezCommunityType": result.setCommunityType(attr.getString()); break; case "ou": result.setOrganization(attr.getString()); break; case "ezTopic": addToList(result.getTopics(), attr.clone()); break; case "ezRegion": addToList(result.getRegions(), attr.clone()); break; case "ezGroupMemberOf": addToList(result.getGroups(), attr.clone()); break; case "ezCommunityFlag": result.getFlags().put(flagFrom(attr.getString()),boolFrom(attr.getString())); break; } } return result; } private List<String> groupsFromType(String type) throws LdapException { List<String> result = new ArrayList<>(); Dn groupTypeDnVal = groupTypeDn(type); logger.trace("looking up group type with dn {}", groupTypeDnVal); Entry typeEntry = connection.lookup(groupTypeDnVal); for (Attribute attr : typeEntry.getAttributes()) { logger.trace("considering attribute {}", attr); switch (attr.getUpId()) { case "ezGroupMemberOf": addToList(result, attr.clone()); break; } } return result; } //-------------------------------------------------------------------------------- private void addToProjects(Map<String,List<String>> groups, Attribute attr) throws LdapInvalidAttributeValueException { logger.trace("adding {} to {}", attr, groups); while(attr.size() > 0) { String groupAndProject = attr.getString(); String groupName = groupFrom(groupAndProject); String projectName = projectFrom(groupAndProject); logger.trace("decomposed {} to {} -> {}. adding to {}", groupAndProject, groupName, projectName, groups); List<String> projects = groups.get(groupName); if (projects == null) { projects = new ArrayList<>(); groups.put(groupName, projects); } projects.add(projectName); attr.remove(groupAndProject); } } //-------------------------------------------------------------------------------- private Boolean boolFrom(String val) { return new Boolean(val.split("=")[1]); } private String flagFrom(String val) { return val.split("=")[0]; } private String groupFrom(String groupAndProject) { return groupAndProject.split(":")[0]; } private String projectFrom(String groupAndProject) { return groupAndProject.split(":")[1]; } //-------------------------------------------------------------------------------- private Dn communityDn(String name) throws LdapInvalidDnException { return baseDn().add(new Rdn("cn","ezbake")).add(new Rdn("cn","communities")).add(new Rdn("cn", name)); } private Dn groupTypeDn(String type) throws LdapInvalidDnException { return baseDn().add(new Rdn("cn","ezbake")).add(new Rdn("cn","grouptypes")).add(new Rdn("cn", type)); } private Dn userDn(String principal) throws LdapInvalidDnException { return new Dn(principal.split(",")); } //-------------------------------------------------------------------------------- protected Dn baseDn() throws LdapInvalidDnException { // This simply takes the domain components of the hostname and // infers the LDAP layout from it. It's presumptuous but // flexible enough to work with the SRP as it's // configured. I'm going to leave this protected to allow base // classes to do it more flexibly if needed. String hostname = null; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { String msg = "localhost unknown. highly unexpected."; logger.error(msg, ex); throw new RuntimeException(msg, ex); } String[] hostElements = hostname.split("\\."); logger.trace("got {} components for hostname {}", hostElements.length, hostname); Dn result = new Dn(); // domain elements (all except first) in reverse order for (int i = hostElements.length - 1; i >= 1; i--) { String elem = hostElements[i]; logger.trace("adding element {}", elem); result = result.add(new Rdn("dc", elem)); } logger.trace("baseDn: {}", result); return result; } //-------------------------------------------------------------------------------- private void maybeBind() throws LdapException { if (!connection.isAuthenticated()) { logger.info("binding to ldap. This should only happen once."); connection.bind(); } } }
logging changes for security service
security/common/ua/src/main/java/ezbake/security/impl/ua/LDAPUAService.java
logging changes for security service
Java
apache-2.0
cf80d880ccf9e86f4a70f7f3b441a18e804ac84d
0
ragnor-rs/sklad
/* * Copyright (C) 2017 Renat Sarymsakov. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reist.sklad; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.SocketException; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import okhttp3.Connection; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import okio.BufferedSource; /** * Created by Reist on 28.06.16. */ public class NetworkStorage implements Storage { private final List<Request> activeRequests = new CopyOnWriteArrayList<>(); private final OkHttpClient client; private final UrlResolver urlResolver; public NetworkStorage(UrlResolver urlResolver) { this(urlResolver, 10, 10, 10); } public NetworkStorage( UrlResolver urlResolver, final long connectTimeout, final long readTimeout, final long writeTimeout ) { this( urlResolver, new ClientConfigurator( readTimeout, connectTimeout, writeTimeout ) ); } public NetworkStorage( UrlResolver urlResolver, ClientConfigurator clientConfigurator ) { this.urlResolver = urlResolver; this.client = clientConfigurator.configure(new OkHttpClient.Builder(), this).build(); } private Response request(@NonNull String name) throws IOException { String url = urlResolver.toUrl(name); Request request = new Request.Builder().url(url).build(); activeRequests.add(request); try { return client.newCall(request).execute(); } catch (SocketException e) { if (!activeRequests.contains(request)) { throw new InterruptedIOException(); } else { throw e; } } } @Override public boolean contains(@NonNull String id) throws IOException { return request(id).isSuccessful(); } @NonNull @Override public OutputStream openOutputStream(@NonNull String id) throws IOException { throw new UnsupportedOperationException(); } @Nullable @Override public InputStream openInputStream(@NonNull String id) throws IOException { final ResponseBody body = request(id).body(); final long contentLength = body.contentLength(); final BufferedSource source = body.source(); return new InputStream() { private int position = 0; @Override public int read(byte[] b) throws IOException { int numRead = source.read(b); position += numRead; return numRead; } @Override public int read(byte[] b, int off, int len) throws IOException { int numRead = source.read(b, off, len); position += numRead; return numRead; } @Override public long skip(long n) throws IOException { source.skip(n); position += n; return n; } @Override public int available() throws IOException { return (int) contentLength - position; } @Override public void close() throws IOException { body.close(); } @Override public synchronized void mark(int readlimit) { throw new UnsupportedOperationException(); } @Override public synchronized void reset() throws IOException { throw new UnsupportedOperationException(); } @Override public boolean markSupported() { return false; } @Override public int read() throws IOException { position++; return source.readByte() & 0xFF; } }; } @Override public boolean delete(@NonNull String id) throws IOException { throw new UnsupportedOperationException(); } @Override public void deleteAll() throws IOException { throw new UnsupportedOperationException(); } /** * Forces a thread which performs socket reading to throw {@link ConnectException} * if {@link java.net.SocketTimeoutException} is not thrown within timeout interval. * See https://bugs.openjdk.java.net/browse/JDK-8049846 */ private static class StuckOnReadHeadersInterceptor implements Interceptor { private final List<Chain> activeChains = new CopyOnWriteArrayList<>(); private final long readTimeout; private final NetworkStorage parent; StuckOnReadHeadersInterceptor(long readTimeout, NetworkStorage parent) { this.readTimeout = readTimeout; this.parent = parent; } @Override public Response intercept(final Chain chain) throws IOException { activeChains.add(chain); final Connection connection = chain.connection(); (new Thread() { @SuppressWarnings("SuspiciousMethodCalls") @Override public void run() { // wait more than just timeout to distinguish from real timeout // in NetworkStorage.request try { sleep(readTimeout + 1000); } catch (InterruptedException ignored) {} try { if (activeChains.contains(chain)) { // tag refers to the original request parent.activeRequests.remove(chain.request().tag()); try { connection.socket().close(); } catch (IOException ignored) {} } } catch (Exception e) { throw new RuntimeException(e); } } }).start(); Response proceed = chain.proceed(chain.request()); activeChains.remove(chain); return proceed; } } public static class ClientConfigurator { private final long readTimeout; private final long connectTimeout; private final long writeTimeout; public ClientConfigurator( long readTimeout, long connectTimeout, long writeTimeout ) { this.readTimeout = readTimeout; this.connectTimeout = connectTimeout; this.writeTimeout = writeTimeout; } protected OkHttpClient.Builder configure( OkHttpClient.Builder builder, NetworkStorage networkStorage ) { StuckOnReadHeadersInterceptor interceptor = new StuckOnReadHeadersInterceptor( readTimeout, networkStorage ); return builder .connectTimeout(connectTimeout, TimeUnit.SECONDS) .writeTimeout(writeTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS) .addNetworkInterceptor(interceptor); } } }
lib/src/main/java/io/reist/sklad/NetworkStorage.java
/* * Copyright (C) 2017 Renat Sarymsakov. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reist.sklad; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.SocketException; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import okhttp3.Connection; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import okio.BufferedSource; /** * Created by Reist on 28.06.16. */ public class NetworkStorage implements Storage { private final List<Request> activeRequests = new CopyOnWriteArrayList<>(); private final OkHttpClient client; private final UrlResolver urlResolver; public NetworkStorage(UrlResolver urlResolver) { this(urlResolver, 10, 10, 10); } public NetworkStorage( UrlResolver urlResolver, final long connectTimeout, final long readTimeout, final long writeTimeout ) { this.urlResolver = urlResolver; this.client = new OkHttpClient.Builder() .connectTimeout(connectTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS) .writeTimeout(writeTimeout, TimeUnit.SECONDS) .addNetworkInterceptor(new StuckOnReadHeadersInterceptor(readTimeout, this)) .build(); } private Response request(@NonNull String name) throws IOException { String url = urlResolver.toUrl(name); Request request = new Request.Builder().url(url).build(); activeRequests.add(request); try { return client.newCall(request).execute(); } catch (SocketException e) { if (!activeRequests.contains(request)) { throw new InterruptedIOException(); } else { throw e; } } } @Override public boolean contains(@NonNull String id) throws IOException { return request(id).isSuccessful(); } @NonNull @Override public OutputStream openOutputStream(@NonNull String id) throws IOException { throw new UnsupportedOperationException(); } @Nullable @Override public InputStream openInputStream(@NonNull String id) throws IOException { final ResponseBody body = request(id).body(); final long contentLength = body.contentLength(); final BufferedSource source = body.source(); return new InputStream() { private int position = 0; @Override public int read(byte[] b) throws IOException { int numRead = source.read(b); position += numRead; return numRead; } @Override public int read(byte[] b, int off, int len) throws IOException { int numRead = source.read(b, off, len); position += numRead; return numRead; } @Override public long skip(long n) throws IOException { source.skip(n); position += n; return n; } @Override public int available() throws IOException { return (int) contentLength - position; } @Override public void close() throws IOException { body.close(); } @Override public synchronized void mark(int readlimit) { throw new UnsupportedOperationException(); } @Override public synchronized void reset() throws IOException { throw new UnsupportedOperationException(); } @Override public boolean markSupported() { return false; } @Override public int read() throws IOException { position++; return source.readByte() & 0xFF; } }; } @Override public boolean delete(@NonNull String id) throws IOException { throw new UnsupportedOperationException(); } @Override public void deleteAll() throws IOException { throw new UnsupportedOperationException(); } /** * Forces a thread which performs socket reading to throw {@link ConnectException} * if {@link java.net.SocketTimeoutException} is not thrown within timeout interval. * See https://bugs.openjdk.java.net/browse/JDK-8049846 */ private static class StuckOnReadHeadersInterceptor implements Interceptor { private final List<Chain> activeChains = new CopyOnWriteArrayList<>(); private final long readTimeout; private final NetworkStorage parent; StuckOnReadHeadersInterceptor(long readTimeout, NetworkStorage parent) { this.readTimeout = readTimeout; this.parent = parent; } @Override public Response intercept(final Chain chain) throws IOException { activeChains.add(chain); final Connection connection = chain.connection(); (new Thread() { @SuppressWarnings("SuspiciousMethodCalls") @Override public void run() { // wait more than just timeout to distinguish from real timeout // in NetworkStorage.request try { sleep(readTimeout + 1000); } catch (InterruptedException ignored) {} try { if (activeChains.contains(chain)) { // tag refers to the original request parent.activeRequests.remove(chain.request().tag()); try { connection.socket().close(); } catch (IOException ignored) {} } } catch (Exception e) { throw new RuntimeException(e); } } }).start(); Response proceed = chain.proceed(chain.request()); activeChains.remove(chain); return proceed; } } }
custom configurator
lib/src/main/java/io/reist/sklad/NetworkStorage.java
custom configurator
Java
apache-2.0
d1a574b80ef35ebdae69718998a2dfcaeafc3cbc
0
haoch/kylin,haoch/kylin,haoch/kylin,haoch/kylin,haoch/kylin,haoch/kylin
/* * * * Licensed to the Apache Software Foundation (ASF) under one or more * * contributor license agreements. See the NOTICE file distributed with * * this work for additional information regarding copyright ownership. * * The ASF licenses this file to You under the Apache License, Version 2.0 * * (the "License"); you may not use this file except in compliance with * * the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * / */ package org.apache.kylin.source.kafka; import java.io.IOException; import java.util.*; import kafka.message.MessageAndOffset; import org.apache.commons.lang3.StringUtils; import org.apache.kylin.common.util.DateFormat; import org.apache.kylin.common.util.StreamingMessage; import org.apache.kylin.common.util.TimeUtil; import org.apache.kylin.metadata.model.TblColRef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.MapType; import com.fasterxml.jackson.databind.type.SimpleType; import com.google.common.collect.Lists; /** * each json message with a "timestamp" field */ public final class TimedJsonStreamParser extends StreamingParser { private static final Logger logger = LoggerFactory.getLogger(TimedJsonStreamParser.class); private List<TblColRef> allColumns; private boolean formatTs = false;//not used private final ObjectMapper mapper = new ObjectMapper(); private String tsColName = "timestamp"; private final JavaType mapType = MapType.construct(HashMap.class, SimpleType.construct(String.class), SimpleType.construct(String.class)); public TimedJsonStreamParser(List<TblColRef> allColumns, String propertiesStr) { this.allColumns = allColumns; if (!StringUtils.isEmpty(propertiesStr)) { String[] properties = propertiesStr.split(";"); for (String prop : properties) { try { String[] parts = prop.split("="); if (parts.length == 2) { switch (parts[0]) { case "formatTs": this.formatTs = Boolean.valueOf(parts[1]); break; case "tsColName": this.tsColName = parts[1]; break; default: break; } } } catch (Exception e) { logger.error("Failed to parse property " + prop); //ignore } } } logger.info("TimedJsonStreamParser with formatTs {} tsColName {}", formatTs, tsColName); } @Override public StreamingMessage parse(MessageAndOffset messageAndOffset) { try { Map<String, String> message = mapper.readValue(new ByteBufferBackedInputStream(messageAndOffset.message().payload()), mapType); Map<String, String> root = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); root.putAll(message); String tsStr = root.get(tsColName); //Preconditions.checkArgument(!StringUtils.isEmpty(tsStr), "Timestamp field " + tsColName + // //" cannot be null, the message offset is " + messageAndOffset.getOffset() + " content is " + new String(messageAndOffset.getRawData())); long t; if (StringUtils.isEmpty(tsStr)) { t = 0; } else { t = Long.valueOf(tsStr); } ArrayList<String> result = Lists.newArrayList(); long normalized = 0; for (TblColRef column : allColumns) { String columnName = column.getName(); if (columnName.equalsIgnoreCase("minute_start")) { normalized = TimeUtil.getMinuteStart(t); result.add(DateFormat.formatToTimeStr(normalized)); } else if (columnName.equalsIgnoreCase("hour_start")) { normalized = TimeUtil.getHourStart(t); result.add(DateFormat.formatToTimeStr(normalized)); } else if (columnName.equalsIgnoreCase("day_start")) { //from day_start on, formatTs will output date format normalized = TimeUtil.getDayStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("week_start")) { normalized = TimeUtil.getWeekStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("month_start")) { normalized = TimeUtil.getMonthStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("quarter_start")) { normalized = TimeUtil.getQuarterStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("year_start")) { normalized = TimeUtil.getYearStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else { String x = root.get(columnName.toLowerCase()); result.add(x); } } return new StreamingMessage(result, messageAndOffset.offset(), t, Collections.<String, Object> emptyMap()); } catch (IOException e) { logger.error("error", e); throw new RuntimeException(e); } } @Override public boolean filter(StreamingMessage streamingMessage) { return true; } }
source-kafka/src/main/java/org/apache/kylin/source/kafka/TimedJsonStreamParser.java
/* * * * Licensed to the Apache Software Foundation (ASF) under one or more * * contributor license agreements. See the NOTICE file distributed with * * this work for additional information regarding copyright ownership. * * The ASF licenses this file to You under the Apache License, Version 2.0 * * (the "License"); you may not use this file except in compliance with * * the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * / */ package org.apache.kylin.source.kafka; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import kafka.message.MessageAndOffset; import org.apache.commons.lang3.StringUtils; import org.apache.kylin.common.util.DateFormat; import org.apache.kylin.common.util.StreamingMessage; import org.apache.kylin.common.util.TimeUtil; import org.apache.kylin.metadata.model.TblColRef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.MapType; import com.fasterxml.jackson.databind.type.SimpleType; import com.google.common.collect.Lists; /** * each json message with a "timestamp" field */ public final class TimedJsonStreamParser extends StreamingParser { private static final Logger logger = LoggerFactory.getLogger(TimedJsonStreamParser.class); private List<TblColRef> allColumns; private boolean formatTs = false;//not used private final ObjectMapper mapper = new ObjectMapper(); private String tsColName = "timestamp"; private final JavaType mapType = MapType.construct(HashMap.class, SimpleType.construct(String.class), SimpleType.construct(String.class)); public TimedJsonStreamParser(List<TblColRef> allColumns, String propertiesStr) { this.allColumns = allColumns; if (!StringUtils.isEmpty(propertiesStr)) { String[] properties = propertiesStr.split(";"); for (String prop : properties) { try { String[] parts = prop.split("="); if (parts.length == 2) { switch (parts[0]) { case "formatTs": this.formatTs = Boolean.valueOf(parts[1]); break; case "tsColName": this.tsColName = parts[1]; break; default: break; } } } catch (Exception e) { logger.error("Failed to parse property " + prop); //ignore } } } logger.info("TimedJsonStreamParser with formatTs {} tsColName {}", formatTs, tsColName); } @Override public StreamingMessage parse(MessageAndOffset messageAndOffset) { try { Map<String, String> root = mapper.readValue(new ByteBufferBackedInputStream(messageAndOffset.message().payload()), mapType); String tsStr = root.get(tsColName); //Preconditions.checkArgument(!StringUtils.isEmpty(tsStr), "Timestamp field " + tsColName + // //" cannot be null, the message offset is " + messageAndOffset.getOffset() + " content is " + new String(messageAndOffset.getRawData())); long t; if (StringUtils.isEmpty(tsStr)) { t = 0; } else { t = Long.valueOf(tsStr); } ArrayList<String> result = Lists.newArrayList(); long normalized = 0; for (TblColRef column : allColumns) { String columnName = column.getName(); if (columnName.equalsIgnoreCase("minute_start")) { normalized = TimeUtil.getMinuteStart(t); result.add(DateFormat.formatToTimeStr(normalized)); } else if (columnName.equalsIgnoreCase("hour_start")) { normalized = TimeUtil.getHourStart(t); result.add(DateFormat.formatToTimeStr(normalized)); } else if (columnName.equalsIgnoreCase("day_start")) { //from day_start on, formatTs will output date format normalized = TimeUtil.getDayStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("week_start")) { normalized = TimeUtil.getWeekStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("month_start")) { normalized = TimeUtil.getMonthStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("quarter_start")) { normalized = TimeUtil.getQuarterStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else if (columnName.equalsIgnoreCase("year_start")) { normalized = TimeUtil.getYearStart(t); result.add(DateFormat.formatToDateStr(normalized)); } else { String x = root.get(columnName.toLowerCase()); result.add(x); } } return new StreamingMessage(result, messageAndOffset.offset(), t, Collections.<String, Object> emptyMap()); } catch (IOException e) { logger.error("error", e); throw new RuntimeException(e); } } @Override public boolean filter(StreamingMessage streamingMessage) { return true; } }
KYLIN-1417 Change to use TreeMap to allow null as value
source-kafka/src/main/java/org/apache/kylin/source/kafka/TimedJsonStreamParser.java
KYLIN-1417 Change to use TreeMap to allow null as value
Java
apache-2.0
58c6387f1c0b8bb573c65da6926b07706bc3080b
0
yeastrc/proxl-web-app,yeastrc/proxl-web-app,yeastrc/proxl-web-app
package org.yeastrc.xlink.www.protein_coverage; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.yeastrc.xlink.db.DBConnectionFactory; import org.yeastrc.xlink.searcher_psm_peptide_cutoff_objects.SearcherCutoffValuesSearchLevel; import org.yeastrc.xlink.www.factories.ProteinSequenceObjectFactory; import org.yeastrc.xlink.www.objects.ProteinSequenceObject; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Range; /** * Manage the cache of protein sequence coverages for given searches with given search * parameters. Keeps an in-memory cache, as well as a database cache * * @author mriffle * */ public class ProteinSequenceCoverageCacheManager { private static final Logger log = Logger.getLogger( ProteinSequenceCoverageCacheManager.class ); // only a single instance of this class can exist, get with getInstance() private static final ProteinSequenceCoverageCacheManager _INSTANCE = new ProteinSequenceCoverageCacheManager(); public static ProteinSequenceCoverageCacheManager getInstance() { return _INSTANCE; } private ProteinSequenceCoverageCacheManager() { } /* * The in-memory cache of discovered protein sequence coverages. This map is keyed on the search parameter object * (i.e., filter cutoffs). This key points to a map keyed on protein Ids which point to the protein sequence * coverage object describing that protein's sequence coverage for the given search and cutoffs. */ private Map<ProteinSequenceCoverageSearchParams, ProteinSequenceCoverage> _MEMORY_CACHE = new HashMap<>(); /** * Attempt to get the requested protein sequence coverage from the cache. It will first try the in-memory cache. * If not found, it will try the database cache. If found there, it will put into the in-memory cache. * If not found in either, it will return null. * * @param proteinId * @param searchParameters * @return */ public ProteinSequenceCoverage getProteinSequenceCoverageFromCache( int proteinId, SearcherCutoffValuesSearchLevel scvsl ) throws Exception { ProteinSequenceCoverageSearchParams searchParameters = ProteinSequenceCoverageSearchParams.getProteinSequenceCoverageSearchParams( scvsl, proteinId); // try memory cache first if( this._MEMORY_CACHE.containsKey( searchParameters ) ) { System.out.println( "Getting seq. cov. from mem cache for protein:" + proteinId + " search:" + scvsl.getSearchId() ); return this._MEMORY_CACHE.get( searchParameters ); } // check the database cache ProteinSequenceCoverage coverage = null; try { coverage = this.getProteinSequenceCoverageFromDbCache( searchParameters); this._MEMORY_CACHE.put( searchParameters, coverage ); } catch ( Exception e ) { // no reason to die if an exception occurred, as protein sequence can be calculated w/o the cache // however, we'd like to know about it, so log it log.error( e.getMessage(), e ); e.printStackTrace(); } return coverage; } /** * Add the supplied protein sequence coverage data to the cache. It will add to both the datbase and in-memory cache--replacing * existing data for that protein and search parameters. * * @param proteinId * @param searchParameters */ public void addProteinSequenceCoverageToCache( int proteinId, SearcherCutoffValuesSearchLevel scvsl, ProteinSequenceCoverage coverage ) { ProteinSequenceCoverageSearchParams searchParameters = ProteinSequenceCoverageSearchParams.getProteinSequenceCoverageSearchParams( scvsl, proteinId); // replace into the memory cache this._MEMORY_CACHE.put( searchParameters, coverage ); // replace into the database cache try { this.addProteinSequenceCoverageToDbCache( searchParameters, coverage ); } catch ( Exception e ) { // don't die if there is a database error, but log it log.error( e.getMessage(), e ); } } /** * Insert or replace the existing entry in the database cache for the sequence coverage in the context of the supplied search parameters * * @param searchParameters * @param coverage */ private void addProteinSequenceCoverageToDbCache( ProteinSequenceCoverageSearchParams searchParameters, ProteinSequenceCoverage coverage ) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { ObjectMapper mapper = new ObjectMapper(); // our json serializer/de-serializer String sql = "SELECT search_param_hash_code, search_param_hash_idx, search_param_json, sequence_coverage_json, search_id FROM sequence_coverage_cache WHERE search_param_hash_code = ?"; int maxIdx = 0; // if there is a collision on the hashCode, use this as a secondary index boolean updatedEntry = false; // whether or not we updated an existing entry conn = DBConnectionFactory.getConnection( DBConnectionFactory.PROXL ); pstmt = conn.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE ); pstmt.setInt( 1, searchParameters.hashCode() ); rs = pstmt.executeQuery(); while( rs.next() ) { // ensure maxIdx stores the max idx for this hash code int tIdx = rs.getInt( "search_param_hash_idx" ); if( tIdx > maxIdx ) maxIdx = tIdx; ProteinSequenceCoverageSearchParams dbParams = mapper.readValue( rs.getString( "search_param_json" ), ProteinSequenceCoverageSearchParams.class ); if( searchParameters.equals( dbParams ) ) { updatedEntry = true; ProteinSequenceCoverageResultsBean coverageResultsBean = new ProteinSequenceCoverageResultsBean(); coverageResultsBean.setProteinId( coverage.getProtein().getProteinSequenceId() ); /* * Guava Range doesn't serialize well (at all). Load data from the ranges into my own objects * and serialize those as json in the database. */ Set<CoverageRangeBean> ranges = new HashSet<>(); for( Range<Integer> r : coverage.getRanges() ) { CoverageRangeBean crb = new CoverageRangeBean( r.lowerEndpoint(), r.upperEndpoint() ); ranges.add( crb ); } coverageResultsBean.setRanges( ranges ); rs.updateString( "sequence_coverage_json", mapper.writeValueAsString( coverageResultsBean ) ); rs.updateRow(); break; } } if( !updatedEntry ) { // move to insert row, insert row using result set rs.moveToInsertRow(); rs.updateInt( "search_param_hash_code", searchParameters.hashCode() ); rs.updateInt( "search_param_hash_idx", maxIdx + 1 ); rs.updateInt( "search_id", searchParameters.getSearchId() ); rs.updateString( "search_param_json", mapper.writeValueAsString( searchParameters ) ); ProteinSequenceCoverageResultsBean coverageResultsBean = new ProteinSequenceCoverageResultsBean(); coverageResultsBean.setProteinId( coverage.getProtein().getProteinSequenceId() ); /* * Guava Range doesn't serialize well (at all). Load data from the ranges into my own objects * and serialize those as json in the database. */ Set<CoverageRangeBean> ranges = new HashSet<>(); for( Range<Integer> r : coverage.getRanges() ) { CoverageRangeBean crb = new CoverageRangeBean( r.lowerEndpoint(), r.upperEndpoint() ); ranges.add( crb ); } coverageResultsBean.setRanges( ranges ); rs.updateString( "sequence_coverage_json", mapper.writeValueAsString( coverageResultsBean ) ); rs.insertRow(); } } finally { // be sure database handles are closed if( rs != null ) { try { rs.close(); } catch( Throwable t ) { ; } rs = null; } if( pstmt != null ) { try { pstmt.close(); } catch( Throwable t ) { ; } pstmt = null; } if( conn != null ) { try { conn.close(); } catch( Throwable t ) { ; } conn = null; } } } /** * Attempt to get the requested protein sequence coverage from the database cache. If not found, returns null. * * @param searchParameters * @return * @throws Exception */ private ProteinSequenceCoverage getProteinSequenceCoverageFromDbCache( ProteinSequenceCoverageSearchParams searchParameters ) throws Exception { ProteinSequenceCoverage returnedProteinCoverage = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { ObjectMapper mapper = new ObjectMapper(); // our json de-serializer String sql = "SELECT search_param_json, sequence_coverage_json FROM sequence_coverage_cache WHERE search_param_hash_code = ?"; conn = DBConnectionFactory.getConnection( DBConnectionFactory.PROXL ); pstmt = conn.prepareStatement( sql ); pstmt.setInt( 1, searchParameters.hashCode() ); rs = pstmt.executeQuery(); while( rs.next() ) { // de-serialize cached search parameters and sequence coverage ProteinSequenceCoverageSearchParams dbParams = mapper.readValue( rs.getString( 1 ), ProteinSequenceCoverageSearchParams.class ); // if the search parameters aren't the same, that means we have a hashCode collision. Try // next one in database, if it exists. if( !searchParameters.equals( dbParams ) ) continue; System.out.println( "Getting seq. cov. from db cache for protein:" + searchParameters.getProteinId() + " search:" + searchParameters.getSearchId() ); // de-serialize the ProteinSequenceCoverage from the database ProteinSequenceCoverageResultsBean coverageResultsBean = mapper.readValue( rs.getString( 2 ), ProteinSequenceCoverageResultsBean.class ); ProteinSequenceObject ps = ProteinSequenceObjectFactory.getProteinSequenceObject( coverageResultsBean.getProteinId() ); returnedProteinCoverage = new ProteinSequenceCoverage( ps ); for( CoverageRangeBean crb : coverageResultsBean.getRanges() ) { returnedProteinCoverage.addStartEndBoundary( crb.getStart(), crb.getEnd() ); } } } finally { // be sure database handles are closed if( rs != null ) { try { rs.close(); } catch( Throwable t ) { ; } rs = null; } if( pstmt != null ) { try { pstmt.close(); } catch( Throwable t ) { ; } pstmt = null; } if( conn != null ) { try { conn.close(); } catch( Throwable t ) { ; } conn = null; } } return returnedProteinCoverage; } }
src/org/yeastrc/xlink/www/protein_coverage/ProteinSequenceCoverageCacheManager.java
package org.yeastrc.xlink.www.protein_coverage; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.yeastrc.xlink.db.DBConnectionFactory; import org.yeastrc.xlink.searcher_psm_peptide_cutoff_objects.SearcherCutoffValuesSearchLevel; import org.yeastrc.xlink.www.factories.ProteinSequenceObjectFactory; import org.yeastrc.xlink.www.objects.ProteinSequenceObject; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Range; /** * Manage the cache of protein sequence coverages for given searches with given search * parameters. Keeps an in-memory cache, as well as a database cache * * @author mriffle * */ public class ProteinSequenceCoverageCacheManager { private static final Logger log = Logger.getLogger( ProteinSequenceCoverageCacheManager.class ); // only a single instance of this class can exist, get with getInstance() private static final ProteinSequenceCoverageCacheManager _INSTANCE = new ProteinSequenceCoverageCacheManager(); public static ProteinSequenceCoverageCacheManager getInstance() { return _INSTANCE; } private ProteinSequenceCoverageCacheManager() { } /* * The in-memory cache of discovered protein sequence coverages. This map is keyed on the search parameter object * (i.e., filter cutoffs). This key points to a map keyed on protein Ids which point to the protein sequence * coverage object describing that protein's sequence coverage for the given search and cutoffs. */ private Map<ProteinSequenceCoverageSearchParams, ProteinSequenceCoverage> _MEMORY_CACHE = new HashMap<>(); /** * Attempt to get the requested protein sequence coverage from the cache. It will first try the in-memory cache. * If not found, it will try the database cache. If found there, it will put into the in-memory cache. * If not found in either, it will return null. * * @param proteinId * @param searchParameters * @return */ public ProteinSequenceCoverage getProteinSequenceCoverageFromCache( int proteinId, SearcherCutoffValuesSearchLevel scvsl ) throws Exception { ProteinSequenceCoverageSearchParams searchParameters = ProteinSequenceCoverageSearchParams.getProteinSequenceCoverageSearchParams( scvsl, proteinId); // try memory cache first if( this._MEMORY_CACHE.containsKey( searchParameters ) ) { System.out.println( "Getting seq. cov. from mem cache for protein:" + proteinId + " search:" + scvsl.getSearchId() ); return this._MEMORY_CACHE.get( searchParameters ); } // check the database cache ProteinSequenceCoverage coverage = null; try { coverage = this.getProteinSequenceCoverageFromDbCache( searchParameters); this._MEMORY_CACHE.put( searchParameters, coverage ); } catch ( Exception e ) { // no reason to die if an exception occurred, as protein sequence can be calculated w/o the cache // however, we'd like to know about it, so log it log.error( e.getMessage(), e ); e.printStackTrace(); } return coverage; } /** * Add the supplied protein sequence coverage data to the cache. It will add to both the datbase and in-memory cache--replacing * existing data for that protein and search parameters. * * @param proteinId * @param searchParameters */ public void addProteinSequenceCoverageToCache( int proteinId, SearcherCutoffValuesSearchLevel scvsl, ProteinSequenceCoverage coverage ) { ProteinSequenceCoverageSearchParams searchParameters = ProteinSequenceCoverageSearchParams.getProteinSequenceCoverageSearchParams( scvsl, proteinId); // replace into the memory cache this._MEMORY_CACHE.put( searchParameters, coverage ); // replace into the database cache try { this.addProteinSequenceCoverageToDbCache( searchParameters, coverage ); } catch ( Exception e ) { // don't die if there is a database error, but log it log.error( e.getMessage(), e ); } } /** * Insert or replace the existing entry in the database cache for the sequence coverage in the context of the supplied search parameters * * @param searchParameters * @param coverage */ private void addProteinSequenceCoverageToDbCache( ProteinSequenceCoverageSearchParams searchParameters, ProteinSequenceCoverage coverage ) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { ObjectMapper mapper = new ObjectMapper(); // our json serializer/de-serializer String sql = "SELECT search_param_hash_code, search_param_hash_idx, search_param_json, sequence_coverage_json FROM sequence_coverage_cache WHERE search_param_hash_code = ?"; int maxIdx = 0; // if there is a collision on the hashCode, use this as a secondary index boolean updatedEntry = false; // whether or not we updated an existing entry conn = DBConnectionFactory.getConnection( DBConnectionFactory.PROXL ); pstmt = conn.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE ); pstmt.setInt( 1, searchParameters.hashCode() ); rs = pstmt.executeQuery(); while( rs.next() ) { // ensure maxIdx stores the max idx for this hash code int tIdx = rs.getInt( "search_param_hash_idx" ); if( tIdx > maxIdx ) maxIdx = tIdx; ProteinSequenceCoverageSearchParams dbParams = mapper.readValue( rs.getString( "search_param_json" ), ProteinSequenceCoverageSearchParams.class ); if( searchParameters.equals( dbParams ) ) { updatedEntry = true; ProteinSequenceCoverageResultsBean coverageResultsBean = new ProteinSequenceCoverageResultsBean(); coverageResultsBean.setProteinId( coverage.getProtein().getProteinSequenceId() ); /* * Guava Range doesn't serialize well (at all). Load data from the ranges into my own objects * and serialize those as json in the database. */ Set<CoverageRangeBean> ranges = new HashSet<>(); for( Range<Integer> r : coverage.getRanges() ) { CoverageRangeBean crb = new CoverageRangeBean( r.lowerEndpoint(), r.upperEndpoint() ); ranges.add( crb ); } coverageResultsBean.setRanges( ranges ); rs.updateString( "sequence_coverage_json", mapper.writeValueAsString( coverageResultsBean ) ); rs.updateRow(); break; } } if( !updatedEntry ) { // move to insert row, insert row using result set rs.moveToInsertRow(); rs.updateInt( "search_param_hash_code", searchParameters.hashCode() ); rs.updateInt( "search_param_hash_idx", maxIdx + 1 ); rs.updateString( "search_param_json", mapper.writeValueAsString( searchParameters ) ); ProteinSequenceCoverageResultsBean coverageResultsBean = new ProteinSequenceCoverageResultsBean(); coverageResultsBean.setProteinId( coverage.getProtein().getProteinSequenceId() ); /* * Guava Range doesn't serialize well (at all). Load data from the ranges into my own objects * and serialize those as json in the database. */ Set<CoverageRangeBean> ranges = new HashSet<>(); for( Range<Integer> r : coverage.getRanges() ) { CoverageRangeBean crb = new CoverageRangeBean( r.lowerEndpoint(), r.upperEndpoint() ); ranges.add( crb ); } coverageResultsBean.setRanges( ranges ); rs.updateString( "sequence_coverage_json", mapper.writeValueAsString( coverageResultsBean ) ); rs.insertRow(); } } finally { // be sure database handles are closed if( rs != null ) { try { rs.close(); } catch( Throwable t ) { ; } rs = null; } if( pstmt != null ) { try { pstmt.close(); } catch( Throwable t ) { ; } pstmt = null; } if( conn != null ) { try { conn.close(); } catch( Throwable t ) { ; } conn = null; } } } /** * Attempt to get the requested protein sequence coverage from the database cache. If not found, returns null. * * @param searchParameters * @return * @throws Exception */ private ProteinSequenceCoverage getProteinSequenceCoverageFromDbCache( ProteinSequenceCoverageSearchParams searchParameters ) throws Exception { ProteinSequenceCoverage returnedProteinCoverage = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { ObjectMapper mapper = new ObjectMapper(); // our json de-serializer String sql = "SELECT search_param_json, sequence_coverage_json FROM sequence_coverage_cache WHERE search_param_hash_code = ?"; conn = DBConnectionFactory.getConnection( DBConnectionFactory.PROXL ); pstmt = conn.prepareStatement( sql ); pstmt.setInt( 1, searchParameters.hashCode() ); rs = pstmt.executeQuery(); while( rs.next() ) { // de-serialize cached search parameters and sequence coverage ProteinSequenceCoverageSearchParams dbParams = mapper.readValue( rs.getString( 1 ), ProteinSequenceCoverageSearchParams.class ); // if the search parameters aren't the same, that means we have a hashCode collision. Try // next one in database, if it exists. if( !searchParameters.equals( dbParams ) ) continue; System.out.println( "Getting seq. cov. from db cache for protein:" + searchParameters.getProteinId() + " search:" + searchParameters.getSearchId() ); // de-serialize the ProteinSequenceCoverage from the database ProteinSequenceCoverageResultsBean coverageResultsBean = mapper.readValue( rs.getString( 2 ), ProteinSequenceCoverageResultsBean.class ); ProteinSequenceObject ps = ProteinSequenceObjectFactory.getProteinSequenceObject( coverageResultsBean.getProteinId() ); returnedProteinCoverage = new ProteinSequenceCoverage( ps ); for( CoverageRangeBean crb : coverageResultsBean.getRanges() ) { returnedProteinCoverage.addStartEndBoundary( crb.getStart(), crb.getEnd() ); } } } finally { // be sure database handles are closed if( rs != null ) { try { rs.close(); } catch( Throwable t ) { ; } rs = null; } if( pstmt != null ) { try { pstmt.close(); } catch( Throwable t ) { ; } pstmt = null; } if( conn != null ) { try { conn.close(); } catch( Throwable t ) { ; } conn = null; } } return returnedProteinCoverage; } }
Added search_id to cache table to help clean the data when searches are deleted.
src/org/yeastrc/xlink/www/protein_coverage/ProteinSequenceCoverageCacheManager.java
Added search_id to cache table to help clean the data when searches are deleted.
Java
apache-2.0
badef0344c6b63e74749068b45d94b8c52c4af16
0
CMPUT301W15T10/301-Project,CMPUT301W15T10/301-Project
package com.cmput301.cs.project.models; import android.content.Context; import android.os.StrictMode; import android.util.Log; import android.widget.Toast; import com.cmput301.cs.project.utils.LocalClaimSaver; import com.cmput301.cs.project.utils.RemoteClaimSaver; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Singleton<p> * A class that contains the ClaimList for the app. This is changed whenever a claim is created, edited or removed. * <p/> * The most important methods used are: * <ul> * <li> addClaim(claim), which is used to store a new claim into the list * <li> deleteClaim(claim), which is used to delete a specific claim from the list * <li> editClaim(oldClaim, newClaim), which is used to replace a claim in the list with a more recently updated version of itself. It is important to note that when editing a claim you should not edit it directly but instead edit a copy of the claim because you need the original claim in order to update the list using this method. * </ul> * This model is used when populating the {@link com.cmput301.cs.project.activities.ClaimListActivity ClaimListActivity}, {@link com.cmput301.cs.project.activities.ClaimViewActivity ClaimViewActivity}, and {@link com.cmput301.cs.project.activities.ExpenseListActivity ExpenseListActivity}. <p> * It is used in the {@link com.cmput301.cs.project.controllers.ClaimListController ClaimListController} to control this activities as well. * * @author rozsa * @author jbenson */ public class ClaimsList { private static final String LOG_TAG = "ClaimsList"; private List<Claim> mClaims = new ArrayList<Claim>(); private static ClaimsList instance; private final LocalClaimSaver mClaimSaves; private final RemoteClaimSaver mRemoteClaimSaves; private final Context mContext; public static ClaimsList getInstance(Context context) { if (instance == null) { instance = new ClaimsList(context); } return instance; } private ClaimsList(Context context) { mContext = context; mClaimSaves = LocalClaimSaver.ofAndroid(context); mRemoteClaimSaves = RemoteClaimSaver.ofAndroid(context); mergeAllClaims(); } /** * */ private void mergeAllClaims() { List<Claim> claims = new ArrayList<Claim>(); List<Claim> remoteClaims = new ArrayList<Claim>(); //http://stackoverflow.com/questions/12650921/quick-fix-for-networkonmainthreadexception [blaine1 april 05 2015] StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); try { remoteClaims = mRemoteClaimSaves.readAllClaims(); } catch (IOException ex) { Toast.makeText(mContext, "Failed to connect to server. In Local mode.", Toast.LENGTH_LONG).show(); } for (Claim next : mClaimSaves.readAllClaims()) { Claim rem = null; for (Claim remoteClaim : remoteClaims) { if (remoteClaim.getId().equals(next.getId())) { rem = remoteClaim; } } if (rem == null) { claims.add(next); } else { remoteClaims.remove(rem); if (rem.getModified() > next.getModified()) { claims.add(rem); } else { claims.add(next); } } } claims.addAll(remoteClaims); try { mRemoteClaimSaves.saveAllClaims(claims); } catch (IOException e) { Log.d(LOG_TAG, "Failed to save claims remotely."); } this.mClaims = claims; } public void addClaim(Claim claim) { mClaims.add(claim); serialize(); } public void deleteClaim(Claim claim) { for (Iterator<Claim> iterator = mClaims.iterator(); iterator.hasNext(); ) { Claim current = iterator.next(); if (current.getId().equals(claim.getId())) { iterator.remove(); } } serialize(); } public void editClaim(Claim oldClaim, Claim newClaim) { for (final Iterator<Claim> iterator = mClaims.iterator(); iterator.hasNext(); ) { Claim current = iterator.next(); if (current.getId().equals(oldClaim.getId())) { iterator.remove(); } } mClaims.add(newClaim); serialize(); } private void serialize() { mClaimSaves.saveAllClaims(mClaims); mergeAllClaims(); } public List<Claim> peekClaims() { return new ArrayList<Claim>(mClaims); } public Claim getClaimById(String id) { for (Claim claim : mClaims) { if (claim.getId().equals(id)) { return claim; } } return null; } }
src/com/cmput301/cs/project/models/ClaimsList.java
package com.cmput301.cs.project.models; import android.content.Context; import android.os.StrictMode; import android.util.Log; import android.widget.Toast; import com.cmput301.cs.project.utils.LocalClaimSaver; import com.cmput301.cs.project.utils.RemoteClaimSaver; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Singleton<p> * A class that contains the ClaimList for the app. This is changed whenever a claim is created, edited or removed. * <p> * The most important methods used are: * <ul> * <li> addClaim(claim), which is used to store a new claim into the list * <li> deleteClaim(claim), which is used to delete a specific claim from the list * <li> editClaim(oldClaim, newClaim), which is used to replace a claim in the list with a more recently updated version of itself. It is important to note that when editing a claim you should not edit it directly but instead edit a copy of the claim because you need the original claim in order to update the list using this method. * </ul> * This model is used when populating the {@link com.cmput301.cs.project.activities.ClaimListActivity ClaimListActivity}, {@link com.cmput301.cs.project.activities.ClaimViewActivity ClaimViewActivity}, and {@link com.cmput301.cs.project.activities.ExpenseListActivity ExpenseListActivity}. <p> * It is used in the {@link com.cmput301.cs.project.controllers.ClaimListController ClaimListController} to control this activities as well. * @author rozsa * @author jbenson * */ public class ClaimsList { private static final String LOG_TAG = "ClaimsList"; private List<Claim> mClaims = new ArrayList<Claim>(); private static ClaimsList instance; private final LocalClaimSaver mClaimSaves; private final RemoteClaimSaver mRemoteClaimSaves; private final Context mContext; public static ClaimsList getInstance(Context context) { if(instance == null){ instance = new ClaimsList(context); } return instance; } private ClaimsList(Context context) { mContext = context; mClaimSaves = LocalClaimSaver.ofAndroid(context); mRemoteClaimSaves = RemoteClaimSaver.ofAndroid(context); mergeAllClaims(); } /** * */ private void mergeAllClaims() { List<Claim> claims = new ArrayList<Claim>(); List<Claim> remoteClaims = new ArrayList<Claim>(); //http://stackoverflow.com/questions/12650921/quick-fix-for-networkonmainthreadexception [blaine1 april 05 2015] StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); try { remoteClaims = mRemoteClaimSaves.readAllClaims(); } catch (IOException ex) { Toast.makeText(mContext, "Failed to connect to server. In Local mode.", Toast.LENGTH_LONG); } List<Claim> localClaims = mClaimSaves.readAllClaims(); for (Iterator<Claim> it = localClaims.iterator(); it.hasNext(); ) { Claim next = it.next(); Claim rem = null; for (Claim remoteClaim : remoteClaims) { if(remoteClaim.getId().equals(next.getId())){ rem = remoteClaim; } } if(rem == null) { claims.add(next); } else { remoteClaims.remove(rem); if(rem.getModified() > next.getModified()){ claims.add(rem); } else { claims.add(next); } } } claims.addAll(remoteClaims); try { mRemoteClaimSaves.saveAllClaims(claims); } catch (IOException e) { Log.d(LOG_TAG, "Failed to save claims remotely."); } this.mClaims = claims; } public void addClaim(Claim claim) { mClaims.add(claim); serialize(); } public void deleteClaim(Claim claim) { Iterator<Claim> iterator = mClaims.iterator(); while (iterator.hasNext()) { Claim current = iterator.next(); if (current.getId().equals(claim.getId())) { iterator.remove(); } } serialize(); } public void editClaim(Claim oldClaim, Claim newClaim) { Iterator<Claim> iterator = mClaims.iterator(); while (iterator.hasNext()) { Claim current = iterator.next(); if (current.getId().equals(oldClaim.getId())) { iterator.remove(); } } mClaims.add(newClaim); serialize(); } private void serialize() { mClaimSaves.saveAllClaims(mClaims); mergeAllClaims(); } public List<Claim> peekClaims() { return mClaims; } public Claim getClaimById(String id) { for (Claim claim : mClaims) { if (claim.getId().equals(id)) { return claim; } } return null; } }
bug fixes in ClaimsList; closed #81
src/com/cmput301/cs/project/models/ClaimsList.java
bug fixes in ClaimsList; closed #81
Java
apache-2.0
602ccc702033565cc466ffd6604cb959fa0a952a
0
zstackio/zstack,MatheMatrix/zstack,zstackio/zstack,AlanJager/zstack,zstackio/zstack,zstackorg/zstack,MatheMatrix/zstack,AlanJager/zstack,zstackorg/zstack,AlanJager/zstack,MatheMatrix/zstack
package org.zstack.portal.managementnode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.zstack.core.CoreGlobalProperty; import org.zstack.core.Platform; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.config.GlobalConfig; import org.zstack.core.config.GlobalConfigUpdateExtensionPoint; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.GLock; import org.zstack.core.thread.AsyncThread; import org.zstack.core.thread.Task; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.header.AbstractService; import org.zstack.header.Component; import org.zstack.header.Service; import org.zstack.header.core.ExceptionSafe; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.managementnode.*; import org.zstack.header.managementnode.ManagementNodeCanonicalEvent.LifeCycle; import org.zstack.header.managementnode.ManagementNodeCanonicalEvent.ManagementNodeLifeCycleData; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.portal.apimediator.ApiMediator; import org.zstack.utils.BootErrorLog; import org.zstack.utils.CollectionUtils; import org.zstack.utils.StringDSL; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.zstack.utils.ExceptionDSL.throwableSafe; public class ManagementNodeManagerImpl extends AbstractService implements ManagementNodeManager { private static final CLogger logger = Utils.getLogger(ManagementNodeManager.class); private List<ComponentWrapper> components; private List<PrepareDbInitialValueExtensionPoint> prepareDbExts; private ManagementNodeVO node; private volatile boolean isRunning = true; private volatile int isNodeRunning = NODE_STARTING; private static final String INVENTORY_LOCK = "ManagementNodeManager.inventory_lock"; private final int INVENTORY_LOCK_TIMEOUT = 600; /* 10 mins */ private static boolean started = false; private static boolean stopped = false; private Future<Void> heartBeatTask = null; private HeartBeatDBSource heartBeatDBSource; private List<ManagementNodeChangeListener> lifeCycleExtension = new ArrayList<ManagementNodeChangeListener>(); private static int NODE_STARTING = 0; private static int NODE_RUNNING = 1; private static int NODE_FAILED = -1; @Autowired private DatabaseFacade dbf; @Autowired private CloudBusIN bus; @Autowired private ApiMediator apim; @Autowired private PluginRegistry pluginRgty; @Autowired private ThreadFacade thdf; @Autowired private ResourceDestinationMaker destinationMaker; @Autowired private EventFacade evtf; void init() { heartBeatDBSource = new HeartBeatDBSource(); } private ManagementNodeChangeListener nodeLifeCycle = new ManagementNodeChangeListener() { @Override public void nodeJoin(String nodeId) { if (destinationMaker.getManagementNodesInHashRing().contains(nodeId)) { logger.debug(String.format("the management node[uuid:%s] is already in our hash ring, ignore this node-join call", nodeId)); return; } ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.nodeJoin(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.nodeJoin(nodeId); } }); } @Override public void nodeLeft(String nodeId) { if (!destinationMaker.getManagementNodesInHashRing().contains(nodeId)) { logger.debug(String.format("the management node[uuid:%s] is not in our hash ring, ignore this node-left call", nodeId)); return; } ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.nodeLeft(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.nodeLeft(nodeId); } }); } @Override public void iAmDead(String nodeId) { ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.iAmDead(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.iAmDead(nodeId); } }); } @Override public void iJoin(String nodeId) { ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.iJoin(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.iJoin(nodeId); } }); } }; private interface ComponentWrapper { void start(); void stop(); } private void notifyStop() { isRunning = false; synchronized (this) { this.notify(); } } private void handle(ManagementNodeExitMsg msg) { logger.debug(getId() + " received ManagementNodeExitMsg, going to exit"); notifyStop(); } @Override @MessageSafe public void handleMessage(Message msg) { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } private void handleApiMessage(APIMessage msg) { if (msg instanceof APIListManagementNodeMsg) { handle((APIListManagementNodeMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(APIListManagementNodeMsg msg) { List<ManagementNodeVO> vos = dbf.listAll(ManagementNodeVO.class); APIListManagementNodeReply reply = new APIListManagementNodeReply(); reply.setInventories(ManagementNodeInventory.valueOf(vos)); bus.reply(msg, reply); } private void handleLocalMessage(Message msg) { if (msg.getClass() == ManagementNodeExitMsg.class) { handle((ManagementNodeExitMsg) msg); } else if (msg instanceof IsManagementNodeReadyMsg) { handle((IsManagementNodeReadyMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(IsManagementNodeReadyMsg msg) { IsManagementNodeReadyReply reply = new IsManagementNodeReadyReply(); reply.setReady(isNodeRunning == NODE_RUNNING); bus.reply(msg, reply); } @Override public String getId() { return bus.makeLocalServiceId(ManagementNodeConstant.SERVICE_ID); } private void startComponents() { for (ComponentWrapper c : components) { c.start(); } } private void stopComponents() { for (final ComponentWrapper c : components) { try { c.stop(); } catch (Throwable t) { logger.warn(t.getMessage(), t); } } } private void installShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { String reason = System.getProperty(Platform.EXIT_REASON); if (reason != null) { logger.debug(String.format("JVM shutdown hook is called[reason: %s], start stopping management node", reason)); } else { logger.debug("JVM shutdown hook is called, start stopping management node"); } stop(); })); } private void populateComponents() { components = new ArrayList<>(); for (final Component c : pluginRgty.getExtensionList(Component.class)) { components.add(new ComponentWrapper() { boolean isStart = false; @Override public void start() { logger.info("starting component: " + c.getClass().getName()); c.start(); logger.info(String.format("component[%s] starts successfully", c.getClass())); isStart = true; } @Override public void stop() { if (isStart) { throwableSafe((Runnable) () -> { c.stop(); logger.info("Stopped component: " + c.getClass().getName()); isStart = false; }, String.format("unable to stop component[%s]", c.getClass().getName())); } } }); } prepareDbExts = pluginRgty.getExtensionList(PrepareDbInitialValueExtensionPoint.class); } private void callPrepareDbExtensions() { for (PrepareDbInitialValueExtensionPoint extp : prepareDbExts) { extp.prepareDbInitialValue(); } } private void populateExtensions() { lifeCycleExtension = pluginRgty.getExtensionList(ManagementNodeChangeListener.class); } private EventCallback nodeLifeCycleCallback = new EventCallback() { @Override protected void run(Map tokens, Object data) { if (evtf.isFromThisManagementNode(tokens)) { return; } ManagementNodeLifeCycleData d = (ManagementNodeLifeCycleData) data; if (LifeCycle.NodeJoin.toString().equals(d.getLifeCycle())) { nodeLifeCycle.nodeJoin(d.getNodeUuid()); } else if (LifeCycle.NodeLeft.toString().equals(d.getLifeCycle())) { nodeLifeCycle.nodeLeft(d.getNodeUuid()); } else { throw new CloudRuntimeException(String.format("unknown lifecycle[%s]", d.getLifeCycle())); } } }; @Override public boolean start() { if (started) { /* largely for unittest, the ComponentLoaderWebListener and Api may both call start() */ logger.debug("Management Node has already started, ignore this call"); return true; } populateExtensions(); started = true; stopped = true; class Result { boolean success; } final Result ret = new Result(); GLock lock = new GLock(INVENTORY_LOCK, INVENTORY_LOCK_TIMEOUT); /* * The lock is being held until we join in, otherwise the inventory * may be deleted by other exiting node because we have not * persisted our entry in management_node table yet, or two starting * nodes persist inventory concurrently. */ lock.lock(); try { final ManagementNodeManagerImpl self = this; FlowChain bootstrap = FlowChainBuilder.newSimpleFlowChain(); bootstrap.setName("management-node-bootstrap"); bootstrap.then(new Flow() { String __name__ = "bootstrap-cloudbus"; // CloudBus is special, it is initialized in Platform.createComponentLoaderFromWebApplicationContext(), // however, when exception happens in bootstrap we need to stop bus in rollback, because the exception // cannot make JVM exist and cloudbus.stop is only called in JVM exit hook; @Override public void run(FlowTrigger trigger, Map data) { trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { bus.stop(); trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "populate-components"; @Override public void run(FlowTrigger trigger, Map data) { populateComponents(); trigger.next(); } }).then(new Flow() { String __name__ = "register-node-on-cloudbus"; @Override public void run(FlowTrigger trigger, Map data) { bus.registerService(self); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { bus.unregisterService(self); trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "call-prepare-db-extension"; @Override public void run(FlowTrigger trigger, Map data) { callPrepareDbExtensions(); trigger.next(); } }).then(new Flow() { String __name__ = "start-components"; @Override public void run(FlowTrigger trigger, Map data) { startComponents(); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { stopComponents(); trigger.rollback(); } }).then(new Flow() { String __name__ = "create-DB-record"; @Override public void run(FlowTrigger trigger, Map data) { ManagementNodeVO vo = new ManagementNodeVO(); vo.setHostName(Platform.getManagementServerIp()); vo.setUuid(UUID.nameUUIDFromBytes(vo.getHostName().getBytes()).toString()); node = dbf.persistAndRefresh(vo); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (node != null) { dbf.remove(node); } trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "start-heartbeat"; @Override public void run(FlowTrigger trigger, Map data) { setupHeartbeat(); trigger.next(); } }).then(new Flow() { String __name__ = "start-api-mediator"; @Override public void run(FlowTrigger trigger, Map data) { apim.start(); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { apim.stop(); trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "set-node-to-running"; @Override public void run(FlowTrigger trigger, Map data) { node.setState(ManagementNodeState.RUNNING); node = dbf.updateAndRefresh(node); trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "I-join"; @Override public void run(FlowTrigger trigger, Map data) { nodeLifeCycle.iJoin(node.getUuid()); trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "node-is-ready"; @Override public void run(FlowTrigger trigger, Map data) { for (ManagementNodeReadyExtensionPoint ext : pluginRgty.getExtensionList(ManagementNodeReadyExtensionPoint.class)) { ext.managementNodeReady(); } trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "listen-node-life-cycle-events"; @Override public void run(FlowTrigger trigger, Map data) { evtf.on(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, nodeLifeCycleCallback); trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "say-I-join"; @Override public void run(FlowTrigger trigger, Map data) { ManagementNodeLifeCycleData d = new ManagementNodeLifeCycleData(); d.setNodeUuid(node.getUuid()); d.setInventory(ManagementNodeInventory.valueOf(node)); d.setLifeCycle(LifeCycle.NodeJoin.toString()); evtf.fire(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, d); trigger.next(); } }).done(new FlowDoneHandler(null) { @Override public void handle(Map data) { ret.success = true; } }).error(new FlowErrorHandler(null) { @Override public void handle(ErrorCode errCode, Map data) { new BootErrorLog().write(errCode.toString()); ret.success = false; } }).start(); } finally { lock.unlock(); } if (!ret.success) { logger.warn(String.format("management node[%s] failed to start for some reason", Platform.getUuid())); stopped = true; if (CoreGlobalProperty.EXIT_JVM_ON_BOOT_FAILURE) { logger.debug(String.format("unable to start management node[%s], see previous exception. exitJVMOnBootFailure is set to true, exit JVM now", Platform.getManagementServerId())); System.exit(1); } else { throw new CloudRuntimeException(String.format("unable to start management node[%s], see previous exception", Platform.getManagementServerId())); } } stopped = false; installShutdownHook(); logger.info("Management node: " + getId() + " starts successfully"); synchronized (this) { isNodeRunning = NODE_RUNNING; while (isRunning) { try { this.wait(); } catch (InterruptedException e) { logger.warn("Interrupted while daemon is running, continue ...", e); } } } logger.debug("quited main-loop, start stopping management node"); stop(); return true; } private void setupHeartbeat() { ManagementNodeGlobalConfig.NODE_HEARTBEAT_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startHeartbeat(); } }); startHeartbeat(); } private class HeartBeatDBSource { private Connection conn; private SingleConnectionDataSource source; JdbcTemplate jdbc; AtomicBoolean destroyed = new AtomicBoolean(false); public HeartBeatDBSource() { try { conn = dbf.getExtraDataSource().getConnection(); source = new SingleConnectionDataSource(conn, true); jdbc = new JdbcTemplate(source); } catch (SQLException e) { throw new CloudRuntimeException(e); } } @ExceptionSafe public void destroy() { if (!destroyed.compareAndSet(false, true)) { return; } source.destroy(); try { conn.close(); } catch (SQLException e) { throw new CloudRuntimeException(e); } } } private void startHeartbeat() { if (heartBeatTask != null) { heartBeatTask.cancel(true); } heartBeatTask = thdf.submit(new Task<Void>() { private List<ManagementNodeVO> suspects = new ArrayList<ManagementNodeVO>(); @Override public String getName() { return String.format("managementNode-%s-heartbeat", Platform.getManagementServerId()); } private boolean amIalive() { String sql = "select count(*) from ManagementNodeVO where uuid = ?"; long count = heartBeatDBSource.jdbc.queryForObject(sql, new Object[]{node.getUuid()}, Long.class); return count != 0; } private ManagementNodeVO getNode(String uuid) { try { String sql = "select * from ManagementNodeVO where uuid = ?"; return (ManagementNodeVO) heartBeatDBSource.jdbc.queryForObject(sql, new Object[]{uuid}, new BeanPropertyRowMapper(ManagementNodeVO.class)); } catch (IncorrectResultSizeDataAccessException e) { return null; } } private int deleteNode(String uuid) { String sql = "delete from ManagementNodeVO where uuid = ?"; return heartBeatDBSource.jdbc.update(sql, uuid); } @AsyncThread private void nodeDie(ManagementNodeVO n) { logger.debug("Node " + n.getUuid() + " has gone because its heartbeat stopped"); nodeLifeCycle.nodeLeft(n.getUuid()); ManagementNodeLifeCycleData d = new ManagementNodeLifeCycleData(); d.setInventory(ManagementNodeInventory.valueOf(n)); d.setNodeUuid(n.getUuid()); d.setLifeCycle(LifeCycle.NodeLeft.toString()); evtf.fire(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, d); } private void fenceSuspects() { for (ManagementNodeVO vo : suspects) { ManagementNodeVO n = getNode(vo.getUuid()); if (n == null) { continue; } long elapse = n.getHeartBeat().getTime() - vo.getHeartBeat().getTime(); if (elapse != 0) { continue; } int ret = deleteNode(n.getUuid()); if (ret > 0) { nodeDie(n); } } } private void updateHeartbeat() { String sql = "update ManagementNodeVO set heartBeat = NULL where uuid = ?"; if (heartBeatDBSource.jdbc.update(sql, node.getUuid()) > 0) { node = getNode(node.getUuid()); } } private void checkAllNodesHealth() { String sql = "select * from ManagementNodeVO where state = 'RUNNING'"; List<ManagementNodeVO> all = heartBeatDBSource.jdbc.query(sql, new BeanPropertyRowMapper(ManagementNodeVO.class)); suspects.clear(); List<String> nodesInDb = new ArrayList<String>(); for (ManagementNodeVO vo : all) { if (!StringDSL.isZStackUuid(vo.getUuid())) { logger.warn(String.format("found a weird management node, it's UUID not a ZStack uuid, delete it. %s", JSONObjectUtil.toJsonString(ManagementNodeInventory.valueOf(vo)))); dbf.remove(vo); continue; } nodesInDb.add(vo.getUuid()); if (vo.getUuid().equals(node.getUuid())) { continue; } Timestamp curr = dbf.getCurrentSqlTime(); Timestamp lastHeartbeat = vo.getHeartBeat(); long end = lastHeartbeat.getTime() + TimeUnit.SECONDS.toMillis(2 * ManagementNodeGlobalConfig.NODE_HEARTBEAT_INTERVAL.value(Integer.class)); if (end < curr.getTime()) { suspects.add(vo); logger.warn(String.format("management node[uuid:%s, hostname: %s]'s heart beat has stopped for %s secs, add it in suspicious list", vo.getUuid(), vo.getHostName(), TimeUnit.MILLISECONDS.toSeconds(curr.getTime() - lastHeartbeat.getTime()))); } } // When a node is dying, we may not receive the the dead notification because the message bus may be also dead // at that moment. By checking if the node UUID is still in our hash ring, we know what nodes should be kicked out for (String ourNode : destinationMaker.getManagementNodesInHashRing()) { if (!nodesInDb.contains(ourNode)) { logger.warn(String.format("found that a management node[uuid:%s] had no heartbeat in database but still in our hash ring," + "notify that it's dead", ourNode)); nodeLifeCycle.nodeLeft(ourNode); } } // check if any node missing in our hash ring nodesInDb.forEach(nuuid -> { if (nuuid.equals(node.getUuid())) { return; } if (!destinationMaker.getManagementNodesInHashRing().contains(nuuid)) { new Runnable() { @Override @AsyncThread public void run() { nodeLifeCycle.nodeJoin(nuuid); } }.run(); } }); } @Override public Void call() { int heartbeatFailure = 0; while (true) { try { if (!amIalive()) { logger.warn(String.format("cannot find my[uuid:%s] heartbeat in database, quit process", node.getUuid())); stop(); return null; } else { updateHeartbeat(); checkAllNodesHealth(); fenceSuspects(); } heartbeatFailure = 0; } catch (Throwable t) { heartbeatFailure++; if (heartbeatFailure > PortalGlobalProperty.MAX_HEARTBEAT_FAILURE) { logger.warn(String.format("the heartbeat has failed %s times that is greater than the max allowed value[%s]," + " quit process", heartbeatFailure, PortalGlobalProperty.MAX_HEARTBEAT_FAILURE)); stop(); return null; } boolean databaseError = false; logger.warn(String.format("an error happened when doing heartbeat, %s, it's going to recover", t.getMessage())); try { heartBeatDBSource.jdbc.queryForObject("select 1", Integer.class); } catch (Throwable t1) { logger.warn(String.format("cannot communicate to the database, it's most likely the DB stopped or rebooted;" + "try creating a new database connection. %s", t1.getMessage()), t1); databaseError = true; } if (databaseError) { if (heartBeatDBSource != null) { heartBeatDBSource.destroy(); } try { heartBeatDBSource = new HeartBeatDBSource(); } catch (Throwable t1) { logger.warn(String.format("unable to create a database connection, %s, will try it later", t1.getMessage()), t1); } } else { logger.warn("unhandled exception happened", t); } } try { TimeUnit.SECONDS.sleep(ManagementNodeGlobalConfig.NODE_HEARTBEAT_INTERVAL.value(Long.class)); } catch (InterruptedException ie) { } if (heartBeatTask.isCancelled()) { break; } } return null; } }); logger.debug(String.format("started heartbeat thread for management node[uuid:%s]", Platform.getManagementServerId())); } @Override public boolean stop() { Platform.IS_RUNNING = false; if (stopped) { /* avoid repeated call from JVM shutdown hook, if process is exited from a former stop() call */ return true; } stopped = true; final Service self = this; logger.debug(String.format("start stopping the management node[uuid:%s]", node.getUuid())); class Stopper { void stop() { stopApiOnCloudBus(); stopApi(); iAmDead(); stopComponents(); deleteNode(); notifyOtherNodes(); unregisterCloudBus(); stopCloudBus(); quitLoop(); stopThreadFacade(); } @ExceptionSafe private void stopThreadFacade() { thdf.stop(); } @ExceptionSafe private void quitLoop() { notifyStop(); } @ExceptionSafe private void stopCloudBus() { bus.stop(); } @ExceptionSafe private void unregisterCloudBus() { bus.unregisterService(self); } @ExceptionSafe private void notifyOtherNodes() { ManagementNodeLifeCycleData d = new ManagementNodeLifeCycleData(); d.setNodeUuid(node.getUuid()); d.setLifeCycle(LifeCycle.NodeLeft.toString()); d.setInventory(ManagementNodeInventory.valueOf(node)); evtf.fire(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, d); } @ExceptionSafe private void deleteNode() { dbf.remove(node); } @ExceptionSafe private void iAmDead() { nodeLifeCycle.iAmDead(node.getUuid()); } @ExceptionSafe private void stopApiOnCloudBus() { bus.unregisterService(apim); } @ExceptionSafe private void stopApi() { apim.stop(); } } new Stopper().stop(); logger.info("Management node: " + getId() + " exits successfully"); if (CoreGlobalProperty.EXIT_JVM_ON_STOP) { logger.info("exitJVMOnStop is set to true, exit the JVM"); System.exit(0); } return true; } @AsyncThread private void startInThread() { try { start(); isNodeRunning = NODE_RUNNING; } catch (Throwable t) { logger.warn(t.getMessage(), t); isNodeRunning = NODE_FAILED; } } @Override public void startNode() { startInThread(); while (isNodeRunning == NODE_STARTING) { logger.debug("management node is still initializing ..."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new CloudRuntimeException(e); } } if (isNodeRunning == NODE_FAILED) { logger.debug(String.format("error happened when starting node, stop the management node now")); stop(); throw new CloudRuntimeException("failed to start management node"); } } @Override public void quit(String reason) { new BootErrorLog().write(reason); logger.debug(String.format("stopping the management node because %s", reason)); stop(); } }
portal/src/main/java/org/zstack/portal/managementnode/ManagementNodeManagerImpl.java
package org.zstack.portal.managementnode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.zstack.core.CoreGlobalProperty; import org.zstack.core.Platform; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.config.GlobalConfig; import org.zstack.core.config.GlobalConfigUpdateExtensionPoint; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.GLock; import org.zstack.core.thread.AsyncThread; import org.zstack.core.thread.Task; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.header.AbstractService; import org.zstack.header.Component; import org.zstack.header.Service; import org.zstack.header.core.ExceptionSafe; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.managementnode.*; import org.zstack.header.managementnode.ManagementNodeCanonicalEvent.LifeCycle; import org.zstack.header.managementnode.ManagementNodeCanonicalEvent.ManagementNodeLifeCycleData; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.portal.apimediator.ApiMediator; import org.zstack.utils.BootErrorLog; import org.zstack.utils.CollectionUtils; import org.zstack.utils.StringDSL; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.zstack.utils.ExceptionDSL.throwableSafe; public class ManagementNodeManagerImpl extends AbstractService implements ManagementNodeManager { private static final CLogger logger = Utils.getLogger(ManagementNodeManager.class); private List<ComponentWrapper> components; private List<PrepareDbInitialValueExtensionPoint> prepareDbExts; private ManagementNodeVO node; private volatile boolean isRunning = true; private volatile int isNodeRunning = NODE_STARTING; private static final String INVENTORY_LOCK = "ManagementNodeManager.inventory_lock"; private final int INVENTORY_LOCK_TIMEOUT = 600; /* 10 mins */ private static boolean started = false; private static boolean stopped = false; private Future<Void> heartBeatTask = null; private HeartBeatDBSource heartBeatDBSource; private List<ManagementNodeChangeListener> lifeCycleExtension = new ArrayList<ManagementNodeChangeListener>(); private static int NODE_STARTING = 0; private static int NODE_RUNNING = 1; private static int NODE_FAILED = -1; @Autowired private DatabaseFacade dbf; @Autowired private CloudBusIN bus; @Autowired private ApiMediator apim; @Autowired private PluginRegistry pluginRgty; @Autowired private ThreadFacade thdf; @Autowired private ResourceDestinationMaker destinationMaker; @Autowired private EventFacade evtf; void init() { heartBeatDBSource = new HeartBeatDBSource(); } private ManagementNodeChangeListener nodeLifeCycle = new ManagementNodeChangeListener() { @Override public void nodeJoin(String nodeId) { if (destinationMaker.getManagementNodesInHashRing().contains(nodeId)) { logger.debug(String.format("the management node[uuid:%s] is already in our hash ring, ignore this node-join call", nodeId)); return; } ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.nodeJoin(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.nodeJoin(nodeId); } }); } @Override public void nodeLeft(String nodeId) { if (!destinationMaker.getManagementNodesInHashRing().contains(nodeId)) { logger.debug(String.format("the management node[uuid:%s] is not in our hash ring, ignore this node-left call", nodeId)); return; } ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.nodeLeft(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.nodeLeft(nodeId); } }); } @Override public void iAmDead(String nodeId) { ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.iAmDead(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.iAmDead(nodeId); } }); } @Override public void iJoin(String nodeId) { ManagementNodeChangeListener l = (ManagementNodeChangeListener) destinationMaker; l.iJoin(nodeId); CollectionUtils.safeForEach(lifeCycleExtension, new ForEachFunction<ManagementNodeChangeListener>() { @Override public void run(ManagementNodeChangeListener arg) { arg.iJoin(nodeId); } }); } }; private interface ComponentWrapper { void start(); void stop(); } private void notifyStop() { isRunning = false; synchronized (this) { this.notify(); } } private void handle(ManagementNodeExitMsg msg) { logger.debug(getId() + " received ManagementNodeExitMsg, going to exit"); notifyStop(); } @Override @MessageSafe public void handleMessage(Message msg) { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } private void handleApiMessage(APIMessage msg) { if (msg instanceof APIListManagementNodeMsg) { handle((APIListManagementNodeMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(APIListManagementNodeMsg msg) { List<ManagementNodeVO> vos = dbf.listAll(ManagementNodeVO.class); APIListManagementNodeReply reply = new APIListManagementNodeReply(); reply.setInventories(ManagementNodeInventory.valueOf(vos)); bus.reply(msg, reply); } private void handleLocalMessage(Message msg) { if (msg.getClass() == ManagementNodeExitMsg.class) { handle((ManagementNodeExitMsg) msg); } else if (msg instanceof IsManagementNodeReadyMsg) { handle((IsManagementNodeReadyMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(IsManagementNodeReadyMsg msg) { IsManagementNodeReadyReply reply = new IsManagementNodeReadyReply(); reply.setReady(isNodeRunning == NODE_RUNNING); bus.reply(msg, reply); } @Override public String getId() { return bus.makeLocalServiceId(ManagementNodeConstant.SERVICE_ID); } private void startComponents() { for (ComponentWrapper c : components) { c.start(); } } private void stopComponents() { for (final ComponentWrapper c : components) { try { c.stop(); } catch (Throwable t) { logger.warn(t.getMessage(), t); } } } private void installShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { String reason = System.getProperty(Platform.EXIT_REASON); if (reason != null) { logger.debug(String.format("JVM shutdown hook is called[reason: %s], start stopping management node", reason)); } else { logger.debug("JVM shutdown hook is called, start stopping management node"); } stop(); })); } private void populateComponents() { components = new ArrayList<>(); for (final Component c : pluginRgty.getExtensionList(Component.class)) { components.add(new ComponentWrapper() { boolean isStart = false; @Override public void start() { logger.info("starting component: " + c.getClass().getName()); c.start(); logger.info(String.format("component[%s] starts successfully", c.getClass())); isStart = true; } @Override public void stop() { if (isStart) { throwableSafe((Runnable) () -> { c.stop(); logger.info("Stopped component: " + c.getClass().getName()); isStart = false; }, String.format("unable to stop component[%s]", c.getClass().getName())); } } }); } prepareDbExts = pluginRgty.getExtensionList(PrepareDbInitialValueExtensionPoint.class); } private void callPrepareDbExtensions() { for (PrepareDbInitialValueExtensionPoint extp : prepareDbExts) { extp.prepareDbInitialValue(); } } private void populateExtensions() { lifeCycleExtension = pluginRgty.getExtensionList(ManagementNodeChangeListener.class); } private EventCallback nodeLifeCycleCallback = new EventCallback() { @Override protected void run(Map tokens, Object data) { if (evtf.isFromThisManagementNode(tokens)) { return; } ManagementNodeLifeCycleData d = (ManagementNodeLifeCycleData) data; if (LifeCycle.NodeJoin.toString().equals(d.getLifeCycle())) { nodeLifeCycle.nodeJoin(d.getNodeUuid()); } else if (LifeCycle.NodeLeft.toString().equals(d.getLifeCycle())) { nodeLifeCycle.nodeLeft(d.getNodeUuid()); } else { throw new CloudRuntimeException(String.format("unknown lifecycle[%s]", d.getLifeCycle())); } } }; @Override public boolean start() { if (started) { /* largely for unittest, the ComponentLoaderWebListener and Api may both call start() */ logger.debug("Management Node has already started, ignore this call"); return true; } populateExtensions(); started = true; stopped = true; class Result { boolean success; } final Result ret = new Result(); GLock lock = new GLock(INVENTORY_LOCK, INVENTORY_LOCK_TIMEOUT); /* * The lock is being held until we join in, otherwise the inventory * may be deleted by other exiting node because we have not * persisted our entry in management_node table yet, or two starting * nodes persist inventory concurrently. */ lock.lock(); try { final ManagementNodeManagerImpl self = this; FlowChain bootstrap = FlowChainBuilder.newSimpleFlowChain(); bootstrap.setName("management-node-bootstrap"); bootstrap.then(new Flow() { String __name__ = "bootstrap-cloudbus"; // CloudBus is special, it is initialized in Platform.createComponentLoaderFromWebApplicationContext(), // however, when exception happens in bootstrap we need to stop bus in rollback, because the exception // cannot make JVM exist and cloudbus.stop is only called in JVM exit hook; @Override public void run(FlowTrigger trigger, Map data) { trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { bus.stop(); trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "populate-components"; @Override public void run(FlowTrigger trigger, Map data) { populateComponents(); trigger.next(); } }).then(new Flow() { String __name__ = "register-node-on-cloudbus"; @Override public void run(FlowTrigger trigger, Map data) { bus.registerService(self); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { bus.unregisterService(self); trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "call-prepare-db-extension"; @Override public void run(FlowTrigger trigger, Map data) { callPrepareDbExtensions(); trigger.next(); } }).then(new Flow() { String __name__ = "start-components"; @Override public void run(FlowTrigger trigger, Map data) { startComponents(); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { stopComponents(); trigger.rollback(); } }).then(new Flow() { String __name__ = "create-DB-record"; @Override public void run(FlowTrigger trigger, Map data) { ManagementNodeVO vo = new ManagementNodeVO(); vo.setHostName(Platform.getManagementServerIp()); vo.setUuid(Platform.getManagementServerId()); node = dbf.persistAndRefresh(vo); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (node != null) { dbf.remove(node); } trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "start-heartbeat"; @Override public void run(FlowTrigger trigger, Map data) { setupHeartbeat(); trigger.next(); } }).then(new Flow() { String __name__ = "start-api-mediator"; @Override public void run(FlowTrigger trigger, Map data) { apim.start(); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { apim.stop(); trigger.rollback(); } }).then(new NoRollbackFlow() { String __name__ = "set-node-to-running"; @Override public void run(FlowTrigger trigger, Map data) { node.setState(ManagementNodeState.RUNNING); node = dbf.updateAndRefresh(node); trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "I-join"; @Override public void run(FlowTrigger trigger, Map data) { nodeLifeCycle.iJoin(node.getUuid()); trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "node-is-ready"; @Override public void run(FlowTrigger trigger, Map data) { for (ManagementNodeReadyExtensionPoint ext : pluginRgty.getExtensionList(ManagementNodeReadyExtensionPoint.class)) { ext.managementNodeReady(); } trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "listen-node-life-cycle-events"; @Override public void run(FlowTrigger trigger, Map data) { evtf.on(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, nodeLifeCycleCallback); trigger.next(); } }).then(new NoRollbackFlow() { String __name__ = "say-I-join"; @Override public void run(FlowTrigger trigger, Map data) { ManagementNodeLifeCycleData d = new ManagementNodeLifeCycleData(); d.setNodeUuid(node.getUuid()); d.setInventory(ManagementNodeInventory.valueOf(node)); d.setLifeCycle(LifeCycle.NodeJoin.toString()); evtf.fire(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, d); trigger.next(); } }).done(new FlowDoneHandler(null) { @Override public void handle(Map data) { ret.success = true; } }).error(new FlowErrorHandler(null) { @Override public void handle(ErrorCode errCode, Map data) { new BootErrorLog().write(errCode.toString()); ret.success = false; } }).start(); } finally { lock.unlock(); } if (!ret.success) { logger.warn(String.format("management node[%s] failed to start for some reason", Platform.getUuid())); stopped = true; if (CoreGlobalProperty.EXIT_JVM_ON_BOOT_FAILURE) { logger.debug(String.format("unable to start management node[%s], see previous exception. exitJVMOnBootFailure is set to true, exit JVM now", Platform.getManagementServerId())); System.exit(1); } else { throw new CloudRuntimeException(String.format("unable to start management node[%s], see previous exception", Platform.getManagementServerId())); } } stopped = false; installShutdownHook(); logger.info("Management node: " + getId() + " starts successfully"); synchronized (this) { isNodeRunning = NODE_RUNNING; while (isRunning) { try { this.wait(); } catch (InterruptedException e) { logger.warn("Interrupted while daemon is running, continue ...", e); } } } logger.debug("quited main-loop, start stopping management node"); stop(); return true; } private void setupHeartbeat() { ManagementNodeGlobalConfig.NODE_HEARTBEAT_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startHeartbeat(); } }); startHeartbeat(); } private class HeartBeatDBSource { private Connection conn; private SingleConnectionDataSource source; JdbcTemplate jdbc; AtomicBoolean destroyed = new AtomicBoolean(false); public HeartBeatDBSource() { try { conn = dbf.getExtraDataSource().getConnection(); source = new SingleConnectionDataSource(conn, true); jdbc = new JdbcTemplate(source); } catch (SQLException e) { throw new CloudRuntimeException(e); } } @ExceptionSafe public void destroy() { if (!destroyed.compareAndSet(false, true)) { return; } source.destroy(); try { conn.close(); } catch (SQLException e) { throw new CloudRuntimeException(e); } } } private void startHeartbeat() { if (heartBeatTask != null) { heartBeatTask.cancel(true); } heartBeatTask = thdf.submit(new Task<Void>() { private List<ManagementNodeVO> suspects = new ArrayList<ManagementNodeVO>(); @Override public String getName() { return String.format("managementNode-%s-heartbeat", Platform.getManagementServerId()); } private boolean amIalive() { String sql = "select count(*) from ManagementNodeVO where uuid = ?"; long count = heartBeatDBSource.jdbc.queryForObject(sql, new Object[]{node.getUuid()}, Long.class); return count != 0; } private ManagementNodeVO getNode(String uuid) { try { String sql = "select * from ManagementNodeVO where uuid = ?"; return (ManagementNodeVO) heartBeatDBSource.jdbc.queryForObject(sql, new Object[]{uuid}, new BeanPropertyRowMapper(ManagementNodeVO.class)); } catch (IncorrectResultSizeDataAccessException e) { return null; } } private int deleteNode(String uuid) { String sql = "delete from ManagementNodeVO where uuid = ?"; return heartBeatDBSource.jdbc.update(sql, uuid); } @AsyncThread private void nodeDie(ManagementNodeVO n) { logger.debug("Node " + n.getUuid() + " has gone because its heartbeat stopped"); nodeLifeCycle.nodeLeft(n.getUuid()); ManagementNodeLifeCycleData d = new ManagementNodeLifeCycleData(); d.setInventory(ManagementNodeInventory.valueOf(n)); d.setNodeUuid(n.getUuid()); d.setLifeCycle(LifeCycle.NodeLeft.toString()); evtf.fire(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, d); } private void fenceSuspects() { for (ManagementNodeVO vo : suspects) { ManagementNodeVO n = getNode(vo.getUuid()); if (n == null) { continue; } long elapse = n.getHeartBeat().getTime() - vo.getHeartBeat().getTime(); if (elapse != 0) { continue; } int ret = deleteNode(n.getUuid()); if (ret > 0) { nodeDie(n); } } } private void updateHeartbeat() { String sql = "update ManagementNodeVO set heartBeat = NULL where uuid = ?"; if (heartBeatDBSource.jdbc.update(sql, node.getUuid()) > 0) { node = getNode(node.getUuid()); } } private void checkAllNodesHealth() { String sql = "select * from ManagementNodeVO where state = 'RUNNING'"; List<ManagementNodeVO> all = heartBeatDBSource.jdbc.query(sql, new BeanPropertyRowMapper(ManagementNodeVO.class)); suspects.clear(); List<String> nodesInDb = new ArrayList<String>(); for (ManagementNodeVO vo : all) { if (!StringDSL.isZStackUuid(vo.getUuid())) { logger.warn(String.format("found a weird management node, it's UUID not a ZStack uuid, delete it. %s", JSONObjectUtil.toJsonString(ManagementNodeInventory.valueOf(vo)))); dbf.remove(vo); continue; } nodesInDb.add(vo.getUuid()); if (vo.getUuid().equals(node.getUuid())) { continue; } Timestamp curr = dbf.getCurrentSqlTime(); Timestamp lastHeartbeat = vo.getHeartBeat(); long end = lastHeartbeat.getTime() + TimeUnit.SECONDS.toMillis(2 * ManagementNodeGlobalConfig.NODE_HEARTBEAT_INTERVAL.value(Integer.class)); if (end < curr.getTime()) { suspects.add(vo); logger.warn(String.format("management node[uuid:%s, hostname: %s]'s heart beat has stopped for %s secs, add it in suspicious list", vo.getUuid(), vo.getHostName(), TimeUnit.MILLISECONDS.toSeconds(curr.getTime() - lastHeartbeat.getTime()))); } } // When a node is dying, we may not receive the the dead notification because the message bus may be also dead // at that moment. By checking if the node UUID is still in our hash ring, we know what nodes should be kicked out for (String ourNode : destinationMaker.getManagementNodesInHashRing()) { if (!nodesInDb.contains(ourNode)) { logger.warn(String.format("found that a management node[uuid:%s] had no heartbeat in database but still in our hash ring," + "notify that it's dead", ourNode)); nodeLifeCycle.nodeLeft(ourNode); } } // check if any node missing in our hash ring nodesInDb.forEach(nuuid -> { if (nuuid.equals(node.getUuid())) { return; } if (!destinationMaker.getManagementNodesInHashRing().contains(nuuid)) { new Runnable() { @Override @AsyncThread public void run() { nodeLifeCycle.nodeJoin(nuuid); } }.run(); } }); } @Override public Void call() { int heartbeatFailure = 0; while (true) { try { if (!amIalive()) { logger.warn(String.format("cannot find my[uuid:%s] heartbeat in database, quit process", node.getUuid())); stop(); return null; } else { updateHeartbeat(); checkAllNodesHealth(); fenceSuspects(); } heartbeatFailure = 0; } catch (Throwable t) { heartbeatFailure++; if (heartbeatFailure > PortalGlobalProperty.MAX_HEARTBEAT_FAILURE) { logger.warn(String.format("the heartbeat has failed %s times that is greater than the max allowed value[%s]," + " quit process", heartbeatFailure, PortalGlobalProperty.MAX_HEARTBEAT_FAILURE)); stop(); return null; } boolean databaseError = false; logger.warn(String.format("an error happened when doing heartbeat, %s, it's going to recover", t.getMessage())); try { heartBeatDBSource.jdbc.queryForObject("select 1", Integer.class); } catch (Throwable t1) { logger.warn(String.format("cannot communicate to the database, it's most likely the DB stopped or rebooted;" + "try creating a new database connection. %s", t1.getMessage()), t1); databaseError = true; } if (databaseError) { if (heartBeatDBSource != null) { heartBeatDBSource.destroy(); } try { heartBeatDBSource = new HeartBeatDBSource(); } catch (Throwable t1) { logger.warn(String.format("unable to create a database connection, %s, will try it later", t1.getMessage()), t1); } } else { logger.warn("unhandled exception happened", t); } } try { TimeUnit.SECONDS.sleep(ManagementNodeGlobalConfig.NODE_HEARTBEAT_INTERVAL.value(Long.class)); } catch (InterruptedException ie) { } if (heartBeatTask.isCancelled()) { break; } } return null; } }); logger.debug(String.format("started heartbeat thread for management node[uuid:%s]", Platform.getManagementServerId())); } @Override public boolean stop() { Platform.IS_RUNNING = false; if (stopped) { /* avoid repeated call from JVM shutdown hook, if process is exited from a former stop() call */ return true; } stopped = true; final Service self = this; logger.debug(String.format("start stopping the management node[uuid:%s]", node.getUuid())); class Stopper { void stop() { stopApiOnCloudBus(); stopApi(); iAmDead(); stopComponents(); deleteNode(); notifyOtherNodes(); unregisterCloudBus(); stopCloudBus(); quitLoop(); stopThreadFacade(); } @ExceptionSafe private void stopThreadFacade() { thdf.stop(); } @ExceptionSafe private void quitLoop() { notifyStop(); } @ExceptionSafe private void stopCloudBus() { bus.stop(); } @ExceptionSafe private void unregisterCloudBus() { bus.unregisterService(self); } @ExceptionSafe private void notifyOtherNodes() { ManagementNodeLifeCycleData d = new ManagementNodeLifeCycleData(); d.setNodeUuid(node.getUuid()); d.setLifeCycle(LifeCycle.NodeLeft.toString()); d.setInventory(ManagementNodeInventory.valueOf(node)); evtf.fire(ManagementNodeCanonicalEvent.NODE_LIFECYCLE_PATH, d); } @ExceptionSafe private void deleteNode() { dbf.remove(node); } @ExceptionSafe private void iAmDead() { nodeLifeCycle.iAmDead(node.getUuid()); } @ExceptionSafe private void stopApiOnCloudBus() { bus.unregisterService(apim); } @ExceptionSafe private void stopApi() { apim.stop(); } } new Stopper().stop(); logger.info("Management node: " + getId() + " exits successfully"); if (CoreGlobalProperty.EXIT_JVM_ON_STOP) { logger.info("exitJVMOnStop is set to true, exit the JVM"); System.exit(0); } return true; } @AsyncThread private void startInThread() { try { start(); isNodeRunning = NODE_RUNNING; } catch (Throwable t) { logger.warn(t.getMessage(), t); isNodeRunning = NODE_FAILED; } } @Override public void startNode() { startInThread(); while (isNodeRunning == NODE_STARTING) { logger.debug("management node is still initializing ..."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new CloudRuntimeException(e); } } if (isNodeRunning == NODE_FAILED) { logger.debug(String.format("error happened when starting node, stop the management node now")); stop(); throw new CloudRuntimeException("failed to start management node"); } } @Override public void quit(String reason) { new BootErrorLog().write(reason); logger.debug(String.format("stopping the management node because %s", reason)); stop(); } }
prometheus aggregator
portal/src/main/java/org/zstack/portal/managementnode/ManagementNodeManagerImpl.java
prometheus aggregator
Java
apache-2.0
a7af237a3639141ac5526ab5711a52a3bb434af2
0
pierre/collector,ning/collector,ning/collector,ning/collector,pierre/collector,pierre/collector,ning/collector,pierre/collector,pierre/collector,ning/collector,pierre/collector
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.metrics.collector.events.hadoop.writer; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import java.io.IOException; class HadoopOutputChunk { private final Path sourcePath; private final Path desintationPath; private final SequenceFile.Writer writer; private boolean isClosed = false; HadoopOutputChunk(Path sourcePath, Path desintationPath, SequenceFile.Writer writer) { this.sourcePath = sourcePath; this.desintationPath = desintationPath; this.writer = writer; } public void close() throws IOException { if (!isClosed) { isClosed = true; writer.close(); } } public void commit(FileSystem fileSystem) throws IOException { Path destinationDir = desintationPath.getParent(); // parent directory has to exist for a hdfs rename to succeed if (!fileSystem.exists(destinationDir) && !fileSystem.mkdirs(desintationPath.getParent())) { throw new IOException(String.format("Unable to make destination directory %s (does the parent directory exist?)", destinationDir)); } if (!fileSystem.rename(sourcePath, desintationPath)) { throw new IOException(String.format("Unable to rename %s to %s", sourcePath, desintationPath)); } } public void rollback(FileSystem fileSystem) throws IOException { deleteIfExists(sourcePath, fileSystem); deleteIfExists(desintationPath, fileSystem); } private void deleteIfExists(Path path, FileSystem fileSystem) throws IOException { if (fileSystem.exists(path) && !fileSystem.delete(path, false)) { throw new IOException(String.format("unable to delete %s", path)); } } public SequenceFile.Writer getWriter() { return writer; } @Override public String toString() { return String.format("%s : %s -> %s", HadoopOutputChunk.class, sourcePath, desintationPath); } }
src/main/java/com/ning/metrics/collector/events/hadoop/writer/HadoopOutputChunk.java
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.metrics.collector.events.hadoop.writer; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.SequenceFile; import java.io.IOException; //package local class HadoopOutputChunk { private final Path sourcePath; private final Path desintationPath; private final SequenceFile.Writer writer; private boolean isClosed = false; HadoopOutputChunk(Path sourcePath, Path desintationPath, SequenceFile.Writer writer) { this.sourcePath = sourcePath; this.desintationPath = desintationPath; this.writer = writer; } public void close() throws IOException { if (!isClosed) { isClosed = true; writer.close(); } } public void commit(FileSystem fileSystem) throws IOException { Path destinationDir = desintationPath.getParent(); // parent directory has to exist for a hdfs rename to succeed if (!fileSystem.exists(destinationDir) && !fileSystem.mkdirs(desintationPath.getParent())) { throw new IOException(String.format("unable to make destination directory %s", destinationDir)); } if (!fileSystem.rename(sourcePath, desintationPath)) { throw new IOException(String.format("unable to rename %s to %s", sourcePath, desintationPath)); } } public void rollback(FileSystem fileSystem) throws IOException { deleteIfExists(sourcePath, fileSystem); deleteIfExists(desintationPath, fileSystem); } private void deleteIfExists(Path path, FileSystem fileSystem) throws IOException { if (fileSystem.exists(path) && !fileSystem.delete(path, false)) { throw new IOException(String.format("unable to delete %s", path)); } } public SequenceFile.Writer getWriter() { return writer; } @Override public String toString() { return String.format("%s : %s -> %s", HadoopOutputChunk.class, sourcePath, desintationPath); } }
writer: hadoop: re-indent HadoopOutputChunk Fix also error message to be more helpful. Signed-off-by: Pierre-Alexandre Meyer <ff019a5748a52b5641624af88a54a2f0e46a9fb5@ning.com>
src/main/java/com/ning/metrics/collector/events/hadoop/writer/HadoopOutputChunk.java
writer: hadoop: re-indent HadoopOutputChunk
Java
apache-2.0
b2893ba15c73f447331ac5fa9681c6a7ac797b6a
0
jeffbrown/grailsnolib,jeffbrown/grailsnolib
/* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.servlet.mvc; import groovy.lang.GroovyClassLoader; import groovy.lang.MetaClassRegistry; import java.util.Iterator; import java.util.Properties; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import org.codehaus.groovy.grails.commons.DefaultGrailsApplication; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.metaclass.ExpandoMetaClassCreationHandle; import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator; import org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext; import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes; import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest; import org.codehaus.groovy.runtime.InvokerHelper; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.servlet.ModelAndView; import grails.util.GrailsWebUtil; /** * * * @author Steven Devijver * @since Jul 2, 2005 */ public class SimpleGrailsControllerTests extends TestCase { public SimpleGrailsControllerTests() { super(); } protected GrailsApplication grailsApplication = null; protected SimpleGrailsController controller = null; private GenericApplicationContext localContext; private ConfigurableApplicationContext appCtx; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { InvokerHelper.getInstance() .getMetaRegistry() .setMetaClassCreationHandle(new ExpandoMetaClassCreationHandle()); GroovyClassLoader cl = new GroovyClassLoader(); Class c1 = cl.parseClass("class TestController {\n"+ " Closure test = {\n"+ "return [ \"test\" : \"123\" ]\n"+ "}\n" + "}"); Class c2 = cl.parseClass("class SimpleController {\n"+ " Closure test = {\n"+ "}\n" + "}"); Class c3 = cl.parseClass("class NoViewController {\n"+ " Closure test = {\n"+ "request, response ->\n" + "new grails.util.OpenRicoBuilder(response).ajax { element(id:\"test\") { } };\n" + "return null;\n" + "}\n" + "}"); Class c4 = cl.parseClass("class RestrictedController {\n"+ "def allowedMethods=[action1:'POST', action3:['PUT', 'DELETE']]\n" + "def action1 = {}\n" + "def action2 = {}\n" + "def action3 = {}\n" + "}"); // this.grailsApplication = new DefaultGrailsApplication(new Class[]{c1,c2,c3},cl); // this.controller = new SimpleGrailsController(); // this.controller.setGrailsApplication(grailsApplication); Thread.currentThread().setContextClassLoader(cl); //grailsApplication = new DefaultGrailsApplication(,cl); this.localContext = new GenericApplicationContext(); ConstructorArgumentValues args = new ConstructorArgumentValues(); args.addGenericArgumentValue(new Class[]{c1,c2,c3,c4}); args.addGenericArgumentValue(cl); MutablePropertyValues propValues = new MutablePropertyValues(); BeanDefinition grailsApplicationBean = new RootBeanDefinition(DefaultGrailsApplication.class,args,propValues); localContext.registerBeanDefinition( "grailsApplication", grailsApplicationBean ); this.localContext.refresh(); this.grailsApplication = (GrailsApplication)localContext.getBean("grailsApplication"); /*BeanDefinition applicationEventMulticaster = new RootBeanDefinition(SimpleApplicationEventMulticaster.class); context.registerBeanDefinition( "applicationEventMulticaster ", applicationEventMulticaster);*/ GrailsRuntimeConfigurator rConfig = new GrailsRuntimeConfigurator(grailsApplication, localContext); MockServletContext servletContext = new MockServletContext(); this.appCtx = (ConfigurableApplicationContext)rConfig.configure(servletContext); this.controller = (SimpleGrailsController)appCtx.getBean("simpleGrailsController"); servletContext.setAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT,appCtx); controller.setServletContext(servletContext); assertNotNull(appCtx); super.setUp(); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { InvokerHelper.getInstance() .getMetaRegistry() .setMetaClassCreationHandle(new MetaClassRegistry.MetaClassCreationHandle()); } private ModelAndView execute(String uri, Properties parameters) throws Exception { return execute(uri, parameters, "GET"); } private ModelAndView execute(String uri, Properties parameters, String requestMethod) throws Exception { GrailsWebRequest webRequest = GrailsWebUtil.bindMockWebRequest((GrailsWebApplicationContext)this.appCtx); MockHttpServletRequest request = (MockHttpServletRequest)((GrailsHttpServletRequest)webRequest.getCurrentRequest()).getRequest(); request.setRequestURI(uri); request.setMethod(requestMethod); request.setContextPath("/simple"); if (parameters != null) { for (Iterator iter = parameters.keySet().iterator(); iter.hasNext();) { String paramName = (String)iter.next(); String paramValue = parameters.getProperty(paramName); request.addParameter(paramName, paramValue); } } return controller.handleRequest(request, null); } public void testSimpleControllerSuccess() throws Exception { ModelAndView modelAndView = execute("/test/test", null); assertNotNull(modelAndView); } public void testAllowedMethods() throws Exception { assertResponseStatusCode("/restricted/action1", "GET", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action1", "PUT", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action1", "POST", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action1", "DELETE", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action2", "GET", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action2", "PUT", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action2", "POST", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action2", "DELETE", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action3", "GET", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action3", "PUT", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action3", "POST", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action3", "DELETE", HttpServletResponse.SC_OK); } private void assertResponseStatusCode(String uri, String httpMethod, int expectedStatusCode) throws Exception { execute(uri, null, httpMethod); GrailsWebRequest gwr = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); MockHttpServletResponse res = (MockHttpServletResponse) gwr.getCurrentResponse().getDelegate(); assertEquals(expectedStatusCode, res.getStatus()); } }
test/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerTests.java
/* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.servlet.mvc; import groovy.lang.GroovyClassLoader; import groovy.lang.MetaClassRegistry; import java.util.Iterator; import java.util.Properties; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import org.codehaus.groovy.grails.commons.DefaultGrailsApplication; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.metaclass.ExpandoMetaClassCreationHandle; import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator; import org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext; import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes; import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest; import org.codehaus.groovy.runtime.InvokerHelper; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.web.servlet.ModelAndView; import grails.util.GrailsWebUtil; /** * * * @author Steven Devijver * @since Jul 2, 2005 */ public class SimpleGrailsControllerTests extends TestCase { public SimpleGrailsControllerTests() { super(); } protected GrailsApplication grailsApplication = null; protected SimpleGrailsController controller = null; private GenericApplicationContext localContext; private ConfigurableApplicationContext appCtx; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { InvokerHelper.getInstance() .getMetaRegistry() .setMetaClassCreationHandle(new ExpandoMetaClassCreationHandle()); GroovyClassLoader cl = new GroovyClassLoader(); Class c1 = cl.parseClass("class TestController {\n"+ " Closure test = {\n"+ "return [ \"test\" : \"123\" ]\n"+ "}\n" + "}"); Class c2 = cl.parseClass("class SimpleController {\n"+ " Closure test = {\n"+ "}\n" + "}"); Class c3 = cl.parseClass("class NoViewController {\n"+ " Closure test = {\n"+ "request, response ->\n" + "new grails.util.OpenRicoBuilder(response).ajax { element(id:\"test\") { } };\n" + "return null;\n" + "}\n" + "}"); Class c4 = cl.parseClass("class RestrictedController {\n"+ "def allowedMethods=[action1:'POST', action3:['PUT', 'DELETE']]\n" + "def action1 = {}\n" + "def action2 = {}\n" + "def action3 = {}\n" + "}"); // this.grailsApplication = new DefaultGrailsApplication(new Class[]{c1,c2,c3},cl); // this.controller = new SimpleGrailsController(); // this.controller.setGrailsApplication(grailsApplication); Thread.currentThread().setContextClassLoader(cl); //grailsApplication = new DefaultGrailsApplication(,cl); this.localContext = new GenericApplicationContext(); ConstructorArgumentValues args = new ConstructorArgumentValues(); args.addGenericArgumentValue(new Class[]{c1,c2,c3,c4}); args.addGenericArgumentValue(cl); MutablePropertyValues propValues = new MutablePropertyValues(); BeanDefinition grailsApplicationBean = new RootBeanDefinition(DefaultGrailsApplication.class,args,propValues); localContext.registerBeanDefinition( "grailsApplication", grailsApplicationBean ); this.localContext.refresh(); this.grailsApplication = (GrailsApplication)localContext.getBean("grailsApplication"); /*BeanDefinition applicationEventMulticaster = new RootBeanDefinition(SimpleApplicationEventMulticaster.class); context.registerBeanDefinition( "applicationEventMulticaster ", applicationEventMulticaster);*/ GrailsRuntimeConfigurator rConfig = new GrailsRuntimeConfigurator(grailsApplication, localContext); MockServletContext servletContext = new MockServletContext(); this.appCtx = (ConfigurableApplicationContext)rConfig.configure(servletContext); this.controller = (SimpleGrailsController)appCtx.getBean("simpleGrailsController"); servletContext.setAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT,appCtx); controller.setServletContext(servletContext); assertNotNull(appCtx); super.setUp(); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { InvokerHelper.getInstance() .getMetaRegistry() .setMetaClassCreationHandle(new MetaClassRegistry.MetaClassCreationHandle()); } private ModelAndView execute(String uri, Properties parameters) throws Exception { return execute(uri, parameters, "GET", new MockHttpServletResponse()); } private ModelAndView execute(String uri, Properties parameters, String requestMethod, HttpServletResponse response) throws Exception { GrailsWebRequest webRequest = GrailsWebUtil.bindMockWebRequest((GrailsWebApplicationContext)this.appCtx); MockHttpServletRequest request = (MockHttpServletRequest)((GrailsHttpServletRequest)webRequest.getCurrentRequest()).getRequest(); request.setRequestURI(uri); request.setMethod(requestMethod); request.setContextPath("/simple"); if (parameters != null) { for (Iterator iter = parameters.keySet().iterator(); iter.hasNext();) { String paramName = (String)iter.next(); String paramValue = parameters.getProperty(paramName); request.addParameter(paramName, paramValue); } } return controller.handleRequest(request, response); } public void testSimpleControllerSuccess() throws Exception { ModelAndView modelAndView = execute("/test/test", null); assertNotNull(modelAndView); } /* TODO fix test case. Feature is definitely working. test case failing. Why?? Jeff to address. * * public void testAllowedMethods() throws Exception { assertResponseStatusCode("/restricted/action1", "GET", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action1", "PUT", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action1", "POST", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action1", "DELETE", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action2", "GET", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action2", "PUT", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action2", "POST", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action2", "DELETE", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action3", "GET", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action3", "PUT", HttpServletResponse.SC_OK); assertResponseStatusCode("/restricted/action3", "POST", HttpServletResponse.SC_FORBIDDEN); assertResponseStatusCode("/restricted/action3", "DELETE", HttpServletResponse.SC_OK); }*/ private void assertResponseStatusCode(String uri, String httpMethod, int expectedStatusCode) throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); execute(uri, null, httpMethod, response); assertEquals(expectedStatusCode, response.getStatus()); } }
GRAILS-955 The test was failing because the handleRequest method in SimpleGrailsController no longer makes use of the HttpServletResponse object that is passed as an argument. The test was passing in a mock response and then inspecting the response after calling handleRequest. The test now deals with this. Note that the feature being tested is working as designed, the test was broken. git-svn-id: 29aad96320b2a07b98332cd568fc1316025c072f@3489 1cfb16fd-6d17-0410-8ff1-b7e8e1e2867d
test/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerTests.java
GRAILS-955 The test was failing because the handleRequest method in SimpleGrailsController no longer makes use of the HttpServletResponse object that is passed as an argument. The test was passing in a mock response and then inspecting the response after calling handleRequest. The test now deals with this. Note that the feature being tested is working as designed, the test was broken.
Java
apache-2.0
e2d6bce289acfb640b7955a70275af699a64a9fb
0
Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces
package org.openspaces.grid.gsm.strategy; import org.openspaces.admin.AdminException; import org.openspaces.admin.alert.AlertFactory; import org.openspaces.admin.alert.AlertSeverity; import org.openspaces.admin.alert.AlertStatus; import org.openspaces.admin.internal.pu.elastic.GridServiceContainerConfig; import org.openspaces.grid.gsm.GridServiceContainerConfigAware; import org.openspaces.grid.gsm.capacity.AggregatedAllocatedCapacity; import org.openspaces.grid.gsm.containers.ContainersSlaEnforcementEndpoint; import org.openspaces.grid.gsm.containers.ContainersSlaEnforcementEndpointAware; import org.openspaces.grid.gsm.containers.ContainersSlaPolicy; import org.openspaces.grid.gsm.machines.CapacityMachinesSlaPolicy; import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementEndpoint; import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementEndpointAware; import org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioning; import org.openspaces.grid.gsm.sla.ServiceLevelAgreementEnforcementEndpointDestroyedException; public class UndeployScaleStrategyBean extends AbstractScaleStrategyBean implements ContainersSlaEnforcementEndpointAware, MachinesSlaEnforcementEndpointAware, GridServiceContainerConfigAware { private static final String containersAlertGroupUidPrefix = "47A94111-5665-4214-9F7A-2962D998DD12"; private static final String machinesAlertGroupUidPrefix = "3BA87E89-449A-4abc-A632-4732246A9EE4"; // injected private MachinesSlaEnforcementEndpoint machinesEndpoint; private ContainersSlaEnforcementEndpoint containersEndpoint; private GridServiceContainerConfig containersConfig; // created by afterPropertiesSet() private boolean undeployComplete; public void setMachinesSlaEnforcementEndpoint(MachinesSlaEnforcementEndpoint endpoint) { this.machinesEndpoint = endpoint; } public void setContainersSlaEnforcementEndpoint(ContainersSlaEnforcementEndpoint containersService) { this.containersEndpoint = containersService; } public void setGridServiceContainerConfig(GridServiceContainerConfig containersConfig) { this.containersConfig = containersConfig; } @Override public void afterPropertiesSet() { super.afterPropertiesSet(); if (machinesEndpoint == null) { throw new IllegalStateException("machines endpoint cannot be null."); } if (containersEndpoint == null) { throw new IllegalStateException("containers endpoint cannot be null"); } } public void run() { if (undeployComplete) { return; } super.run(); getLogger().debug("Undeploying processing unit " + getProcessingUnit().getName()); try { getLogger().debug("Undeploying containers for " + getProcessingUnit().getName()); boolean containersSlaEnforced = enforceContainersSla(); if (getLogger().isDebugEnabled()) { if (!containersSlaEnforced) { getLogger().debug("Containers undeploy is incomplete."); } } getLogger().debug("Undeploying machines for " + getProcessingUnit().getName()); boolean machinesSlaEnforced = enforceMachinesSla(); if (getLogger().isDebugEnabled()) { if (!machinesSlaEnforced) { getLogger().debug("Machines undeploy incomplete."); } } if (containersSlaEnforced && machinesSlaEnforced) { getLogger().info(getProcessingUnit().getName() + " undeploy is complete."); undeployComplete = true; } } catch (AgentsNotYetDiscoveredException e) { getLogger().debug("Existing agents not discovered yet",e); } catch (ServiceLevelAgreementEnforcementEndpointDestroyedException e) { getLogger().debug("AdminService was destroyed",e); } catch (AdminException e) { getLogger().warn("Unhandled AdminException",e); } catch (Exception e) { getLogger().error("Unhandled Exception",e); } } public boolean isUndeployComplete() { return undeployComplete; } private boolean enforceMachinesSla() throws AgentsNotYetDiscoveredException { final CapacityMachinesSlaPolicy sla = new CapacityMachinesSlaPolicy(); NonBlockingElasticMachineProvisioning machineProvisioning = super.getMachineProvisioning(); sla.setMachineProvisioning(machineProvisioning); sla.setCpuCapacity(0); sla.setMemoryCapacityInMB(0); sla.setMinimumNumberOfMachines(0); sla.setMaximumNumberOfMachines(getMaximumNumberOfInstances()); sla.setContainerMemoryCapacityInMB(containersConfig.getMaximumJavaHeapSizeInMB()); sla.setProvisionedAgents(getDiscoveredAgents()); sla.setMachineIsolation(getIsolation()); boolean reachedSla = machinesEndpoint.enforceSla(sla); if (reachedSla) { triggerAlert( AlertSeverity.WARNING, AlertStatus.RESOLVED, machinesAlertGroupUidPrefix, "Machines Capacity SLA", "Machines for " + getProcessingUnit().getName() + " have been terminated."); } else { triggerAlert( AlertSeverity.WARNING, AlertStatus.RAISED, containersAlertGroupUidPrefix, "Machines Capacity SLA", "Machines for " + getProcessingUnit().getName() + " are being terminated."); } return reachedSla; } private boolean enforceContainersSla() throws ServiceLevelAgreementEnforcementEndpointDestroyedException { final ContainersSlaPolicy sla = new ContainersSlaPolicy(); sla.setNewContainerConfig(containersConfig); sla.setAllocatedCapacity(new AggregatedAllocatedCapacity()); boolean reachedSla = containersEndpoint.enforceSla(sla); if (reachedSla) { triggerAlert( AlertSeverity.WARNING, AlertStatus.RESOLVED, containersAlertGroupUidPrefix, "Containers Capacity SLA", "Containers for " + getProcessingUnit().getName() + " have been terminated."); } else { triggerAlert( AlertSeverity.WARNING, AlertStatus.RAISED, containersAlertGroupUidPrefix, "Containers Capacity SLA", "Contains capacity for " + getProcessingUnit().getName() + " " + "Containers for " + getProcessingUnit().getName() + " are being terminated."); } return reachedSla; } private void triggerAlert(AlertSeverity severity, AlertStatus status, String alertGroupUidPrefix, String alertName, String alertDescription) { AlertFactory alertFactory = new AlertFactory(); alertFactory.name(alertName); alertFactory.description(alertDescription); alertFactory.severity(severity); alertFactory.status(status); alertFactory.componentUid(getProcessingUnit().getName()); alertFactory.groupUid(alertGroupUidPrefix + "-" + getProcessingUnit().getName()); getAdmin().getAlertManager().triggerAlert(alertFactory.toAlert()); getLogger().debug(alertDescription); } }
src/main/src/org/openspaces/grid/gsm/strategy/UndeployScaleStrategyBean.java
package org.openspaces.grid.gsm.strategy; import org.openspaces.admin.AdminException; import org.openspaces.admin.alert.AlertFactory; import org.openspaces.admin.alert.AlertSeverity; import org.openspaces.admin.alert.AlertStatus; import org.openspaces.admin.internal.pu.elastic.GridServiceContainerConfig; import org.openspaces.grid.gsm.GridServiceContainerConfigAware; import org.openspaces.grid.gsm.capacity.AggregatedAllocatedCapacity; import org.openspaces.grid.gsm.containers.ContainersSlaEnforcementEndpoint; import org.openspaces.grid.gsm.containers.ContainersSlaEnforcementEndpointAware; import org.openspaces.grid.gsm.containers.ContainersSlaPolicy; import org.openspaces.grid.gsm.machines.CapacityMachinesSlaPolicy; import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementEndpoint; import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementEndpointAware; import org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioning; import org.openspaces.grid.gsm.sla.ServiceLevelAgreementEnforcementEndpointDestroyedException; public class UndeployScaleStrategyBean extends AbstractScaleStrategyBean implements ContainersSlaEnforcementEndpointAware, MachinesSlaEnforcementEndpointAware, GridServiceContainerConfigAware { private static final String containersAlertGroupUidPrefix = "47A94111-5665-4214-9F7A-2962D998DD12"; private static final String machinesAlertGroupUidPrefix = "3BA87E89-449A-4abc-A632-4732246A9EE4"; // injected private MachinesSlaEnforcementEndpoint machinesEndpoint; private ContainersSlaEnforcementEndpoint containersEndpoint; private GridServiceContainerConfig containersConfig; // created by afterPropertiesSet() private boolean undeployComplete; public void setMachinesSlaEnforcementEndpoint(MachinesSlaEnforcementEndpoint endpoint) { this.machinesEndpoint = endpoint; } public void setContainersSlaEnforcementEndpoint(ContainersSlaEnforcementEndpoint containersService) { this.containersEndpoint = containersService; } public void setGridServiceContainerConfig(GridServiceContainerConfig containersConfig) { this.containersConfig = containersConfig; } @Override public void afterPropertiesSet() { super.afterPropertiesSet(); if (machinesEndpoint == null) { throw new IllegalStateException("machines endpoint cannot be null."); } if (containersEndpoint == null) { throw new IllegalStateException("containers endpoint cannot be null"); } } public void run() { if (undeployComplete) { return; } super.run(); getLogger().debug("Undeploying processing unit " + getProcessingUnit().getName()); try { getLogger().debug("Undeploying containers for " + getProcessingUnit().getName()); boolean containersSlaEnforced = enforceContainersSla(); if (getLogger().isDebugEnabled()) { if (!containersSlaEnforced) { getLogger().debug("Containers undeploy is incomplete."); } } getLogger().debug("Undeploying machines for " + getProcessingUnit().getName()); boolean machinesSlaEnforced = enforceMachinesSla(); if (getLogger().isDebugEnabled()) { if (!machinesSlaEnforced) { getLogger().debug("Machines undeploy incomplete."); } } if (containersSlaEnforced && machinesSlaEnforced) { getLogger().info(getProcessingUnit().getName() + " undeploy is complete."); undeployComplete = true; } } catch (AgentsNotYetDiscoveredException e) { getLogger().debug("Existing agents not discovered yet",e); } catch (ServiceLevelAgreementEnforcementEndpointDestroyedException e) { getLogger().debug("AdminService was destroyed",e); } catch (AdminException e) { getLogger().warn("Unhandled AdminException",e); } catch (Exception e) { getLogger().error("Unhandled Exception",e); } } public boolean isUndeployComplete() { return undeployComplete; } private boolean enforceMachinesSla() throws AgentsNotYetDiscoveredException { final CapacityMachinesSlaPolicy sla = new CapacityMachinesSlaPolicy(); NonBlockingElasticMachineProvisioning machineProvisioning = super.getMachineProvisioning(); sla.setMachineProvisioning(machineProvisioning); sla.setCpuCapacity(0); sla.setMemoryCapacityInMB(0); sla.setMinimumNumberOfMachines(0); sla.setContainerMemoryCapacityInMB(containersConfig.getMaximumJavaHeapSizeInMB()); sla.setProvisionedAgents(getDiscoveredAgents()); sla.setMachineIsolation(getIsolation()); boolean reachedSla = machinesEndpoint.enforceSla(sla); if (reachedSla) { triggerAlert( AlertSeverity.WARNING, AlertStatus.RESOLVED, machinesAlertGroupUidPrefix, "Machines Capacity SLA", "Machines for " + getProcessingUnit().getName() + " have been terminated."); } else { triggerAlert( AlertSeverity.WARNING, AlertStatus.RAISED, containersAlertGroupUidPrefix, "Machines Capacity SLA", "Machines for " + getProcessingUnit().getName() + " are being terminated."); } return reachedSla; } private boolean enforceContainersSla() throws ServiceLevelAgreementEnforcementEndpointDestroyedException { final ContainersSlaPolicy sla = new ContainersSlaPolicy(); sla.setNewContainerConfig(containersConfig); sla.setAllocatedCapacity(new AggregatedAllocatedCapacity()); boolean reachedSla = containersEndpoint.enforceSla(sla); if (reachedSla) { triggerAlert( AlertSeverity.WARNING, AlertStatus.RESOLVED, containersAlertGroupUidPrefix, "Containers Capacity SLA", "Containers for " + getProcessingUnit().getName() + " have been terminated."); } else { triggerAlert( AlertSeverity.WARNING, AlertStatus.RAISED, containersAlertGroupUidPrefix, "Containers Capacity SLA", "Contains capacity for " + getProcessingUnit().getName() + " " + "Containers for " + getProcessingUnit().getName() + " are being terminated."); } return reachedSla; } private void triggerAlert(AlertSeverity severity, AlertStatus status, String alertGroupUidPrefix, String alertName, String alertDescription) { AlertFactory alertFactory = new AlertFactory(); alertFactory.name(alertName); alertFactory.description(alertDescription); alertFactory.severity(severity); alertFactory.status(status); alertFactory.componentUid(getProcessingUnit().getName()); alertFactory.groupUid(alertGroupUidPrefix + "-" + getProcessingUnit().getName()); getAdmin().getAlertManager().triggerAlert(alertFactory.toAlert()); getLogger().debug(alertDescription); } }
GS-8654 Fixed problem with Undeploy strategy bean machines sla policy. svn path=/trunk/openspaces/; revision=85790 Former-commit-id: 3fb59337e5a6a74170c1c5529210d972c610841f
src/main/src/org/openspaces/grid/gsm/strategy/UndeployScaleStrategyBean.java
GS-8654 Fixed problem with Undeploy strategy bean machines sla policy.
Java
apache-2.0
4fc6b006229deb8c6aad3e67ae0a3a96544a7533
0
GerritCodeReview/plugins_replication,qtproject/qtqa-gerrit-plugin-replication
// Copyright (C) 2019 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Stopwatch; import com.google.gerrit.acceptance.LightweightPluginDaemonTest; import com.google.gerrit.acceptance.PushOneCommit.Result; import com.google.gerrit.acceptance.TestPlugin; import com.google.gerrit.acceptance.UseLocalDisk; import com.google.gerrit.extensions.common.ProjectInfo; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.IOException; import java.nio.file.Path; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; import org.junit.Test; @UseLocalDisk @TestPlugin( name = "replication", sysModule = "com.googlesource.gerrit.plugins.replication.ReplicationModule") public class ReplicationIT extends LightweightPluginDaemonTest { private static final int TEST_REPLICATION_DELAY = 1; private static final Duration TEST_TIMEMOUT = Duration.ofSeconds(TEST_REPLICATION_DELAY * 10); @Inject private SitePaths sitePaths; private Path gitPath; private FileBasedConfig config; @Override public void setUpTestPlugin() throws Exception { config = new FileBasedConfig(sitePaths.etc_dir.resolve("replication.config").toFile(), FS.DETECTED); config.save(); gitPath = sitePaths.site_path.resolve("git"); super.setUpTestPlugin(); } @Test public void shouldReplicateNewProject() throws Exception { setReplicationDestination("foo", "replica"); Project.NameKey sourceProject = createProject("foo"); waitUntil(() -> gitPath.resolve(sourceProject + "replica.git").toFile().isDirectory()); ProjectInfo replicaProject = gApi.projects().name(sourceProject + "replica").get(); assertThat(replicaProject).isNotNull(); } @Test public void shouldReplicateNewChangeRef() throws Exception { setReplicationDestination("foo", "replica"); Project.NameKey targetProject = createProject("projectreplica"); Result pushResult = createChange(); RevCommit sourceCommit = pushResult.getCommit(); String sourceRef = pushResult.getPatchSet().getRefName(); waitUntil(() -> getRef(getRepo(targetProject), sourceRef) != null); Ref targetBranchRef = getRef(getRepo(targetProject), sourceRef); assertThat(targetBranchRef).isNotNull(); assertThat(targetBranchRef.getObjectId()).isEqualTo(sourceCommit.getId()); } private Repository getRepo(Project.NameKey targetProject) { try { return repoManager.openRepository(targetProject); } catch (Exception e) { e.printStackTrace(); return null; } } private Ref getRef(Repository repo, String branchName) { try { return repo.getRefDatabase().exactRef(branchName); } catch (IOException e) { e.printStackTrace(); return null; } } private void setReplicationDestination(String remoteName, String replicaSuffix) throws IOException { config.setString( "remote", remoteName, "url", gitPath.resolve("${name}" + replicaSuffix + ".git").toString()); config.setInt("remote", remoteName, "replicationDelay", TEST_REPLICATION_DELAY); config.save(); reloadConfig(); } private void waitUntil(Supplier<Boolean> waitCondition) throws InterruptedException { Stopwatch stopwatch = Stopwatch.createStarted(); while (!waitCondition.get() && stopwatch.elapsed().compareTo(TEST_TIMEMOUT) < 0) { TimeUnit.SECONDS.sleep(1); } } private void reloadConfig() { plugin.getSysInjector().getInstance(AutoReloadConfigDecorator.class).forceReload(); } }
src/test/java/com/googlesource/gerrit/plugins/replication/ReplicationIT.java
// Copyright (C) 2019 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Stopwatch; import com.google.gerrit.acceptance.LightweightPluginDaemonTest; import com.google.gerrit.acceptance.PushOneCommit.Result; import com.google.gerrit.acceptance.TestPlugin; import com.google.gerrit.acceptance.UseLocalDisk; import com.google.gerrit.extensions.common.ProjectInfo; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.IOException; import java.nio.file.Path; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; import org.junit.Test; @UseLocalDisk @TestPlugin( name = "replication", sysModule = "com.googlesource.gerrit.plugins.replication.ReplicationModule") public class ReplicationIT extends LightweightPluginDaemonTest { private static final int TEST_REPLICATION_DELAY = 1; private static final Duration TEST_TIMEMOUT = Duration.ofSeconds(TEST_REPLICATION_DELAY * 10); @Inject private SitePaths sitePaths; private Path gitPath; private FileBasedConfig config; @Override public void setUpTestPlugin() throws Exception { config = new FileBasedConfig(sitePaths.etc_dir.resolve("replication.config").toFile(), FS.DETECTED); config.save(); gitPath = sitePaths.site_path.resolve("git"); super.setUpTestPlugin(); } @Test public void shouldReplicateNewProject() throws Exception { setReplicationDestination("foo", "replica"); Project.NameKey sourceProject = createProject("foo"); waitUntil(() -> gitPath.resolve(sourceProject + "replica.git").toFile().isDirectory()); ProjectInfo replicaProject = gApi.projects().name(sourceProject + "replica").get(); assertThat(replicaProject).isNotNull(); } @Test public void shouldReplicateNewBranch() throws Exception { setReplicationDestination("foo", "replica"); Project.NameKey targetProject = createProject("projectreplica"); Result pushResult = createChange(); RevCommit sourceCommit = pushResult.getCommit(); String sourceRef = pushResult.getPatchSet().getRefName(); waitUntil(() -> getRef(getRepo(targetProject), sourceRef) != null); Ref targetBranchRef = getRef(getRepo(targetProject), sourceRef); assertThat(targetBranchRef).isNotNull(); assertThat(targetBranchRef.getObjectId()).isEqualTo(sourceCommit.getId()); } private Repository getRepo(Project.NameKey targetProject) { try { return repoManager.openRepository(targetProject); } catch (Exception e) { e.printStackTrace(); return null; } } private Ref getRef(Repository repo, String branchName) { try { return repo.getRefDatabase().exactRef(branchName); } catch (IOException e) { e.printStackTrace(); return null; } } private void setReplicationDestination(String remoteName, String replicaSuffix) throws IOException { config.setString( "remote", remoteName, "url", gitPath.resolve("${name}" + replicaSuffix + ".git").toString()); config.setInt("remote", remoteName, "replicationDelay", TEST_REPLICATION_DELAY); config.save(); reloadConfig(); } private void waitUntil(Supplier<Boolean> waitCondition) throws InterruptedException { Stopwatch stopwatch = Stopwatch.createStarted(); while (!waitCondition.get() && stopwatch.elapsed().compareTo(TEST_TIMEMOUT) < 0) { TimeUnit.SECONDS.sleep(1); } } private void reloadConfig() { plugin.getSysInjector().getInstance(AutoReloadConfigDecorator.class).forceReload(); } }
ReplicationIT: Change test method name to reflect actual operation The test shouldReplicateNewBranch creates a new change and then verifies that the corresponding refs/changes/xx/yy/zzzzzz ref is replicated to the destination. Rename it to shouldReplicateNewChangeRef to match what it's actually doing. Change-Id: I32fe7237c8857907dd51d627a571f6ccb73741a3
src/test/java/com/googlesource/gerrit/plugins/replication/ReplicationIT.java
ReplicationIT: Change test method name to reflect actual operation
Java
apache-2.0
c8be9057eb8f1cdd514c8504bd4bbcb781c60b25
0
P2Pvalue/swellrt,Grasia/swellrt,P2Pvalue/swellrt,P2Pvalue/swellrt,Grasia/swellrt,Grasia/swellrt,P2Pvalue/swellrt,Grasia/swellrt
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.waveprotocol.box.server.rpc; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.google.inject.servlet.GuiceFilter; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.Message; import com.google.protobuf.RpcCallback; import com.google.protobuf.Service; import com.typesafe.config.Config; import org.apache.commons.lang.StringUtils; import org.atmosphere.cache.UUIDBroadcasterCache; import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.*; import org.atmosphere.cpr.AtmosphereResource.TRANSPORT; import org.atmosphere.guice.AtmosphereGuiceServlet; import org.atmosphere.util.IOUtils; import org.eclipse.jetty.proxy.ProxyServlet; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.session.HashSessionManager; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.eclipse.jetty.servlets.GzipFilter; import org.eclipse.jetty.util.resource.ResourceCollection; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.websocket.servlet.*; import org.swellrt.model.generic.Model; import org.waveprotocol.box.common.comms.WaveClientRpc.ProtocolAuthenticate; import org.waveprotocol.box.common.comms.WaveClientRpc.ProtocolAuthenticationResult; import org.waveprotocol.box.server.authentication.HttpWindowSession; import org.waveprotocol.box.server.authentication.SessionManager; import org.waveprotocol.box.server.executor.ExecutorAnnotations.ClientServerExecutor; import org.waveprotocol.box.server.persistence.file.FileUtils; import org.waveprotocol.box.server.rpc.atmosphere.AtmosphereChannel; import org.waveprotocol.box.server.rpc.atmosphere.AtmosphereClientInterceptor; import org.waveprotocol.box.server.rpc.atmosphere.AtmosphereUtil; import org.waveprotocol.box.server.util.NetUtils; import org.waveprotocol.box.stat.Timer; import org.waveprotocol.box.stat.Timing; import org.waveprotocol.wave.model.util.Pair; import org.waveprotocol.wave.model.wave.ParticipantId; import org.waveprotocol.wave.util.logging.Log; import javax.annotation.Nullable; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.ServletContextListener; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; /** * ServerRpcProvider can provide instances of type Service over an incoming * network socket and service incoming RPCs to these services and their methods. * * */ public class ServerRpcProvider { private static final Log LOG = Log.get(ServerRpcProvider.class); /** * The buffer size is passed to implementations of {@link WaveWebSocketServlet} as init * param. It defines the response buffer size. */ private static final int BUFFER_SIZE = 1024 * 1024; private final InetSocketAddress[] httpAddresses; private final Executor threadPool; private final SessionManager sessionManager; private final org.eclipse.jetty.server.SessionManager jettySessionManager; private Server httpServer = null; private final boolean sslEnabled; private final String sslKeystorePath; private final String sslKeystorePassword; private static ConcurrentHashMap<HttpWindowSession, Connection> ATMOSPHERE_CONNECTIONS = new ConcurrentHashMap<HttpWindowSession, Connection>(); // Mapping from incoming protocol buffer type -> specific handler. private final Map<Descriptors.Descriptor, RegisteredServiceMethod> registeredServices = Maps.newHashMap(); // List of webApp source directories ("./war", etc) private final String[] resourceBases; private final String sessionStoreDir; private int webSocketMaxIdleTime; private int webSocketMaxMessageSize; private int websocketHeartbeat; private final int sessionMaxInactiveTime; private final static String SESSION_URL_PARAM = "sid"; private final static String SESSION_COOKIE_NAME = "WSESSIONID"; /** * Internal, static container class for any specific registered service * method. */ static class RegisteredServiceMethod { final Service service; final MethodDescriptor method; RegisteredServiceMethod(Service service, MethodDescriptor method) { this.service = service; this.method = method; } } static class WebSocketConnection extends Connection { private final WebSocketChannel socketChannel; WebSocketConnection(ParticipantId loggedInUser, ServerRpcProvider provider) { super(loggedInUser, provider); socketChannel = new WebSocketChannelImpl(this); LOG.info("New websocket connection set up for user " + loggedInUser); expectMessages(socketChannel); } @Override protected void sendMessage(int sequenceNo, Message message) { socketChannel.sendMessage(sequenceNo, message); } public WebSocketChannel getWebSocketServerChannel() { return socketChannel; } } /** * The glue class between the Atmoshphere Framework (communication layer) and * the RPCs for each remote client. * * A connection is associated with an unique pair (HTTP session, browser * window/tab), the {@link HttpWindowSession} * * This implementation supports WebSockets and Long-Polling transports over * Atmosphere. * * * @author pablojan@gmail.com (Pablo Ojanguren) * */ static class AtmosphereConnection extends Connection { private final AtmosphereChannel atmosphereChannel; private HttpWindowSession id; private Broadcaster broadcaster; private TRANSPORT transport; public AtmosphereConnection(HttpWindowSession id, ServerRpcProvider provider) { super(null, provider); this.id = id; this.broadcaster = BroadcasterFactory.getDefault().get(this.id.toString()); atmosphereChannel = new AtmosphereChannel(this, broadcaster); expectMessages(atmosphereChannel); } /** * Handle an incoming request through an {@link AtmosphereResource}. * * @param resource the resource with the incoming message or new connection * signal */ public void onRequest(AtmosphereResource resource, ParticipantId loggedInUser) { // Update current transport this.transport = resource.transport(); if (isWebSocket(this.transport)) { if (isGET(resource)) { // New connection resource.setBroadcaster(broadcaster); resource.suspend(); } if (isPOST(resource)) { String data = AtmosphereUtil.readMessage(resource); atmosphereChannel.handleMessageString(data, loggedInUser); } } /* * Responses are always sent back through the GET request (resource). POST * requests are released as soon as the request has been delivered */ if (isLongPolling(this.transport)) { if (isGET(resource)) { // New connection resource.suspend(); broadcaster.addAtmosphereResource(resource); } if (isPOST(resource)) { String data = AtmosphereUtil.readMessage(resource); atmosphereChannel.handleMessageString(data, loggedInUser); resource.resume(); } } } /** * Closes the connection and its RPCs. This method must be invoked when * client closes the communication. */ public void close() { this.cancelRpcs(); for (AtmosphereResource r : this.broadcaster.getAtmosphereResources()) { try { r.close(); } catch (IOException e) { LOG.warning("Error closing resource on session " + id, e); } } this.broadcaster.destroy(); } // // Send back // @Override protected void sendMessage(int sequenceNo, Message message) { atmosphereChannel.sendMessage(sequenceNo, message); if (isLongPolling(transport)) { broadcaster.resumeAll(); } } // // Utility methods // protected static boolean isWebSocket(TRANSPORT transport) { return transport.equals(TRANSPORT.WEBSOCKET); } protected static boolean isLongPolling(TRANSPORT transport) { return transport.equals(TRANSPORT.LONG_POLLING) || transport.equals(TRANSPORT.POLLING); } protected static boolean isGET(AtmosphereResource r) { return r.getRequest().getMethod().equalsIgnoreCase("GET"); } protected static boolean isPOST(AtmosphereResource r) { return r.getRequest().getMethod().equalsIgnoreCase("POST"); } } static abstract class Connection implements ProtoCallback { private final Map<Integer, ServerRpcController> activeRpcs = new ConcurrentHashMap<Integer, ServerRpcController>(); // The logged in user. // Note: Due to this bug: // http://code.google.com/p/wave-protocol/issues/detail?id=119, // the field may be null on first connect and then set later using an RPC. private ParticipantId loggedInUser; private final ServerRpcProvider provider; private boolean isFirstRequest = true; private boolean isStatusOk = true; /** * @param loggedInUser The currently logged in user, or null if no user is * logged in. * @param provider the provider */ public Connection(ParticipantId loggedInUser, ServerRpcProvider provider) { this.loggedInUser = loggedInUser; this.provider = provider; } protected void expectMessages(MessageExpectingChannel channel) { synchronized (provider.registeredServices) { for (RegisteredServiceMethod serviceMethod : provider.registeredServices.values()) { channel.expectMessage(serviceMethod.service.getRequestPrototype(serviceMethod.method)); LOG.fine("Expecting: " + serviceMethod.method.getFullName()); } } channel.expectMessage(Rpc.CancelRpc.getDefaultInstance()); } protected abstract void sendMessage(int sequenceNo, Message message); private ParticipantId authenticate(String token) { HttpSession session = provider.sessionManager.getSessionFromToken(token); ParticipantId user = provider.sessionManager.getLoggedInUser(session); return user; } protected boolean isStatusOk() { return isStatusOk; } public ParticipantId getParticipantId() { return loggedInUser; } protected void cancelRpcs() { if (!activeRpcs.isEmpty()) { LOG.info("Cleaning up RPCs"); for (ServerRpcController controller : activeRpcs.values()) { if (!controller.isCanceled()) { controller.cancel(); } } activeRpcs.clear(); } } @Override public void message(final int sequenceNo, Message message, ParticipantId loggedInUser) { final String messageName = "/" + message.getClass().getSimpleName(); final Timer profilingTimer = Timing.startRequest(messageName); if (isFirstRequest && sequenceNo != 0) { // On server's reboot, clients can get reconnected (sequenceNo !=0) but // server won't be able to process the request. LOG.info("First RPC request but sequence number >0"); throw new IllegalStateException("First RPC request nut sequence number >0"); } isFirstRequest = false; // Clean up ServerRpcControllers if remote client starts a new // sequence of protocol messages. // This allows dirty reconnections, resuming current sessions... // This should been handle before, detecting new logins for the same if (sequenceNo == 0) { // Don't update on null to keep backwards compat. if (loggedInUser != null) this.loggedInUser = loggedInUser; cancelRpcs(); } else { if (!this.loggedInUser.equals(loggedInUser)) { LOG.info("Request's participant doesn't match connection's participant. Spoofing?"); throw new IllegalStateException( "Request's participant doesn't match connection's participant."); } } if (message instanceof Rpc.CancelRpc) { final ServerRpcController controller = activeRpcs.get(sequenceNo); if (controller == null) { throw new IllegalStateException("Trying to cancel an RPC that is not active!"); } else { LOG.info("Cancelling open RPC " + sequenceNo); controller.cancel(); } } else if (message instanceof ProtocolAuthenticate) { // Workaround for bug: http://codereview.waveprotocol.org/224001/ // When we get this message, either the connection will not be logged in // (loggedInUser == null) or the connection will have been authenticated // via cookies // (in which case loggedInUser must match the authenticated user, and // this message has no // effect). ProtocolAuthenticate authMessage = (ProtocolAuthenticate) message; ParticipantId authenticatedAs = authenticate(authMessage.getToken()); Preconditions.checkArgument(authenticatedAs != null, "Auth token invalid"); sendMessage(sequenceNo, ProtocolAuthenticationResult.getDefaultInstance()); } else if (provider.registeredServices.containsKey(message.getDescriptorForType())) { if (activeRpcs.containsKey(sequenceNo)) { throw new IllegalStateException( "Can't invoke a new RPC with a sequence number already in use."); } else { final RegisteredServiceMethod serviceMethod = provider.registeredServices.get(message.getDescriptorForType()); // Create the internal ServerRpcController used to invoke the call. final ServerRpcController controller = new ServerRpcControllerImpl(message, serviceMethod.service, serviceMethod.method, loggedInUser, new RpcCallback<Message>() { @Override synchronized public void run(Message message) { if (message instanceof Rpc.RpcFinished || !serviceMethod.method.getOptions().getExtension(Rpc.isStreamingRpc)) { // This RPC is over - remove it from the map. boolean failed = message instanceof Rpc.RpcFinished && ((Rpc.RpcFinished) message).getFailed(); LOG.fine("RPC " + sequenceNo + " is now finished, failed = " + failed); if (failed) { LOG.info("error = " + ((Rpc.RpcFinished) message).getErrorText()); } activeRpcs.remove(sequenceNo); } sendMessage(sequenceNo, message); if (profilingTimer != null) { Timing.stop(profilingTimer); } } }); // Kick off a new thread specific to this RPC. activeRpcs.put(sequenceNo, controller); provider.threadPool.execute(controller); } } else { // Sent a message type we understand, but don't expect - erronous case! throw new IllegalStateException( "Got expected but unknown message (" + message + ") for sequence: " + sequenceNo); } } } /** * Construct a new ServerRpcProvider, hosting on the specified * WebSocket addresses. * * Also accepts an ExecutorService for spawning managing threads. */ public ServerRpcProvider(InetSocketAddress[] httpAddresses, String[] resourceBases, Executor threadPool, SessionManager sessionManager, org.eclipse.jetty.server.SessionManager jettySessionManager, String sessionStoreDir, boolean sslEnabled, String sslKeystorePath, String sslKeystorePassword, int webSocketMaxIdleTime, int webSocketMaxMessageSize, int websocketHeartbeat, int sessionMaxInactiveTime) { this.httpAddresses = httpAddresses; this.resourceBases = resourceBases; this.threadPool = threadPool; this.sessionManager = sessionManager; this.jettySessionManager = jettySessionManager; this.sessionStoreDir = sessionStoreDir; this.sslEnabled = sslEnabled; this.sslKeystorePath = sslKeystorePath; this.sslKeystorePassword = sslKeystorePassword; this.webSocketMaxIdleTime = webSocketMaxIdleTime; this.webSocketMaxMessageSize = webSocketMaxMessageSize; this.websocketHeartbeat = websocketHeartbeat; this.sessionMaxInactiveTime = sessionMaxInactiveTime; } /** * Constructs a new ServerRpcProvider with a default ExecutorService. */ public ServerRpcProvider(InetSocketAddress[] httpAddresses, String[] resourceBases, SessionManager sessionManager, org.eclipse.jetty.server.SessionManager jettySessionManager, String sessionStoreDir, boolean sslEnabled, String sslKeystorePath, String sslKeystorePassword, Executor executor, int webSocketMaxIdleTime, int webSocketMaxMessageSize, int websocketHeartbeat, int sessionMaxInactiveTime) { this(httpAddresses, resourceBases, executor, sessionManager, jettySessionManager, sessionStoreDir, sslEnabled, sslKeystorePath, sslKeystorePassword, webSocketMaxIdleTime, webSocketMaxMessageSize, websocketHeartbeat, sessionMaxInactiveTime); } @Inject public ServerRpcProvider(Config config, SessionManager sessionManager, org.eclipse.jetty.server.SessionManager jettySessionManager, @ClientServerExecutor Executor executorService) { this(parseAddressList(config.getStringList("core.http_frontend_addresses"), config.getString("core.http_websocket_public_address")), config.getStringList("core.resource_bases").toArray(new String[0]), sessionManager, jettySessionManager, config.getString("core.sessions_store_directory"), config.getBoolean("security.enable_ssl"), config.getString("security.ssl_keystore_path"), config.getString("security.ssl_keystore_password"), executorService, config.getInt("network.websocket_max_idle_time"), config.getInt("network.websocket_max_message_size"), config.getInt("network.websocket_heartbeat"), config.getInt("network.session_max_inactive_time") ); } public void startWebSocketServer(final Injector injector) { httpServer = new Server(); List<Connector> connectors = getSelectChannelConnectors(httpAddresses); if (connectors.isEmpty()) { LOG.severe("No valid http end point address provided!"); } for (Connector connector : connectors) { httpServer.addConnector(connector); } final WebAppContext context = new WebAppContext(); context.setParentLoaderPriority(true); if (jettySessionManager != null) { context.getSessionHandler().setSessionManager(jettySessionManager); context.getSessionHandler().getSessionManager() .setMaxInactiveInterval(sessionMaxInactiveTime); Set<SessionTrackingMode> sessionTrackingModes = new HashSet<SessionTrackingMode>(); sessionTrackingModes.add(SessionTrackingMode.URL); sessionTrackingModes.add(SessionTrackingMode.COOKIE); context.getSessionHandler().getSessionManager().setSessionTrackingModes(sessionTrackingModes); context.getSessionHandler().getSessionManager() .setSessionIdPathParameterName(SESSION_URL_PARAM); } final ResourceCollection resources = new ResourceCollection(resourceBases); context.setBaseResource(resources); context.setInitParameter("org.eclipse.jetty.servlet.SessionCookie", SESSION_COOKIE_NAME); FilterHolder corsFilterHolder = new FilterHolder(CrossOriginFilter.class); corsFilterHolder.setInitParameter("allowedOrigins", "*"); // Set explicit methods to allow CORS with DELETE corsFilterHolder.setInitParameter("allowedMethods", "GET,POST,DELETE,PUT,HEAD"); corsFilterHolder.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin,X-window-id"); context.addFilter(corsFilterHolder, "/*", EnumSet.allOf(DispatcherType.class)); // Set cache header rewriter filter FilterHolder cacheFilterHolder = new FilterHolder(CacheHeaderFilter.class); context.addFilter(cacheFilterHolder, "/*", EnumSet.allOf(DispatcherType.class)); addWebSocketServlets(); try { final ServletModule servletModule = getServletModule(); ServletContextListener contextListener = new GuiceServletContextListener() { private final Injector childInjector = injector.createChildInjector(servletModule); @Override protected Injector getInjector() { return childInjector; } }; context.addEventListener(contextListener); context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class)); context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class)); httpServer.setHandler(context); httpServer.start(); restoreSessions(); } catch (Exception e) { // yes, .start() throws "Exception" LOG.severe("Fatal error starting http server.", e); return; } LOG.fine("WebSocket server running."); } private void restoreSessions() { try { HashSessionManager hashSessionManager = (HashSessionManager) jettySessionManager; hashSessionManager.setStoreDirectory(FileUtils.createDirIfNotExists(sessionStoreDir, "Session persistence")); hashSessionManager.setSavePeriod(60); hashSessionManager.restoreSessions(); } catch (Exception e) { LOG.warning("Cannot restore sessions"); } } public void addWebSocketServlets() { // Servlet where the websocket connection is served from. ServletHolder wsholder = addServlet("/socket", WaveWebSocketServlet.class); // TODO(zamfi): fix to let messages span frames. wsholder.setInitParameter("bufferSize", "" + BUFFER_SIZE); // // Atmosphere framework. Replacement of Socket.IO // See https://issues.apache.org/jira/browse/WAVE-405 // ServletHolder atholder = addServlet("/atmosphere*", AtmosphereGuiceServlet.class); // Avoid loading defualt CORS interceptor which is in conflict with general // jetty CORS filter atholder.setInitParameter("org.atmosphere.cpr.AtmosphereInterceptor.disableDefaults", "true"); // Setting a low HeartBeat frequency to avoid network issues. Let clients to // set a hihger value. atholder.setInitParameter( "org.atmosphere.interceptor.HeartbeatInterceptor.heartbeatFrequencyInSeconds", "" + websocketHeartbeat); // // Configure Atmosphere Broadcaster class // // Comment out following line to enable Threaded broadcasters atholder.setInitParameter("org.atmosphere.cpr.broadcasterClass", "org.atmosphere.util.SimpleBroadcaster"); // // Configuring Atmosphere threads: this config is considered if // SimpleBroadcaster is not used // // Use same thread pool for all brodcaster (AtmosphereConnection) atholder.setInitParameter("org.atmosphere.cpr.broadcaster.shareableThreadPool", "true"); // Set number of threads for atmosphere atholder.setInitParameter("org.atmosphere.cpr.broadcaster.maxProcessingThreads", "4"); // Setting all buffers at least to 2MB atholder.setInitParameter("org.atmosphere.websocket.maxTextMessageSize", "" + (BUFFER_SIZE * webSocketMaxMessageSize)); atholder.setInitParameter("org.atmosphere.websocket.maxBinaryMessageSize", "" + (BUFFER_SIZE * webSocketMaxMessageSize)); atholder.setInitParameter("org.atmosphere.websocket.webSocketBufferingMaxSize", "" + (BUFFER_SIZE * webSocketMaxMessageSize)); // Enable guice. See // https://github.com/Atmosphere/atmosphere/wiki/Configuring-Atmosphere%27s-Classes-Creation-and-Injection atholder.setInitParameter("org.atmosphere.cpr.objectFactory", "org.waveprotocol.box.server.rpc.atmosphere.GuiceAtmosphereFactory"); atholder.setAsyncSupported(true); atholder.setInitOrder(0); // Serve the static content and GWT web client with the default servlet // (acts like a standard file-based web server). // addServlet("/static/*", DefaultServlet.class); // addServlet("/webclient/*", DefaultServlet.class); } public ServletModule getServletModule() { return new ServletModule() { @Override protected void configureServlets() { // We add servlets here to override the DefaultServlet automatic registered by WebAppContext // in path "/" with our WaveClientServlet. Any other way to do this? // Related question (unanswered 08-Apr-2011) // http://web.archiveorange.com/archive/v/d0LdlXf1kN0OXyPNyQZp for (Pair<String, ServletHolder> servlet : servletRegistry) { String url = servlet.getFirst(); @SuppressWarnings("unchecked") Class<HttpServlet> clazz = (Class<HttpServlet>) servlet.getSecond().getHeldClass(); Map<String,String> params = servlet.getSecond().getInitParameters(); serve(url).with(clazz,params); bind(clazz).in(Singleton.class); } for (Pair<String, Class<? extends Filter>> filter : filterRegistry) { filter(filter.first).through(filter.second); } } }; } private static InetSocketAddress[] parseAddressList(List<String> addressList, String websocketAddress) { if (addressList == null || addressList.size() == 0) { return new InetSocketAddress[0]; } else { Set<InetSocketAddress> addresses = Sets.newHashSet(); // We add the websocketAddress as another listening address. ArrayList<String> mergedAddressList = new ArrayList<>(addressList); if (!StringUtils.isEmpty(websocketAddress)) { mergedAddressList.add(websocketAddress); } for (String str : mergedAddressList) { if (str.length() == 0) { LOG.warning("Encountered empty address in http addresses list."); } else { try { InetSocketAddress address = NetUtils.parseHttpAddress(str); if (!addresses.contains(address)) { addresses.add(address); } else { LOG.warning( "Ignoring duplicate address in http addresses list: Duplicate entry '" + str + "' resolved to " + address.getAddress().getHostAddress()); } } catch (IOException e) { LOG.severe("Unable to process address " + str, e); } } } return addresses.toArray(new InetSocketAddress[addresses.size()]); } } /** * @return a list of {@link Connector} each bound to a host:port * pair form the list addresses. */ private List<Connector> getSelectChannelConnectors( InetSocketAddress[] httpAddresses) { List<Connector> list = Lists.newArrayList(); String[] excludeCiphers = {"SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"}; SslContextFactory sslContextFactory = null; if (sslEnabled) { Preconditions.checkState(sslKeystorePath != null && !sslKeystorePath.isEmpty(), "SSL Keystore path left blank"); Preconditions.checkState(sslKeystorePassword != null && !sslKeystorePassword.isEmpty(), "SSL Keystore password left blank"); sslContextFactory = new SslContextFactory(sslKeystorePath); sslContextFactory.setKeyStorePassword(sslKeystorePassword); sslContextFactory.setRenegotiationAllowed(false); sslContextFactory.setExcludeCipherSuites(excludeCiphers); // Note: we only actually needed client auth for AuthenticationServlet. // Using Need instead of Want prevents web-sockets from working on // Chrome. sslContextFactory.setWantClientAuth(true); } for (InetSocketAddress address : httpAddresses) { ServerConnector connector; if (sslEnabled) { connector = new ServerConnector(httpServer, sslContextFactory); } else { connector = new ServerConnector(httpServer); } connector.setHost(address.getAddress().getHostAddress()); connector.setPort(address.getPort()); connector.setIdleTimeout(0); list.add(connector); } return list; } @SuppressWarnings("serial") @Singleton public static class WaveWebSocketServlet extends WebSocketServlet { final ServerRpcProvider provider; final int websocketMaxIdleTime; final int websocketMaxMessageSize; @Inject public WaveWebSocketServlet(ServerRpcProvider provider, Config config) { super(); this.provider = provider; this.websocketMaxIdleTime = config.getInt("network.websocket_max_idle_time"); this.websocketMaxMessageSize = config.getInt("network.websocket_max_message_size"); } @SuppressWarnings("cast") @Override public void configure(WebSocketServletFactory factory) { if (websocketMaxIdleTime == 0) { // Jetty does not allow to set infinite timeout. factory.getPolicy().setIdleTimeout(Integer.MAX_VALUE); } else { factory.getPolicy().setIdleTimeout(websocketMaxIdleTime); } factory.getPolicy().setMaxTextMessageSize(websocketMaxMessageSize * 1024 * 1024); factory.setCreator(new WebSocketCreator() { @Override public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) { ParticipantId loggedInUser = provider.sessionManager.getLoggedInUser((HttpSession) req.getSession()); return new WebSocketConnection(loggedInUser, provider).getWebSocketServerChannel(); } }); } } /** * The Atmosphere handler. Dispatchs incoming requests from remote clients to * the right {@link AtmosphereConnection}. * * It handles transport-level events: * * <ul> * <li>Session expiration: close remote clients properly.</li> * <li>Server reboot refusing further operations. Close remote clientes * properly.</li> * <li>Allow reconnection of remote clients if HTTP session is still active * despite the transport failure.</li> * <li>Keep connections opened sending heartbeat signal</li> * <li>Remote clients reconnection on timeout to avoid silent network * failures.</li> * </ul> * * Atmosphere interceptors are set manually here, to avoid duplicated CORS * response headers. * * About session tracking: The session token is expected to be stored as a * cookie by default. In some cases where cookies are not available (Browser * previnting 3rd party cookies,...) the session token can be propagated as a * path element /atmosphere/sessionId. * * * @author pablojan@gmail.com <Pablo Ojanguren> * */ @Singleton @AtmosphereHandlerService(path = "/atmosphere", interceptors = { AtmosphereClientInterceptor.class, org.atmosphere.interceptor.CacheHeadersInterceptor.class, org.atmosphere.interceptor.PaddingAtmosphereInterceptor.class, org.atmosphere.interceptor.AndroidAtmosphereInterceptor.class, org.atmosphere.interceptor.HeartbeatInterceptor.class, org.atmosphere.interceptor.SSEAtmosphereInterceptor.class, org.atmosphere.interceptor.JSONPAtmosphereInterceptor.class, org.atmosphere.interceptor.JavaScriptProtocol.class, org.atmosphere.interceptor.OnDisconnectInterceptor.class, org.atmosphere.interceptor.IdleResourceInterceptor.class, org.atmosphere.interceptor.WebSocketMessageSuspendInterceptor.class, org.atmosphere.interceptor.TrackMessageSizeB64Interceptor.class}, broadcasterCache = UUIDBroadcasterCache.class) public static class WaveAtmosphereService implements AtmosphereHandler { private static final Log LOG = Log.get(WaveAtmosphereService.class); private static final String EXT_CLIENT_VERSION_HEADER = "X-client-version"; /** Header name for extensions of the wave socket protocol */ private static final String EXT_RESPONSE_HEADER = "X-RESPONSE:"; private static final String EXT_RESPONSE_CLIENT_NOT_SUPPORTED = "CLIENT_NOT_SUPPORTED"; private static final String EXT_RESPONSE_INVALID_SESSION = "INVALID_SESSION"; private static final String EXT_RESPONSE_SERVER_EXCEPTION = "SERVER_EXCEPTION"; @Inject public ServerRpcProvider provider; /** * Get the session for the Atmosphere resource based on the session token * passes as path part. * * We ignore cookies explicity here. If request come from an iframe, the * websocket request can send parent's window cookie session causing a * mismatch with session id given in a login request. * * @param resource * @return */ private HttpSession getSession(AtmosphereResource resource) { /* * Cookie[] cookies = resource.getRequest().getCookies(); String * cookieSessionId = null; if (cookies != null) for (Cookie c : cookies) { * if (c.getName().equals(SESSION_COOKIE_NAME)) cookieSessionId = * c.getValue(); } */ // Get the session URL path /atmosphere/<sessionId>:<windowId> String urlToken = null; int lastPathSeparatorIndex = resource.getRequest().getPathInfo().lastIndexOf("/"); if (lastPathSeparatorIndex >= 0) { urlToken = resource.getRequest().getPathInfo().substring(lastPathSeparatorIndex + 1); } // Trust first in the session token passed as URL path. // Inside IFrames, we could get the wrong cookie! if (urlToken != null) { return provider.sessionManager.getSessionFromToken(urlToken); } return null; } @Override public void onRequest(AtmosphereResource resource) throws IOException { // Check if SwellRT client is compatible with server String clientVersionHeader = resource.getRequest().getHeader(EXT_CLIENT_VERSION_HEADER); if ((clientVersionHeader == null) || (!clientVersionHeader.equals(Model.MODEL_VERSION))) { AtmosphereUtil.writeMessage(resource, EXT_RESPONSE_HEADER + EXT_RESPONSE_CLIENT_NOT_SUPPORTED); resource.close(); return; } // Atmosphere requires specialized HttpWindowSession instances. See // SessionServerImpl class. HttpSession httpSession = getSession(resource); HttpWindowSession windowSession = null; if (httpSession != null && httpSession instanceof HttpWindowSession) windowSession = (HttpWindowSession) httpSession; // if (windowSession == null) { AtmosphereUtil.writeMessage(resource, EXT_RESPONSE_HEADER + EXT_RESPONSE_INVALID_SESSION); resource.close(); return; } ParticipantId participantId = provider.sessionManager.getLoggedInUser(httpSession); if (!ATMOSPHERE_CONNECTIONS.containsKey(windowSession)) { ATMOSPHERE_CONNECTIONS .put(windowSession, new AtmosphereConnection(windowSession, provider)); } AtmosphereConnection connection = (AtmosphereConnection) ATMOSPHERE_CONNECTIONS.get(windowSession); try { connection.onRequest(resource, participantId); } catch (Exception e) { LOG.warning("Error handling request for session " + windowSession, e); AtmosphereUtil.writeMessage(resource, EXT_RESPONSE_HEADER + EXT_RESPONSE_SERVER_EXCEPTION); resource.close(); return; } } @Override public void onStateChange(AtmosphereResourceEvent event) throws IOException { AtmosphereResource resource = event.getResource(); HttpSession session = getSession(resource); if (event.isSuspended()) { AtmosphereUtil.writeMessage(resource, event.getMessage()); } else if (event.isCancelled()) { LOG.info("Resource cancelled by remote client, session " + session); } else if (event.isResumedOnTimeout()) { LOG.fine("Resource resumed on timeout, session " + session); } else if (event.isClosedByClient()) { LOG.info("Resource closed by client, session " + session); AtmosphereConnection connection = (AtmosphereConnection) ATMOSPHERE_CONNECTIONS.get(session); if (connection != null) connection.close(); } else if (event.isResumedOnTimeout()) { LOG.info("Resource resumed by timeout, session " + session); } } @Override public void destroy() { // Nothing to do } } /** * Returns the socket the WebSocket server is listening on. */ public SocketAddress getWebSocketAddress() { if (httpServer == null) { return null; } else { ServerConnector c = (ServerConnector)httpServer.getConnectors()[0]; return new InetSocketAddress(c.getHost(), c.getLocalPort()); } } /** * Stops this server. */ public void stopServer() throws IOException { try { httpServer.stop(); // yes, .stop() throws "Exception" } catch (Exception e) { LOG.warning("Fatal error stopping http server.", e); } LOG.fine("server shutdown."); } /** * Register all methods provided by the given service type. */ public void registerService(Service service) { synchronized (registeredServices) { for (MethodDescriptor methodDescriptor : service.getDescriptorForType().getMethods()) { registeredServices.put(methodDescriptor.getInputType(), new RegisteredServiceMethod(service, methodDescriptor)); } } } /** * List of servlets */ List<Pair<String, ServletHolder>> servletRegistry = Lists.newArrayList(); /** * List of filters */ List<Pair<String, Class<? extends Filter>>> filterRegistry = Lists.newArrayList(); /** * Add a servlet to the servlet registry. This servlet will be attached to the * specified URL pattern when the server is started up. * * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * @param servlet the servlet class to bind to the specified paths. * @param initParams the map with init params, can be null or empty. * @return the {@link ServletHolder} that holds the servlet. */ public ServletHolder addServlet(String urlPattern, Class<? extends HttpServlet> servlet, @Nullable Map<String, String> initParams) { ServletHolder servletHolder = new ServletHolder(servlet); if (initParams != null) { servletHolder.setInitParameters(initParams); } servletRegistry.add(Pair.of(urlPattern, servletHolder)); return servletHolder; } /** * Add a servlet to the servlet registry. This servlet will be attached to the * specified URL pattern when the server is started up. * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * @param servlet the servlet class to bind to the specified paths. * @return the {@link ServletHolder} that holds the servlet. */ public ServletHolder addServlet(String urlPattern, Class<? extends HttpServlet> servlet) { return addServlet(urlPattern, servlet, null); } /** * Add a filter to the filter registry. This filter will be attached to the * specified URL pattern when the server is started up. * * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * */ public void addFilter(String urlPattern, Class<? extends Filter> filter) { filterRegistry.add(new Pair<String, Class<? extends Filter>>(urlPattern, filter)); } /** * Add a transparent proxy to the servlet registry. The servlet will proxy to the * specified URL pattern. * For example: addTransparentProxy("/gadgets/*","http://gmodules:80/gadgets", "/gadgets") * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * @param proxyTo the URL to proxy to. * @param prefix the prefix that should be proxied. */ public void addTransparentProxy(String urlPattern, String proxyTo, String prefix) { Preconditions.checkNotNull(urlPattern); Preconditions.checkNotNull(proxyTo); Preconditions.checkNotNull(prefix); ServletHolder proxy = new ServletHolder(ProxyServlet.Transparent.class); proxy.setInitParameter("proxyTo", proxyTo); proxy.setInitParameter("prefix", prefix); servletRegistry.add(Pair.of(urlPattern, proxy)); } }
wave/src/main/java/org/waveprotocol/box/server/rpc/ServerRpcProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.waveprotocol.box.server.rpc; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.google.inject.servlet.GuiceFilter; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.Message; import com.google.protobuf.RpcCallback; import com.google.protobuf.Service; import com.typesafe.config.Config; import org.apache.commons.lang.StringUtils; import org.atmosphere.cache.UUIDBroadcasterCache; import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.*; import org.atmosphere.cpr.AtmosphereResource.TRANSPORT; import org.atmosphere.guice.AtmosphereGuiceServlet; import org.atmosphere.util.IOUtils; import org.eclipse.jetty.proxy.ProxyServlet; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.session.HashSessionManager; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.eclipse.jetty.servlets.GzipFilter; import org.eclipse.jetty.util.resource.ResourceCollection; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.websocket.servlet.*; import org.swellrt.model.generic.Model; import org.waveprotocol.box.common.comms.WaveClientRpc.ProtocolAuthenticate; import org.waveprotocol.box.common.comms.WaveClientRpc.ProtocolAuthenticationResult; import org.waveprotocol.box.server.authentication.HttpWindowSession; import org.waveprotocol.box.server.authentication.SessionManager; import org.waveprotocol.box.server.executor.ExecutorAnnotations.ClientServerExecutor; import org.waveprotocol.box.server.persistence.file.FileUtils; import org.waveprotocol.box.server.rpc.atmosphere.AtmosphereChannel; import org.waveprotocol.box.server.rpc.atmosphere.AtmosphereClientInterceptor; import org.waveprotocol.box.server.rpc.atmosphere.AtmosphereUtil; import org.waveprotocol.box.server.util.NetUtils; import org.waveprotocol.box.stat.Timer; import org.waveprotocol.box.stat.Timing; import org.waveprotocol.wave.model.util.Pair; import org.waveprotocol.wave.model.wave.ParticipantId; import org.waveprotocol.wave.util.logging.Log; import javax.annotation.Nullable; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.ServletContextListener; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; /** * ServerRpcProvider can provide instances of type Service over an incoming * network socket and service incoming RPCs to these services and their methods. * * */ public class ServerRpcProvider { private static final Log LOG = Log.get(ServerRpcProvider.class); /** * The buffer size is passed to implementations of {@link WaveWebSocketServlet} as init * param. It defines the response buffer size. */ private static final int BUFFER_SIZE = 1024 * 1024; private final InetSocketAddress[] httpAddresses; private final Executor threadPool; private final SessionManager sessionManager; private final org.eclipse.jetty.server.SessionManager jettySessionManager; private Server httpServer = null; private final boolean sslEnabled; private final String sslKeystorePath; private final String sslKeystorePassword; private static ConcurrentHashMap<HttpWindowSession, Connection> ATMOSPHERE_CONNECTIONS = new ConcurrentHashMap<HttpWindowSession, Connection>(); // Mapping from incoming protocol buffer type -> specific handler. private final Map<Descriptors.Descriptor, RegisteredServiceMethod> registeredServices = Maps.newHashMap(); // List of webApp source directories ("./war", etc) private final String[] resourceBases; private final String sessionStoreDir; private int webSocketMaxIdleTime; private int webSocketMaxMessageSize; private int websocketHeartbeat; private final int sessionMaxInactiveTime; private final static String SESSION_URL_PARAM = "sid"; private final static String SESSION_COOKIE_NAME = "WSESSIONID"; /** * Internal, static container class for any specific registered service * method. */ static class RegisteredServiceMethod { final Service service; final MethodDescriptor method; RegisteredServiceMethod(Service service, MethodDescriptor method) { this.service = service; this.method = method; } } static class WebSocketConnection extends Connection { private final WebSocketChannel socketChannel; WebSocketConnection(ParticipantId loggedInUser, ServerRpcProvider provider) { super(loggedInUser, provider); socketChannel = new WebSocketChannelImpl(this); LOG.info("New websocket connection set up for user " + loggedInUser); expectMessages(socketChannel); } @Override protected void sendMessage(int sequenceNo, Message message) { socketChannel.sendMessage(sequenceNo, message); } public WebSocketChannel getWebSocketServerChannel() { return socketChannel; } } /** * The glue class between the Atmoshphere Framework (communication layer) and * the RPCs for each remote client. * * A connection is associated with an unique pair (HTTP session, browser * window/tab), the {@link HttpWindowSession} * * This implementation supports WebSockets and Long-Polling transports over * Atmosphere. * * * @author pablojan@gmail.com (Pablo Ojanguren) * */ static class AtmosphereConnection extends Connection { private final AtmosphereChannel atmosphereChannel; private HttpWindowSession id; private Broadcaster broadcaster; private TRANSPORT transport; public AtmosphereConnection(HttpWindowSession id, ServerRpcProvider provider) { super(null, provider); this.id = id; this.broadcaster = BroadcasterFactory.getDefault().get(this.id.toString()); atmosphereChannel = new AtmosphereChannel(this, broadcaster); expectMessages(atmosphereChannel); } /** * Handle an incoming request through an {@link AtmosphereResource}. * * @param resource the resource with the incoming message or new connection * signal */ public void onRequest(AtmosphereResource resource, ParticipantId loggedInUser) { // Update current transport this.transport = resource.transport(); if (isWebSocket(this.transport)) { if (isGET(resource)) { // New connection resource.setBroadcaster(broadcaster); resource.suspend(); } if (isPOST(resource)) { String data = AtmosphereUtil.readMessage(resource); atmosphereChannel.handleMessageString(data, loggedInUser); } } /* * Responses are always sent back through the GET request (resource). POST * requests are released as soon as the request has been delivered */ if (isLongPolling(this.transport)) { if (isGET(resource)) { // New connection resource.suspend(); broadcaster.addAtmosphereResource(resource); } if (isPOST(resource)) { String data = AtmosphereUtil.readMessage(resource); atmosphereChannel.handleMessageString(data, loggedInUser); resource.resume(); } } } /** * Closes the connection and its RPCs. This method must be invoked when * client closes the communication. */ public void close() { this.cancelRpcs(); for (AtmosphereResource r : this.broadcaster.getAtmosphereResources()) { try { r.close(); } catch (IOException e) { LOG.warning("Error closing resource on session " + id, e); } } this.broadcaster.destroy(); } // // Send back // @Override protected void sendMessage(int sequenceNo, Message message) { atmosphereChannel.sendMessage(sequenceNo, message); if (isLongPolling(transport)) { broadcaster.resumeAll(); } } // // Utility methods // protected static boolean isWebSocket(TRANSPORT transport) { return transport.equals(TRANSPORT.WEBSOCKET); } protected static boolean isLongPolling(TRANSPORT transport) { return transport.equals(TRANSPORT.LONG_POLLING) || transport.equals(TRANSPORT.POLLING); } protected static boolean isGET(AtmosphereResource r) { return r.getRequest().getMethod().equalsIgnoreCase("GET"); } protected static boolean isPOST(AtmosphereResource r) { return r.getRequest().getMethod().equalsIgnoreCase("POST"); } } static abstract class Connection implements ProtoCallback { private final Map<Integer, ServerRpcController> activeRpcs = new ConcurrentHashMap<Integer, ServerRpcController>(); // The logged in user. // Note: Due to this bug: // http://code.google.com/p/wave-protocol/issues/detail?id=119, // the field may be null on first connect and then set later using an RPC. private ParticipantId loggedInUser; private final ServerRpcProvider provider; private boolean isFirstRequest = true; private boolean isStatusOk = true; /** * @param loggedInUser The currently logged in user, or null if no user is * logged in. * @param provider the provider */ public Connection(ParticipantId loggedInUser, ServerRpcProvider provider) { this.loggedInUser = loggedInUser; this.provider = provider; } protected void expectMessages(MessageExpectingChannel channel) { synchronized (provider.registeredServices) { for (RegisteredServiceMethod serviceMethod : provider.registeredServices.values()) { channel.expectMessage(serviceMethod.service.getRequestPrototype(serviceMethod.method)); LOG.fine("Expecting: " + serviceMethod.method.getFullName()); } } channel.expectMessage(Rpc.CancelRpc.getDefaultInstance()); } protected abstract void sendMessage(int sequenceNo, Message message); private ParticipantId authenticate(String token) { HttpSession session = provider.sessionManager.getSessionFromToken(token); ParticipantId user = provider.sessionManager.getLoggedInUser(session); return user; } protected boolean isStatusOk() { return isStatusOk; } public ParticipantId getParticipantId() { return loggedInUser; } protected void cancelRpcs() { if (!activeRpcs.isEmpty()) { LOG.info("Cleaning up RPCs"); for (ServerRpcController controller : activeRpcs.values()) { if (!controller.isCanceled()) { controller.cancel(); } } activeRpcs.clear(); } } @Override public void message(final int sequenceNo, Message message, ParticipantId loggedInUser) { final String messageName = "/" + message.getClass().getSimpleName(); final Timer profilingTimer = Timing.startRequest(messageName); if (isFirstRequest && sequenceNo != 0) { // On server's reboot, clients can get reconnected (sequenceNo !=0) but // server won't be able to process the request. LOG.info("First RPC request but sequence number >0"); throw new IllegalStateException("First RPC request nut sequence number >0"); } isFirstRequest = false; // Clean up ServerRpcControllers if remote client starts a new // sequence of protocol messages. // This allows dirty reconnections, resuming current sessions... // This should been handle before, detecting new logins for the same if (sequenceNo == 0) { // Don't update on null to keep backwards compat. if (loggedInUser != null) this.loggedInUser = loggedInUser; cancelRpcs(); } else { if (!this.loggedInUser.equals(loggedInUser)) { LOG.info("Request's participant doesn't match connection's participant. Spoofing?"); throw new IllegalStateException( "Request's participant doesn't match connection's participant."); } } if (message instanceof Rpc.CancelRpc) { final ServerRpcController controller = activeRpcs.get(sequenceNo); if (controller == null) { throw new IllegalStateException("Trying to cancel an RPC that is not active!"); } else { LOG.info("Cancelling open RPC " + sequenceNo); controller.cancel(); } } else if (message instanceof ProtocolAuthenticate) { // Workaround for bug: http://codereview.waveprotocol.org/224001/ // When we get this message, either the connection will not be logged in // (loggedInUser == null) or the connection will have been authenticated // via cookies // (in which case loggedInUser must match the authenticated user, and // this message has no // effect). ProtocolAuthenticate authMessage = (ProtocolAuthenticate) message; ParticipantId authenticatedAs = authenticate(authMessage.getToken()); Preconditions.checkArgument(authenticatedAs != null, "Auth token invalid"); sendMessage(sequenceNo, ProtocolAuthenticationResult.getDefaultInstance()); } else if (provider.registeredServices.containsKey(message.getDescriptorForType())) { if (activeRpcs.containsKey(sequenceNo)) { throw new IllegalStateException( "Can't invoke a new RPC with a sequence number already in use."); } else { final RegisteredServiceMethod serviceMethod = provider.registeredServices.get(message.getDescriptorForType()); // Create the internal ServerRpcController used to invoke the call. final ServerRpcController controller = new ServerRpcControllerImpl(message, serviceMethod.service, serviceMethod.method, loggedInUser, new RpcCallback<Message>() { @Override synchronized public void run(Message message) { if (message instanceof Rpc.RpcFinished || !serviceMethod.method.getOptions().getExtension(Rpc.isStreamingRpc)) { // This RPC is over - remove it from the map. boolean failed = message instanceof Rpc.RpcFinished && ((Rpc.RpcFinished) message).getFailed(); LOG.fine("RPC " + sequenceNo + " is now finished, failed = " + failed); if (failed) { LOG.info("error = " + ((Rpc.RpcFinished) message).getErrorText()); } activeRpcs.remove(sequenceNo); } sendMessage(sequenceNo, message); if (profilingTimer != null) { Timing.stop(profilingTimer); } } }); // Kick off a new thread specific to this RPC. activeRpcs.put(sequenceNo, controller); provider.threadPool.execute(controller); } } else { // Sent a message type we understand, but don't expect - erronous case! throw new IllegalStateException( "Got expected but unknown message (" + message + ") for sequence: " + sequenceNo); } } } /** * Construct a new ServerRpcProvider, hosting on the specified * WebSocket addresses. * * Also accepts an ExecutorService for spawning managing threads. */ public ServerRpcProvider(InetSocketAddress[] httpAddresses, String[] resourceBases, Executor threadPool, SessionManager sessionManager, org.eclipse.jetty.server.SessionManager jettySessionManager, String sessionStoreDir, boolean sslEnabled, String sslKeystorePath, String sslKeystorePassword, int webSocketMaxIdleTime, int webSocketMaxMessageSize, int websocketHeartbeat, int sessionMaxInactiveTime) { this.httpAddresses = httpAddresses; this.resourceBases = resourceBases; this.threadPool = threadPool; this.sessionManager = sessionManager; this.jettySessionManager = jettySessionManager; this.sessionStoreDir = sessionStoreDir; this.sslEnabled = sslEnabled; this.sslKeystorePath = sslKeystorePath; this.sslKeystorePassword = sslKeystorePassword; this.webSocketMaxIdleTime = webSocketMaxIdleTime; this.webSocketMaxMessageSize = webSocketMaxMessageSize; this.websocketHeartbeat = websocketHeartbeat; this.sessionMaxInactiveTime = sessionMaxInactiveTime; } /** * Constructs a new ServerRpcProvider with a default ExecutorService. */ public ServerRpcProvider(InetSocketAddress[] httpAddresses, String[] resourceBases, SessionManager sessionManager, org.eclipse.jetty.server.SessionManager jettySessionManager, String sessionStoreDir, boolean sslEnabled, String sslKeystorePath, String sslKeystorePassword, Executor executor, int webSocketMaxIdleTime, int webSocketMaxMessageSize, int websocketHeartbeat, int sessionMaxInactiveTime) { this(httpAddresses, resourceBases, executor, sessionManager, jettySessionManager, sessionStoreDir, sslEnabled, sslKeystorePath, sslKeystorePassword, webSocketMaxIdleTime, webSocketMaxMessageSize, websocketHeartbeat, sessionMaxInactiveTime); } @Inject public ServerRpcProvider(Config config, SessionManager sessionManager, org.eclipse.jetty.server.SessionManager jettySessionManager, @ClientServerExecutor Executor executorService) { this(parseAddressList(config.getStringList("core.http_frontend_addresses"), config.getString("core.http_websocket_public_address")), config.getStringList("core.resource_bases").toArray(new String[0]), sessionManager, jettySessionManager, config.getString("core.sessions_store_directory"), config.getBoolean("security.enable_ssl"), config.getString("security.ssl_keystore_path"), config.getString("security.ssl_keystore_password"), executorService, config.getInt("network.websocket_max_idle_time"), config.getInt("network.websocket_max_message_size"), config.getInt("network.websocket_heartbeat"), config.getInt("network.session_max_inactive_time") ); } public void startWebSocketServer(final Injector injector) { httpServer = new Server(); List<Connector> connectors = getSelectChannelConnectors(httpAddresses); if (connectors.isEmpty()) { LOG.severe("No valid http end point address provided!"); } for (Connector connector : connectors) { httpServer.addConnector(connector); } final WebAppContext context = new WebAppContext(); context.setParentLoaderPriority(true); if (jettySessionManager != null) { context.getSessionHandler().setSessionManager(jettySessionManager); context.getSessionHandler().getSessionManager() .setMaxInactiveInterval(sessionMaxInactiveTime); Set<SessionTrackingMode> sessionTrackingModes = new HashSet<SessionTrackingMode>(); sessionTrackingModes.add(SessionTrackingMode.URL); sessionTrackingModes.add(SessionTrackingMode.COOKIE); context.getSessionHandler().getSessionManager().setSessionTrackingModes(sessionTrackingModes); context.getSessionHandler().getSessionManager() .setSessionIdPathParameterName(SESSION_URL_PARAM); } final ResourceCollection resources = new ResourceCollection(resourceBases); context.setBaseResource(resources); context.setInitParameter("org.eclipse.jetty.servlet.SessionCookie", SESSION_COOKIE_NAME); FilterHolder corsFilterHolder = new FilterHolder(CrossOriginFilter.class); corsFilterHolder.setInitParameter("allowedOrigins", "*"); // Set explicit methods to allow CORS with DELETE corsFilterHolder.setInitParameter("allowedMethods", "GET,POST,DELETE,PUT,HEAD"); corsFilterHolder.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin,X-window-id"); context.addFilter(corsFilterHolder, "/*", EnumSet.allOf(DispatcherType.class)); // Set cache header rewriter filter FilterHolder cacheFilterHolder = new FilterHolder(CacheHeaderFilter.class); context.addFilter(cacheFilterHolder, "/*", EnumSet.allOf(DispatcherType.class)); addWebSocketServlets(); try { final ServletModule servletModule = getServletModule(); ServletContextListener contextListener = new GuiceServletContextListener() { private final Injector childInjector = injector.createChildInjector(servletModule); @Override protected Injector getInjector() { return childInjector; } }; context.addEventListener(contextListener); context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class)); context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class)); httpServer.setHandler(context); httpServer.start(); restoreSessions(); } catch (Exception e) { // yes, .start() throws "Exception" LOG.severe("Fatal error starting http server.", e); return; } LOG.fine("WebSocket server running."); } private void restoreSessions() { try { HashSessionManager hashSessionManager = (HashSessionManager) jettySessionManager; hashSessionManager.setStoreDirectory(FileUtils.createDirIfNotExists(sessionStoreDir, "Session persistence")); hashSessionManager.setSavePeriod(60); hashSessionManager.restoreSessions(); } catch (Exception e) { LOG.warning("Cannot restore sessions"); } } public void addWebSocketServlets() { // Servlet where the websocket connection is served from. // ServletHolder wsholder = addServlet("/socket", WaveWebSocketServlet.class); // TODO(zamfi): fix to let messages span frames. // wsholder.setInitParameter("bufferSize", "" + BUFFER_SIZE); // // Atmosphere framework. Replacement of Socket.IO // See https://issues.apache.org/jira/browse/WAVE-405 // ServletHolder atholder = addServlet("/atmosphere*", AtmosphereGuiceServlet.class); // Avoid loading defualt CORS interceptor which is in conflict with general // jetty CORS filter atholder.setInitParameter("org.atmosphere.cpr.AtmosphereInterceptor.disableDefaults", "true"); // Setting a low HeartBeat frequency to avoid network issues. Let clients to // set a hihger value. atholder.setInitParameter( "org.atmosphere.interceptor.HeartbeatInterceptor.heartbeatFrequencyInSeconds", "" + websocketHeartbeat); // // Configure Atmosphere Broadcaster class // // Comment out following line to enable Threaded broadcasters atholder.setInitParameter("org.atmosphere.cpr.broadcasterClass", "org.atmosphere.util.SimpleBroadcaster"); // // Configuring Atmosphere threads: this config is considered if // SimpleBroadcaster is not used // // Use same thread pool for all brodcaster (AtmosphereConnection) atholder.setInitParameter("org.atmosphere.cpr.broadcaster.shareableThreadPool", "true"); // Set number of threads for atmosphere atholder.setInitParameter("org.atmosphere.cpr.broadcaster.maxProcessingThreads", "4"); // Setting all buffers at least to 2MB atholder.setInitParameter("org.atmosphere.websocket.maxTextMessageSize", "" + (BUFFER_SIZE * webSocketMaxMessageSize)); atholder.setInitParameter("org.atmosphere.websocket.maxBinaryMessageSize", "" + (BUFFER_SIZE * webSocketMaxMessageSize)); atholder.setInitParameter("org.atmosphere.websocket.webSocketBufferingMaxSize", "" + (BUFFER_SIZE * webSocketMaxMessageSize)); // Enable guice. See // https://github.com/Atmosphere/atmosphere/wiki/Configuring-Atmosphere%27s-Classes-Creation-and-Injection atholder.setInitParameter("org.atmosphere.cpr.objectFactory", "org.waveprotocol.box.server.rpc.atmosphere.GuiceAtmosphereFactory"); atholder.setAsyncSupported(true); atholder.setInitOrder(0); // Serve the static content and GWT web client with the default servlet // (acts like a standard file-based web server). // addServlet("/static/*", DefaultServlet.class); // addServlet("/webclient/*", DefaultServlet.class); } public ServletModule getServletModule() { return new ServletModule() { @Override protected void configureServlets() { // We add servlets here to override the DefaultServlet automatic registered by WebAppContext // in path "/" with our WaveClientServlet. Any other way to do this? // Related question (unanswered 08-Apr-2011) // http://web.archiveorange.com/archive/v/d0LdlXf1kN0OXyPNyQZp for (Pair<String, ServletHolder> servlet : servletRegistry) { String url = servlet.getFirst(); @SuppressWarnings("unchecked") Class<HttpServlet> clazz = (Class<HttpServlet>) servlet.getSecond().getHeldClass(); Map<String,String> params = servlet.getSecond().getInitParameters(); serve(url).with(clazz,params); bind(clazz).in(Singleton.class); } for (Pair<String, Class<? extends Filter>> filter : filterRegistry) { filter(filter.first).through(filter.second); } } }; } private static InetSocketAddress[] parseAddressList(List<String> addressList, String websocketAddress) { if (addressList == null || addressList.size() == 0) { return new InetSocketAddress[0]; } else { Set<InetSocketAddress> addresses = Sets.newHashSet(); // We add the websocketAddress as another listening address. ArrayList<String> mergedAddressList = new ArrayList<>(addressList); if (!StringUtils.isEmpty(websocketAddress)) { mergedAddressList.add(websocketAddress); } for (String str : mergedAddressList) { if (str.length() == 0) { LOG.warning("Encountered empty address in http addresses list."); } else { try { InetSocketAddress address = NetUtils.parseHttpAddress(str); if (!addresses.contains(address)) { addresses.add(address); } else { LOG.warning( "Ignoring duplicate address in http addresses list: Duplicate entry '" + str + "' resolved to " + address.getAddress().getHostAddress()); } } catch (IOException e) { LOG.severe("Unable to process address " + str, e); } } } return addresses.toArray(new InetSocketAddress[addresses.size()]); } } /** * @return a list of {@link Connector} each bound to a host:port * pair form the list addresses. */ private List<Connector> getSelectChannelConnectors( InetSocketAddress[] httpAddresses) { List<Connector> list = Lists.newArrayList(); String[] excludeCiphers = {"SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"}; SslContextFactory sslContextFactory = null; if (sslEnabled) { Preconditions.checkState(sslKeystorePath != null && !sslKeystorePath.isEmpty(), "SSL Keystore path left blank"); Preconditions.checkState(sslKeystorePassword != null && !sslKeystorePassword.isEmpty(), "SSL Keystore password left blank"); sslContextFactory = new SslContextFactory(sslKeystorePath); sslContextFactory.setKeyStorePassword(sslKeystorePassword); sslContextFactory.setRenegotiationAllowed(false); sslContextFactory.setExcludeCipherSuites(excludeCiphers); // Note: we only actually needed client auth for AuthenticationServlet. // Using Need instead of Want prevents web-sockets from working on // Chrome. sslContextFactory.setWantClientAuth(true); } for (InetSocketAddress address : httpAddresses) { ServerConnector connector; if (sslEnabled) { connector = new ServerConnector(httpServer, sslContextFactory); } else { connector = new ServerConnector(httpServer); } connector.setHost(address.getAddress().getHostAddress()); connector.setPort(address.getPort()); connector.setIdleTimeout(0); list.add(connector); } return list; } @SuppressWarnings("serial") @Singleton public static class WaveWebSocketServlet extends WebSocketServlet { final ServerRpcProvider provider; final int websocketMaxIdleTime; final int websocketMaxMessageSize; @Inject public WaveWebSocketServlet(ServerRpcProvider provider, Config config) { super(); this.provider = provider; this.websocketMaxIdleTime = config.getInt("network.websocket_max_idle_time"); this.websocketMaxMessageSize = config.getInt("network.websocket_max_message_size"); } @SuppressWarnings("cast") @Override public void configure(WebSocketServletFactory factory) { if (websocketMaxIdleTime == 0) { // Jetty does not allow to set infinite timeout. factory.getPolicy().setIdleTimeout(Integer.MAX_VALUE); } else { factory.getPolicy().setIdleTimeout(websocketMaxIdleTime); } factory.getPolicy().setMaxTextMessageSize(websocketMaxMessageSize * 1024 * 1024); factory.setCreator(new WebSocketCreator() { @Override public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) { ParticipantId loggedInUser = provider.sessionManager.getLoggedInUser((HttpSession) req.getSession()); return new WebSocketConnection(loggedInUser, provider).getWebSocketServerChannel(); } }); } } /** * The Atmosphere handler. Dispatchs incoming requests from remote clients to * the right {@link AtmosphereConnection}. * * It handles transport-level events: * * <ul> * <li>Session expiration: close remote clients properly.</li> * <li>Server reboot refusing further operations. Close remote clientes * properly.</li> * <li>Allow reconnection of remote clients if HTTP session is still active * despite the transport failure.</li> * <li>Keep connections opened sending heartbeat signal</li> * <li>Remote clients reconnection on timeout to avoid silent network * failures.</li> * </ul> * * Atmosphere interceptors are set manually here, to avoid duplicated CORS * response headers. * * About session tracking: The session token is expected to be stored as a * cookie by default. In some cases where cookies are not available (Browser * previnting 3rd party cookies,...) the session token can be propagated as a * path element /atmosphere/sessionId. * * * @author pablojan@gmail.com <Pablo Ojanguren> * */ @Singleton @AtmosphereHandlerService(path = "/atmosphere", interceptors = { AtmosphereClientInterceptor.class, org.atmosphere.interceptor.CacheHeadersInterceptor.class, org.atmosphere.interceptor.PaddingAtmosphereInterceptor.class, org.atmosphere.interceptor.AndroidAtmosphereInterceptor.class, org.atmosphere.interceptor.HeartbeatInterceptor.class, org.atmosphere.interceptor.SSEAtmosphereInterceptor.class, org.atmosphere.interceptor.JSONPAtmosphereInterceptor.class, org.atmosphere.interceptor.JavaScriptProtocol.class, org.atmosphere.interceptor.OnDisconnectInterceptor.class, org.atmosphere.interceptor.IdleResourceInterceptor.class, org.atmosphere.interceptor.WebSocketMessageSuspendInterceptor.class, org.atmosphere.interceptor.TrackMessageSizeB64Interceptor.class}, broadcasterCache = UUIDBroadcasterCache.class) public static class WaveAtmosphereService implements AtmosphereHandler { private static final Log LOG = Log.get(WaveAtmosphereService.class); private static final String EXT_CLIENT_VERSION_HEADER = "X-client-version"; /** Header name for extensions of the wave socket protocol */ private static final String EXT_RESPONSE_HEADER = "X-RESPONSE:"; private static final String EXT_RESPONSE_CLIENT_NOT_SUPPORTED = "CLIENT_NOT_SUPPORTED"; private static final String EXT_RESPONSE_INVALID_SESSION = "INVALID_SESSION"; private static final String EXT_RESPONSE_SERVER_EXCEPTION = "SERVER_EXCEPTION"; @Inject public ServerRpcProvider provider; /** * Get the session for the Atmosphere resource based on the session token * passes as path part. * * We ignore cookies explicity here. If request come from an iframe, the * websocket request can send parent's window cookie session causing a * mismatch with session id given in a login request. * * @param resource * @return */ private HttpSession getSession(AtmosphereResource resource) { /* * Cookie[] cookies = resource.getRequest().getCookies(); String * cookieSessionId = null; if (cookies != null) for (Cookie c : cookies) { * if (c.getName().equals(SESSION_COOKIE_NAME)) cookieSessionId = * c.getValue(); } */ // Get the session URL path /atmosphere/<sessionId>:<windowId> String urlToken = null; int lastPathSeparatorIndex = resource.getRequest().getPathInfo().lastIndexOf("/"); if (lastPathSeparatorIndex >= 0) { urlToken = resource.getRequest().getPathInfo().substring(lastPathSeparatorIndex + 1); } // Trust first in the session token passed as URL path. // Inside IFrames, we could get the wrong cookie! if (urlToken != null) { return provider.sessionManager.getSessionFromToken(urlToken); } return null; } @Override public void onRequest(AtmosphereResource resource) throws IOException { // Check if SwellRT client is compatible with server String clientVersionHeader = resource.getRequest().getHeader(EXT_CLIENT_VERSION_HEADER); if ((clientVersionHeader == null) || (!clientVersionHeader.equals(Model.MODEL_VERSION))) { AtmosphereUtil.writeMessage(resource, EXT_RESPONSE_HEADER + EXT_RESPONSE_CLIENT_NOT_SUPPORTED); resource.close(); return; } // Atmosphere requires specialized HttpWindowSession instances. See // SessionServerImpl class. HttpSession httpSession = getSession(resource); HttpWindowSession windowSession = null; if (httpSession != null && httpSession instanceof HttpWindowSession) windowSession = (HttpWindowSession) httpSession; // if (windowSession == null) { AtmosphereUtil.writeMessage(resource, EXT_RESPONSE_HEADER + EXT_RESPONSE_INVALID_SESSION); resource.close(); return; } ParticipantId participantId = provider.sessionManager.getLoggedInUser(httpSession); if (!ATMOSPHERE_CONNECTIONS.containsKey(windowSession)) { ATMOSPHERE_CONNECTIONS .put(windowSession, new AtmosphereConnection(windowSession, provider)); } AtmosphereConnection connection = (AtmosphereConnection) ATMOSPHERE_CONNECTIONS.get(windowSession); try { connection.onRequest(resource, participantId); } catch (Exception e) { LOG.warning("Error handling request for session " + windowSession, e); AtmosphereUtil.writeMessage(resource, EXT_RESPONSE_HEADER + EXT_RESPONSE_SERVER_EXCEPTION); resource.close(); return; } } @Override public void onStateChange(AtmosphereResourceEvent event) throws IOException { AtmosphereResource resource = event.getResource(); HttpSession session = getSession(resource); if (event.isSuspended()) { AtmosphereUtil.writeMessage(resource, event.getMessage()); } else if (event.isCancelled()) { LOG.info("Resource cancelled by remote client, session " + session); } else if (event.isResumedOnTimeout()) { LOG.fine("Resource resumed on timeout, session " + session); } else if (event.isClosedByClient()) { LOG.info("Resource closed by client, session " + session); AtmosphereConnection connection = (AtmosphereConnection) ATMOSPHERE_CONNECTIONS.get(session); if (connection != null) connection.close(); } else if (event.isResumedOnTimeout()) { LOG.info("Resource resumed by timeout, session " + session); } } @Override public void destroy() { // Nothing to do } } /** * Returns the socket the WebSocket server is listening on. */ public SocketAddress getWebSocketAddress() { if (httpServer == null) { return null; } else { ServerConnector c = (ServerConnector)httpServer.getConnectors()[0]; return new InetSocketAddress(c.getHost(), c.getLocalPort()); } } /** * Stops this server. */ public void stopServer() throws IOException { try { httpServer.stop(); // yes, .stop() throws "Exception" } catch (Exception e) { LOG.warning("Fatal error stopping http server.", e); } LOG.fine("server shutdown."); } /** * Register all methods provided by the given service type. */ public void registerService(Service service) { synchronized (registeredServices) { for (MethodDescriptor methodDescriptor : service.getDescriptorForType().getMethods()) { registeredServices.put(methodDescriptor.getInputType(), new RegisteredServiceMethod(service, methodDescriptor)); } } } /** * List of servlets */ List<Pair<String, ServletHolder>> servletRegistry = Lists.newArrayList(); /** * List of filters */ List<Pair<String, Class<? extends Filter>>> filterRegistry = Lists.newArrayList(); /** * Add a servlet to the servlet registry. This servlet will be attached to the * specified URL pattern when the server is started up. * * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * @param servlet the servlet class to bind to the specified paths. * @param initParams the map with init params, can be null or empty. * @return the {@link ServletHolder} that holds the servlet. */ public ServletHolder addServlet(String urlPattern, Class<? extends HttpServlet> servlet, @Nullable Map<String, String> initParams) { ServletHolder servletHolder = new ServletHolder(servlet); if (initParams != null) { servletHolder.setInitParameters(initParams); } servletRegistry.add(Pair.of(urlPattern, servletHolder)); return servletHolder; } /** * Add a servlet to the servlet registry. This servlet will be attached to the * specified URL pattern when the server is started up. * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * @param servlet the servlet class to bind to the specified paths. * @return the {@link ServletHolder} that holds the servlet. */ public ServletHolder addServlet(String urlPattern, Class<? extends HttpServlet> servlet) { return addServlet(urlPattern, servlet, null); } /** * Add a filter to the filter registry. This filter will be attached to the * specified URL pattern when the server is started up. * * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * */ public void addFilter(String urlPattern, Class<? extends Filter> filter) { filterRegistry.add(new Pair<String, Class<? extends Filter>>(urlPattern, filter)); } /** * Add a transparent proxy to the servlet registry. The servlet will proxy to the * specified URL pattern. * For example: addTransparentProxy("/gadgets/*","http://gmodules:80/gadgets", "/gadgets") * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'. * @param proxyTo the URL to proxy to. * @param prefix the prefix that should be proxied. */ public void addTransparentProxy(String urlPattern, String proxyTo, String prefix) { Preconditions.checkNotNull(urlPattern); Preconditions.checkNotNull(proxyTo); Preconditions.checkNotNull(prefix); ServletHolder proxy = new ServletHolder(ProxyServlet.Transparent.class); proxy.setInitParameter("proxyTo", proxyTo); proxy.setInitParameter("prefix", prefix); servletRegistry.add(Pair.of(urlPattern, proxy)); } }
Moving to gradle. Enable jetty websockets for unit testing
wave/src/main/java/org/waveprotocol/box/server/rpc/ServerRpcProvider.java
Moving to gradle. Enable jetty websockets for unit testing
Java
apache-2.0
a6e703df9e0a9e190f2f30eec84766b4745044cc
0
dimagi/commcare-core,dimagi/commcare-core,dimagi/commcare,dimagi/commcare,dimagi/commcare,dimagi/commcare-core
package org.javarosa.patient.util; import java.util.Vector; import org.javarosa.core.model.IDataReference; import org.javarosa.core.model.IFormDataModel; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.IntegerData; import org.javarosa.core.model.utils.IPreloadHandler; import org.javarosa.patient.model.Patient; import org.javarosa.patient.model.data.ImmunizationAnswerData; import org.javarosa.patient.model.data.ImmunizationData; import org.javarosa.patient.model.data.NumericListData; public class PatientPreloadHandler implements IPreloadHandler { /** The patient for this handler */ private Patient patient; /** * Creates a preload handler that can pull values from * the patient object provided. * * @param thePatient the patient whose data is to be * retrevied from this preload handler */ public PatientPreloadHandler(Patient thePatient) { patient = thePatient; } /** * */ public IAnswerData handlePreload(String preloadParams) { IAnswerData returnVal = null; /*if(preloadParams == "monthsOnTreatment") { //TODO: Get actual data from patient returnVal = new IntegerData(12); } else*/ if("vaccination_table".equals(preloadParams)) { returnVal = new ImmunizationAnswerData(patient.getVaccinations()); } else { int selectorStart = preloadParams.indexOf("["); if(selectorStart == -1) { returnVal = (IAnswerData)patient.getRecord(preloadParams); } else { String type = preloadParams.substring(0, selectorStart); String selector = preloadParams.substring(selectorStart, preloadParams.length()); Vector data = patient.getRecordSet(type, selector); returnVal = new NumericListData(); returnVal.setValue(data); } } return returnVal; } public boolean handlePostProcess(IFormDataModel model, IDataReference ref, String params) { IAnswerData data = model.getDataValue(ref); if ("vaccination_table".equals(params)) { patient.setVaccinations((ImmunizationData)data); return true; } else { } return false; } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IPreloadHandler#preloadHandled() */ public String preloadHandled() { return "patient"; } }
org.javarosa.patient/src/org/javarosa/patient/util/PatientPreloadHandler.java
package org.javarosa.patient.util; import java.util.Vector; import org.javarosa.core.model.IDataReference; import org.javarosa.core.model.IFormDataModel; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.IntegerData; import org.javarosa.core.model.utils.IPreloadHandler; import org.javarosa.patient.model.Patient; import org.javarosa.patient.model.data.ImmunizationAnswerData; import org.javarosa.patient.model.data.NumericListData; public class PatientPreloadHandler implements IPreloadHandler { /** The patient for this handler */ private Patient patient; /** * Creates a preload handler that can pull values from * the patient object provided. * * @param thePatient the patient whose data is to be * retrevied from this preload handler */ public PatientPreloadHandler(Patient thePatient) { patient = thePatient; } /** * */ public IAnswerData handlePreload(String preloadParams) { IAnswerData returnVal = null; if(preloadParams == "monthsOnTreatment") { //TODO: Get actual data from patient returnVal = new IntegerData(12); } else if("vaccination_table".equals(preloadParams)) { returnVal = new ImmunizationAnswerData(patient.getVaccinations()); } else { int selectorStart = preloadParams.indexOf("["); if(selectorStart == -1) { returnVal = (IAnswerData)patient.getRecord(preloadParams); } else { String type = preloadParams.substring(0, selectorStart); String selector = preloadParams.substring(selectorStart, preloadParams.length()); Vector data = patient.getRecordSet(type, selector); returnVal = new NumericListData(); returnVal.setValue(data); } } return returnVal; } public boolean handlePostProcess(IFormDataModel model, IDataReference ref, String params) { return false; } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IPreloadHandler#preloadHandled() */ public String preloadHandled() { return "patient"; } }
[r868] [branches/dev] updates to patient object, saving immunization data
org.javarosa.patient/src/org/javarosa/patient/util/PatientPreloadHandler.java
[r868] [branches/dev] updates to patient object, saving immunization data
Java
apache-2.0
3d3d429922b824fcce7f907e7e9f189a4dceb900
0
mrniko/redisson,redisson/redisson
/** * Copyright (c) 2013-2019 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.connection; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.stream.Collectors; import org.redisson.api.NodeType; import org.redisson.api.RFuture; import org.redisson.client.RedisAuthRequiredException; import org.redisson.client.RedisClient; import org.redisson.client.RedisClientConfig; import org.redisson.client.RedisConnection; import org.redisson.client.RedisConnectionException; import org.redisson.client.codec.StringCodec; import org.redisson.client.protocol.RedisCommands; import org.redisson.config.BaseMasterSlaveServersConfig; import org.redisson.config.Config; import org.redisson.config.MasterSlaveServersConfig; import org.redisson.config.ReadMode; import org.redisson.config.SentinelServersConfig; import org.redisson.connection.ClientConnectionsEntry.FreezeReason; import org.redisson.misc.CountableListener; import org.redisson.misc.RPromise; import org.redisson.misc.RedisURI; import org.redisson.misc.RedissonPromise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.resolver.AddressResolver; import io.netty.util.NetUtil; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.ScheduledFuture; /** * * @author Nikita Koksharov * */ public class SentinelConnectionManager extends MasterSlaveConnectionManager { private final Logger log = LoggerFactory.getLogger(getClass()); private final Set<RedisURI> sentinelHosts = new HashSet<>(); private final ConcurrentMap<RedisURI, RedisClient> sentinels = new ConcurrentHashMap<>(); private final AtomicReference<String> currentMaster = new AtomicReference<>(); private final Set<RedisURI> disconnectedSlaves = new HashSet<>(); private ScheduledFuture<?> monitorFuture; private AddressResolver<InetSocketAddress> sentinelResolver; private final Map<String, String> natMap; private boolean usePassword = false; private String scheme; public SentinelConnectionManager(SentinelServersConfig cfg, Config config, UUID id) { super(config, id); if (cfg.getMasterName() == null) { throw new IllegalArgumentException("masterName parameter is not defined!"); } if (cfg.getSentinelAddresses().isEmpty()) { throw new IllegalArgumentException("At least one sentinel node should be defined!"); } this.config = create(cfg); initTimer(this.config); this.natMap=cfg.getNatMap(); this.sentinelResolver = resolverGroup.getResolver(getGroup().next()); boolean connected = false; for (String address : cfg.getSentinelAddresses()) { RedisURI addr = new RedisURI(address); RedisClient client = createClient(NodeType.SENTINEL, addr, this.config.getConnectTimeout(), this.config.getTimeout(), null); try { RedisConnection c = client.connect(); connected = true; try { c.sync(RedisCommands.PING); scheme = addr.getScheme(); } catch (RedisAuthRequiredException e) { usePassword = true; } break; } catch (RedisConnectionException e) { log.warn("Can't connect to sentinel server. {}", e.getMessage()); } catch (Exception e) { // skip } finally { client.shutdown(); } } if (!connected) { stopThreads(); StringBuilder list = new StringBuilder(); for (String address : cfg.getSentinelAddresses()) { list.append(address).append(", "); } throw new RedisConnectionException("Unable to connect to Redis sentinel servers: " + list); } for (String address : cfg.getSentinelAddresses()) { RedisURI addr = new RedisURI(address); if (NetUtil.createByteArrayFromIpAddressString(addr.getHost()) == null && !addr.getHost().equals("localhost")) { sentinelHosts.add(addr); } RedisClient client = createClient(NodeType.SENTINEL, addr, this.config.getConnectTimeout(), this.config.getTimeout(), null); try { RedisConnection connection = client.connect(); if (!connection.isActive()) { continue; } List<String> master = connection.sync(RedisCommands.SENTINEL_GET_MASTER_ADDR_BY_NAME, cfg.getMasterName()); if (master.isEmpty()) { throw new RedisConnectionException("Master node is undefined! SENTINEL GET-MASTER-ADDR-BY-NAME command returns empty result!"); } String masterHost = createAddress(master.get(0), master.get(1)); this.config.setMasterAddress(masterHost); currentMaster.set(masterHost); log.info("master: {} added", masterHost); List<Map<String, String>> sentinelSlaves = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, cfg.getMasterName()); for (Map<String, String> map : sentinelSlaves) { if (map.isEmpty()) { continue; } String ip = map.get("ip"); String port = map.get("port"); String flags = map.get("flags"); String host = createAddress(ip, port); this.config.addSlaveAddress(host); log.debug("slave {} state: {}", host, map); log.info("slave: {} added", host); if (flags.contains("s_down") || flags.contains("disconnected")) { RedisURI uri = new RedisURI(host); disconnectedSlaves.add(uri); log.warn("slave: {} is down", host); } } List<Map<String, String>> sentinelSentinels = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SENTINELS, cfg.getMasterName()); List<RFuture<Void>> connectionFutures = new ArrayList<>(sentinelSentinels.size()); for (Map<String, String> map : sentinelSentinels) { if (map.isEmpty()) { continue; } String ip = map.get("ip"); String port = map.get("port"); RedisURI sentinelAddr = convert(ip, port); RFuture<Void> future = registerSentinel(sentinelAddr, this.config); connectionFutures.add(future); } RedisURI currentAddr = convert(client.getAddr().getAddress().getHostAddress(), "" + client.getAddr().getPort()); RFuture<Void> f = registerSentinel(currentAddr, this.config); connectionFutures.add(f); for (RFuture<Void> future : connectionFutures) { future.awaitUninterruptibly(this.config.getConnectTimeout()); } break; } catch (RedisConnectionException e) { // skip } finally { client.shutdownAsync(); } } if (sentinels.isEmpty()) { stopThreads(); throw new RedisConnectionException("At least two sentinels should be defined in Redis configuration! SENTINEL SENTINELS command returns empty result!"); } if (currentMaster.get() == null) { stopThreads(); throw new RedisConnectionException("Can't connect to servers!"); } if (this.config.getReadMode() != ReadMode.MASTER && this.config.getSlaveAddresses().isEmpty()) { log.warn("ReadMode = " + this.config.getReadMode() + ", but slave nodes are not found!"); } initSingleEntry(); scheduleChangeCheck(cfg, null); } @Override protected void startDNSMonitoring(RedisClient masterHost) { if (config.getDnsMonitoringInterval() == -1 || sentinelHosts.isEmpty()) { return; } scheduleSentinelDNSCheck(); } @Override protected RedisClientConfig createRedisConfig(NodeType type, RedisURI address, int timeout, int commandTimeout, String sslHostname) { RedisClientConfig result = super.createRedisConfig(type, address, timeout, commandTimeout, sslHostname); if (type == NodeType.SENTINEL && !usePassword) { result.setPassword(null); } return result; } private void scheduleSentinelDNSCheck() { monitorFuture = group.schedule(new Runnable() { @Override public void run() { AtomicInteger sentinelsCounter = new AtomicInteger(sentinelHosts.size()); FutureListener<List<InetSocketAddress>> commonListener = new FutureListener<List<InetSocketAddress>>() { @Override public void operationComplete(Future<List<InetSocketAddress>> future) throws Exception { if (sentinelsCounter.decrementAndGet() == 0) { scheduleSentinelDNSCheck(); } } }; for (RedisURI host : sentinelHosts) { Future<List<InetSocketAddress>> allNodes = sentinelResolver.resolveAll(InetSocketAddress.createUnresolved(host.getHost(), host.getPort())); allNodes.addListener(new FutureListener<List<InetSocketAddress>>() { @Override public void operationComplete(Future<List<InetSocketAddress>> future) throws Exception { if (!future.isSuccess()) { log.error("Unable to resolve " + host.getHost(), future.cause()); return; } Set<RedisURI> newUris = future.getNow().stream() .map(addr -> convert(addr.getAddress().getHostAddress(), "" + addr.getPort())) .collect(Collectors.toSet()); for (RedisURI uri : newUris) { if (!sentinels.containsKey(uri)) { registerSentinel(uri, getConfig()); } } } }); allNodes.addListener(commonListener); } } }, config.getDnsMonitoringInterval(), TimeUnit.MILLISECONDS); } private void scheduleChangeCheck(SentinelServersConfig cfg, Iterator<RedisClient> iterator) { monitorFuture = group.schedule(new Runnable() { @Override public void run() { AtomicReference<Throwable> lastException = new AtomicReference<Throwable>(); Iterator<RedisClient> iter = iterator; if (iter == null) { // Shuffle the list so all clients don't prefer the same sentinel List<RedisClient> clients = new ArrayList<>(sentinels.values()); Collections.shuffle(clients); iter = clients.iterator(); } checkState(cfg, iter, lastException); } }, cfg.getScanInterval(), TimeUnit.MILLISECONDS); } private void checkState(SentinelServersConfig cfg, Iterator<RedisClient> iterator, AtomicReference<Throwable> lastException) { if (!iterator.hasNext()) { if (lastException.get() != null) { log.error("Can't update cluster state", lastException.get()); } scheduleChangeCheck(cfg, null); return; } if (!getShutdownLatch().acquire()) { return; } RedisClient client = iterator.next(); RFuture<RedisConnection> connectionFuture = connectToNode(null, null, client, null); connectionFuture.onComplete((connection, e) -> { if (e != null) { lastException.set(e); getShutdownLatch().release(); checkState(cfg, iterator, lastException); return; } updateState(cfg, connection, iterator); }); } private void updateState(SentinelServersConfig cfg, RedisConnection connection, Iterator<RedisClient> iterator) { AtomicInteger commands = new AtomicInteger(2); BiConsumer<Object, Throwable> commonListener = new BiConsumer<Object, Throwable>() { private final AtomicBoolean failed = new AtomicBoolean(); @Override public void accept(Object t, Throwable u) { if (commands.decrementAndGet() == 0) { getShutdownLatch().release(); if (failed.get()) { scheduleChangeCheck(cfg, iterator); } else { scheduleChangeCheck(cfg, null); } } if (u != null && failed.compareAndSet(false, true)) { log.error("Can't execute SENTINEL commands on " + connection.getRedisClient().getAddr(), u); closeNodeConnection(connection); } } }; RFuture<List<String>> masterFuture = connection.async(StringCodec.INSTANCE, RedisCommands.SENTINEL_GET_MASTER_ADDR_BY_NAME, cfg.getMasterName()); masterFuture.onComplete((master, e) -> { if (e != null) { return; } String current = currentMaster.get(); String newMaster = createAddress(master.get(0), master.get(1)); if (!newMaster.equals(current) && currentMaster.compareAndSet(current, newMaster)) { RFuture<RedisClient> changeFuture = changeMaster(singleSlotRange.getStartSlot(), new RedisURI(newMaster)); changeFuture.onComplete((res, ex) -> { if (ex != null) { currentMaster.compareAndSet(newMaster, current); } }); } }); masterFuture.onComplete(commonListener); if (!config.checkSkipSlavesInit()) { RFuture<List<Map<String, String>>> slavesFuture = connection.async(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, cfg.getMasterName()); commands.incrementAndGet(); slavesFuture.onComplete((slavesMap, e) -> { if (e != null) { return; } Set<String> currentSlaves = new HashSet<String>(slavesMap.size()); List<RFuture<Void>> futures = new ArrayList<>(); for (Map<String, String> map : slavesMap) { if (map.isEmpty()) { continue; } String ip = map.get("ip"); String port = map.get("port"); String flags = map.get("flags"); String masterHost = map.get("master-host"); String masterPort = map.get("master-port"); if (flags.contains("s_down") || flags.contains("disconnected")) { slaveDown(ip, port); continue; } if ("?".equals(masterHost) || !isUseSameMaster(ip, port, masterHost, masterPort)) { continue; } String slaveAddr = createAddress(ip, port); currentSlaves.add(slaveAddr); RFuture<Void> slaveFuture = addSlave(ip, port, slaveAddr); futures.add(slaveFuture); } CountableListener<Void> listener = new CountableListener<Void>() { @Override protected void onSuccess(Void value) { MasterSlaveEntry entry = getEntry(singleSlotRange.getStartSlot()); Set<String> removedSlaves = new HashSet<String>(); for (ClientConnectionsEntry e : entry.getAllEntries()) { InetSocketAddress addr = e.getClient().getAddr(); String slaveAddr = createAddress(addr.getAddress().getHostAddress(), addr.getPort()); removedSlaves.add(slaveAddr); } removedSlaves.removeAll(currentSlaves); for (String slave : removedSlaves) { if (slave.equals(currentMaster.get())) { continue; } String hostPort = slave.replace("redis://", ""); int lastColonIdx = hostPort.lastIndexOf(":"); String host = hostPort.substring(0, lastColonIdx); String port = hostPort.substring(lastColonIdx + 1); slaveDown(host, port); } }; }; listener.setCounter(futures.size()); for (RFuture<Void> f : futures) { f.onComplete(listener); } }); slavesFuture.onComplete(commonListener); } RFuture<List<Map<String, String>>> sentinelsFuture = connection.async(StringCodec.INSTANCE, RedisCommands.SENTINEL_SENTINELS, cfg.getMasterName()); sentinelsFuture.onComplete((list, e) -> { if (e != null) { return; } Set<RedisURI> newUris = list.stream().filter(m -> { String flags = m.get("flags"); if (!m.isEmpty() && !flags.contains("disconnected") && !flags.contains("s_down")) { return true; } return false; }).map(m -> { String ip = m.get("ip"); String port = m.get("port"); return convert(ip, port); }).collect(Collectors.toSet()); InetSocketAddress addr = connection.getRedisClient().getAddr(); RedisURI currentAddr = convert(addr.getAddress().getHostAddress(), "" + addr.getPort()); newUris.add(currentAddr); updateSentinels(newUris); }); sentinelsFuture.onComplete(commonListener); } private void updateSentinels(Set<RedisURI> newUris) { Set<RedisURI> currentUris = new HashSet<>(SentinelConnectionManager.this.sentinels.keySet()); Set<RedisURI> addedUris = new HashSet<>(newUris); addedUris.removeAll(currentUris); for (RedisURI uri : addedUris) { registerSentinel(uri, getConfig()); } currentUris.removeAll(newUris); for (RedisURI uri : currentUris) { RedisClient sentinel = SentinelConnectionManager.this.sentinels.remove(uri); if (sentinel != null) { sentinel.shutdownAsync(); log.warn("sentinel: {} has down", uri); } } } private String createAddress(String host, Object port) { if (host.contains(":")){ String pureHost = host.replaceAll("[\\[\\]]", ""); host = applyNatMap(pureHost); if (host.contains(":")) { host = "[" + host + "]"; } } else { host = applyNatMap(host); } return scheme + "://" + host + ":" + port; } @Override protected MasterSlaveEntry createMasterSlaveEntry(MasterSlaveServersConfig config) { MasterSlaveEntry entry = new MasterSlaveEntry(this, config); List<RFuture<Void>> fs = entry.initSlaveBalancer(disconnectedSlaves); for (RFuture<Void> future : fs) { future.syncUninterruptibly(); } return entry; } private RFuture<Void> registerSentinel(RedisURI addr, MasterSlaveServersConfig c) { RedisClient sentinel = sentinels.get(addr); if (sentinel != null) { return RedissonPromise.newSucceededFuture(null); } RedisClient client = createClient(NodeType.SENTINEL, addr, c.getConnectTimeout(), c.getTimeout(), null); RPromise<Void> result = new RedissonPromise<Void>(); RFuture<InetSocketAddress> future = client.resolveAddr(); future.onComplete((res, e) -> { if (e != null) { result.tryFailure(e); return; } RFuture<RedisConnection> f = client.connectAsync(); f.onComplete((connection, ex) -> { if (ex != null) { result.tryFailure(ex); return; } RFuture<String> r = connection.async(config.getTimeout(), RedisCommands.PING); r.onComplete((resp, exc) -> { if (exc != null) { result.tryFailure(exc); return; } if (sentinels.putIfAbsent(addr, client) == null) { log.info("sentinel: {} added", addr); } result.trySuccess(null); }); }); }); return result; } private RFuture<Void> addSlave(String ip, String port, String addr) { RPromise<Void> result = new RedissonPromise<Void>(); // to avoid addition twice MasterSlaveEntry entry = getEntry(singleSlotRange.getStartSlot()); RedisURI uri = convert(ip, port); if (!entry.hasSlave(uri) && !config.checkSkipSlavesInit()) { RFuture<Void> future = entry.addSlave(new RedisURI(addr)); future.onComplete((res, e) -> { if (e != null) { result.tryFailure(e); log.error("Can't add slave: " + addr, e); return; } if (entry.isSlaveUnfreezed(uri) || entry.slaveUp(uri, FreezeReason.MANAGER)) { String slaveAddr = ip + ":" + port; log.info("slave: {} added", slaveAddr); result.trySuccess(null); } }); } else { if (entry.hasSlave(uri)) { slaveUp(ip, port); } result.trySuccess(null); } return result; } private RedisURI convert(String ip, String port) { String addr = createAddress(ip, port); RedisURI uri = new RedisURI(addr); return uri; } private void slaveDown(String ip, String port) { if (config.checkSkipSlavesInit()) { log.warn("slave: {}:{} has down", ip, port); } else { MasterSlaveEntry entry = getEntry(singleSlotRange.getStartSlot()); RedisURI uri = convert(ip, port); if (entry.slaveDown(uri, FreezeReason.MANAGER)) { log.warn("slave: {}:{} has down", ip, port); } } } private boolean isUseSameMaster(String slaveIp, String slavePort, String slaveMasterHost, String slaveMasterPort) { String master = currentMaster.get(); String slaveMaster = createAddress(slaveMasterHost, slaveMasterPort); if (!master.equals(slaveMaster)) { log.warn("Skipped slave up {} for master {} differs from current {}", slaveIp + ":" + slavePort, slaveMaster, master); return false; } return true; } private void slaveUp(String ip, String port) { if (config.checkSkipSlavesInit()) { String slaveAddr = ip + ":" + port; log.info("slave: {} has up", slaveAddr); return; } RedisURI uri = convert(ip, port); if (getEntry(singleSlotRange.getStartSlot()).slaveUp(uri, FreezeReason.MANAGER)) { String slaveAddr = ip + ":" + port; log.info("slave: {} has up", slaveAddr); } } @Override protected MasterSlaveServersConfig create(BaseMasterSlaveServersConfig<?> cfg) { MasterSlaveServersConfig res = super.create(cfg); res.setDatabase(((SentinelServersConfig) cfg).getDatabase()); return res; } public Collection<RedisClient> getSentinels() { return sentinels.values(); } @Override public void shutdown() { if (monitorFuture != null) { monitorFuture.cancel(true); } List<RFuture<Void>> futures = new ArrayList<>(); for (RedisClient sentinel : sentinels.values()) { RFuture<Void> future = sentinel.shutdownAsync(); futures.add(future); } for (RFuture<Void> future : futures) { future.syncUninterruptibly(); } super.shutdown(); } private String applyNatMap(String ip) { String mappedAddress = natMap.get(ip); if (mappedAddress != null) { return mappedAddress; } return ip; } }
redisson/src/main/java/org/redisson/connection/SentinelConnectionManager.java
/** * Copyright (c) 2013-2019 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.connection; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.stream.Collectors; import org.redisson.api.NodeType; import org.redisson.api.RFuture; import org.redisson.client.RedisAuthRequiredException; import org.redisson.client.RedisClient; import org.redisson.client.RedisClientConfig; import org.redisson.client.RedisConnection; import org.redisson.client.RedisConnectionException; import org.redisson.client.codec.StringCodec; import org.redisson.client.protocol.RedisCommands; import org.redisson.config.BaseMasterSlaveServersConfig; import org.redisson.config.Config; import org.redisson.config.MasterSlaveServersConfig; import org.redisson.config.ReadMode; import org.redisson.config.SentinelServersConfig; import org.redisson.connection.ClientConnectionsEntry.FreezeReason; import org.redisson.misc.CountableListener; import org.redisson.misc.RPromise; import org.redisson.misc.RedisURI; import org.redisson.misc.RedissonPromise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.resolver.AddressResolver; import io.netty.util.NetUtil; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.ScheduledFuture; /** * * @author Nikita Koksharov * */ public class SentinelConnectionManager extends MasterSlaveConnectionManager { private final Logger log = LoggerFactory.getLogger(getClass()); private final Set<RedisURI> sentinelHosts = new HashSet<>(); private final ConcurrentMap<RedisURI, RedisClient> sentinels = new ConcurrentHashMap<>(); private final AtomicReference<String> currentMaster = new AtomicReference<>(); private final Set<RedisURI> disconnectedSlaves = new HashSet<>(); private ScheduledFuture<?> monitorFuture; private AddressResolver<InetSocketAddress> sentinelResolver; private final Map<String, String> natMap; private boolean usePassword = false; private String scheme; public SentinelConnectionManager(SentinelServersConfig cfg, Config config, UUID id) { super(config, id); if (cfg.getMasterName() == null) { throw new IllegalArgumentException("masterName parameter is not defined!"); } if (cfg.getSentinelAddresses().isEmpty()) { throw new IllegalArgumentException("At least one sentinel node should be defined!"); } this.config = create(cfg); initTimer(this.config); this.natMap=cfg.getNatMap(); this.sentinelResolver = resolverGroup.getResolver(getGroup().next()); for (String address : cfg.getSentinelAddresses()) { RedisURI addr = new RedisURI(address); RedisClient client = createClient(NodeType.SENTINEL, addr, this.config.getConnectTimeout(), this.config.getTimeout(), null); try { RedisConnection c = client.connect(); try { c.sync(RedisCommands.PING); scheme = addr.getScheme(); } catch (RedisAuthRequiredException e) { usePassword = true; } client.shutdown(); break; } catch (Exception e) { // skip } } for (String address : cfg.getSentinelAddresses()) { RedisURI addr = new RedisURI(address); if (NetUtil.createByteArrayFromIpAddressString(addr.getHost()) == null && !addr.getHost().equals("localhost")) { sentinelHosts.add(addr); } RedisClient client = createClient(NodeType.SENTINEL, addr, this.config.getConnectTimeout(), this.config.getTimeout(), null); try { RedisConnection connection = client.connect(); if (!connection.isActive()) { continue; } List<String> master = connection.sync(RedisCommands.SENTINEL_GET_MASTER_ADDR_BY_NAME, cfg.getMasterName()); if (master.isEmpty()) { throw new RedisConnectionException("Master node is undefined! SENTINEL GET-MASTER-ADDR-BY-NAME command returns empty result!"); } String masterHost = createAddress(master.get(0), master.get(1)); this.config.setMasterAddress(masterHost); currentMaster.set(masterHost); log.info("master: {} added", masterHost); List<Map<String, String>> sentinelSlaves = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, cfg.getMasterName()); for (Map<String, String> map : sentinelSlaves) { if (map.isEmpty()) { continue; } String ip = map.get("ip"); String port = map.get("port"); String flags = map.get("flags"); String host = createAddress(ip, port); this.config.addSlaveAddress(host); log.debug("slave {} state: {}", host, map); log.info("slave: {} added", host); if (flags.contains("s_down") || flags.contains("disconnected")) { RedisURI uri = new RedisURI(host); disconnectedSlaves.add(uri); log.warn("slave: {} is down", host); } } List<Map<String, String>> sentinelSentinels = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SENTINELS, cfg.getMasterName()); List<RFuture<Void>> connectionFutures = new ArrayList<>(sentinelSentinels.size()); for (Map<String, String> map : sentinelSentinels) { if (map.isEmpty()) { continue; } String ip = map.get("ip"); String port = map.get("port"); RedisURI sentinelAddr = convert(ip, port); RFuture<Void> future = registerSentinel(sentinelAddr, this.config); connectionFutures.add(future); } RedisURI currentAddr = convert(client.getAddr().getAddress().getHostAddress(), "" + client.getAddr().getPort()); RFuture<Void> f = registerSentinel(currentAddr, this.config); connectionFutures.add(f); for (RFuture<Void> future : connectionFutures) { future.awaitUninterruptibly(this.config.getConnectTimeout()); } break; } catch (RedisConnectionException e) { log.warn("Can't connect to sentinel server. {}", e.getMessage()); } finally { client.shutdownAsync(); } } if (sentinels.isEmpty()) { stopThreads(); throw new RedisConnectionException("At least two sentinels should be defined in Redis configuration! SENTINEL SENTINELS command returns empty result!"); } if (currentMaster.get() == null) { stopThreads(); throw new RedisConnectionException("Can't connect to servers!"); } if (this.config.getReadMode() != ReadMode.MASTER && this.config.getSlaveAddresses().isEmpty()) { log.warn("ReadMode = " + this.config.getReadMode() + ", but slave nodes are not found!"); } initSingleEntry(); scheduleChangeCheck(cfg, null); } @Override protected void startDNSMonitoring(RedisClient masterHost) { if (config.getDnsMonitoringInterval() == -1 || sentinelHosts.isEmpty()) { return; } scheduleSentinelDNSCheck(); } @Override protected RedisClientConfig createRedisConfig(NodeType type, RedisURI address, int timeout, int commandTimeout, String sslHostname) { RedisClientConfig result = super.createRedisConfig(type, address, timeout, commandTimeout, sslHostname); if (type == NodeType.SENTINEL && !usePassword) { result.setPassword(null); } return result; } private void scheduleSentinelDNSCheck() { monitorFuture = group.schedule(new Runnable() { @Override public void run() { AtomicInteger sentinelsCounter = new AtomicInteger(sentinelHosts.size()); FutureListener<List<InetSocketAddress>> commonListener = new FutureListener<List<InetSocketAddress>>() { @Override public void operationComplete(Future<List<InetSocketAddress>> future) throws Exception { if (sentinelsCounter.decrementAndGet() == 0) { scheduleSentinelDNSCheck(); } } }; for (RedisURI host : sentinelHosts) { Future<List<InetSocketAddress>> allNodes = sentinelResolver.resolveAll(InetSocketAddress.createUnresolved(host.getHost(), host.getPort())); allNodes.addListener(new FutureListener<List<InetSocketAddress>>() { @Override public void operationComplete(Future<List<InetSocketAddress>> future) throws Exception { if (!future.isSuccess()) { log.error("Unable to resolve " + host.getHost(), future.cause()); return; } Set<RedisURI> newUris = future.getNow().stream() .map(addr -> convert(addr.getAddress().getHostAddress(), "" + addr.getPort())) .collect(Collectors.toSet()); for (RedisURI uri : newUris) { if (!sentinels.containsKey(uri)) { registerSentinel(uri, getConfig()); } } } }); allNodes.addListener(commonListener); } } }, config.getDnsMonitoringInterval(), TimeUnit.MILLISECONDS); } private void scheduleChangeCheck(SentinelServersConfig cfg, Iterator<RedisClient> iterator) { monitorFuture = group.schedule(new Runnable() { @Override public void run() { AtomicReference<Throwable> lastException = new AtomicReference<Throwable>(); Iterator<RedisClient> iter = iterator; if (iter == null) { // Shuffle the list so all clients don't prefer the same sentinel List<RedisClient> clients = new ArrayList<>(sentinels.values()); Collections.shuffle(clients); iter = clients.iterator(); } checkState(cfg, iter, lastException); } }, cfg.getScanInterval(), TimeUnit.MILLISECONDS); } private void checkState(SentinelServersConfig cfg, Iterator<RedisClient> iterator, AtomicReference<Throwable> lastException) { if (!iterator.hasNext()) { if (lastException.get() != null) { log.error("Can't update cluster state", lastException.get()); } scheduleChangeCheck(cfg, null); return; } if (!getShutdownLatch().acquire()) { return; } RedisClient client = iterator.next(); RFuture<RedisConnection> connectionFuture = connectToNode(null, null, client, null); connectionFuture.onComplete((connection, e) -> { if (e != null) { lastException.set(e); getShutdownLatch().release(); checkState(cfg, iterator, lastException); return; } updateState(cfg, connection, iterator); }); } private void updateState(SentinelServersConfig cfg, RedisConnection connection, Iterator<RedisClient> iterator) { AtomicInteger commands = new AtomicInteger(2); BiConsumer<Object, Throwable> commonListener = new BiConsumer<Object, Throwable>() { private final AtomicBoolean failed = new AtomicBoolean(); @Override public void accept(Object t, Throwable u) { if (commands.decrementAndGet() == 0) { getShutdownLatch().release(); if (failed.get()) { scheduleChangeCheck(cfg, iterator); } else { scheduleChangeCheck(cfg, null); } } if (u != null && failed.compareAndSet(false, true)) { log.error("Can't execute SENTINEL commands on " + connection.getRedisClient().getAddr(), u); closeNodeConnection(connection); } } }; RFuture<List<String>> masterFuture = connection.async(StringCodec.INSTANCE, RedisCommands.SENTINEL_GET_MASTER_ADDR_BY_NAME, cfg.getMasterName()); masterFuture.onComplete((master, e) -> { if (e != null) { return; } String current = currentMaster.get(); String newMaster = createAddress(master.get(0), master.get(1)); if (!newMaster.equals(current) && currentMaster.compareAndSet(current, newMaster)) { RFuture<RedisClient> changeFuture = changeMaster(singleSlotRange.getStartSlot(), new RedisURI(newMaster)); changeFuture.onComplete((res, ex) -> { if (ex != null) { currentMaster.compareAndSet(newMaster, current); } }); } }); masterFuture.onComplete(commonListener); if (!config.checkSkipSlavesInit()) { RFuture<List<Map<String, String>>> slavesFuture = connection.async(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, cfg.getMasterName()); commands.incrementAndGet(); slavesFuture.onComplete((slavesMap, e) -> { if (e != null) { return; } Set<String> currentSlaves = new HashSet<String>(slavesMap.size()); List<RFuture<Void>> futures = new ArrayList<>(); for (Map<String, String> map : slavesMap) { if (map.isEmpty()) { continue; } String ip = map.get("ip"); String port = map.get("port"); String flags = map.get("flags"); String masterHost = map.get("master-host"); String masterPort = map.get("master-port"); if (flags.contains("s_down") || flags.contains("disconnected")) { slaveDown(ip, port); continue; } if ("?".equals(masterHost) || !isUseSameMaster(ip, port, masterHost, masterPort)) { continue; } String slaveAddr = createAddress(ip, port); currentSlaves.add(slaveAddr); RFuture<Void> slaveFuture = addSlave(ip, port, slaveAddr); futures.add(slaveFuture); } CountableListener<Void> listener = new CountableListener<Void>() { @Override protected void onSuccess(Void value) { MasterSlaveEntry entry = getEntry(singleSlotRange.getStartSlot()); Set<String> removedSlaves = new HashSet<String>(); for (ClientConnectionsEntry e : entry.getAllEntries()) { InetSocketAddress addr = e.getClient().getAddr(); String slaveAddr = createAddress(addr.getAddress().getHostAddress(), addr.getPort()); removedSlaves.add(slaveAddr); } removedSlaves.removeAll(currentSlaves); for (String slave : removedSlaves) { if (slave.equals(currentMaster.get())) { continue; } String hostPort = slave.replace("redis://", ""); int lastColonIdx = hostPort.lastIndexOf(":"); String host = hostPort.substring(0, lastColonIdx); String port = hostPort.substring(lastColonIdx + 1); slaveDown(host, port); } }; }; listener.setCounter(futures.size()); for (RFuture<Void> f : futures) { f.onComplete(listener); } }); slavesFuture.onComplete(commonListener); } RFuture<List<Map<String, String>>> sentinelsFuture = connection.async(StringCodec.INSTANCE, RedisCommands.SENTINEL_SENTINELS, cfg.getMasterName()); sentinelsFuture.onComplete((list, e) -> { if (e != null) { return; } Set<RedisURI> newUris = list.stream().filter(m -> { String flags = m.get("flags"); if (!m.isEmpty() && !flags.contains("disconnected") && !flags.contains("s_down")) { return true; } return false; }).map(m -> { String ip = m.get("ip"); String port = m.get("port"); return convert(ip, port); }).collect(Collectors.toSet()); InetSocketAddress addr = connection.getRedisClient().getAddr(); RedisURI currentAddr = convert(addr.getAddress().getHostAddress(), "" + addr.getPort()); newUris.add(currentAddr); updateSentinels(newUris); }); sentinelsFuture.onComplete(commonListener); } private void updateSentinels(Set<RedisURI> newUris) { Set<RedisURI> currentUris = new HashSet<>(SentinelConnectionManager.this.sentinels.keySet()); Set<RedisURI> addedUris = new HashSet<>(newUris); addedUris.removeAll(currentUris); for (RedisURI uri : addedUris) { registerSentinel(uri, getConfig()); } currentUris.removeAll(newUris); for (RedisURI uri : currentUris) { RedisClient sentinel = SentinelConnectionManager.this.sentinels.remove(uri); if (sentinel != null) { sentinel.shutdownAsync(); log.warn("sentinel: {} has down", uri); } } } private String createAddress(String host, Object port) { if (host.contains(":")){ String pureHost = host.replaceAll("[\\[\\]]", ""); host = applyNatMap(pureHost); if (host.contains(":")) { host = "[" + host + "]"; } } else { host = applyNatMap(host); } return scheme + "://" + host + ":" + port; } @Override protected MasterSlaveEntry createMasterSlaveEntry(MasterSlaveServersConfig config) { MasterSlaveEntry entry = new MasterSlaveEntry(this, config); List<RFuture<Void>> fs = entry.initSlaveBalancer(disconnectedSlaves); for (RFuture<Void> future : fs) { future.syncUninterruptibly(); } return entry; } private RFuture<Void> registerSentinel(RedisURI addr, MasterSlaveServersConfig c) { RedisClient sentinel = sentinels.get(addr); if (sentinel != null) { return RedissonPromise.newSucceededFuture(null); } RedisClient client = createClient(NodeType.SENTINEL, addr, c.getConnectTimeout(), c.getTimeout(), null); RPromise<Void> result = new RedissonPromise<Void>(); RFuture<InetSocketAddress> future = client.resolveAddr(); future.onComplete((res, e) -> { if (e != null) { result.tryFailure(e); return; } RFuture<RedisConnection> f = client.connectAsync(); f.onComplete((connection, ex) -> { if (ex != null) { result.tryFailure(ex); return; } RFuture<String> r = connection.async(config.getTimeout(), RedisCommands.PING); r.onComplete((resp, exc) -> { if (exc != null) { result.tryFailure(exc); return; } if (sentinels.putIfAbsent(addr, client) == null) { log.info("sentinel: {} added", addr); } result.trySuccess(null); }); }); }); return result; } private RFuture<Void> addSlave(String ip, String port, String addr) { RPromise<Void> result = new RedissonPromise<Void>(); // to avoid addition twice MasterSlaveEntry entry = getEntry(singleSlotRange.getStartSlot()); RedisURI uri = convert(ip, port); if (!entry.hasSlave(uri) && !config.checkSkipSlavesInit()) { RFuture<Void> future = entry.addSlave(new RedisURI(addr)); future.onComplete((res, e) -> { if (e != null) { result.tryFailure(e); log.error("Can't add slave: " + addr, e); return; } if (entry.isSlaveUnfreezed(uri) || entry.slaveUp(uri, FreezeReason.MANAGER)) { String slaveAddr = ip + ":" + port; log.info("slave: {} added", slaveAddr); result.trySuccess(null); } }); } else { if (entry.hasSlave(uri)) { slaveUp(ip, port); } result.trySuccess(null); } return result; } private RedisURI convert(String ip, String port) { String addr = createAddress(ip, port); RedisURI uri = new RedisURI(addr); return uri; } private void slaveDown(String ip, String port) { if (config.checkSkipSlavesInit()) { log.warn("slave: {}:{} has down", ip, port); } else { MasterSlaveEntry entry = getEntry(singleSlotRange.getStartSlot()); RedisURI uri = convert(ip, port); if (entry.slaveDown(uri, FreezeReason.MANAGER)) { log.warn("slave: {}:{} has down", ip, port); } } } private boolean isUseSameMaster(String slaveIp, String slavePort, String slaveMasterHost, String slaveMasterPort) { String master = currentMaster.get(); String slaveMaster = createAddress(slaveMasterHost, slaveMasterPort); if (!master.equals(slaveMaster)) { log.warn("Skipped slave up {} for master {} differs from current {}", slaveIp + ":" + slavePort, slaveMaster, master); return false; } return true; } private void slaveUp(String ip, String port) { if (config.checkSkipSlavesInit()) { String slaveAddr = ip + ":" + port; log.info("slave: {} has up", slaveAddr); return; } RedisURI uri = convert(ip, port); if (getEntry(singleSlotRange.getStartSlot()).slaveUp(uri, FreezeReason.MANAGER)) { String slaveAddr = ip + ":" + port; log.info("slave: {} has up", slaveAddr); } } @Override protected MasterSlaveServersConfig create(BaseMasterSlaveServersConfig<?> cfg) { MasterSlaveServersConfig res = super.create(cfg); res.setDatabase(((SentinelServersConfig) cfg).getDatabase()); return res; } public Collection<RedisClient> getSentinels() { return sentinels.values(); } @Override public void shutdown() { if (monitorFuture != null) { monitorFuture.cancel(true); } List<RFuture<Void>> futures = new ArrayList<>(); for (RedisClient sentinel : sentinels.values()) { RFuture<Void> future = sentinel.shutdownAsync(); futures.add(future); } for (RFuture<Void> future : futures) { future.syncUninterruptibly(); } super.shutdown(); } private String applyNatMap(String ip) { String mappedAddress = natMap.get(ip); if (mappedAddress != null) { return mappedAddress; } return ip; } }
refactoring
redisson/src/main/java/org/redisson/connection/SentinelConnectionManager.java
refactoring
Java
apache-2.0
0e7ea404d434cd4d1316aa7d43ef50a5a3ef98a5
0
amir-zeldes/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,zangsir/ANNIS,korpling/ANNIS,zangsir/ANNIS,korpling/ANNIS,korpling/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licsense is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package annis.gui; import annis.VersionInfo; import annis.gui.requesthandler.ResourceRequestHandler; import annis.gui.requesthandler.LoginServletRequestHandler; import annis.gui.components.ExceptionDialog; import annis.libgui.AnnisBaseUI; import annis.libgui.InstanceConfig; import annis.libgui.Helper; import annis.gui.controlpanel.ControlPanel; import annis.gui.docbrowser.DocBrowserController; import annis.libgui.media.MediaController; import annis.libgui.media.MimeTypeErrorListener; import annis.libgui.media.MediaControllerImpl; import annis.gui.objects.PagedResultQuery; import annis.gui.objects.Query; import annis.gui.querybuilder.TigerQueryBuilderPlugin; import annis.gui.flatquerybuilder.FlatQueryBuilderPlugin; import annis.gui.frequency.FrequencyQueryPanel; import annis.gui.requesthandler.BinaryRequestHandler; import annis.gui.resultview.ResultViewPanel; import annis.gui.servlets.ResourceServlet; import static annis.libgui.Helper.*; import annis.libgui.media.PDFController; import annis.libgui.media.PDFControllerImpl; import annis.service.objects.AnnisCorpus; import annis.service.objects.CorpusConfig; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.vaadin.annotations.Theme; import com.vaadin.data.validator.EmailValidator; import com.vaadin.event.ShortcutListener; import com.vaadin.server.ErrorHandler; import com.vaadin.server.Page; import com.vaadin.server.Page.UriFragmentChangedEvent; import com.vaadin.server.RequestHandler; import com.vaadin.server.ThemeResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinResponse; import com.vaadin.server.VaadinService; import com.vaadin.server.VaadinSession; import com.vaadin.server.WebBrowser; import com.vaadin.ui.*; import com.vaadin.ui.TabSheet.Tab; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.*; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.util.uri.ClassURI; import org.apache.commons.lang3.StringUtils; import org.slf4j.LoggerFactory; /** * GUI for searching in corpora. * * @author Thomas Krause <krauseto@hu-berlin.de> */ @Theme("annis") public class SearchUI extends AnnisBaseUI implements MimeTypeErrorListener, Page.UriFragmentChangedListener, ErrorHandler, TabSheet.CloseHandler, LoginListener, Sidebar { private static final org.slf4j.Logger log = LoggerFactory.getLogger( SearchUI.class); private transient Cache<String, CorpusConfig> corpusConfigCache; // regular expression matching, CLEFT and CRIGHT are optional // indexes: AQL=1, CIDS=2, CLEFT=4, CRIGHT=6 private final Pattern citationPattern = Pattern. compile( "AQL\\((.*)\\),CIDS\\(([^)]*)\\)(,CLEFT\\(([^)]*)\\),)?(CRIGHT\\(([^)]*)\\))?", Pattern.MULTILINE | Pattern.DOTALL); private MainToolbar toolbar; private ControlPanel controlPanel; private TabSheet mainTab; private QueryController queryController; private String lastQueriedFragment; private InstanceConfig instanceConfig; private DocBrowserController docBrowserController; public final static int CONTROL_PANEL_WIDTH = 360; private void initTransients() { corpusConfigCache = CacheBuilder.newBuilder().maximumSize(250).build(); } public SearchUI() { initTransients(); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); initTransients(); } @Override protected void init(VaadinRequest request) { super.init(request); setErrorHandler(this); this.instanceConfig = getInstanceConfig(request); getPage().setTitle( instanceConfig.getInstanceDisplayName() + " (ANNIS Corpus Search)"); // init a doc browser controller docBrowserController = new DocBrowserController(this); queryController = new QueryController(this); // always get the resize events directly setImmediate(true); GridLayout mainLayout = new GridLayout(2,2); setContent(mainLayout); mainLayout.setSizeFull(); mainLayout.setMargin(false); mainLayout.setRowExpandRatio(1, 1.0f); mainLayout.setColumnExpandRatio(1, 1.0f); toolbar = new MainToolbar(SearchUI.this); toolbar.addLoginListener(SearchUI.this); addExtension(toolbar.getScreenshotExtension()); mainLayout.addComponent(toolbar, 0,0, 1, 0); final HelpPanel help = new HelpPanel(this); mainTab = new TabSheet(); mainTab.setSizeFull(); mainTab.setCloseHandler(this); mainTab.addSelectedTabChangeListener(queryController); mainTab.addStyleName("blue-tab"); Tab helpTab = mainTab.addTab(help, "Help/Examples"); helpTab.setIcon(new ThemeResource("images/tango-icons/16x16/help-browser.png")); helpTab.setClosable(false); controlPanel = new ControlPanel(queryController, instanceConfig, help.getExamples(), this); controlPanel.setWidth(CONTROL_PANEL_WIDTH, Layout.Unit.PIXELS); controlPanel.setHeight(100f, Layout.Unit.PERCENTAGE); mainLayout.addComponent(controlPanel, 0, 1); mainLayout.addComponent(mainTab, 1,1); addAction(new ShortcutListener("Tutor^eial") { @Override public void handleAction(Object sender, Object target) { mainTab.setSelectedTab(help); } }); getPage().addUriFragmentChangedListener(this); getSession().addRequestHandler(new CitationRequestHandler()); getSession().addRequestHandler(new ResourceRequestHandler()); getSession().addRequestHandler(new LoginServletRequestHandler()); getSession().addRequestHandler(new BinaryRequestHandler()); getSession().setAttribute(MediaController.class, new MediaControllerImpl()); getSession().setAttribute(PDFController.class, new PDFControllerImpl()); loadInstanceFonts(); checkCitation(); lastQueriedFragment = ""; evaluateFragment(getPage().getUriFragment()); checkServiceVersion(); } private void checkServiceVersion() { try { WebResource resRelease = Helper.getAnnisWebResource().path("version").path("release"); String releaseService = resRelease.get(String.class); String releaseGUI = VersionInfo.getReleaseName(); // check if the release version differs and show a big warning if(!releaseGUI.equals(releaseService)) { Notification.show("Different service version", "The service uses version " + releaseService + " but the user interface is using version " + releaseGUI + ". This can produce unwanted errors.", Notification.Type.WARNING_MESSAGE); } else { // show a smaller warning if the revisions are not the same WebResource resRevision = Helper.getAnnisWebResource().path("version").path("revision"); String revisionService = resRevision.get(String.class); String revisionGUI = VersionInfo.getBuildRevision(); if(!revisionService.equals(revisionGUI)) { Notification.show("Different service revision", "The service uses revision " + revisionService + " but the user interface is using revision " + revisionGUI + ".", Notification.Type.TRAY_NOTIFICATION); } } } catch(UniformInterfaceException ex) { log.warn("Could not get the version of the service", ex); } catch(ClientHandlerException ex) { log.warn("Could not get the version of the service because service is not running", ex); } } @Override public void error(com.vaadin.server.ErrorEvent event) { log.error("Unknown error in some component: " + event.getThrowable(). getLocalizedMessage(), event.getThrowable()); // get the source throwable (thus the one that triggered the error) Throwable source = event.getThrowable(); if(source != null) { while (source.getCause() != null) { source = source.getCause(); } ExceptionDialog.show(source); } } public boolean canReportBugs() { if(toolbar != null) { return toolbar.canReportBugs(); } return false; } public void reportBug() { toolbar.reportBug(); } public void reportBug(Throwable cause) { toolbar.reportBug(cause); } private void loadInstanceFonts() { if (instanceConfig != null && instanceConfig.getFont() != null) { FontConfig cfg = instanceConfig.getFont(); if (cfg.getSize() == null || cfg.getSize().isEmpty()) { injectUniqueCSS( "@import url(" + cfg.getUrl() + ");\n" + "." + CORPUS_FONT_FORCE + " {font-family: '" + cfg.getName() + "', monospace !important; }\n" + "." + CORPUS_FONT + " {font-family: '" + cfg.getName() + "', monospace; }\n" // this one is for the virtual keyboard + "#keyboardInputMaster tbody tr td table tbody tr td {\n" + " font-family: '" + cfg.getName() + "', 'Lucida Console','Arial Unicode MS',monospace; " + "}"); } else { injectUniqueCSS( "@import url(" + cfg.getUrl() + ");\n" + "." + CORPUS_FONT_FORCE + " {\n" + " font-family: '" + cfg.getName() + "', monospace !important;\n" + " font-size: " + cfg.getSize() + " !important;\n" + "}\n" + "." + CORPUS_FONT + " {\n" + " font-family: '" + cfg.getName() + "', monospace;\n" + " font-size: " + cfg.getSize() + ";\n" + "}\n" + "." + CORPUS_FONT + " .v-table-table {\n" + " font-size: " + cfg.getSize() + ";\n" + "}" // this one is for the virtual keyboard + "#keyboardInputMaster tbody tr td table tbody tr td {\n" + " font-family: '" + cfg.getName() + "', 'Lucida Console','Arial Unicode MS',monospace; " + "}"); } } else { injectUniqueCSS( // use original font definition from keyboard.css if no font given "#keyboardInputMaster tbody tr td table tbody tr td {\n" + " font-family: 'Lucida Console','Arial Unicode MS',monospace;" + "}"); } } private InstanceConfig getInstanceConfig(VaadinRequest request) { String instance = null; String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1); } if (pathInfo != null && pathInfo.endsWith("/")) { pathInfo = pathInfo.substring(0, pathInfo.length() - 1); } Map<String, InstanceConfig> allConfigs = loadInstanceConfig(); if (pathInfo != null && !pathInfo.isEmpty()) { instance = pathInfo; } if (instance != null && allConfigs.containsKey(instance)) { // return the config that matches the parsed name return allConfigs.get(instance); } else if (allConfigs.containsKey("default")) { // return the default config return allConfigs.get("default"); } else if (allConfigs.size() > 0) { // just return any existing config as a fallback log. warn( "Instance config {} not found or null and default config is not available.", instance); return allConfigs.values().iterator().next(); } // default to an empty instance config return new InstanceConfig(); } /** * Get a cached version of the {@link CorpusConfig} for a corpus. * * @param corpus * @return */ public CorpusConfig getCorpusConfigWithCache(String corpus) { CorpusConfig config = new CorpusConfig(); if (corpusConfigCache != null) { config = corpusConfigCache.getIfPresent(corpus); if (config == null) { if (corpus.equals(DEFAULT_CONFIG)) { config = Helper.getDefaultCorpusConfig(); } else { config = Helper.getCorpusConfig(corpus); } corpusConfigCache.put(corpus, config); } } return config; } public void clearCorpusConfigCache() { if (corpusConfigCache != null) { corpusConfigCache.invalidateAll(); } } @Override protected void addCustomUIPlugins(PluginManager pluginManager) { pluginManager.addPluginsFrom(new ClassURI(TigerQueryBuilderPlugin.class). toURI()); pluginManager.addPluginsFrom(new ClassURI(FlatQueryBuilderPlugin.class). toURI()); pluginManager.addPluginsFrom(new ClassURI(ResourceServlet.class).toURI()); } public void checkCitation() { if (VaadinSession.getCurrent() == null || VaadinSession.getCurrent(). getSession() == null) { return; } Object origURLRaw = VaadinSession.getCurrent().getSession().getAttribute( "citation"); if (origURLRaw == null || !(origURLRaw instanceof String)) { return; } String origURL = (String) origURLRaw; String parameters = origURL.replaceAll(".*?/Cite(/)?", ""); if (!"".equals(parameters) && !origURL.equals(parameters)) { try { String decoded = URLDecoder.decode(parameters, "UTF-8"); evaluateCitation(decoded); } catch (UnsupportedEncodingException ex) { log.error(null, ex); } } } public void evaluateCitation(String relativeUri) { Matcher m = citationPattern.matcher(relativeUri); if (m.matches()) { // AQL String aql = ""; if (m.group(1) != null) { aql = m.group(1); } // CIDS Set<String> selectedCorpora = new HashSet<>(); if (m.group(2) != null) { String[] cids = m.group(2).split(","); selectedCorpora.addAll(Arrays.asList(cids)); } // filter by actually avaible user corpora in order not to get any exception later WebResource res = Helper.getAnnisWebResource(); List<AnnisCorpus> userCorpora = res.path("query").path("corpora"). get(new AnnisCorpusListType()); LinkedList<String> userCorporaStrings = new LinkedList<>(); for (AnnisCorpus c : userCorpora) { userCorporaStrings.add(c.getName()); } selectedCorpora.retainAll(userCorporaStrings); // CLEFT and CRIGHT if (m.group(4) != null && m.group(6) != null) { int cleft = 0; int cright = 0; try { cleft = Integer.parseInt(m.group(4)); cright = Integer.parseInt(m.group(6)); } catch (NumberFormatException ex) { log.error( "could not parse context value", ex); } queryController. setQuery( new PagedResultQuery(cleft, cright, 0, 10, null, aql, selectedCorpora)); } else { queryController.setQuery(new Query(aql, selectedCorpora)); } // remove all currently openend sub-windows Set<Window> all = new HashSet<>(getWindows()); for (Window w : all) { removeWindow(w); } } else { Notification.show("Invalid citation", Notification.Type.WARNING_MESSAGE); } } @Override public void updateSidebarState(SidebarState state) { if(controlPanel != null && state != null && toolbar != null) { controlPanel.setVisible(state.isSidebarVisible()); // set cookie Cookie c = new Cookie("annis-sidebar-state", state.name()); c.setMaxAge(30*24*60*60); // 30 days c.setPath(VaadinService.getCurrentRequest().getContextPath()); VaadinService.getCurrentResponse().addCookie(c); } } @Override public void onTabClose(TabSheet tabsheet, Component tabContent) { tabsheet.removeComponent(tabContent); if (tabContent instanceof ResultViewPanel) { getQueryController().notifyTabClose((ResultViewPanel) tabContent); } else if (tabContent instanceof FrequencyQueryPanel) { controlPanel.getQueryPanel().notifyFrequencyTabClose(); } } public ControlPanel getControlPanel() { return controlPanel; } public InstanceConfig getInstanceConfig() { return instanceConfig; } public QueryController getQueryController() { return queryController; } public TabSheet getMainTab() { return mainTab; } @Override public void notifyCannotPlayMimeType(String mimeType) { if (mimeType == null) { return; } if (mimeType.startsWith("audio/ogg") || mimeType.startsWith("video/web")) { String browserList = "<ul>" + "<li>Mozilla Firefox: <a href=\"http://www.mozilla.org/firefox\" target=\"_blank\">http://www.mozilla.org/firefox</a></li>" + "<li>Google Chrome: <a href=\"http://www.google.com/chrome\" target=\"_blank\">http://www.google.com/chrome</a></li>" + "</ul>"; WebBrowser browser = getPage().getWebBrowser(); // IE9 users can install a plugin Set<String> supportedByIE9Plugin = new HashSet<>(); supportedByIE9Plugin.add("video/webm"); supportedByIE9Plugin.add("audio/ogg"); supportedByIE9Plugin.add("video/ogg"); if (browser.isIE() && browser.getBrowserMajorVersion() >= 9 && supportedByIE9Plugin. contains(mimeType)) { Notification n = new Notification("Media file type unsupported by your browser", "Please install the WebM plugin for Internet Explorer 9 from " + "<a target=\"_blank\" href=\"https://tools.google.com/dlpage/webmmf\">https://tools.google.com/dlpage/webmmf</a> " + " or use a browser from the following list " + "(these are known to work with WebM or OGG files)<br/>" + browserList + "<br/><br /><strong>Click on this message to hide it</strong>", Notification.Type.WARNING_MESSAGE, true); n.setDelayMsec(15000); n.show(Page.getCurrent()); } else { Notification n = new Notification("Media file type unsupported by your browser", "Please use a browser from the following list " + "(these are known to work with WebM or OGG files)<br/>" + browserList + "<br/><br /><strong>Click on this message to hide it</strong>", Notification.Type.WARNING_MESSAGE, true); n.setDelayMsec(15000); n.show(Page.getCurrent()); } } else { Notification.show( "Media file type \"" + mimeType + "\" unsupported by your browser!", "Try to check your browsers documentation how to enable " + "support for the media type or inform the corpus creator about this problem.", Notification.Type.WARNING_MESSAGE); } } public void notifiyQueryStarted() { toolbar.notifiyQueryStarted(); } @Override public void onLogin() { queryController.updateCorpusSetList(); } @Override public void onLogout() { queryController.updateCorpusSetList(); } @Override public void notifyMightNotPlayMimeType(String mimeType) { /* if(!warnedAboutPossibleMediaFormatProblem) { Notification notify = new Notification("Media file type \"" + mimeType + "\" might be unsupported by your browser!", "This means you might get errors playing this file.<br/><br /> " + "<em>If you have problems with this media file:</em><br /> Try to check your browsers " + "documentation how to enable " + "support for the media type or inform the corpus creator about this problem.", Notification.Type.TRAY_NOTIFICATION, true); notify.setDelayMsec(15000); showNotification(notify); warnedAboutPossibleMediaFormatProblem = true; } */ } @Override public void uriFragmentChanged(UriFragmentChangedEvent event) { evaluateFragment(event.getUriFragment()); } /** * Takes a list of raw corpus names as given by the #c parameter and returns * a list of corpus names that are known to exist. * It also replaces alias names * with the real corpus names. * @param originalNames * @return */ private Set<String> getMappedCorpora(List<String> originalNames) { WebResource rootRes = Helper.getAnnisWebResource(); Set<String> mappedNames = new HashSet<>(); // iterate over given corpora and map names if necessary for (String selectedCorpusName : originalNames) { // get the real corpus descriptions by the name (which could be an alias) try { List<AnnisCorpus> corporaByName = rootRes.path("query").path("corpora").path(URLEncoder.encode(selectedCorpusName, "UTF-8")) .get(new GenericType<List<AnnisCorpus>>() { }); for (AnnisCorpus c : corporaByName) { mappedNames.add(c.getName()); } } catch(UnsupportedEncodingException ex) { log. error("UTF-8 encoding is not supported on server, this is weird", ex); } catch (ClientHandlerException ex) { String msg = "alias mapping does not work for alias: " + selectedCorpusName; log.error(msg, ex); Notification.show(msg, Notification.Type.TRAY_NOTIFICATION); } } return mappedNames; } private void evaluateFragment(String fragment) { // do nothing if not changed if (fragment == null || fragment.isEmpty() || fragment.equals( lastQueriedFragment)) { return; } Map<String, String> args = Helper.parseFragment(fragment); Set<String> corpora = new TreeSet<>(); if (args.containsKey("c")) { String[] originalCorpusNames = args.get("c").split("\\s*,\\s*"); corpora = getMappedCorpora(Arrays.asList(originalCorpusNames)); } if (args.containsKey("c") && args.size() == 1) { // special case: we were called from outside and should only select, // but not query, the selected corpora if (corpora.isEmpty()) { // show a warning message that the corpus was not imported yet new Notification("Linked corpus does not exist", "<div><p>The corpus you wanted to access unfortunally does not (yet) exist" + " in ANNIS.</p>" + "<h2>possible reasons are:</h2>" + "<ul><li>that it has not been imported yet.</li>" + "<li>The ANNIS service is not running</li></ul>" + "<p>Please ask the responsible person of the site that contained " + "the link to import the corpus.</p></div>", Notification.Type.WARNING_MESSAGE, true).show(Page.getCurrent()); } else { getControlPanel().getCorpusList().selectCorpora(corpora); } } else if (args.get("cl") != null && args.get("cr") != null) { // do not change the manually selected search options controlPanel.getSearchOptions().setOptionsManuallyChanged(true); // full query with given context queryController.setQuery(new PagedResultQuery( Integer.parseInt(args.get("cl")), Integer.parseInt(args.get("cr")), Integer.parseInt(args.get("s")), Integer.parseInt(args.get("l")), args.get("seg"), args.get("q"), corpora)); queryController.executeQuery(); } else { // do not change the manually selected search options controlPanel.getSearchOptions().setOptionsManuallyChanged(true); // use default context queryController.setQuery(new Query(args.get("q"), corpora)); queryController.executeQuery(); } } /** * Updates the browser address bar with the current query paramaters and the * query itself. * * This is for convenient reloading the vaadin app and easy copying citation * links. * * @param q The query where the parameters are extracted from. */ public void updateFragment(PagedResultQuery q) { List<String> args = Helper.citationFragment(q.getQuery(), q.getCorpora(), q.getContextLeft(), q.getContextRight(), q.getSegmentation(), q.getOffset(), q.getLimit()); // set our fragment lastQueriedFragment = StringUtils.join(args, "&"); UI.getCurrent().getPage().setUriFragment(lastQueriedFragment); // reset title getPage().setTitle( instanceConfig.getInstanceDisplayName() + " (ANNIS Corpus Search)"); } /** * Adds the _c fragement to the URL in the browser adress bar when a corpus is * selected. * * @param corpora A list of corpora, which are add to the fragment. */ public void updateFragementWithSelectedCorpus(Set<String> corpora) { if (corpora != null && !corpora.isEmpty()) { String fragment = "_c=" + Helper.encodeBase64URL(StringUtils. join(corpora, ",")); UI.getCurrent().getPage().setUriFragment(fragment); } else { UI.getCurrent().getPage().setUriFragment(""); } } private class CitationRequestHandler implements RequestHandler { @Override public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { checkCitation(); return false; } } private static class AnnisCorpusListType extends GenericType<List<AnnisCorpus>> { public AnnisCorpusListType() { } } public TabSheet getTabSheet() { return mainTab; } public DocBrowserController getDocBrowserController() { return docBrowserController; } }
annis-gui/src/main/java/annis/gui/SearchUI.java
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licsense is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package annis.gui; import annis.VersionInfo; import annis.gui.requesthandler.ResourceRequestHandler; import annis.gui.requesthandler.LoginServletRequestHandler; import annis.gui.components.ExceptionDialog; import annis.libgui.AnnisBaseUI; import annis.libgui.InstanceConfig; import annis.libgui.Helper; import annis.gui.controlpanel.ControlPanel; import annis.gui.docbrowser.DocBrowserController; import annis.libgui.media.MediaController; import annis.libgui.media.MimeTypeErrorListener; import annis.libgui.media.MediaControllerImpl; import annis.gui.objects.PagedResultQuery; import annis.gui.objects.Query; import annis.gui.querybuilder.TigerQueryBuilderPlugin; import annis.gui.flatquerybuilder.FlatQueryBuilderPlugin; import annis.gui.frequency.FrequencyQueryPanel; import annis.gui.requesthandler.BinaryRequestHandler; import annis.gui.resultview.ResultViewPanel; import annis.gui.servlets.ResourceServlet; import static annis.libgui.Helper.*; import annis.libgui.media.PDFController; import annis.libgui.media.PDFControllerImpl; import annis.service.objects.AnnisCorpus; import annis.service.objects.CorpusConfig; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.vaadin.annotations.Theme; import com.vaadin.data.validator.EmailValidator; import com.vaadin.event.ShortcutListener; import com.vaadin.server.ErrorHandler; import com.vaadin.server.Page; import com.vaadin.server.Page.UriFragmentChangedEvent; import com.vaadin.server.RequestHandler; import com.vaadin.server.ThemeResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinResponse; import com.vaadin.server.VaadinService; import com.vaadin.server.VaadinSession; import com.vaadin.server.WebBrowser; import com.vaadin.ui.*; import com.vaadin.ui.TabSheet.Tab; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.*; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.util.uri.ClassURI; import org.apache.commons.lang3.StringUtils; import org.slf4j.LoggerFactory; /** * GUI for searching in corpora. * * @author Thomas Krause <krauseto@hu-berlin.de> */ @Theme("annis") public class SearchUI extends AnnisBaseUI implements MimeTypeErrorListener, Page.UriFragmentChangedListener, ErrorHandler, TabSheet.CloseHandler, LoginListener, Sidebar { private static final org.slf4j.Logger log = LoggerFactory.getLogger( SearchUI.class); private transient Cache<String, CorpusConfig> corpusConfigCache; // regular expression matching, CLEFT and CRIGHT are optional // indexes: AQL=1, CIDS=2, CLEFT=4, CRIGHT=6 private final Pattern citationPattern = Pattern. compile( "AQL\\((.*)\\),CIDS\\(([^)]*)\\)(,CLEFT\\(([^)]*)\\),)?(CRIGHT\\(([^)]*)\\))?", Pattern.MULTILINE | Pattern.DOTALL); private MainToolbar toolbar; private ControlPanel controlPanel; private TabSheet mainTab; private QueryController queryController; private String lastQueriedFragment; private InstanceConfig instanceConfig; private DocBrowserController docBrowserController; public final static int CONTROL_PANEL_WIDTH = 360; private void initTransients() { corpusConfigCache = CacheBuilder.newBuilder().maximumSize(250).build(); } public SearchUI() { initTransients(); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); initTransients(); } @Override protected void init(VaadinRequest request) { super.init(request); setErrorHandler(this); this.instanceConfig = getInstanceConfig(request); getPage().setTitle( instanceConfig.getInstanceDisplayName() + " (ANNIS Corpus Search)"); // init a doc browser controller docBrowserController = new DocBrowserController(this); queryController = new QueryController(this); // always get the resize events directly setImmediate(true); GridLayout mainLayout = new GridLayout(2,2); setContent(mainLayout); mainLayout.setSizeFull(); mainLayout.setMargin(false); mainLayout.setRowExpandRatio(1, 1.0f); mainLayout.setColumnExpandRatio(1, 1.0f); toolbar = new MainToolbar(SearchUI.this); toolbar.addLoginListener(SearchUI.this); addExtension(toolbar.getScreenshotExtension()); mainLayout.addComponent(toolbar, 0,0, 1, 0); final HelpPanel help = new HelpPanel(this); mainTab = new TabSheet(); mainTab.setSizeFull(); mainTab.setCloseHandler(this); mainTab.addSelectedTabChangeListener(queryController); mainTab.addStyleName("blue-tab"); Tab helpTab = mainTab.addTab(help, "Help/Examples"); helpTab.setIcon(new ThemeResource("images/tango-icons/16x16/help-browser.png")); helpTab.setClosable(false); controlPanel = new ControlPanel(queryController, instanceConfig, help.getExamples(), this); controlPanel.setWidth(CONTROL_PANEL_WIDTH, Layout.Unit.PIXELS); controlPanel.setHeight(100f, Layout.Unit.PERCENTAGE); mainLayout.addComponent(controlPanel, 0, 1); mainLayout.addComponent(mainTab, 1,1); addAction(new ShortcutListener("Tutor^eial") { @Override public void handleAction(Object sender, Object target) { mainTab.setSelectedTab(help); } }); getPage().addUriFragmentChangedListener(this); getSession().addRequestHandler(new CitationRequestHandler()); getSession().addRequestHandler(new ResourceRequestHandler()); getSession().addRequestHandler(new LoginServletRequestHandler()); getSession().addRequestHandler(new BinaryRequestHandler()); getSession().setAttribute(MediaController.class, new MediaControllerImpl()); getSession().setAttribute(PDFController.class, new PDFControllerImpl()); loadInstanceFonts(); checkCitation(); lastQueriedFragment = ""; evaluateFragment(getPage().getUriFragment()); checkServiceVersion(); } private void checkServiceVersion() { try { WebResource resRelease = Helper.getAnnisWebResource().path("version").path("release"); String releaseService = resRelease.get(String.class); String releaseGUI = VersionInfo.getReleaseName(); // check if the release version differs and show a big warning if(!releaseGUI.equals(releaseService)) { Notification.show("Different service version", "The service uses version " + releaseService + " but the user interface is using version " + releaseGUI + ". This can produce unwanted errors.", Notification.Type.WARNING_MESSAGE); } else { // show a smaller warning if the revisions are not the same WebResource resRevision = Helper.getAnnisWebResource().path("version").path("revision"); String revisionService = resRevision.get(String.class); String revisionGUI = VersionInfo.getBuildRevision(); if(!revisionService.equals(revisionGUI)) { Notification.show("Different service revision", "The service uses revision " + revisionService + " but the user interface is using revision " + revisionGUI + ".", Notification.Type.TRAY_NOTIFICATION); } } } catch(UniformInterfaceException ex) { log.warn("Could not get the version of the service", ex); } } @Override public void error(com.vaadin.server.ErrorEvent event) { log.error("Unknown error in some component: " + event.getThrowable(). getLocalizedMessage(), event.getThrowable()); // get the source throwable (thus the one that triggered the error) Throwable source = event.getThrowable(); if(source != null) { while (source.getCause() != null) { source = source.getCause(); } ExceptionDialog.show(source); } } public boolean canReportBugs() { if(toolbar != null) { return toolbar.canReportBugs(); } return false; } public void reportBug() { toolbar.reportBug(); } public void reportBug(Throwable cause) { toolbar.reportBug(cause); } private void loadInstanceFonts() { if (instanceConfig != null && instanceConfig.getFont() != null) { FontConfig cfg = instanceConfig.getFont(); if (cfg.getSize() == null || cfg.getSize().isEmpty()) { injectUniqueCSS( "@import url(" + cfg.getUrl() + ");\n" + "." + CORPUS_FONT_FORCE + " {font-family: '" + cfg.getName() + "', monospace !important; }\n" + "." + CORPUS_FONT + " {font-family: '" + cfg.getName() + "', monospace; }\n" // this one is for the virtual keyboard + "#keyboardInputMaster tbody tr td table tbody tr td {\n" + " font-family: '" + cfg.getName() + "', 'Lucida Console','Arial Unicode MS',monospace; " + "}"); } else { injectUniqueCSS( "@import url(" + cfg.getUrl() + ");\n" + "." + CORPUS_FONT_FORCE + " {\n" + " font-family: '" + cfg.getName() + "', monospace !important;\n" + " font-size: " + cfg.getSize() + " !important;\n" + "}\n" + "." + CORPUS_FONT + " {\n" + " font-family: '" + cfg.getName() + "', monospace;\n" + " font-size: " + cfg.getSize() + ";\n" + "}\n" + "." + CORPUS_FONT + " .v-table-table {\n" + " font-size: " + cfg.getSize() + ";\n" + "}" // this one is for the virtual keyboard + "#keyboardInputMaster tbody tr td table tbody tr td {\n" + " font-family: '" + cfg.getName() + "', 'Lucida Console','Arial Unicode MS',monospace; " + "}"); } } else { injectUniqueCSS( // use original font definition from keyboard.css if no font given "#keyboardInputMaster tbody tr td table tbody tr td {\n" + " font-family: 'Lucida Console','Arial Unicode MS',monospace;" + "}"); } } private InstanceConfig getInstanceConfig(VaadinRequest request) { String instance = null; String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1); } if (pathInfo != null && pathInfo.endsWith("/")) { pathInfo = pathInfo.substring(0, pathInfo.length() - 1); } Map<String, InstanceConfig> allConfigs = loadInstanceConfig(); if (pathInfo != null && !pathInfo.isEmpty()) { instance = pathInfo; } if (instance != null && allConfigs.containsKey(instance)) { // return the config that matches the parsed name return allConfigs.get(instance); } else if (allConfigs.containsKey("default")) { // return the default config return allConfigs.get("default"); } else if (allConfigs.size() > 0) { // just return any existing config as a fallback log. warn( "Instance config {} not found or null and default config is not available.", instance); return allConfigs.values().iterator().next(); } // default to an empty instance config return new InstanceConfig(); } /** * Get a cached version of the {@link CorpusConfig} for a corpus. * * @param corpus * @return */ public CorpusConfig getCorpusConfigWithCache(String corpus) { CorpusConfig config = new CorpusConfig(); if (corpusConfigCache != null) { config = corpusConfigCache.getIfPresent(corpus); if (config == null) { if (corpus.equals(DEFAULT_CONFIG)) { config = Helper.getDefaultCorpusConfig(); } else { config = Helper.getCorpusConfig(corpus); } corpusConfigCache.put(corpus, config); } } return config; } public void clearCorpusConfigCache() { if (corpusConfigCache != null) { corpusConfigCache.invalidateAll(); } } @Override protected void addCustomUIPlugins(PluginManager pluginManager) { pluginManager.addPluginsFrom(new ClassURI(TigerQueryBuilderPlugin.class). toURI()); pluginManager.addPluginsFrom(new ClassURI(FlatQueryBuilderPlugin.class). toURI()); pluginManager.addPluginsFrom(new ClassURI(ResourceServlet.class).toURI()); } public void checkCitation() { if (VaadinSession.getCurrent() == null || VaadinSession.getCurrent(). getSession() == null) { return; } Object origURLRaw = VaadinSession.getCurrent().getSession().getAttribute( "citation"); if (origURLRaw == null || !(origURLRaw instanceof String)) { return; } String origURL = (String) origURLRaw; String parameters = origURL.replaceAll(".*?/Cite(/)?", ""); if (!"".equals(parameters) && !origURL.equals(parameters)) { try { String decoded = URLDecoder.decode(parameters, "UTF-8"); evaluateCitation(decoded); } catch (UnsupportedEncodingException ex) { log.error(null, ex); } } } public void evaluateCitation(String relativeUri) { Matcher m = citationPattern.matcher(relativeUri); if (m.matches()) { // AQL String aql = ""; if (m.group(1) != null) { aql = m.group(1); } // CIDS Set<String> selectedCorpora = new HashSet<>(); if (m.group(2) != null) { String[] cids = m.group(2).split(","); selectedCorpora.addAll(Arrays.asList(cids)); } // filter by actually avaible user corpora in order not to get any exception later WebResource res = Helper.getAnnisWebResource(); List<AnnisCorpus> userCorpora = res.path("query").path("corpora"). get(new AnnisCorpusListType()); LinkedList<String> userCorporaStrings = new LinkedList<>(); for (AnnisCorpus c : userCorpora) { userCorporaStrings.add(c.getName()); } selectedCorpora.retainAll(userCorporaStrings); // CLEFT and CRIGHT if (m.group(4) != null && m.group(6) != null) { int cleft = 0; int cright = 0; try { cleft = Integer.parseInt(m.group(4)); cright = Integer.parseInt(m.group(6)); } catch (NumberFormatException ex) { log.error( "could not parse context value", ex); } queryController. setQuery( new PagedResultQuery(cleft, cright, 0, 10, null, aql, selectedCorpora)); } else { queryController.setQuery(new Query(aql, selectedCorpora)); } // remove all currently openend sub-windows Set<Window> all = new HashSet<>(getWindows()); for (Window w : all) { removeWindow(w); } } else { Notification.show("Invalid citation", Notification.Type.WARNING_MESSAGE); } } @Override public void updateSidebarState(SidebarState state) { if(controlPanel != null && state != null && toolbar != null) { controlPanel.setVisible(state.isSidebarVisible()); // set cookie Cookie c = new Cookie("annis-sidebar-state", state.name()); c.setMaxAge(30*24*60*60); // 30 days c.setPath(VaadinService.getCurrentRequest().getContextPath()); VaadinService.getCurrentResponse().addCookie(c); } } @Override public void onTabClose(TabSheet tabsheet, Component tabContent) { tabsheet.removeComponent(tabContent); if (tabContent instanceof ResultViewPanel) { getQueryController().notifyTabClose((ResultViewPanel) tabContent); } else if (tabContent instanceof FrequencyQueryPanel) { controlPanel.getQueryPanel().notifyFrequencyTabClose(); } } public ControlPanel getControlPanel() { return controlPanel; } public InstanceConfig getInstanceConfig() { return instanceConfig; } public QueryController getQueryController() { return queryController; } public TabSheet getMainTab() { return mainTab; } @Override public void notifyCannotPlayMimeType(String mimeType) { if (mimeType == null) { return; } if (mimeType.startsWith("audio/ogg") || mimeType.startsWith("video/web")) { String browserList = "<ul>" + "<li>Mozilla Firefox: <a href=\"http://www.mozilla.org/firefox\" target=\"_blank\">http://www.mozilla.org/firefox</a></li>" + "<li>Google Chrome: <a href=\"http://www.google.com/chrome\" target=\"_blank\">http://www.google.com/chrome</a></li>" + "</ul>"; WebBrowser browser = getPage().getWebBrowser(); // IE9 users can install a plugin Set<String> supportedByIE9Plugin = new HashSet<>(); supportedByIE9Plugin.add("video/webm"); supportedByIE9Plugin.add("audio/ogg"); supportedByIE9Plugin.add("video/ogg"); if (browser.isIE() && browser.getBrowserMajorVersion() >= 9 && supportedByIE9Plugin. contains(mimeType)) { Notification n = new Notification("Media file type unsupported by your browser", "Please install the WebM plugin for Internet Explorer 9 from " + "<a target=\"_blank\" href=\"https://tools.google.com/dlpage/webmmf\">https://tools.google.com/dlpage/webmmf</a> " + " or use a browser from the following list " + "(these are known to work with WebM or OGG files)<br/>" + browserList + "<br/><br /><strong>Click on this message to hide it</strong>", Notification.Type.WARNING_MESSAGE, true); n.setDelayMsec(15000); n.show(Page.getCurrent()); } else { Notification n = new Notification("Media file type unsupported by your browser", "Please use a browser from the following list " + "(these are known to work with WebM or OGG files)<br/>" + browserList + "<br/><br /><strong>Click on this message to hide it</strong>", Notification.Type.WARNING_MESSAGE, true); n.setDelayMsec(15000); n.show(Page.getCurrent()); } } else { Notification.show( "Media file type \"" + mimeType + "\" unsupported by your browser!", "Try to check your browsers documentation how to enable " + "support for the media type or inform the corpus creator about this problem.", Notification.Type.WARNING_MESSAGE); } } public void notifiyQueryStarted() { toolbar.notifiyQueryStarted(); } @Override public void onLogin() { queryController.updateCorpusSetList(); } @Override public void onLogout() { queryController.updateCorpusSetList(); } @Override public void notifyMightNotPlayMimeType(String mimeType) { /* if(!warnedAboutPossibleMediaFormatProblem) { Notification notify = new Notification("Media file type \"" + mimeType + "\" might be unsupported by your browser!", "This means you might get errors playing this file.<br/><br /> " + "<em>If you have problems with this media file:</em><br /> Try to check your browsers " + "documentation how to enable " + "support for the media type or inform the corpus creator about this problem.", Notification.Type.TRAY_NOTIFICATION, true); notify.setDelayMsec(15000); showNotification(notify); warnedAboutPossibleMediaFormatProblem = true; } */ } @Override public void uriFragmentChanged(UriFragmentChangedEvent event) { evaluateFragment(event.getUriFragment()); } /** * Takes a list of raw corpus names as given by the #c parameter and returns * a list of corpus names that are known to exist. * It also replaces alias names * with the real corpus names. * @param originalNames * @return */ private Set<String> getMappedCorpora(List<String> originalNames) { WebResource rootRes = Helper.getAnnisWebResource(); Set<String> mappedNames = new HashSet<>(); // iterate over given corpora and map names if necessary for (String selectedCorpusName : originalNames) { // get the real corpus descriptions by the name (which could be an alias) try { List<AnnisCorpus> corporaByName = rootRes.path("query").path("corpora").path(URLEncoder.encode(selectedCorpusName, "UTF-8")) .get(new GenericType<List<AnnisCorpus>>() { }); for (AnnisCorpus c : corporaByName) { mappedNames.add(c.getName()); } } catch(UnsupportedEncodingException ex) { log. error("UTF-8 encoding is not supported on server, this is weird", ex); } catch (ClientHandlerException ex) { String msg = "alias mapping does not work for alias: " + selectedCorpusName; log.error(msg, ex); Notification.show(msg, Notification.Type.TRAY_NOTIFICATION); } } return mappedNames; } private void evaluateFragment(String fragment) { // do nothing if not changed if (fragment == null || fragment.isEmpty() || fragment.equals( lastQueriedFragment)) { return; } Map<String, String> args = Helper.parseFragment(fragment); Set<String> corpora = new TreeSet<>(); if (args.containsKey("c")) { String[] originalCorpusNames = args.get("c").split("\\s*,\\s*"); corpora = getMappedCorpora(Arrays.asList(originalCorpusNames)); } if (args.containsKey("c") && args.size() == 1) { // special case: we were called from outside and should only select, // but not query, the selected corpora if (corpora.isEmpty()) { // show a warning message that the corpus was not imported yet new Notification("Linked corpus does not exist", "<div><p>The corpus you wanted to access unfortunally does not (yet) exist" + " in ANNIS.</p>" + "<h2>possible reasons are:</h2>" + "<ul><li>that it has not been imported yet.</li>" + "<li>The ANNIS service is not running</li></ul>" + "<p>Please ask the responsible person of the site that contained " + "the link to import the corpus.</p></div>", Notification.Type.WARNING_MESSAGE, true).show(Page.getCurrent()); } else { getControlPanel().getCorpusList().selectCorpora(corpora); } } else if (args.get("cl") != null && args.get("cr") != null) { // do not change the manually selected search options controlPanel.getSearchOptions().setOptionsManuallyChanged(true); // full query with given context queryController.setQuery(new PagedResultQuery( Integer.parseInt(args.get("cl")), Integer.parseInt(args.get("cr")), Integer.parseInt(args.get("s")), Integer.parseInt(args.get("l")), args.get("seg"), args.get("q"), corpora)); queryController.executeQuery(); } else { // do not change the manually selected search options controlPanel.getSearchOptions().setOptionsManuallyChanged(true); // use default context queryController.setQuery(new Query(args.get("q"), corpora)); queryController.executeQuery(); } } /** * Updates the browser address bar with the current query paramaters and the * query itself. * * This is for convenient reloading the vaadin app and easy copying citation * links. * * @param q The query where the parameters are extracted from. */ public void updateFragment(PagedResultQuery q) { List<String> args = Helper.citationFragment(q.getQuery(), q.getCorpora(), q.getContextLeft(), q.getContextRight(), q.getSegmentation(), q.getOffset(), q.getLimit()); // set our fragment lastQueriedFragment = StringUtils.join(args, "&"); UI.getCurrent().getPage().setUriFragment(lastQueriedFragment); // reset title getPage().setTitle( instanceConfig.getInstanceDisplayName() + " (ANNIS Corpus Search)"); } /** * Adds the _c fragement to the URL in the browser adress bar when a corpus is * selected. * * @param corpora A list of corpora, which are add to the fragment. */ public void updateFragementWithSelectedCorpus(Set<String> corpora) { if (corpora != null && !corpora.isEmpty()) { String fragment = "_c=" + Helper.encodeBase64URL(StringUtils. join(corpora, ",")); UI.getCurrent().getPage().setUriFragment(fragment); } else { UI.getCurrent().getPage().setUriFragment(""); } } private class CitationRequestHandler implements RequestHandler { @Override public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { checkCitation(); return false; } } private static class AnnisCorpusListType extends GenericType<List<AnnisCorpus>> { public AnnisCorpusListType() { } } public TabSheet getTabSheet() { return mainTab; } public DocBrowserController getDocBrowserController() { return docBrowserController; } }
don't show exception whenever the service is not running
annis-gui/src/main/java/annis/gui/SearchUI.java
don't show exception whenever the service is not running
Java
apache-2.0
705d35a9d0dca3303e4ca6b550083b81b72bd801
0
zahid-ali-shah/SignatureView
package com.kyanogen.signatureview; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.kyanogen.signatureview.model.Point; public class SignatureView extends View { public static final String TAG = SignatureView.class.getSimpleName(); private Canvas canvasBmp; private boolean ignoreTouch; private Point previousPoint, startPoint, currentPoint; public static final float MIN_PEN_SIZE = 1f; private static final float MIN_INCREMENT = 0.01f; private static final float INCREMENT_CONSTANT = 0.0005f; private static final float DRAWING_CONSTANT = 0.0085f; public static final float MAX_VELOCITY_BOUND = 15f; private static final float MIN_VELOCITY_BOUND = 1.6f; private static final float STROKE_DES_VELOCITY = 1.0f; private float VELOCITY_FILTER_WEIGHT = 0.2f; private float lastVelocity, lastWidth; private Paint paint, paintBm; private Bitmap bmp; private int layoutLeft, layoutTop, layoutRight, layoutBottom; private Rect drawViewRect; private int penColor, backgroundColor; private boolean enableSignature; private float penSize; private Context context; @SuppressWarnings("deprecation") public SignatureView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; this.setWillNotDraw(false); this.setDrawingCacheEnabled(true); TypedArray typedArray = context.getTheme().obtainStyledAttributes( attrs,R.styleable.signature, 0, 0); try { backgroundColor = typedArray.getColor(R.styleable.signature_backgroundColor, context.getResources().getColor(R.color.white)); penColor = typedArray.getColor(R.styleable.signature_penColor, context.getResources().getColor(R.color.penRoyalBlue)); penSize = typedArray.getDimension(R.styleable.signature_penSize, context.getResources().getDimension(R.dimen.pen_size)); enableSignature = typedArray.getBoolean(R.styleable.signature_enableSignature, true); } finally { typedArray.recycle(); } paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(penColor); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth(penSize); paintBm = new Paint(Paint.ANTI_ALIAS_FLAG); paintBm.setAntiAlias(true); paintBm.setStyle(Paint.Style.STROKE); paintBm.setStrokeJoin(Paint.Join.ROUND); paintBm.setStrokeCap(Paint.Cap.ROUND); paintBm.setColor(Color.BLACK); } /**************** Getter/Setter *****************/ /** * Get stoke size for signature creation * * @return float */ public float getPenSize() { return penSize; } /** * Set stoke size for signature creation * * @param penSize float */ public void setPenSize(float penSize) { this.penSize = penSize; } /** * Check if drawing on canvas is enabled or disabled * * @return boolean */ public boolean isEnableSignature() { return enableSignature; } /** * Enable or disable drawing on canvas * * @param enableSignature boolean */ public void setEnableSignature(boolean enableSignature) { this.enableSignature = enableSignature; } /** * Get stoke color for signature creation * * @return int */ public int getPenColor() { return penColor; } /** * Set stoke color for signature creation * * @param penColor int */ public void setPenColor(int penColor) { this.penColor = penColor; } /** * Get background color * * @return int */ public int getBackgroundColor() { return backgroundColor; } /** * Set background color * * @param backgroundColor int */ @Override public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; } /** * Clear signature from canvas * */ public void clearCanvas(){ previousPoint=null; startPoint=null; currentPoint=null; lastVelocity = 0; lastWidth = 0; newBitmapCanvas(layoutLeft, layoutTop, layoutRight, layoutBottom); postInvalidate(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); layoutLeft = left; layoutTop = top; layoutRight = right; layoutBottom = bottom; if(bmp == null){ newBitmapCanvas(layoutLeft, layoutTop, layoutRight, layoutBottom); } } private void newBitmapCanvas(int left, int top, int right, int bottom) { bmp = null; canvasBmp = null; bmp = Bitmap.createBitmap(right - left, bottom - top, Bitmap.Config.ARGB_8888); canvasBmp = new Canvas(bmp); canvasBmp.drawColor(backgroundColor); } @Override public boolean onTouchEvent(MotionEvent event) { if (!isEnableSignature()){ return false; } if(event.getPointerCount() > 1) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: ignoreTouch = false; drawViewRect = new Rect(this.getLeft(), this.getTop(), this.getRight(), this.getBottom()); onTouchDownEvent(event.getX(), event.getY()); break; case MotionEvent.ACTION_MOVE: if(!drawViewRect.contains(getLeft() + (int) event.getX(), this.getTop() + (int) event.getY())){ //You are out of drawing area if(!ignoreTouch){ ignoreTouch = true; onTouchUpEvent(event.getX(), event.getY()); } } else { //You are in the drawing area if(ignoreTouch){ ignoreTouch = false; onTouchDownEvent(event.getX(), event.getY()); }else{ onTouchMoveEvent(event.getX(), event.getY()); } } break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: onTouchUpEvent(event.getX(), event.getY()); break; default: break; } return true;// super.onTouchEvent(event); } private void onTouchDownEvent(float x, float y) { previousPoint=null; startPoint=null; currentPoint=null; lastVelocity = 0; lastWidth = penSize; currentPoint = new Point(x, y, System.currentTimeMillis()); previousPoint = currentPoint; startPoint = previousPoint; postInvalidate(); } private void onTouchMoveEvent(float x, float y) { if(previousPoint==null){ return; } startPoint = previousPoint; previousPoint = currentPoint; currentPoint = new Point(x, y, System.currentTimeMillis()); float velocity = currentPoint.velocityFrom(previousPoint); velocity = VELOCITY_FILTER_WEIGHT * velocity + (1 - VELOCITY_FILTER_WEIGHT) * lastVelocity; float strokeWidth = getStrokeWidth(velocity); drawLine(lastWidth, strokeWidth, velocity); lastVelocity = velocity; lastWidth = strokeWidth; postInvalidate(); } private void onTouchUpEvent(float x, float y) { if(previousPoint==null){ return; } startPoint = previousPoint; previousPoint = currentPoint; currentPoint = new Point(x, y, System.currentTimeMillis()); drawLine(lastWidth, 0, lastVelocity); postInvalidate(); } private float getStrokeWidth(float velocity){ return penSize - (velocity * STROKE_DES_VELOCITY); } @Override protected void onDraw(Canvas canvas) { canvas.drawBitmap(bmp, 0, 0, paintBm); } private void drawLine(final float lastWidth, final float currentWidth, final float velocity){ final Point mid1 = midPoint(previousPoint, startPoint); final Point mid2 = midPoint(currentPoint, previousPoint); draw(mid1, previousPoint, mid2, lastWidth, currentWidth, velocity); } private float getPt( float n1 , float n2 , float perc){ float diff = n2 - n1; return n1 + ( diff * perc ); } private void draw(Point p0, Point p1, Point p2, float lastWidth, float currentWidth, float velocity){ float xa, xb, ya, yb, x, y; float increment; if(velocity>MIN_VELOCITY_BOUND && velocity< MAX_VELOCITY_BOUND){ increment = DRAWING_CONSTANT - (velocity * INCREMENT_CONSTANT); }else{ increment = MIN_INCREMENT; } for(float i = 0f; i < 1f; i += increment){ xa = getPt( p0.x , p1.x , i ); ya = getPt( p0.y , p1.y , i ); xb = getPt( p1.x , p2.x , i ); yb = getPt( p1.y , p2.y , i ); x = getPt( xa , xb , i ); y = getPt( ya , yb , i ); float strokeVal = lastWidth + (currentWidth - lastWidth) * (i); paint.setStrokeWidth(strokeVal < MIN_PEN_SIZE ? MIN_PEN_SIZE : strokeVal); canvasBmp.drawPoint(x, y, paint); } } private Point midPoint(Point p1, Point p2){ return new Point((p1.x + p2.x) / 2.0f , (p1.y + p2.y) / 2, (p1.time + p2.time) / 2); } /** * Get signature as bitmap * * @return Bitmap */ public Bitmap getSignatureBitmap(){ return Bitmap.createScaledBitmap(bmp, bmp.getWidth(), bmp.getHeight(), true); } /** * Render bitmap in signature * * @param bitmap Bitmap */ public void setBitmap(Bitmap bitmap) { bmp=bitmap; canvasBmp = new Canvas(bitmap); postInvalidate(); } /** * Get version info related to library * * @return String */ public String getVersionInfo(){ String versionInfo = null; PackageInfo pInfo = null; try { pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); if(pInfo!=null){ versionInfo = "SignatureView Version : "+pInfo.versionName; } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionInfo; } }
signature-view/src/main/java/com/kyanogen/signatureview/SignatureView.java
package com.kyanogen.signatureview; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.kyanogen.signatureview.model.Point; public class SignatureView extends View { public static final String TAG = SignatureView.class.getSimpleName(); private Canvas canvasBmp; private boolean ignoreTouch; private Point previousPoint, startPoint, currentPoint; public static final float MIN_PEN_SIZE = 1f; private static final float MIN_INCREMENT = 0.01f; private static final float INCREMENT_CONSTANT = 0.0005f; private static final float DRAWING_CONSTANT = 0.0085f; public static final float MAX_VELOCITY_BOUND = 15f; private static final float MIN_VELOCITY_BOUND = 1.6f; private static final float STROKE_DES_VELOCITY = 1.0f; private float VELOCITY_FILTER_WEIGHT = 0.2f; private float lastVelocity, lastWidth; private Paint paint, paintBm; private Bitmap bmp; private int layoutLeft, layoutTop, layoutRight, layoutBottom; private Rect drawViewRect; private int penColor, backgroundColor; private boolean enableSignature; private float penSize; private Context context; @SuppressWarnings("deprecation") public SignatureView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; this.setWillNotDraw(false); this.setDrawingCacheEnabled(true); TypedArray typedArray = context.getTheme().obtainStyledAttributes( attrs,R.styleable.signature, 0, 0); try { backgroundColor = typedArray.getColor(R.styleable.signature_backgroundColor, context.getResources().getColor(R.color.white)); penColor = typedArray.getColor(R.styleable.signature_penColor, context.getResources().getColor(R.color.penRoyalBlue)); penSize = typedArray.getDimension(R.styleable.signature_penSize, context.getResources().getDimension(R.dimen.pen_size)); enableSignature = typedArray.getBoolean(R.styleable.signature_enableSignature, true); } finally { typedArray.recycle(); } paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(penColor); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth(penSize); paintBm = new Paint(Paint.ANTI_ALIAS_FLAG); paintBm.setAntiAlias(true); paintBm.setStyle(Paint.Style.STROKE); paintBm.setStrokeJoin(Paint.Join.ROUND); paintBm.setStrokeCap(Paint.Cap.ROUND); paintBm.setColor(Color.BLACK); } /**************** Getter/Setter *****************/ /** * Get stoke size for signature creation * * @return float */ public float getPenSize() { return penSize; } /** * Set stoke size for signature creation * * @param penSize float */ public void setPenSize(float penSize) { this.penSize = penSize; } /** * Check if drawing on canvas is enabled or disabled * * @return boolean */ public boolean isEnableSignature() { return enableSignature; } /** * Enable or disable drawing on canvas * * @param enableSignature boolean */ public void setEnableSignature(boolean enableSignature) { this.enableSignature = enableSignature; } /** * Get stoke color for signature creation * * @return int */ public int getPenColor() { return penColor; } /** * Set stoke color for signature creation * * @param penColor int */ public void setPenColor(int penColor) { this.penColor = penColor; } /** * Get background color * * @return int */ public int getBackgroundColor() { return backgroundColor; } /** * Set background color * * @param backgroundColor int */ @Override public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; } /** * Clear signature from canvas * */ public void clearCanvas(){ previousPoint=null; startPoint=null; currentPoint=null; lastVelocity = 0; lastWidth = 0; newBitmapCanvas(layoutLeft, layoutTop, layoutRight, layoutBottom); postInvalidate(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); layoutLeft = left; layoutTop = top; layoutRight = right; layoutBottom = bottom; if(bmp == null){ newBitmapCanvas(layoutLeft, layoutTop, layoutRight, layoutBottom); } } private void newBitmapCanvas(int left, int top, int right, int bottom) { bmp = null; canvasBmp = null; bmp = Bitmap.createBitmap(right - left, bottom - top, Bitmap.Config.ARGB_8888); canvasBmp = new Canvas(bmp); canvasBmp.drawColor(backgroundColor); } @Override public boolean onTouchEvent(MotionEvent event) { if (!isEnableSignature()){ return false; } if(event.getPointerCount() > 1) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: ignoreTouch = false; drawViewRect = new Rect(this.getLeft(), this.getTop(), this.getRight(), this.getBottom()); onTouchDownEvent(event.getX(), event.getY()); break; case MotionEvent.ACTION_MOVE: if(!drawViewRect.contains(getLeft() + (int) event.getX(), this.getTop() + (int) event.getY())){ //You are out of drawing area if(!ignoreTouch){ ignoreTouch = true; onTouchUpEvent(event.getX(), event.getY()); } } else { //You are in the drawing area if(ignoreTouch){ ignoreTouch = false; onTouchDownEvent(event.getX(), event.getY()); }else{ onTouchMoveEvent(event.getX(), event.getY()); } } break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: onTouchUpEvent(event.getX(), event.getY()); break; default: break; } return true;// super.onTouchEvent(event); } private void onTouchDownEvent(float x, float y) { previousPoint=null; startPoint=null; currentPoint=null; lastVelocity = 0; lastWidth = penSize; currentPoint = new Point(x, y, System.currentTimeMillis()); previousPoint = currentPoint; startPoint = previousPoint; postInvalidate(); } private void onTouchMoveEvent(float x, float y) { if(previousPoint==null){ return; } startPoint = previousPoint; previousPoint = currentPoint; currentPoint = new Point(x, y, System.currentTimeMillis()); float velocity = currentPoint.velocityFrom(previousPoint); velocity = VELOCITY_FILTER_WEIGHT * velocity + (1 - VELOCITY_FILTER_WEIGHT) * lastVelocity; float strokeWidth = getStrokeWidth(velocity); drawLine(lastWidth, strokeWidth, velocity); lastVelocity = velocity; lastWidth = strokeWidth; postInvalidate(); } private void onTouchUpEvent(float x, float y) { if(previousPoint==null){ return; } startPoint = previousPoint; previousPoint = currentPoint; currentPoint = new Point(x, y, System.currentTimeMillis()); drawLine(lastWidth, 0, lastVelocity); postInvalidate(); } private float getStrokeWidth(float velocity){ return penSize - (velocity * STROKE_DES_VELOCITY); } @Override protected void onDraw(Canvas canvas) { canvas.drawBitmap(bmp, 0, 0, paintBm); } private void drawLine(final float lastWidth, final float currentWidth, final float velocity){ final Point mid1 = midPoint(previousPoint, startPoint); final Point mid2 = midPoint(currentPoint, previousPoint); draw(mid1, previousPoint, mid2, lastWidth, currentWidth, velocity); } private float getPt( float n1 , float n2 , float perc){ float diff = n2 - n1; return n1 + ( diff * perc ); } private void draw(Point p0, Point p1, Point p2, float lastWidth, float currentWidth, float velocity){ float xa, xb, ya, yb, x, y; float increment; if(velocity>MIN_VELOCITY_BOUND && velocity< MAX_VELOCITY_BOUND){ increment = DRAWING_CONSTANT - (velocity * INCREMENT_CONSTANT); }else{ increment = MIN_INCREMENT; } for(float i = 0f; i < 1f; i += increment){ xa = getPt( p0.x , p1.x , i ); ya = getPt( p0.y , p1.y , i ); xb = getPt( p1.x , p2.x , i ); yb = getPt( p1.y , p2.y , i ); x = getPt( xa , xb , i ); y = getPt( ya , yb , i ); float strokeVal = lastWidth + (currentWidth - lastWidth) * (i); paint.setStrokeWidth(strokeVal < MIN_PEN_SIZE ? MIN_PEN_SIZE : strokeVal); canvasBmp.drawPoint(x, y, paint); } } private Point midPoint(Point p1, Point p2){ return new Point((p1.x + p2.x) / 2.0f , (p1.y + p2.y) / 2, (p1.time + p2.time) / 2); } /** * Get signature as bitmap * * @return Bitmap */ public Bitmap getSignatureBitmap(){ return Bitmap.createScaledBitmap(bmp, bmp.getWidth(), bmp.getHeight(), true); } /** * Get version info related to library * * @return String */ public String getVersionInfo(){ String versionInfo = null; PackageInfo pInfo = null; try { pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); if(pInfo!=null){ versionInfo = "SignatureView Version : "+pInfo.versionName; } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionInfo; } }
Update SignatureView.java
signature-view/src/main/java/com/kyanogen/signatureview/SignatureView.java
Update SignatureView.java
Java
apache-2.0
3ecc73192a65a313c8db42223cd25e60511fe4c3
0
foundation-runtime/service-directory,foundation-runtime/service-directory
package com.cisco.oss.foundation.directory.impl; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cisco.oss.foundation.directory.DirectoryServiceClientManager; import com.cisco.oss.foundation.directory.ServiceDirectory; import com.cisco.oss.foundation.directory.entity.ModelMetadataKey; import com.cisco.oss.foundation.directory.entity.ModelService; import com.cisco.oss.foundation.directory.entity.ModelServiceInstance; import com.cisco.oss.foundation.directory.entity.OperationResult; import com.cisco.oss.foundation.directory.entity.OperationalStatus; import com.cisco.oss.foundation.directory.exception.ServiceException; import com.cisco.oss.foundation.directory.query.ServiceInstanceQuery; public class LookupManagerImplTest { public static final Logger LOGGER = LoggerFactory.getLogger(LookupManagerImplTest.class); @Test public void test01(){ ServiceDirectory.getServiceDirectoryConfig().setProperty("heartbeat.interval", 1); ServiceDirectory.getServiceDirectoryConfig().setProperty("registry.health.check.interval", 1); final String serviceName = "odrm"; final String instanceId = "192.168.2.3-8901"; final String keyName = "solution"; final Date date = new Date(); Map<String, String> metadata = new HashMap<String, String>(); metadata.put("datacenter", "dc01"); metadata.put("solution", "core"); List<ModelServiceInstance> instances = new ArrayList<ModelServiceInstance>(); ModelServiceInstance instance = new ModelServiceInstance("odrm", "192.168.2.3-8901", "192.168.2.3-8901", "http://cisco.com/vbo/odrm/setupsession", OperationalStatus.UP, date, date, metadata); instance.setHeartbeatTime(date); instances.add(instance); final ModelService result = new ModelService("odrm", "odrm", date, date); result.setServiceInstances(instances); final ModelMetadataKey keyResult = new ModelMetadataKey(keyName, keyName, date, date); keyResult.setServiceInstances(instances); // final ProvidedServiceInstance instance = new ProvidedServiceInstance("odrm", "192.168.7.4", 8901); // instance.setMonitorEnabled(true); // instance.setStatus(OperationalStatus.UP); // instance.setUri("http://cisco.com/vbo/odrm/setupsession"); // Map<String, String> metadata = new HashMap<String, String>(); // metadata.put("datacenter", "dc01"); // metadata.put("solution", "core"); // instance.setMetadata(metadata); // // final ProvidedServiceInstance instance2 = new ProvidedServiceInstance("odrm", "192.168.7.4", 8902); // instance2.setMonitorEnabled(false); // instance2.setStatus(OperationalStatus.UP); // instance2.setUri("http://cisco.com/vbo/odrm/setupsession"); // instance2.setMetadata(metadata); // final AtomicInteger serviceInvoked = new AtomicInteger(0); final AtomicInteger keyInvoked = new AtomicInteger(0); final AtomicInteger serviceChangingInvoked = new AtomicInteger(0); final AtomicInteger keyChangingInvoked = new AtomicInteger(0); // final AtomicInteger unregisterInvoked = new AtomicInteger(0); LookupManagerImpl impl = new LookupManagerImpl(new DirectoryServiceClientManager(){ @Override public DirectoryServiceClient getDirectoryServiceClient() { return new DirectoryServiceClient(){ @Override public ModelService lookupService(String serviceName){ Assert.assertTrue(serviceName.equals("odrm")); serviceInvoked.incrementAndGet(); return result; } @Override public ModelMetadataKey getMetadataKey(String keyName){ Assert.assertTrue(keyName.equals("solution")); keyInvoked.incrementAndGet(); return keyResult; } @Override public Map<String, OperationResult<ModelService>> getServiceChanging(Map<String, ModelService> services){ serviceChangingInvoked.incrementAndGet(); Assert.assertTrue(services.containsKey("odrm")); Map<String, OperationResult<ModelService>> rr = new HashMap<String, OperationResult<ModelService>>(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Map<String, String> metadata = new HashMap<String, String>(); metadata.put("datacenter", "dc02"); metadata.put("solution", "core02"); List<ModelServiceInstance> instances = new ArrayList<ModelServiceInstance>(); ModelServiceInstance instance = new ModelServiceInstance("odrm", "192.168.2.3-8901", "192.168.2.3-8901", "http://cisco.com/vbo/odrm/setupsession/v02", OperationalStatus.UP, date, date, metadata); instance.setHeartbeatTime(date); instances.add(instance); ModelService service = new ModelService("odrm", "odrm", date, date); service.setServiceInstances(instances); rr.put("odrm", new OperationResult<ModelService>(true, service, null)); return rr; } @Override public Map<String, OperationResult<ModelMetadataKey>> getMetadataKeyChanging(Map<String, ModelMetadataKey> keys) { keyChangingInvoked.incrementAndGet(); Assert.assertTrue(keys.containsKey("solution")); Map<String, OperationResult<ModelMetadataKey>> rr = new HashMap<String, OperationResult<ModelMetadataKey>>(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Map<String, String> metadata = new HashMap<String, String>(); metadata.put("datacenter", "dc03"); metadata.put("solution", "core03"); List<ModelServiceInstance> instances = new ArrayList<ModelServiceInstance>(); ModelServiceInstance instance = new ModelServiceInstance("odrm", "192.168.2.3-8901", "192.168.2.3-8901", "http://cisco.com/vbo/odrm/setupsession/v03", OperationalStatus.UP, date, date, metadata); instance.setHeartbeatTime(date); instances.add(instance); ModelMetadataKey key = new ModelMetadataKey(keyName, keyName, date, date); key.setServiceInstances(instances); rr.put("solution", new OperationResult<ModelMetadataKey>(true, key, null)); return rr; } }; } }); impl.start(); ServiceInstanceQuery query = new ServiceInstanceQuery().getEqualQueryCriterion("solution", "core"); try { Assert.assertEquals(impl.getAllInstances(serviceName).get(0).getInstanceId(), instanceId); Assert.assertTrue(impl.getAllInstances(serviceName, query).get(0).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getAllInstancesByKey(query).get(0).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getInstance(serviceName, instanceId).getInstanceId().equals(instanceId)); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertEquals(serviceInvoked.get(), 1); Assert.assertEquals(keyInvoked.get(), 1); // wait for cache sync. LOGGER.info("Start sleep....."); try { Thread.sleep(8000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } LOGGER.info("finished sleep....."); List<String> list = new ArrayList<String>(); list.add("core02"); list.add("core03"); query = new ServiceInstanceQuery().getInQueryCriterion("solution", list); try { Assert.assertEquals(impl.getAllInstances(serviceName).get(0).getInstanceId(), instanceId); Assert.assertTrue(impl.getAllInstances(serviceName, query).get(0).getUri().equals("http://cisco.com/vbo/odrm/setupsession/v02")); Assert.assertTrue(impl.getAllInstancesByKey(query).get(0).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getAllInstancesByKey(query).get(0).getUri().equals("http://cisco.com/vbo/odrm/setupsession/v03")); Assert.assertTrue(impl.getInstance(serviceName, instanceId).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getInstance(serviceName, instanceId).getMetadata().get("solution").equals("core02")); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertEquals(serviceInvoked.get(), 1); Assert.assertEquals(keyInvoked.get(), 1); Assert.assertTrue(serviceChangingInvoked.get()> 0); Assert.assertTrue(keyChangingInvoked.get()> 0); } }
sd-api/src/test/java/com/cisco/oss/foundation/directory/impl/LookupManagerImplTest.java
package com.cisco.oss.foundation.directory.impl; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import com.cisco.oss.foundation.directory.DirectoryServiceClientManager; import com.cisco.oss.foundation.directory.ServiceDirectory; import com.cisco.oss.foundation.directory.entity.ModelMetadataKey; import com.cisco.oss.foundation.directory.entity.ModelService; import com.cisco.oss.foundation.directory.entity.ModelServiceInstance; import com.cisco.oss.foundation.directory.entity.OperationResult; import com.cisco.oss.foundation.directory.entity.OperationalStatus; import com.cisco.oss.foundation.directory.exception.ServiceException; import com.cisco.oss.foundation.directory.query.ServiceInstanceQuery; public class LookupManagerImplTest { @Test public void test01(){ ServiceDirectory.getServiceDirectoryConfig().setProperty("heartbeat.interval", 1); ServiceDirectory.getServiceDirectoryConfig().setProperty("registry.health.check.interval", 1); final String serviceName = "odrm"; final String instanceId = "192.168.2.3-8901"; final String keyName = "solution"; final Date date = new Date(); Map<String, String> metadata = new HashMap<String, String>(); metadata.put("datacenter", "dc01"); metadata.put("solution", "core"); List<ModelServiceInstance> instances = new ArrayList<ModelServiceInstance>(); ModelServiceInstance instance = new ModelServiceInstance("odrm", "192.168.2.3-8901", "192.168.2.3-8901", "http://cisco.com/vbo/odrm/setupsession", OperationalStatus.UP, date, date, metadata); instance.setHeartbeatTime(date); instances.add(instance); final ModelService result = new ModelService("odrm", "odrm", date, date); result.setServiceInstances(instances); final ModelMetadataKey keyResult = new ModelMetadataKey(keyName, keyName, date, date); keyResult.setServiceInstances(instances); // final ProvidedServiceInstance instance = new ProvidedServiceInstance("odrm", "192.168.7.4", 8901); // instance.setMonitorEnabled(true); // instance.setStatus(OperationalStatus.UP); // instance.setUri("http://cisco.com/vbo/odrm/setupsession"); // Map<String, String> metadata = new HashMap<String, String>(); // metadata.put("datacenter", "dc01"); // metadata.put("solution", "core"); // instance.setMetadata(metadata); // // final ProvidedServiceInstance instance2 = new ProvidedServiceInstance("odrm", "192.168.7.4", 8902); // instance2.setMonitorEnabled(false); // instance2.setStatus(OperationalStatus.UP); // instance2.setUri("http://cisco.com/vbo/odrm/setupsession"); // instance2.setMetadata(metadata); // final AtomicInteger serviceInvoked = new AtomicInteger(0); final AtomicInteger keyInvoked = new AtomicInteger(0); final AtomicInteger serviceChangingInvoked = new AtomicInteger(0); final AtomicInteger keyChangingInvoked = new AtomicInteger(0); // final AtomicInteger unregisterInvoked = new AtomicInteger(0); LookupManagerImpl impl = new LookupManagerImpl(new DirectoryServiceClientManager(){ @Override public DirectoryServiceClient getDirectoryServiceClient() { return new DirectoryServiceClient(){ @Override public ModelService lookupService(String serviceName){ Assert.assertTrue(serviceName.equals("odrm")); serviceInvoked.incrementAndGet(); return result; } @Override public ModelMetadataKey getMetadataKey(String keyName){ Assert.assertTrue(keyName.equals("solution")); keyInvoked.incrementAndGet(); return keyResult; } @Override public Map<String, OperationResult<ModelService>> getServiceChanging(Map<String, ModelService> services){ serviceChangingInvoked.incrementAndGet(); Assert.assertTrue(services.containsKey("odrm")); Map<String, OperationResult<ModelService>> rr = new HashMap<String, OperationResult<ModelService>>(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Map<String, String> metadata = new HashMap<String, String>(); metadata.put("datacenter", "dc02"); metadata.put("solution", "core02"); List<ModelServiceInstance> instances = new ArrayList<ModelServiceInstance>(); ModelServiceInstance instance = new ModelServiceInstance("odrm", "192.168.2.3-8901", "192.168.2.3-8901", "http://cisco.com/vbo/odrm/setupsession/v02", OperationalStatus.UP, date, date, metadata); instance.setHeartbeatTime(date); instances.add(instance); ModelService service = new ModelService("odrm", "odrm", date, date); service.setServiceInstances(instances); rr.put("odrm", new OperationResult<ModelService>(true, service, null)); return rr; } @Override public Map<String, OperationResult<ModelMetadataKey>> getMetadataKeyChanging(Map<String, ModelMetadataKey> keys) { keyChangingInvoked.incrementAndGet(); Assert.assertTrue(keys.containsKey("solution")); Map<String, OperationResult<ModelMetadataKey>> rr = new HashMap<String, OperationResult<ModelMetadataKey>>(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Map<String, String> metadata = new HashMap<String, String>(); metadata.put("datacenter", "dc03"); metadata.put("solution", "core03"); List<ModelServiceInstance> instances = new ArrayList<ModelServiceInstance>(); ModelServiceInstance instance = new ModelServiceInstance("odrm", "192.168.2.3-8901", "192.168.2.3-8901", "http://cisco.com/vbo/odrm/setupsession/v03", OperationalStatus.UP, date, date, metadata); instance.setHeartbeatTime(date); instances.add(instance); ModelMetadataKey key = new ModelMetadataKey(keyName, keyName, date, date); key.setServiceInstances(instances); rr.put("solution", new OperationResult<ModelMetadataKey>(true, key, null)); return rr; } }; } }); impl.start(); ServiceInstanceQuery query = new ServiceInstanceQuery().getEqualQueryCriterion("solution", "core"); try { Assert.assertEquals(impl.getAllInstances(serviceName).get(0).getInstanceId(), instanceId); Assert.assertTrue(impl.getAllInstances(serviceName, query).get(0).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getAllInstancesByKey(query).get(0).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getInstance(serviceName, instanceId).getInstanceId().equals(instanceId)); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertEquals(serviceInvoked.get(), 1); Assert.assertEquals(keyInvoked.get(), 1); // wait for cache sync. try { Thread.sleep(8000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<String> list = new ArrayList<String>(); list.add("core02"); list.add("core03"); query = new ServiceInstanceQuery().getInQueryCriterion("solution", list); try { Assert.assertEquals(impl.getAllInstances(serviceName).get(0).getInstanceId(), instanceId); Assert.assertTrue(impl.getAllInstances(serviceName, query).get(0).getUri().equals("http://cisco.com/vbo/odrm/setupsession/v02")); Assert.assertTrue(impl.getAllInstancesByKey(query).get(0).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getAllInstancesByKey(query).get(0).getUri().equals("http://cisco.com/vbo/odrm/setupsession/v03")); Assert.assertTrue(impl.getInstance(serviceName, instanceId).getInstanceId().equals(instanceId)); Assert.assertTrue(impl.getInstance(serviceName, instanceId).getMetadata().get("solution").equals("core02")); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertEquals(serviceInvoked.get(), 1); Assert.assertEquals(keyInvoked.get(), 1); Assert.assertTrue(serviceChangingInvoked.get()> 0); Assert.assertTrue(keyChangingInvoked.get()> 0); } }
Add the Logger to debug.....
sd-api/src/test/java/com/cisco/oss/foundation/directory/impl/LookupManagerImplTest.java
Add the Logger to debug.....
Java
apache-2.0
f318cec2895fceeb6b7c26f988525f2cde16e711
0
FelixGV/voldemort,FelixGV/voldemort,rickbw/voldemort,HB-SI/voldemort,HB-SI/voldemort,FelixGV/voldemort,birendraa/voldemort,mabh/voldemort,arunthirupathi/voldemort,jalkjaer/voldemort,LeoYao/voldemort,stotch/voldemort,jeffpc/voldemort,null-exception/voldemort,HB-SI/voldemort,gnb/voldemort,medallia/voldemort,jwlent55/voldemort,jwlent55/voldemort,birendraa/voldemort,birendraa/voldemort,LeoYao/voldemort,null-exception/voldemort,squarY/voldemort,dallasmarlow/voldemort,FelixGV/voldemort,birendraa/voldemort,jalkjaer/voldemort,bitti/voldemort,jalkjaer/voldemort,jwlent55/voldemort,stotch/voldemort,jeffpc/voldemort,jeffpc/voldemort,dallasmarlow/voldemort,rickbw/voldemort,voldemort/voldemort,rickbw/voldemort,voldemort/voldemort,jalkjaer/voldemort,arunthirupathi/voldemort,HB-SI/voldemort,mabh/voldemort,stotch/voldemort,arunthirupathi/voldemort,mabh/voldemort,jalkjaer/voldemort,voldemort/voldemort,dallasmarlow/voldemort,medallia/voldemort,arunthirupathi/voldemort,squarY/voldemort,squarY/voldemort,bhasudha/voldemort,rickbw/voldemort,bhasudha/voldemort,gnb/voldemort,jeffpc/voldemort,jwlent55/voldemort,dallasmarlow/voldemort,bitti/voldemort,bitti/voldemort,squarY/voldemort,cshaxu/voldemort,dallasmarlow/voldemort,squarY/voldemort,bhasudha/voldemort,medallia/voldemort,rickbw/voldemort,dallasmarlow/voldemort,HB-SI/voldemort,squarY/voldemort,stotch/voldemort,LeoYao/voldemort,gnb/voldemort,jalkjaer/voldemort,null-exception/voldemort,rickbw/voldemort,gnb/voldemort,cshaxu/voldemort,LeoYao/voldemort,PratikDeshpande/voldemort,voldemort/voldemort,mabh/voldemort,bitti/voldemort,FelixGV/voldemort,FelixGV/voldemort,PratikDeshpande/voldemort,mabh/voldemort,bitti/voldemort,gnb/voldemort,PratikDeshpande/voldemort,squarY/voldemort,stotch/voldemort,LeoYao/voldemort,jwlent55/voldemort,arunthirupathi/voldemort,HB-SI/voldemort,voldemort/voldemort,medallia/voldemort,jalkjaer/voldemort,bhasudha/voldemort,arunthirupathi/voldemort,gnb/voldemort,FelixGV/voldemort,birendraa/voldemort,jwlent55/voldemort,bhasudha/voldemort,cshaxu/voldemort,cshaxu/voldemort,PratikDeshpande/voldemort,birendraa/voldemort,medallia/voldemort,PratikDeshpande/voldemort,jeffpc/voldemort,voldemort/voldemort,stotch/voldemort,jeffpc/voldemort,cshaxu/voldemort,arunthirupathi/voldemort,cshaxu/voldemort,medallia/voldemort,mabh/voldemort,PratikDeshpande/voldemort,bhasudha/voldemort,null-exception/voldemort,voldemort/voldemort,null-exception/voldemort,bitti/voldemort,null-exception/voldemort,LeoYao/voldemort,bitti/voldemort
/* * Copyright 2010 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.store.socket.clientrequest; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import voldemort.client.protocol.RequestFormat; import voldemort.server.RequestRoutingType; import voldemort.utils.ByteArray; import voldemort.versioning.Versioned; public class GetClientRequest extends AbstractStoreClientRequest<List<Versioned<byte[]>>> { private final ByteArray key; public GetClientRequest(String storeName, RequestFormat requestFormat, RequestRoutingType requestRoutingType, ByteArray key) { super(storeName, requestFormat, requestRoutingType); this.key = key; } public void write(DataOutputStream outputStream) throws IOException { requestFormat.writeGetRequest(outputStream, storeName, key, requestRoutingType); } @Override protected List<Versioned<byte[]>> readInternal(DataInputStream inputStream) throws IOException { return requestFormat.readGetResponse(inputStream); } @Override public boolean isCompleteResponse(ByteBuffer buffer) { return requestFormat.isCompleteGetResponse(buffer); } }
src/java/voldemort/store/socket/clientrequest/GetClientRequest.java
/* * Copyright 2010 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.store.socket.clientrequest; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import voldemort.client.protocol.RequestFormat; import voldemort.server.RequestRoutingType; import voldemort.utils.ByteArray; import voldemort.versioning.Versioned; public class GetClientRequest extends AbstractStoreClientRequest<List<Versioned<byte[]>>> { private final ByteArray key; public GetClientRequest(String storeName, RequestFormat requestFormat, RequestRoutingType requestRoutingType, ByteArray key) { super(storeName, requestFormat, requestRoutingType); this.key = key; } public void write(DataOutputStream outputStream) throws IOException { requestFormat.writeGetRequest(outputStream, storeName, key, requestRoutingType); } @Override protected List<Versioned<byte[]>> readInternal(DataInputStream inputStream) throws IOException { return requestFormat.readGetResponse(inputStream); } /* * @Override public boolean isCompleteResponse(ByteBuffer buffer) { return * requestFormat.isCompleteGetResponse(buffer); } */ }
Revert "Temporarily reverting to ensure the bug reappears" This reverts commit 9918dad7d62cba3b610e338e568532919240f88a.
src/java/voldemort/store/socket/clientrequest/GetClientRequest.java
Revert "Temporarily reverting to ensure the bug reappears"
Java
apache-2.0
419358381748e10f404098662f7bf9dd235ac19c
0
pivotal-bank/accounts-service,pivotal-bank/accounts-service
package io.pivotal.accounts.controller; import java.math.BigDecimal; import java.security.Principal; import java.util.List; import io.pivotal.accounts.domain.Account; import io.pivotal.accounts.domain.AccountType; import io.pivotal.accounts.domain.Transaction; import io.pivotal.accounts.domain.TransactionType; import io.pivotal.accounts.service.AccountService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; /** * REST controller for the accounts microservice. Provides the following * endpoints: * <p> * <ul> * <li>GET <code>/accounts/{id}</code> retrieves the account with given id. * <li>POST <code>/accounts</code> stores the account object passed in body. * <li>POST <code>/accounts/transaction</code> receives a transaction to * process. * </ul> * <p> * * @author David Ferreira Pinto * @author Maxim Avezbakiev * @author Simon Rowe * */ @RestController public class AccountController { private static final Logger logger = LoggerFactory .getLogger(AccountController.class); /** * The service to delegate calls to. */ @Autowired private AccountService service; /** * REST call to retrieve the account with the given id. * * @param id * The id of the account to retrieve the account for. * @return The account object if found. */ @RequestMapping(value = "/accounts/{id}", method = RequestMethod.GET) public ResponseEntity<Account> find(@PathVariable("id") Integer id) { logger.info("AccountController.find: id=" + id); Account accountResponse = this.service.findAccount(id); return new ResponseEntity<Account>(accountResponse, getNoCacheHeaders(), HttpStatus.OK); } @RequestMapping(value = "/accounts", method = RequestMethod.GET) public ResponseEntity<List<Account>> findAccounts( @RequestParam(value = "type", required = false) final String type) { if (type == null) { List<Account> accountResponse = this.service.findAccounts(); return new ResponseEntity<List<Account>>(accountResponse, getNoCacheHeaders(), HttpStatus.OK); } else { List<Account> accountResponse = this.service.findAccountsByType( AccountType.valueOf(type)); return new ResponseEntity<List<Account>>(accountResponse, getNoCacheHeaders(), HttpStatus.OK); } } /** * REST call to save the account provided in the request body. * * @param accountRequest * The account to save. * @param builder * @return */ @RequestMapping(value = "/accounts", method = RequestMethod.POST) public Boolean save(@RequestBody Account accountRequest, UriComponentsBuilder builder, @AuthenticationPrincipal JwtAuthenticationToken token) { accountRequest.setUserid(token.getName()); logger.debug("AccountController.save: userId=" + accountRequest.getUserid()); Integer accountProfileId = this.service.saveAccount(accountRequest); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(builder.path("/account/{id}") .buildAndExpand(accountProfileId).toUri()); return Boolean.TRUE; } //TODO move logic to AccountService! /** * REST call to process a transaction of an account. * * @param transaction the transaction to process. * @return a response entity with either SUCCESS or FAILED. */ @RequestMapping(value = "/accounts/transaction", method = RequestMethod.POST) public ResponseEntity<String> transaction( @RequestBody Transaction transaction) { logger.debug("AccountController.transaction: " + transaction.toString()); if (transaction.getType().equals(TransactionType.DEBIT)) { logger.debug("debit transaction"); Account accountResponse = this.service.findAccount(transaction .getAccountId()); BigDecimal currentBalance = accountResponse.getBalance(); BigDecimal newBalance = currentBalance.subtract(transaction .getAmount()); if (newBalance.compareTo(BigDecimal.ZERO) >= 0) { accountResponse.setBalance(newBalance); this.service.saveAccount(accountResponse); // TODO save transaction? logger.debug("transaction processed."); return new ResponseEntity<String>("SUCCESS", getNoCacheHeaders(), HttpStatus.OK); } else { // no sufficient founds available return new ResponseEntity<String>("FAILED", getNoCacheHeaders(), HttpStatus.EXPECTATION_FAILED); } } else if (transaction.getType().equals(TransactionType.CREDIT)) { logger.debug("credit transaction"); Account accountResponse = this.service.findAccount(transaction.getAccountId()); BigDecimal currentBalance = accountResponse.getBalance(); logger.debug("AccountController.transaction: current balance='" + currentBalance + "'."); if (transaction.getAmount().compareTo(BigDecimal.ZERO) > 0) { BigDecimal newBalance = currentBalance.add(transaction.getAmount()); logger.debug("AccountController.increaseBalance: new balance='" + newBalance + "'."); accountResponse.setBalance(newBalance); this.service.saveAccount(accountResponse); // TODO save transaction? return new ResponseEntity<String>("SUCCESS", getNoCacheHeaders(), HttpStatus.OK); } else { // amount can not be negative for increaseBalance, please use // decreaseBalance return new ResponseEntity<String>("FAILED", getNoCacheHeaders(), HttpStatus.EXPECTATION_FAILED); } } return null; } private HttpHeaders getNoCacheHeaders() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Cache-Control", "no-cache"); return responseHeaders; } }
src/main/java/io/pivotal/accounts/controller/AccountController.java
package io.pivotal.accounts.controller; import java.math.BigDecimal; import java.security.Principal; import java.util.List; import io.pivotal.accounts.domain.Account; import io.pivotal.accounts.domain.AccountType; import io.pivotal.accounts.domain.Transaction; import io.pivotal.accounts.domain.TransactionType; import io.pivotal.accounts.service.AccountService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; /** * REST controller for the accounts microservice. Provides the following * endpoints: * <p> * <ul> * <li>GET <code>/accounts/{id}</code> retrieves the account with given id. * <li>POST <code>/accounts</code> stores the account object passed in body. * <li>POST <code>/accounts/transaction</code> receives a transaction to * process. * </ul> * <p> * * @author David Ferreira Pinto * @author Maxim Avezbakiev * @author Simon Rowe * */ @RestController public class AccountController { private static final Logger logger = LoggerFactory .getLogger(AccountController.class); /** * The service to delegate calls to. */ @Autowired private AccountService service; /** * REST call to retrieve the account with the given id. * * @param id * The id of the account to retrieve the account for. * @return The account object if found. */ @RequestMapping(value = "/accounts/{id}", method = RequestMethod.GET) public ResponseEntity<Account> find(@PathVariable("id") Integer id) { logger.info("AccountController.find: id=" + id); Account accountResponse = this.service.findAccount(id); return new ResponseEntity<Account>(accountResponse, getNoCacheHeaders(), HttpStatus.OK); } @RequestMapping(value = "/accounts", method = RequestMethod.GET) public ResponseEntity<List<Account>> findAccounts( @RequestParam(value = "type", required = false) final String type) { if (type == null) { List<Account> accountResponse = this.service.findAccounts(); return new ResponseEntity<List<Account>>(accountResponse, getNoCacheHeaders(), HttpStatus.OK); } else { List<Account> accountResponse = this.service.findAccountsByType( AccountType.valueOf(type)); return new ResponseEntity<List<Account>>(accountResponse, getNoCacheHeaders(), HttpStatus.OK); } } /** * REST call to save the account provided in the request body. * * @param accountRequest * The account to save. * @param builder * @return */ @RequestMapping(value = "/accounts", method = RequestMethod.POST) public ResponseEntity<String> save(@RequestBody Account accountRequest, UriComponentsBuilder builder, @AuthenticationPrincipal OAuth2User oAuth2User) { accountRequest.setUserid(oAuth2User.getName()); logger.debug("AccountController.save: userId=" + accountRequest.getUserid()); Integer accountProfileId = this.service.saveAccount(accountRequest); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(builder.path("/account/{id}") .buildAndExpand(accountProfileId).toUri()); return new ResponseEntity<String>(responseHeaders, HttpStatus.CREATED); } //TODO move logic to AccountService! /** * REST call to process a transaction of an account. * * @param transaction the transaction to process. * @return a response entity with either SUCCESS or FAILED. */ @RequestMapping(value = "/accounts/transaction", method = RequestMethod.POST) public ResponseEntity<String> transaction( @RequestBody Transaction transaction) { logger.debug("AccountController.transaction: " + transaction.toString()); if (transaction.getType().equals(TransactionType.DEBIT)) { logger.debug("debit transaction"); Account accountResponse = this.service.findAccount(transaction .getAccountId()); BigDecimal currentBalance = accountResponse.getBalance(); BigDecimal newBalance = currentBalance.subtract(transaction .getAmount()); if (newBalance.compareTo(BigDecimal.ZERO) >= 0) { accountResponse.setBalance(newBalance); this.service.saveAccount(accountResponse); // TODO save transaction? logger.debug("transaction processed."); return new ResponseEntity<String>("SUCCESS", getNoCacheHeaders(), HttpStatus.OK); } else { // no sufficient founds available return new ResponseEntity<String>("FAILED", getNoCacheHeaders(), HttpStatus.EXPECTATION_FAILED); } } else if (transaction.getType().equals(TransactionType.CREDIT)) { logger.debug("credit transaction"); Account accountResponse = this.service.findAccount(transaction.getAccountId()); BigDecimal currentBalance = accountResponse.getBalance(); logger.debug("AccountController.transaction: current balance='" + currentBalance + "'."); if (transaction.getAmount().compareTo(BigDecimal.ZERO) > 0) { BigDecimal newBalance = currentBalance.add(transaction.getAmount()); logger.debug("AccountController.increaseBalance: new balance='" + newBalance + "'."); accountResponse.setBalance(newBalance); this.service.saveAccount(accountResponse); // TODO save transaction? return new ResponseEntity<String>("SUCCESS", getNoCacheHeaders(), HttpStatus.OK); } else { // amount can not be negative for increaseBalance, please use // decreaseBalance return new ResponseEntity<String>("FAILED", getNoCacheHeaders(), HttpStatus.EXPECTATION_FAILED); } } return null; } private HttpHeaders getNoCacheHeaders() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Cache-Control", "no-cache"); return responseHeaders; } }
secure
src/main/java/io/pivotal/accounts/controller/AccountController.java
secure
Java
apache-2.0
a38ef3a85f7a9787ecd5ab1fee3df89fb06c1a2a
0
JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,quarian/dataverse,bmckinney/dataverse-canonical,majorseitan/dataverse,jacksonokuhn/dataverse,leeper/dataverse-1,leeper/dataverse-1,quarian/dataverse,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,majorseitan/dataverse,bmckinney/dataverse-canonical,leeper/dataverse-1,leeper/dataverse-1,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,quarian/dataverse,majorseitan/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,leeper/dataverse-1,bmckinney/dataverse-canonical,bmckinney/dataverse-canonical,majorseitan/dataverse,leeper/dataverse-1,quarian/dataverse,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,majorseitan/dataverse,quarian/dataverse,quarian/dataverse,JayanthyChengan/dataverse,leeper/dataverse-1,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,quarian/dataverse,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,leeper/dataverse-1,JayanthyChengan/dataverse,JayanthyChengan/dataverse,jacksonokuhn/dataverse,quarian/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,majorseitan/dataverse
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dataverse; import java.util.List; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author xyang */ @Stateless @Named public class DataverseUserServiceBean { @PersistenceContext(unitName = "VDCNet-ejbPU") private EntityManager em; public String encryptPassword(String plainText) { return PasswordEncryption.getInstance().encrypt(plainText); } public DataverseUser save(DataverseUser dataverseUser) { return em.merge(dataverseUser); } }
src/main/java/edu/harvard/iq/dataverse/DataverseUserServiceBean.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dataverse; import java.util.List; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author xyang */ @Stateless @Named public class DataverseUserServiceBean { @PersistenceContext(unitName = "VDCNet-ejbPU") private EntityManager em; public DataverseUser save(DataverseUser dataverseUser) { return em.merge(dataverseUser); } }
Encrypt password.
src/main/java/edu/harvard/iq/dataverse/DataverseUserServiceBean.java
Encrypt password.
Java
bsd-3-clause
733195c33caba3b6a2b4e113c33e8d7de789665e
0
danteinforno/jmonkeyengine,jMonkeyEngine/jmonkeyengine,olafmaas/jmonkeyengine,skapi1992/jmonkeyengine,aaronang/jmonkeyengine,tr0k/jmonkeyengine,wrvangeest/jmonkeyengine,shurun19851206/jMonkeyEngine,Georgeto/jmonkeyengine,OpenGrabeso/jmonkeyengine,sandervdo/jmonkeyengine,amit2103/jmonkeyengine,olafmaas/jmonkeyengine,g-rocket/jmonkeyengine,nickschot/jmonkeyengine,mbenson/jmonkeyengine,OpenGrabeso/jmonkeyengine,bertleft/jmonkeyengine,g-rocket/jmonkeyengine,shurun19851206/jMonkeyEngine,skapi1992/jmonkeyengine,davidB/jmonkeyengine,davidB/jmonkeyengine,delftsre/jmonkeyengine,phr00t/jmonkeyengine,InShadow/jmonkeyengine,d235j/jmonkeyengine,yetanotherindie/jMonkey-Engine,delftsre/jmonkeyengine,OpenGrabeso/jmonkeyengine,yetanotherindie/jMonkey-Engine,skapi1992/jmonkeyengine,danteinforno/jmonkeyengine,delftsre/jmonkeyengine,danteinforno/jmonkeyengine,wrvangeest/jmonkeyengine,danteinforno/jmonkeyengine,tr0k/jmonkeyengine,Georgeto/jmonkeyengine,bertleft/jmonkeyengine,InShadow/jmonkeyengine,rbottema/jmonkeyengine,atomixnmc/jmonkeyengine,GreenCubes/jmonkeyengine,weilichuang/jmonkeyengine,d235j/jmonkeyengine,bertleft/jmonkeyengine,mbenson/jmonkeyengine,phr00t/jmonkeyengine,Georgeto/jmonkeyengine,atomixnmc/jmonkeyengine,amit2103/jmonkeyengine,zzuegg/jmonkeyengine,Georgeto/jmonkeyengine,OpenGrabeso/jmonkeyengine,danteinforno/jmonkeyengine,skapi1992/jmonkeyengine,Georgeto/jmonkeyengine,amit2103/jmonkeyengine,zzuegg/jmonkeyengine,g-rocket/jmonkeyengine,Georgeto/jmonkeyengine,rbottema/jmonkeyengine,bsmr-java/jmonkeyengine,phr00t/jmonkeyengine,amit2103/jmonkeyengine,yetanotherindie/jMonkey-Engine,mbenson/jmonkeyengine,tr0k/jmonkeyengine,nickschot/jmonkeyengine,g-rocket/jmonkeyengine,weilichuang/jmonkeyengine,rbottema/jmonkeyengine,mbenson/jmonkeyengine,GreenCubes/jmonkeyengine,nickschot/jmonkeyengine,GreenCubes/jmonkeyengine,g-rocket/jmonkeyengine,rbottema/jmonkeyengine,zzuegg/jmonkeyengine,davidB/jmonkeyengine,InShadow/jmonkeyengine,bertleft/jmonkeyengine,atomixnmc/jmonkeyengine,aaronang/jmonkeyengine,weilichuang/jmonkeyengine,weilichuang/jmonkeyengine,jMonkeyEngine/jmonkeyengine,sandervdo/jmonkeyengine,OpenGrabeso/jmonkeyengine,d235j/jmonkeyengine,shurun19851206/jMonkeyEngine,bsmr-java/jmonkeyengine,weilichuang/jmonkeyengine,g-rocket/jmonkeyengine,tr0k/jmonkeyengine,d235j/jmonkeyengine,nickschot/jmonkeyengine,sandervdo/jmonkeyengine,olafmaas/jmonkeyengine,amit2103/jmonkeyengine,davidB/jmonkeyengine,sandervdo/jmonkeyengine,shurun19851206/jMonkeyEngine,davidB/jmonkeyengine,mbenson/jmonkeyengine,wrvangeest/jmonkeyengine,wrvangeest/jmonkeyengine,zzuegg/jmonkeyengine,delftsre/jmonkeyengine,davidB/jmonkeyengine,atomixnmc/jmonkeyengine,bsmr-java/jmonkeyengine,danteinforno/jmonkeyengine,OpenGrabeso/jmonkeyengine,bsmr-java/jmonkeyengine,yetanotherindie/jMonkey-Engine,InShadow/jmonkeyengine,amit2103/jmonkeyengine,shurun19851206/jMonkeyEngine,atomixnmc/jmonkeyengine,d235j/jmonkeyengine,weilichuang/jmonkeyengine,jMonkeyEngine/jmonkeyengine,shurun19851206/jMonkeyEngine,yetanotherindie/jMonkey-Engine,mbenson/jmonkeyengine,phr00t/jmonkeyengine,atomixnmc/jmonkeyengine,yetanotherindie/jMonkey-Engine,aaronang/jmonkeyengine,olafmaas/jmonkeyengine,GreenCubes/jmonkeyengine,jMonkeyEngine/jmonkeyengine,d235j/jmonkeyengine,aaronang/jmonkeyengine
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.scene.plugins.blender.helpers.v249; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.jme3.animation.AnimControl; import com.jme3.animation.Bone; import com.jme3.animation.BoneAnimation; import com.jme3.animation.BoneTrack; import com.jme3.animation.Skeleton; import com.jme3.animation.SkeletonControl; import com.jme3.bounding.BoundingBox; import com.jme3.bounding.BoundingSphere; import com.jme3.bounding.BoundingVolume; import com.jme3.effect.ParticleEmitter; import com.jme3.effect.shapes.EmitterMeshVertexShape; import com.jme3.effect.shapes.EmitterShape; import com.jme3.material.Material; import com.jme3.math.Matrix4f; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.plugins.blender.data.FileBlockHeader; import com.jme3.scene.plugins.blender.data.Structure; import com.jme3.scene.plugins.blender.exception.BlenderFileException; import com.jme3.scene.plugins.blender.helpers.ParticlesHelper; import com.jme3.scene.plugins.blender.structures.Constraint; import com.jme3.scene.plugins.blender.structures.Ipo; import com.jme3.scene.plugins.blender.structures.Modifier; import com.jme3.scene.plugins.blender.utils.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.utils.DataRepository; import com.jme3.scene.plugins.blender.utils.DataRepository.LoadedFeatureDataType; import com.jme3.scene.plugins.blender.utils.DynamicArray; import com.jme3.scene.plugins.blender.utils.Pointer; import com.jme3.scene.plugins.ogre.AnimData; import com.jme3.scene.shape.Curve; /** * A class that is used in modifiers calculations. * @author Marcin Roguski */ public class ModifierHelper extends AbstractBlenderHelper { private static final Logger LOGGER = Logger.getLogger(ModifierHelper.class.getName()); /** * This constructor parses the given blender version and stores the result. Some functionalities may differ in * different blender versions. * @param blenderVersion * the version read from the blend file */ public ModifierHelper(String blenderVersion) { super(blenderVersion); } /** * This method applies modifier to the object. * @param node * the loaded object * @param modifier * the modifier to apply * @param dataRepository * the data repository * @return the node to whom the modifier was applied */ public Node applyModifier(Node node, Modifier modifier, DataRepository dataRepository) { if (Modifier.ARMATURE_MODIFIER_DATA.equals(modifier.getType())) { return this.applyArmatureModifierData(node, modifier, dataRepository); } else if (Modifier.OBJECT_ANIMATION_MODIFIER_DATA.equals(modifier.getType())) { return this.applyObjectAnimationModifier(node, modifier, dataRepository); } else if (Modifier.ARRAY_MODIFIER_DATA.equals(modifier.getType())) { return this.applyArrayModifierData(node, modifier, dataRepository); } else if (Modifier.PARTICLE_MODIFIER_DATA.equals(modifier.getType())) { return this.applyParticleSystemModifierData(node, modifier, dataRepository); } else if (Modifier.MIRROR_MODIFIER_DATA.equals(modifier.getType())) { return this.applyMirrorModifierData(node, modifier, dataRepository); } else { LOGGER.log(Level.WARNING, "Modifier: {0} not yet implemented!!!", modifier.getType()); return node; } } /** * This method reads the given object's modifiers. * @param objectStructure * the object structure * @param dataRepository * the data repository * @param converter * the converter object (in some cases we need to read an object first before loading the modifier) * @throws BlenderFileException * this exception is thrown when the blender file is somehow corrupted */ @SuppressWarnings("unchecked") public void readModifiers(Structure objectStructure, DataRepository dataRepository) throws BlenderFileException { Structure modifiersListBase = (Structure) objectStructure.getFieldValue("modifiers"); List<Structure> modifiers = modifiersListBase.evaluateListBase(dataRepository); for (Structure modifier : modifiers) { Object loadedModifier = null; Object modifierAdditionalData = null; if (Modifier.ARRAY_MODIFIER_DATA.equals(modifier.getType())) {// ****************ARRAY MODIFIER Map<String, Object> params = new HashMap<String, Object>(); Number fittype = (Number) modifier.getFieldValue("fit_type"); params.put("fittype", fittype); switch (fittype.intValue()) { case 0:// FIXED COUNT params.put("count", modifier.getFieldValue("count")); break; case 1:// FIXED LENGTH params.put("length", modifier.getFieldValue("length")); break; case 2:// FITCURVE Pointer pCurveOb = (Pointer) modifier.getFieldValue("curve_ob"); float length = 0; if (pCurveOb.isNotNull()) { Structure curveStructure = pCurveOb.fetchData(dataRepository.getInputStream()).get(0); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Node curveObject = (Node) objectHelper.toObject(curveStructure, dataRepository); Set<Number> referencesToCurveLengths = new HashSet<Number>(curveObject.getChildren().size()); for (Spatial spatial : curveObject.getChildren()) { if (spatial instanceof Geometry) { Mesh mesh = ((Geometry) spatial).getMesh(); if (mesh instanceof Curve) { length += ((Curve) mesh).getLength(); } else { //if bevel object has several parts then each mesh will have the same reference //to length value (and we should use only one) Number curveLength = spatial.getUserData("curveLength"); if (curveLength != null && !referencesToCurveLengths.contains(curveLength)) { length += curveLength.floatValue(); referencesToCurveLengths.add(curveLength); } } } } } params.put("length", Float.valueOf(length)); params.put("fittype", Integer.valueOf(1));// treat it like FIXED LENGTH break; default: assert false : "Unknown array modifier fit type: " + fittype; } // offset parameters int offsettype = ((Number) modifier.getFieldValue("offset_type")).intValue(); if ((offsettype & 0x01) != 0) {// Constant offset DynamicArray<Number> offsetArray = (DynamicArray<Number>) modifier.getFieldValue("offset"); float[] offset = new float[]{offsetArray.get(0).floatValue(), offsetArray.get(1).floatValue(), offsetArray.get(2).floatValue()}; params.put("offset", offset); } if ((offsettype & 0x02) != 0) {// Relative offset DynamicArray<Number> scaleArray = (DynamicArray<Number>) modifier.getFieldValue("scale"); float[] scale = new float[]{scaleArray.get(0).floatValue(), scaleArray.get(1).floatValue(), scaleArray.get(2).floatValue()}; params.put("scale", scale); } if ((offsettype & 0x04) != 0) {// Object offset Pointer pOffsetObject = (Pointer) modifier.getFieldValue("offset_ob"); if (pOffsetObject.isNotNull()) { params.put("offsetob", pOffsetObject); } } // start cap and end cap Pointer pStartCap = (Pointer) modifier.getFieldValue("start_cap"); if (pStartCap.isNotNull()) { params.put("startcap", pStartCap); } Pointer pEndCap = (Pointer) modifier.getFieldValue("end_cap"); if (pEndCap.isNotNull()) { params.put("endcap", pEndCap); } loadedModifier = params; } else if (Modifier.MIRROR_MODIFIER_DATA.equals(modifier.getType())) {// ****************MIRROR MODIFIER Map<String, Object> params = new HashMap<String, Object>(); params.put("flag", modifier.getFieldValue("flag")); params.put("tolerance", modifier.getFieldValue("tolerance")); Pointer pMirrorOb = (Pointer) modifier.getFieldValue("mirror_ob"); if (pMirrorOb.isNotNull()) { params.put("mirrorob", pMirrorOb); } loadedModifier = params; } else if (Modifier.ARMATURE_MODIFIER_DATA.equals(modifier.getType())) {// ****************ARMATURE MODIFIER Pointer pArmatureObject = (Pointer) modifier.getFieldValue("object"); if (pArmatureObject.isNotNull()) { ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Structure armatureObject = (Structure) dataRepository.getLoadedFeature(pArmatureObject.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_STRUCTURE); if (armatureObject == null) {// we check this first not to fetch the structure unnecessary armatureObject = pArmatureObject.fetchData(dataRepository.getInputStream()).get(0); objectHelper.toObject(armatureObject, dataRepository); } modifierAdditionalData = armatureObject.getOldMemoryAddress(); ArmatureHelper armatureHelper = dataRepository.getHelper(ArmatureHelper.class); // changing bones matrices so that they fit the current object (that is why we need a copy of a skeleton) Matrix4f armatureObjectMatrix = objectHelper.getTransformationMatrix(armatureObject); Matrix4f inverseMeshObjectMatrix = objectHelper.getTransformationMatrix(objectStructure).invert(); Matrix4f additionalRootBoneTransformation = inverseMeshObjectMatrix.multLocal(armatureObjectMatrix); Bone[] bones = armatureHelper.buildBonesStructure(Long.valueOf(0L), additionalRootBoneTransformation); //setting the bones structure inside the skeleton (thus completing its loading) Skeleton skeleton = new Skeleton(bones); dataRepository.addLoadedFeatures(armatureObject.getOldMemoryAddress(), armatureObject.getName(), armatureObject, skeleton); String objectName = objectStructure.getName(); Set<String> animationNames = dataRepository.getBlenderKey().getAnimationNames(objectName); if (animationNames != null && animationNames.size() > 0) { ArrayList<BoneAnimation> animations = new ArrayList<BoneAnimation>(); List<FileBlockHeader> actionHeaders = dataRepository.getFileBlocks(Integer.valueOf(FileBlockHeader.BLOCK_AC00)); for (FileBlockHeader header : actionHeaders) { Structure actionStructure = header.getStructure(dataRepository); String actionName = actionStructure.getName(); if (animationNames.contains(actionName)) { int[] animationFrames = dataRepository.getBlenderKey().getAnimationFrames(objectName, actionName); int fps = dataRepository.getBlenderKey().getFps(); float start = (float) animationFrames[0] / (float) fps; float stop = (float) animationFrames[1] / (float) fps; BoneAnimation boneAnimation = new BoneAnimation(actionName, stop - start); boneAnimation.setTracks(armatureHelper.getTracks(actionStructure, dataRepository, objectName, actionName)); animations.add(boneAnimation); } } loadedModifier = new AnimData(new Skeleton(bones), animations); } } else { LOGGER.log(Level.WARNING, "Unsupported modifier type: {0}", modifier.getType()); } } else if (Modifier.PARTICLE_MODIFIER_DATA.equals(modifier.getType())) {// ****************PARTICLES MODIFIER Pointer pParticleSystem = (Pointer) modifier.getFieldValue("psys"); if (pParticleSystem.isNotNull()) { ParticlesHelper particlesHelper = dataRepository.getHelper(ParticlesHelper.class); Structure particleSystem = pParticleSystem.fetchData(dataRepository.getInputStream()).get(0); loadedModifier = particlesHelper.toParticleEmitter(particleSystem, dataRepository); } } // adding modifier to the modifier's lists if (loadedModifier != null) { dataRepository.addModifier(objectStructure.getOldMemoryAddress(), modifier.getType(), loadedModifier, modifierAdditionalData); modifierAdditionalData = null; } } //at the end read object's animation modifier Modifier objectAnimationModifier = this.readObjectAnimation(objectStructure, dataRepository); if (objectAnimationModifier != null) { dataRepository.addModifier(objectStructure.getOldMemoryAddress(), objectAnimationModifier.getType(), objectAnimationModifier.getJmeModifierRepresentation(), objectAnimationModifier.getAdditionalData()); } } /** * This method reads animation of the object itself (without bones) and stores it as an ArmatureModifierData * modifier. The animation is returned as a modifier. It should be later applied regardless other modifiers. The * reason for this is that object may not have modifiers added but it's animation should be working. * @param objectStructure * the structure of the object * @param dataRepository * the data repository * @return animation modifier is returned, it should be separately applied when the object is loaded * @throws BlenderFileException * this exception is thrown when the blender file is somehow corrupted */ protected Modifier readObjectAnimation(Structure objectStructure, DataRepository dataRepository) throws BlenderFileException { Pointer pIpo = (Pointer) objectStructure.getFieldValue("ipo"); if (pIpo.isNotNull()) { //check if there is an action name connected with this ipo String objectAnimationName = null; List<FileBlockHeader> actionBlocks = dataRepository.getFileBlocks(Integer.valueOf(FileBlockHeader.BLOCK_AC00)); for (FileBlockHeader actionBlock : actionBlocks) { Structure action = actionBlock.getStructure(dataRepository); List<Structure> actionChannels = ((Structure) action.getFieldValue("chanbase")).evaluateListBase(dataRepository); if (actionChannels.size() == 1) {//object's animtion action has only one channel Pointer pChannelIpo = (Pointer) actionChannels.get(0).getFieldValue("ipo"); if (pChannelIpo.equals(pIpo)) { objectAnimationName = action.getName(); break; } } } String objectName = objectStructure.getName(); if (objectAnimationName == null) {//set the object's animation name to object's name objectAnimationName = objectName; } IpoHelper ipoHelper = dataRepository.getHelper(IpoHelper.class); Structure ipoStructure = pIpo.fetchData(dataRepository.getInputStream()).get(0); Ipo ipo = ipoHelper.createIpo(ipoStructure, dataRepository); int[] animationFrames = dataRepository.getBlenderKey().getAnimationFrames(objectName, objectAnimationName); if (animationFrames == null) {//if the name was created here there are no frames set for the animation animationFrames = new int[]{1, ipo.getLastFrame()}; } int fps = dataRepository.getBlenderKey().getFps(); float start = (float) animationFrames[0] / (float) fps; float stop = (float) animationFrames[1] / (float) fps; //calculating track for the only bone in this skeleton BoneTrack[] tracks = new BoneTrack[1]; tracks[0] = ipo.calculateTrack(0, animationFrames[0], animationFrames[1], fps); BoneAnimation boneAnimation = new BoneAnimation(objectAnimationName, stop - start); boneAnimation.setTracks(tracks); ArrayList<BoneAnimation> animations = new ArrayList<BoneAnimation>(1); animations.add(boneAnimation); //preparing the object's bone ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Transform t = objectHelper.getTransformation(objectStructure, dataRepository); Bone bone = new Bone(null); bone.setBindTransforms(t.getTranslation(), t.getRotation(), t.getScale()); return new Modifier(Modifier.OBJECT_ANIMATION_MODIFIER_DATA, new AnimData(new Skeleton(new Bone[]{bone}), animations), objectStructure.getOldMemoryAddress()); } return null; } /** * This method applies particles emitter to the given node. * @param node * the particles emitter node * @param modifier * the modifier containing the emitter data * @param dataRepository * the data repository * @return node with particles' emitter applied */ protected Node applyParticleSystemModifierData(Node node, Modifier modifier, DataRepository dataRepository) { MaterialHelper materialHelper = dataRepository.getHelper(MaterialHelper.class); ParticleEmitter emitter = (ParticleEmitter) modifier.getJmeModifierRepresentation(); emitter = emitter.clone(); // veryfying the alpha function for particles' texture Integer alphaFunction = MaterialHelper.ALPHA_MASK_HYPERBOLE; char nameSuffix = emitter.getName().charAt(emitter.getName().length() - 1); if (nameSuffix == 'B' || nameSuffix == 'N') { alphaFunction = MaterialHelper.ALPHA_MASK_NONE; } // removing the type suffix from the name emitter.setName(emitter.getName().substring(0, emitter.getName().length() - 1)); // applying emitter shape EmitterShape emitterShape = emitter.getShape(); List<Mesh> meshes = new ArrayList<Mesh>(); for (Spatial spatial : node.getChildren()) { if (spatial instanceof Geometry) { Mesh mesh = ((Geometry) spatial).getMesh(); if (mesh != null) { meshes.add(mesh); Material material = materialHelper.getParticlesMaterial(((Geometry) spatial).getMaterial(), alphaFunction, dataRepository); emitter.setMaterial(material);// TODO: divide into several pieces } } } if (meshes.size() > 0 && emitterShape instanceof EmitterMeshVertexShape) { ((EmitterMeshVertexShape) emitterShape).setMeshes(meshes); } node.attachChild(emitter); return node; } /** * This method applies ArmatureModifierData to the loaded object. * @param node * the loaded object * @param modifier * the modifier to apply * @param dataRepository * the data repository * @return the node to whom the modifier was applied */ protected Node applyArmatureModifierData(Node node, Modifier modifier, DataRepository dataRepository) { AnimData ad = (AnimData) modifier.getJmeModifierRepresentation(); ArrayList<BoneAnimation> animList = ad.anims; Long modifierArmatureObject = (Long) modifier.getAdditionalData(); if (animList != null && animList.size() > 0) { ConstraintHelper constraintHelper = dataRepository.getHelper(ConstraintHelper.class); Constraint[] constraints = constraintHelper.getConstraints(modifierArmatureObject); HashMap<String, BoneAnimation> anims = new HashMap<String, BoneAnimation>(); for (int i = 0; i < animList.size(); ++i) { BoneAnimation boneAnimation = animList.get(i).clone(); // baking constraints into animations if (constraints != null && constraints.length > 0) { for (Constraint constraint : constraints) { constraint.affectAnimation(ad.skeleton, boneAnimation); } } anims.put(boneAnimation.getName(), boneAnimation); } // getting meshes Mesh[] meshes = null; List<Mesh> meshesList = new ArrayList<Mesh>(); List<Spatial> children = node.getChildren(); for (Spatial child : children) { if (child instanceof Geometry) { meshesList.add(((Geometry) child).getMesh()); } } if (meshesList.size() > 0) { meshes = meshesList.toArray(new Mesh[meshesList.size()]); } // applying the control to the node SkeletonControl skeletonControl = new SkeletonControl(meshes, ad.skeleton); AnimControl control = node.getControl(AnimControl.class); if (control == null) { control = new AnimControl(ad.skeleton); } else { // merging skeletons Skeleton controlSkeleton = control.getSkeleton(); int boneIndexIncrease = controlSkeleton.getBoneCount(); Skeleton skeleton = this.merge(controlSkeleton, ad.skeleton); // merging animations HashMap<String, BoneAnimation> animations = new HashMap<String, BoneAnimation>(); for (String animationName : control.getAnimationNames()) { animations.put(animationName, control.getAnim(animationName)); } for (Entry<String, BoneAnimation> animEntry : anims.entrySet()) { BoneAnimation ba = animEntry.getValue(); for (int i = 0; i < ba.getTracks().length; ++i) { BoneTrack bt = ba.getTracks()[i]; int newBoneIndex = bt.getTargetBoneIndex() + boneIndexIncrease; ba.getTracks()[i] = new BoneTrack(newBoneIndex, bt.getTimes(), bt.getTranslations(), bt.getRotations(), bt.getScales()); } animations.put(animEntry.getKey(), animEntry.getValue()); } // replacing the control node.removeControl(control); control = new AnimControl(skeleton); } control.setAnimations(anims); node.addControl(control); node.addControl(skeletonControl); } return node; } protected Node applyObjectAnimationModifier(Node node, Modifier modifier, DataRepository dataRepository) { AnimData ad = (AnimData) modifier.getJmeModifierRepresentation(); // TODO: Why is this line here? Why is this needed? // Remove if necessary. //ad.skeleton.getBone(0).setAttachNode(node); return this.applyArmatureModifierData(node, modifier, dataRepository); } /** * This method applies the array modifier to the node. * @param node * the object the modifier will be applied to * @param modifier * the modifier to be applied * @param dataRepository * the data repository * @return object node with array modifier applied */ @SuppressWarnings("unchecked") protected Node applyArrayModifierData(Node node, Modifier modifier, DataRepository dataRepository) { Map<String, Object> modifierData = (Map<String, Object>) modifier.getJmeModifierRepresentation(); int fittype = ((Number) modifierData.get("fittype")).intValue(); float[] offset = (float[]) modifierData.get("offset"); if (offset == null) {// the node will be repeated several times in the same place offset = new float[]{0.0f, 0.0f, 0.0f}; } float[] scale = (float[]) modifierData.get("scale"); if (scale == null) {// the node will be repeated several times in the same place scale = new float[]{0.0f, 0.0f, 0.0f}; } else { // getting bounding box node.updateModelBound(); BoundingVolume boundingVolume = node.getWorldBound(); if (boundingVolume instanceof BoundingBox) { scale[0] *= ((BoundingBox) boundingVolume).getXExtent() * 2.0f; scale[1] *= ((BoundingBox) boundingVolume).getYExtent() * 2.0f; scale[2] *= ((BoundingBox) boundingVolume).getZExtent() * 2.0f; } else if (boundingVolume instanceof BoundingSphere) { float radius = ((BoundingSphere) boundingVolume).getRadius(); scale[0] *= radius * 2.0f; scale[1] *= radius * 2.0f; scale[2] *= radius * 2.0f; } else { throw new IllegalStateException("Unknown bounding volume type: " + boundingVolume.getClass().getName()); } } // adding object's offset float[] objectOffset = new float[]{0.0f, 0.0f, 0.0f}; Pointer pOffsetObject = (Pointer) modifierData.get("offsetob"); if (pOffsetObject != null) { FileBlockHeader offsetObjectBlock = dataRepository.getFileBlock(pOffsetObject.getOldMemoryAddress()); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); try {// we take the structure in case the object was not yet loaded Structure offsetStructure = offsetObjectBlock.getStructure(dataRepository); Vector3f translation = objectHelper.getTransformation(offsetStructure, dataRepository).getTranslation(); objectOffset[0] = translation.x; objectOffset[1] = translation.y; objectOffset[2] = translation.z; } catch (BlenderFileException e) { LOGGER.log(Level.WARNING, "Problems in blender file structure! Object offset cannot be applied! The problem: {0}", e.getMessage()); } } // getting start and end caps Node[] caps = new Node[]{null, null}; Pointer[] pCaps = new Pointer[]{(Pointer) modifierData.get("startcap"), (Pointer) modifierData.get("endcap")}; for (int i = 0; i < pCaps.length; ++i) { if (pCaps[i] != null) { caps[i] = (Node) dataRepository.getLoadedFeature(pCaps[i].getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (caps[i] != null) { caps[i] = (Node) caps[i].clone(); } else { FileBlockHeader capBlock = dataRepository.getFileBlock(pOffsetObject.getOldMemoryAddress()); try {// we take the structure in case the object was not yet loaded Structure capStructure = capBlock.getStructure(dataRepository); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); caps[i] = (Node) objectHelper.toObject(capStructure, dataRepository); if (caps[i] == null) { LOGGER.log(Level.WARNING, "Cap object ''{0}'' couldn''t be loaded!", capStructure.getName()); } } catch (BlenderFileException e) { LOGGER.log(Level.WARNING, "Problems in blender file structure! Cap object cannot be applied! The problem: {0}", e.getMessage()); } } } } Vector3f translationVector = new Vector3f(offset[0] + scale[0] + objectOffset[0], offset[1] + scale[1] + objectOffset[1], offset[2] + scale[2] + objectOffset[2]); // getting/calculating repeats amount int count = 0; if (fittype == 0) {// Fixed count count = ((Number) modifierData.get("count")).intValue() - 1; } else if (fittype == 1) {// Fixed length float length = ((Number) modifierData.get("length")).floatValue(); if (translationVector.length() > 0.0f) { count = (int) (length / translationVector.length()) - 1; } } else if (fittype == 2) {// Fit curve throw new IllegalStateException("Fit curve should be transformed to Fixed Length array type!"); } else { throw new IllegalStateException("Unknown fit type: " + fittype); } // adding translated nodes and caps if (count > 0) { Node[] arrayNodes = new Node[count]; Vector3f newTranslation = new Vector3f(); for (int i = 0; i < count; ++i) { newTranslation.addLocal(translationVector); Node nodeClone = (Node) node.clone(); nodeClone.setLocalTranslation(newTranslation); arrayNodes[i] = nodeClone; } for (Node nodeClone : arrayNodes) { node.attachChild(nodeClone); } if (caps[0] != null) { caps[0].getLocalTranslation().set(node.getLocalTranslation()).subtractLocal(translationVector); node.attachChild(caps[0]); } if (caps[1] != null) { caps[1].getLocalTranslation().set(newTranslation).addLocal(translationVector); node.attachChild(caps[1]); } } return node; } /** * This method applies the mirror modifier to the node. * @param node * the object the modifier will be applied to * @param modifier * the modifier to be applied * @param dataRepository * the data repository * @return object node with mirror modifier applied */ @SuppressWarnings("unchecked") protected Node applyMirrorModifierData(Node node, Modifier modifier, DataRepository dataRepository) { Map<String, Object> modifierData = (Map<String, Object>) modifier.getJmeModifierRepresentation(); int flag = ((Number) modifierData.get("flag")).intValue(); float[] mirrorFactor = new float[]{ (flag & 0x08) != 0 ? -1.0f : 1.0f, (flag & 0x10) != 0 ? -1.0f : 1.0f, (flag & 0x20) != 0 ? -1.0f : 1.0f }; float[] center = new float[]{0.0f, 0.0f, 0.0f}; Pointer pObject = (Pointer) modifierData.get("mirrorob"); if (pObject != null) { Structure objectStructure; try { objectStructure = pObject.fetchData(dataRepository.getInputStream()).get(0); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Node object = (Node) objectHelper.toObject(objectStructure, dataRepository); if (object != null) { Vector3f translation = object.getWorldTranslation(); center[0] = translation.x; center[1] = translation.y; center[2] = translation.z; } } catch (BlenderFileException e) { LOGGER.log(Level.SEVERE, "Cannot load mirror''s reference object. Cause: {0}", e.getLocalizedMessage()); } } float tolerance = ((Number) modifierData.get("tolerance")).floatValue(); boolean mirrorU = (flag & 0x01) != 0; boolean mirrorV = (flag & 0x02) != 0; // boolean mirrorVGroup = (flag & 0x20) != 0; List<Geometry> geometriesToAdd = new ArrayList<Geometry>(); for (int mirrorIndex = 0; mirrorIndex < 3; ++mirrorIndex) { if (mirrorFactor[mirrorIndex] == -1.0f) { for (Spatial spatial : node.getChildren()) { if (spatial instanceof Geometry) { Mesh mesh = ((Geometry) spatial).getMesh(); Mesh clone = mesh.deepClone(); // getting buffers FloatBuffer position = mesh.getFloatBuffer(Type.Position); FloatBuffer bindPosePosition = mesh.getFloatBuffer(Type.BindPosePosition); FloatBuffer clonePosition = clone.getFloatBuffer(Type.Position); FloatBuffer cloneBindPosePosition = clone.getFloatBuffer(Type.BindPosePosition); FloatBuffer cloneNormals = clone.getFloatBuffer(Type.Normal); FloatBuffer cloneBindPoseNormals = clone.getFloatBuffer(Type.BindPoseNormal); IntBuffer cloneIndexes = (IntBuffer) clone.getBuffer(Type.Index).getData(); // modyfying data for (int i = mirrorIndex; i < clonePosition.limit(); i += 3) { float value = clonePosition.get(i); float d = center[mirrorIndex] - value; if (Math.abs(d) <= tolerance) { clonePosition.put(i, center[mirrorIndex]); cloneBindPosePosition.put(i, center[mirrorIndex]); position.put(i, center[mirrorIndex]); bindPosePosition.put(i, center[mirrorIndex]); } else { clonePosition.put(i, value + 2.0f * d); cloneBindPosePosition.put(i, value + 2.0f * d); } cloneNormals.put(i, -cloneNormals.get(i)); cloneBindPoseNormals.put(i, -cloneNormals.get(i)); //modifying clone indexes int vertexIndex = (i - mirrorIndex) / 3; if (vertexIndex % 3 == 0) { int index = cloneIndexes.get(vertexIndex + 2); cloneIndexes.put(vertexIndex + 2, cloneIndexes.get(vertexIndex + 1)); cloneIndexes.put(vertexIndex + 1, index); } } if (mirrorU) { FloatBuffer cloneUVs = (FloatBuffer) clone.getBuffer(Type.TexCoord).getData(); for (int i = 0; i < cloneUVs.limit(); i += 2) { cloneUVs.put(i, 1.0f - cloneUVs.get(i)); } } if (mirrorV) { FloatBuffer cloneUVs = (FloatBuffer) clone.getBuffer(Type.TexCoord).getData(); for (int i = 1; i < cloneUVs.limit(); i += 2) { cloneUVs.put(i, 1.0f - cloneUVs.get(i)); } } Geometry geometry = new Geometry(null, clone); geometry.setMaterial(((Geometry) spatial).getMaterial()); geometriesToAdd.add(geometry); } } // adding meshes to node for (Geometry geometry : geometriesToAdd) { node.attachChild(geometry); } geometriesToAdd.clear(); } } return node; } /** * This method merges two skeletons into one. I assume that each skeleton's 0-indexed bone is objectAnimationBone so * only one such bone should be placed in the result * @param s1 * first skeleton * @param s2 * second skeleton * @return merged skeleton */ protected Skeleton merge(Skeleton s1, Skeleton s2) { List<Bone> bones = new ArrayList<Bone>(s1.getBoneCount() + s2.getBoneCount()); for (int i = 0; i < s1.getBoneCount(); ++i) { bones.add(s1.getBone(i)); } for (int i = 1; i < s2.getBoneCount(); ++i) {// ommit objectAnimationBone bones.add(s2.getBone(i)); } return new Skeleton(bones.toArray(new Bone[bones.size()])); } @Override public boolean shouldBeLoaded(Structure structure, DataRepository dataRepository) { return true; } }
engine/src/blender/com/jme3/scene/plugins/blender/helpers/v249/ModifierHelper.java
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.scene.plugins.blender.helpers.v249; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.jme3.animation.AnimControl; import com.jme3.animation.Bone; import com.jme3.animation.BoneAnimation; import com.jme3.animation.BoneTrack; import com.jme3.animation.Skeleton; import com.jme3.animation.SkeletonControl; import com.jme3.bounding.BoundingBox; import com.jme3.bounding.BoundingSphere; import com.jme3.bounding.BoundingVolume; import com.jme3.effect.ParticleEmitter; import com.jme3.effect.shapes.EmitterMeshVertexShape; import com.jme3.effect.shapes.EmitterShape; import com.jme3.material.Material; import com.jme3.math.Matrix4f; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.plugins.blender.data.FileBlockHeader; import com.jme3.scene.plugins.blender.data.Structure; import com.jme3.scene.plugins.blender.exception.BlenderFileException; import com.jme3.scene.plugins.blender.helpers.ParticlesHelper; import com.jme3.scene.plugins.blender.structures.Constraint; import com.jme3.scene.plugins.blender.structures.Ipo; import com.jme3.scene.plugins.blender.structures.Modifier; import com.jme3.scene.plugins.blender.utils.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.utils.DataRepository; import com.jme3.scene.plugins.blender.utils.DataRepository.LoadedFeatureDataType; import com.jme3.scene.plugins.blender.utils.DynamicArray; import com.jme3.scene.plugins.blender.utils.Pointer; import com.jme3.scene.plugins.ogre.AnimData; import com.jme3.scene.shape.Curve; /** * A class that is used in modifiers calculations. * @author Marcin Roguski */ public class ModifierHelper extends AbstractBlenderHelper { private static final Logger LOGGER = Logger.getLogger(ModifierHelper.class.getName()); /** * This constructor parses the given blender version and stores the result. Some functionalities may differ in * different blender versions. * @param blenderVersion * the version read from the blend file */ public ModifierHelper(String blenderVersion) { super(blenderVersion); } /** * This method applies modifier to the object. * @param node * the loaded object * @param modifier * the modifier to apply * @param dataRepository * the data repository * @return the node to whom the modifier was applied */ public Node applyModifier(Node node, Modifier modifier, DataRepository dataRepository) { if (Modifier.ARMATURE_MODIFIER_DATA.equals(modifier.getType())) { return this.applyArmatureModifierData(node, modifier, dataRepository); } else if (Modifier.OBJECT_ANIMATION_MODIFIER_DATA.equals(modifier.getType())) { return this.applyObjectAnimationModifier(node, modifier, dataRepository); } else if (Modifier.ARRAY_MODIFIER_DATA.equals(modifier.getType())) { return this.applyArrayModifierData(node, modifier, dataRepository); } else if (Modifier.PARTICLE_MODIFIER_DATA.equals(modifier.getType())) { return this.applyParticleSystemModifierData(node, modifier, dataRepository); } else if (Modifier.MIRROR_MODIFIER_DATA.equals(modifier.getType())) { return this.applyMirrorModifierData(node, modifier, dataRepository); } else { LOGGER.log(Level.WARNING, "Modifier: {0} not yet implemented!!!", modifier.getType()); return node; } } /** * This method reads the given object's modifiers. * @param objectStructure * the object structure * @param dataRepository * the data repository * @param converter * the converter object (in some cases we need to read an object first before loading the modifier) * @throws BlenderFileException * this exception is thrown when the blender file is somehow corrupted */ @SuppressWarnings("unchecked") public void readModifiers(Structure objectStructure, DataRepository dataRepository) throws BlenderFileException { Structure modifiersListBase = (Structure) objectStructure.getFieldValue("modifiers"); List<Structure> modifiers = modifiersListBase.evaluateListBase(dataRepository); for (Structure modifier : modifiers) { Object loadedModifier = null; Object modifierAdditionalData = null; if (Modifier.ARRAY_MODIFIER_DATA.equals(modifier.getType())) {// ****************ARRAY MODIFIER Map<String, Object> params = new HashMap<String, Object>(); Number fittype = (Number) modifier.getFieldValue("fit_type"); params.put("fittype", fittype); switch (fittype.intValue()) { case 0:// FIXED COUNT params.put("count", modifier.getFieldValue("count")); break; case 1:// FIXED LENGTH params.put("length", modifier.getFieldValue("length")); break; case 2:// FITCURVE Pointer pCurveOb = (Pointer) modifier.getFieldValue("curve_ob"); float length = 0; if (pCurveOb.isNotNull()) { Structure curveStructure = pCurveOb.fetchData(dataRepository.getInputStream()).get(0); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Node curveObject = (Node) objectHelper.toObject(curveStructure, dataRepository); Set<Number> referencesToCurveLengths = new HashSet<Number>(curveObject.getChildren().size()); for (Spatial spatial : curveObject.getChildren()) { if (spatial instanceof Geometry) { Mesh mesh = ((Geometry) spatial).getMesh(); if (mesh instanceof Curve) { length += ((Curve) mesh).getLength(); } else { //if bevel object has several parts then each mesh will have the same reference //to length value (and we should use only one) Number curveLength = spatial.getUserData("curveLength"); if (curveLength != null && !referencesToCurveLengths.contains(curveLength)) { length += curveLength.floatValue(); referencesToCurveLengths.add(curveLength); } } } } } params.put("length", Float.valueOf(length)); params.put("fittype", Integer.valueOf(1));// treat it like FIXED LENGTH break; default: assert false : "Unknown array modifier fit type: " + fittype; } // offset parameters int offsettype = ((Number) modifier.getFieldValue("offset_type")).intValue(); if ((offsettype & 0x01) != 0) {// Constant offset DynamicArray<Number> offsetArray = (DynamicArray<Number>) modifier.getFieldValue("offset"); float[] offset = new float[]{offsetArray.get(0).floatValue(), offsetArray.get(1).floatValue(), offsetArray.get(2).floatValue()}; params.put("offset", offset); } if ((offsettype & 0x02) != 0) {// Relative offset DynamicArray<Number> scaleArray = (DynamicArray<Number>) modifier.getFieldValue("scale"); float[] scale = new float[]{scaleArray.get(0).floatValue(), scaleArray.get(1).floatValue(), scaleArray.get(2).floatValue()}; params.put("scale", scale); } if ((offsettype & 0x04) != 0) {// Object offset Pointer pOffsetObject = (Pointer) modifier.getFieldValue("offset_ob"); if (pOffsetObject.isNotNull()) { params.put("offsetob", pOffsetObject); } } // start cap and end cap Pointer pStartCap = (Pointer) modifier.getFieldValue("start_cap"); if (pStartCap.isNotNull()) { params.put("startcap", pStartCap); } Pointer pEndCap = (Pointer) modifier.getFieldValue("end_cap"); if (pEndCap.isNotNull()) { params.put("endcap", pEndCap); } loadedModifier = params; } else if (Modifier.MIRROR_MODIFIER_DATA.equals(modifier.getType())) {// ****************MIRROR MODIFIER Map<String, Object> params = new HashMap<String, Object>(); params.put("flag", modifier.getFieldValue("flag")); params.put("tolerance", modifier.getFieldValue("tolerance")); Pointer pMirrorOb = (Pointer) modifier.getFieldValue("mirror_ob"); if (pMirrorOb.isNotNull()) { params.put("mirrorob", pMirrorOb); } loadedModifier = params; } else if (Modifier.ARMATURE_MODIFIER_DATA.equals(modifier.getType())) {// ****************ARMATURE MODIFIER Pointer pArmatureObject = (Pointer) modifier.getFieldValue("object"); if (pArmatureObject.isNotNull()) { ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Structure armatureObject = (Structure) dataRepository.getLoadedFeature(pArmatureObject.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_STRUCTURE); if (armatureObject == null) {// we check this first not to fetch the structure unnecessary armatureObject = pArmatureObject.fetchData(dataRepository.getInputStream()).get(0); objectHelper.toObject(armatureObject, dataRepository); } modifierAdditionalData = armatureObject.getOldMemoryAddress(); ArmatureHelper armatureHelper = dataRepository.getHelper(ArmatureHelper.class); // changing bones matrices so that they fit the current object (that is why we need a copy of a skeleton) Matrix4f armatureObjectMatrix = objectHelper.getTransformationMatrix(armatureObject); Matrix4f inverseMeshObjectMatrix = objectHelper.getTransformationMatrix(objectStructure).invert(); Matrix4f additionalRootBoneTransformation = inverseMeshObjectMatrix.multLocal(armatureObjectMatrix); Bone[] bones = armatureHelper.buildBonesStructure(Long.valueOf(0L), additionalRootBoneTransformation); //setting the bones structure inside the skeleton (thus completing its loading) Skeleton skeleton = new Skeleton(bones); dataRepository.addLoadedFeatures(armatureObject.getOldMemoryAddress(), armatureObject.getName(), armatureObject, skeleton); String objectName = objectStructure.getName(); Set<String> animationNames = dataRepository.getBlenderKey().getAnimationNames(objectName); if (animationNames != null && animationNames.size() > 0) { ArrayList<BoneAnimation> animations = new ArrayList<BoneAnimation>(); List<FileBlockHeader> actionHeaders = dataRepository.getFileBlocks(Integer.valueOf(FileBlockHeader.BLOCK_AC00)); for (FileBlockHeader header : actionHeaders) { Structure actionStructure = header.getStructure(dataRepository); String actionName = actionStructure.getName(); if (animationNames.contains(actionName)) { int[] animationFrames = dataRepository.getBlenderKey().getAnimationFrames(objectName, actionName); int fps = dataRepository.getBlenderKey().getFps(); float start = (float) animationFrames[0] / (float) fps; float stop = (float) animationFrames[1] / (float) fps; BoneAnimation boneAnimation = new BoneAnimation(actionName, stop - start); boneAnimation.setTracks(armatureHelper.getTracks(actionStructure, dataRepository, objectName, actionName)); animations.add(boneAnimation); } } loadedModifier = new AnimData(new Skeleton(bones), animations); } } else { LOGGER.log(Level.WARNING, "Unsupported modifier type: {0}", modifier.getType()); } } else if (Modifier.PARTICLE_MODIFIER_DATA.equals(modifier.getType())) {// ****************PARTICLES MODIFIER Pointer pParticleSystem = (Pointer) modifier.getFieldValue("psys"); if (pParticleSystem.isNotNull()) { ParticlesHelper particlesHelper = dataRepository.getHelper(ParticlesHelper.class); Structure particleSystem = pParticleSystem.fetchData(dataRepository.getInputStream()).get(0); loadedModifier = particlesHelper.toParticleEmitter(particleSystem, dataRepository); } } // adding modifier to the modifier's lists if (loadedModifier != null) { dataRepository.addModifier(objectStructure.getOldMemoryAddress(), modifier.getType(), loadedModifier, modifierAdditionalData); modifierAdditionalData = null; } } //at the end read object's animation modifier Modifier objectAnimationModifier = this.readObjectAnimation(objectStructure, dataRepository); if (objectAnimationModifier != null) { dataRepository.addModifier(objectStructure.getOldMemoryAddress(), objectAnimationModifier.getType(), objectAnimationModifier.getJmeModifierRepresentation(), objectAnimationModifier.getAdditionalData()); } } /** * This method reads animation of the object itself (without bones) and stores it as an ArmatureModifierData * modifier. The animation is returned as a modifier. It should be later applied regardless other modifiers. The * reason for this is that object may not have modifiers added but it's animation should be working. * @param objectStructure * the structure of the object * @param dataRepository * the data repository * @return animation modifier is returned, it should be separately applied when the object is loaded * @throws BlenderFileException * this exception is thrown when the blender file is somehow corrupted */ protected Modifier readObjectAnimation(Structure objectStructure, DataRepository dataRepository) throws BlenderFileException { Pointer pIpo = (Pointer) objectStructure.getFieldValue("ipo"); if (pIpo.isNotNull()) { //check if there is an action name connected with this ipo String objectAnimationName = null; List<FileBlockHeader> actionBlocks = dataRepository.getFileBlocks(Integer.valueOf(FileBlockHeader.BLOCK_AC00)); for (FileBlockHeader actionBlock : actionBlocks) { Structure action = actionBlock.getStructure(dataRepository); List<Structure> actionChannels = ((Structure) action.getFieldValue("chanbase")).evaluateListBase(dataRepository); if (actionChannels.size() == 1) {//object's animtion action has only one channel Pointer pChannelIpo = (Pointer) actionChannels.get(0).getFieldValue("ipo"); if (pChannelIpo.equals(pIpo)) { objectAnimationName = action.getName(); break; } } } String objectName = objectStructure.getName(); if (objectAnimationName == null) {//set the object's animation name to object's name objectAnimationName = objectName; } IpoHelper ipoHelper = dataRepository.getHelper(IpoHelper.class); Structure ipoStructure = pIpo.fetchData(dataRepository.getInputStream()).get(0); Ipo ipo = ipoHelper.createIpo(ipoStructure, dataRepository); int[] animationFrames = dataRepository.getBlenderKey().getAnimationFrames(objectName, objectAnimationName); if (animationFrames == null) {//if the name was created here there are no frames set for the animation animationFrames = new int[]{1, ipo.getLastFrame()}; } int fps = dataRepository.getBlenderKey().getFps(); float start = (float) animationFrames[0] / (float) fps; float stop = (float) animationFrames[1] / (float) fps; //calculating track for the only bone in this skeleton BoneTrack[] tracks = new BoneTrack[1]; tracks[0] = ipo.calculateTrack(0, animationFrames[0], animationFrames[1], fps); BoneAnimation boneAnimation = new BoneAnimation(objectAnimationName, stop - start); boneAnimation.setTracks(tracks); ArrayList<BoneAnimation> animations = new ArrayList<BoneAnimation>(1); animations.add(boneAnimation); //preparing the object's bone ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Transform t = objectHelper.getTransformation(objectStructure, dataRepository); Bone bone = new Bone(null); bone.setBindTransforms(t.getTranslation(), t.getRotation(), t.getScale()); return new Modifier(Modifier.OBJECT_ANIMATION_MODIFIER_DATA, new AnimData(new Skeleton(new Bone[]{bone}), animations), objectStructure.getOldMemoryAddress()); } return null; } /** * This method applies particles emitter to the given node. * @param node * the particles emitter node * @param modifier * the modifier containing the emitter data * @param dataRepository * the data repository * @return node with particles' emitter applied */ protected Node applyParticleSystemModifierData(Node node, Modifier modifier, DataRepository dataRepository) { MaterialHelper materialHelper = dataRepository.getHelper(MaterialHelper.class); ParticleEmitter emitter = (ParticleEmitter) modifier.getJmeModifierRepresentation(); emitter = emitter.clone(); // veryfying the alpha function for particles' texture Integer alphaFunction = MaterialHelper.ALPHA_MASK_HYPERBOLE; char nameSuffix = emitter.getName().charAt(emitter.getName().length() - 1); if (nameSuffix == 'B' || nameSuffix == 'N') { alphaFunction = MaterialHelper.ALPHA_MASK_NONE; } // removing the type suffix from the name emitter.setName(emitter.getName().substring(0, emitter.getName().length() - 1)); // applying emitter shape EmitterShape emitterShape = emitter.getShape(); List<Mesh> meshes = new ArrayList<Mesh>(); for (Spatial spatial : node.getChildren()) { if (spatial instanceof Geometry) { Mesh mesh = ((Geometry) spatial).getMesh(); if (mesh != null) { meshes.add(mesh); Material material = materialHelper.getParticlesMaterial(((Geometry) spatial).getMaterial(), alphaFunction, dataRepository); emitter.setMaterial(material);// TODO: divide into several pieces } } } if (meshes.size() > 0 && emitterShape instanceof EmitterMeshVertexShape) { ((EmitterMeshVertexShape) emitterShape).setMeshes(meshes); } node.attachChild(emitter); return node; } /** * This method applies ArmatureModifierData to the loaded object. * @param node * the loaded object * @param modifier * the modifier to apply * @param dataRepository * the data repository * @return the node to whom the modifier was applied */ protected Node applyArmatureModifierData(Node node, Modifier modifier, DataRepository dataRepository) { AnimData ad = (AnimData) modifier.getJmeModifierRepresentation(); ArrayList<BoneAnimation> animList = ad.anims; Long modifierArmatureObject = (Long) modifier.getAdditionalData(); if (animList != null && animList.size() > 0) { ConstraintHelper constraintHelper = dataRepository.getHelper(ConstraintHelper.class); Constraint[] constraints = constraintHelper.getConstraints(modifierArmatureObject); HashMap<String, BoneAnimation> anims = new HashMap<String, BoneAnimation>(); for (int i = 0; i < animList.size(); ++i) { BoneAnimation boneAnimation = animList.get(i).clone(); // baking constraints into animations if (constraints != null && constraints.length > 0) { for (Constraint constraint : constraints) { constraint.affectAnimation(ad.skeleton, boneAnimation); } } anims.put(boneAnimation.getName(), boneAnimation); } // getting meshes Mesh[] meshes = null; List<Mesh> meshesList = new ArrayList<Mesh>(); List<Spatial> children = node.getChildren(); for (Spatial child : children) { if (child instanceof Geometry) { meshesList.add(((Geometry) child).getMesh()); } } if (meshesList.size() > 0) { meshes = meshesList.toArray(new Mesh[meshesList.size()]); } // applying the control to the node SkeletonControl skeletonControl = new SkeletonControl(meshes, ad.skeleton); AnimControl control = node.getControl(AnimControl.class); if (control == null) { control = new AnimControl(ad.skeleton); } else { // merging skeletons Skeleton controlSkeleton = control.getSkeleton(); int boneIndexIncrease = controlSkeleton.getBoneCount(); Skeleton skeleton = this.merge(controlSkeleton, ad.skeleton); // merging animations HashMap<String, BoneAnimation> animations = new HashMap<String, BoneAnimation>(); for (String animationName : control.getAnimationNames()) { animations.put(animationName, control.getAnim(animationName)); } for (Entry<String, BoneAnimation> animEntry : anims.entrySet()) { BoneAnimation ba = animEntry.getValue(); for (int i = 0; i < ba.getTracks().length; ++i) { BoneTrack bt = ba.getTracks()[i]; int newBoneIndex = bt.getTargetBoneIndex() + boneIndexIncrease; ba.getTracks()[i] = new BoneTrack(newBoneIndex, bt.getTimes(), bt.getTranslations(), bt.getRotations(), bt.getScales()); } animations.put(animEntry.getKey(), animEntry.getValue()); } // replacing the control node.removeControl(control); control = new AnimControl(skeleton); } control.setAnimations(anims); node.addControl(control); node.addControl(skeletonControl); } return node; } protected Node applyObjectAnimationModifier(Node node, Modifier modifier, DataRepository dataRepository) { AnimData ad = (AnimData) modifier.getJmeModifierRepresentation(); // TODO: Why is this line here? Why is this needed? // Remove if necessary. //ad.skeleton.getBone(0).setAttachNode(node); return this.applyArmatureModifierData(node, modifier, dataRepository); } /** * This method applies the array modifier to the node. * @param node * the object the modifier will be applied to * @param modifier * the modifier to be applied * @param dataRepository * the data repository * @return object node with array modifier applied */ @SuppressWarnings("unchecked") protected Node applyArrayModifierData(Node node, Modifier modifier, DataRepository dataRepository) { Map<String, Object> modifierData = (Map<String, Object>) modifier.getJmeModifierRepresentation(); int fittype = ((Number) modifierData.get("fittype")).intValue(); float[] offset = (float[]) modifierData.get("offset"); if (offset == null) {// the node will be repeated several times in the same place offset = new float[]{0.0f, 0.0f, 0.0f}; } float[] scale = (float[]) modifierData.get("scale"); if (scale == null) {// the node will be repeated several times in the same place scale = new float[]{0.0f, 0.0f, 0.0f}; } else { // getting bounding box node.updateModelBound(); BoundingVolume boundingVolume = node.getWorldBound(); if (boundingVolume instanceof BoundingBox) { scale[0] *= ((BoundingBox) boundingVolume).getXExtent() * 2.0f; scale[1] *= ((BoundingBox) boundingVolume).getYExtent() * 2.0f; scale[2] *= ((BoundingBox) boundingVolume).getZExtent() * 2.0f; } else if (boundingVolume instanceof BoundingSphere) { float radius = ((BoundingSphere) boundingVolume).getRadius(); scale[0] *= radius * 2.0f; scale[1] *= radius * 2.0f; scale[2] *= radius * 2.0f; } else { throw new IllegalStateException("Unknown bounding volume type: " + boundingVolume.getClass().getName()); } } // adding object's offset float[] objectOffset = new float[]{0.0f, 0.0f, 0.0f}; Pointer pOffsetObject = (Pointer) modifierData.get("offsetob"); if (pOffsetObject != null) { FileBlockHeader offsetObjectBlock = dataRepository.getFileBlock(pOffsetObject.getOldMemoryAddress()); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); try {// we take the structure in case the object was not yet loaded Structure offsetStructure = offsetObjectBlock.getStructure(dataRepository); Vector3f translation = objectHelper.getTransformation(offsetStructure, dataRepository).getTranslation(); objectOffset[0] = translation.x; objectOffset[1] = translation.y; objectOffset[2] = translation.z; } catch (BlenderFileException e) { LOGGER.log(Level.WARNING, "Problems in blender file structure! Object offset cannot be applied! The problem: {0}", e.getMessage()); } } // getting start and end caps Node[] caps = new Node[]{null, null}; Pointer[] pCaps = new Pointer[]{(Pointer) modifierData.get("startcap"), (Pointer) modifierData.get("endcap")}; for (int i = 0; i < pCaps.length; ++i) { if (pCaps[i] != null) { caps[i] = (Node) dataRepository.getLoadedFeature(pCaps[i].getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (caps[i] != null) { caps[i] = (Node) caps[i].clone(); } else { FileBlockHeader capBlock = dataRepository.getFileBlock(pOffsetObject.getOldMemoryAddress()); try {// we take the structure in case the object was not yet loaded Structure capStructure = capBlock.getStructure(dataRepository); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); caps[i] = (Node) objectHelper.toObject(capStructure, dataRepository); if (caps[i] == null) { LOGGER.log(Level.WARNING, "Cap object ''{0}'' couldn''t be loaded!", capStructure.getName()); } } catch (BlenderFileException e) { LOGGER.log(Level.WARNING, "Problems in blender file structure! Cap object cannot be applied! The problem: {0}", e.getMessage()); } } } } Vector3f translationVector = new Vector3f(offset[0] + scale[0] + objectOffset[0], offset[1] + scale[1] + objectOffset[1], offset[2] + scale[2] + objectOffset[2]); // getting/calculating repeats amount int count = 0; if (fittype == 0) {// Fixed count count = ((Number) modifierData.get("count")).intValue() - 1; } else if (fittype == 1) {// Fixed length float length = ((Number) modifierData.get("length")).floatValue(); if (translationVector.length() > 0.0f) { count = (int) (length / translationVector.length()) - 1; } } else if (fittype == 2) {// Fit curve throw new IllegalStateException("Fit curve should be transformed to Fixed Length array type!"); } else { throw new IllegalStateException("Unknown fit type: " + fittype); } // adding translated nodes and caps if (count > 0) { Node[] arrayNodes = new Node[count]; Vector3f newTranslation = new Vector3f(); for (int i = 0; i < count; ++i) { newTranslation.addLocal(translationVector); Node nodeClone = (Node) node.clone(); nodeClone.setLocalTranslation(newTranslation); arrayNodes[i] = nodeClone; } for (Node nodeClone : arrayNodes) { node.attachChild(nodeClone); } if (caps[0] != null) { caps[0].getLocalTranslation().set(node.getLocalTranslation()).subtractLocal(translationVector); node.attachChild(caps[0]); } if (caps[1] != null) { caps[1].getLocalTranslation().set(newTranslation).addLocal(translationVector); node.attachChild(caps[1]); } } return node; } /** * This method applies the mirror modifier to the node. * @param node * the object the modifier will be applied to * @param modifier * the modifier to be applied * @param dataRepository * the data repository * @return object node with mirror modifier applied */ @SuppressWarnings("unchecked") protected Node applyMirrorModifierData(Node node, Modifier modifier, DataRepository dataRepository) { Map<String, Object> modifierData = (Map<String, Object>) modifier.getJmeModifierRepresentation(); int flag = ((Number) modifierData.get("flag")).intValue(); float[] mirrorFactor = new float[]{ (flag & 0x08) != 0 ? -1.0f : 1.0f, (flag & 0x10) != 0 ? -1.0f : 1.0f, (flag & 0x20) != 0 ? -1.0f : 1.0f }; float[] center = new float[]{0.0f, 0.0f, 0.0f}; Pointer pObject = (Pointer) modifierData.get("mirrorob"); if (pObject != null) { Structure objectStructure; try { objectStructure = pObject.fetchData(dataRepository.getInputStream()).get(0); ObjectHelper objectHelper = dataRepository.getHelper(ObjectHelper.class); Node object = (Node) objectHelper.toObject(objectStructure, dataRepository); if (object != null) { Vector3f translation = object.getWorldTranslation(); center[0] = translation.x; center[1] = translation.y; center[2] = translation.z; } } catch (BlenderFileException e) { LOGGER.log(Level.SEVERE, "Cannot load mirror''s reference object. Cause: {0}", e.getLocalizedMessage()); } } float tolerance = ((Number) modifierData.get("tolerance")).floatValue(); boolean mirrorU = (flag & 0x01) != 0; boolean mirrorV = (flag & 0x02) != 0; // boolean mirrorVGroup = (flag & 0x20) != 0; List<Geometry> geometriesToAdd = new ArrayList<Geometry>(); for (int mirrorIndex = 0; mirrorIndex < 3; ++mirrorIndex) { if (mirrorFactor[mirrorIndex] == -1.0f) { for (Spatial spatial : node.getChildren()) { if (spatial instanceof Geometry) { Mesh mesh = ((Geometry) spatial).getMesh(); Mesh clone = mesh.deepClone(); // getting buffers FloatBuffer position = mesh.getFloatBuffer(Type.Position); FloatBuffer bindPosePosition = mesh.getFloatBuffer(Type.BindPosePosition); FloatBuffer clonePosition = clone.getFloatBuffer(Type.Position); FloatBuffer cloneBindPosePosition = clone.getFloatBuffer(Type.BindPosePosition); FloatBuffer cloneNormals = clone.getFloatBuffer(Type.Normal); FloatBuffer cloneBindPoseNormals = clone.getFloatBuffer(Type.BindPoseNormal); ShortBuffer cloneIndexes = (ShortBuffer) clone.getBuffer(Type.Index).getData(); // modyfying data for (int i = mirrorIndex; i < clonePosition.limit(); i += 3) { float value = clonePosition.get(i); float d = center[mirrorIndex] - value; if (Math.abs(d) <= tolerance) { clonePosition.put(i, center[mirrorIndex]); cloneBindPosePosition.put(i, center[mirrorIndex]); position.put(i, center[mirrorIndex]); bindPosePosition.put(i, center[mirrorIndex]); } else { clonePosition.put(i, value + 2.0f * d); cloneBindPosePosition.put(i, value + 2.0f * d); } cloneNormals.put(i, -cloneNormals.get(i)); cloneBindPoseNormals.put(i, -cloneNormals.get(i)); //modifying clone indexes int vertexIndex = (i - mirrorIndex) / 3; if (vertexIndex % 3 == 0) { short index = cloneIndexes.get(vertexIndex + 2); cloneIndexes.put(vertexIndex + 2, cloneIndexes.get(vertexIndex + 1)); cloneIndexes.put(vertexIndex + 1, index); } } if (mirrorU) { FloatBuffer cloneUVs = (FloatBuffer) clone.getBuffer(Type.TexCoord).getData(); for (int i = 0; i < cloneUVs.limit(); i += 2) { cloneUVs.put(i, 1.0f - cloneUVs.get(i)); } } if (mirrorV) { FloatBuffer cloneUVs = (FloatBuffer) clone.getBuffer(Type.TexCoord).getData(); for (int i = 1; i < cloneUVs.limit(); i += 2) { cloneUVs.put(i, 1.0f - cloneUVs.get(i)); } } Geometry geometry = new Geometry(null, clone); geometry.setMaterial(((Geometry) spatial).getMaterial()); geometriesToAdd.add(geometry); } } // adding meshes to node for (Geometry geometry : geometriesToAdd) { node.attachChild(geometry); } geometriesToAdd.clear(); } } return node; } /** * This method merges two skeletons into one. I assume that each skeleton's 0-indexed bone is objectAnimationBone so * only one such bone should be placed in the result * @param s1 * first skeleton * @param s2 * second skeleton * @return merged skeleton */ protected Skeleton merge(Skeleton s1, Skeleton s2) { List<Bone> bones = new ArrayList<Bone>(s1.getBoneCount() + s2.getBoneCount()); for (int i = 0; i < s1.getBoneCount(); ++i) { bones.add(s1.getBone(i)); } for (int i = 1; i < s2.getBoneCount(); ++i) {// ommit objectAnimationBone bones.add(s2.getBone(i)); } return new Skeleton(bones.toArray(new Bone[bones.size()])); } @Override public boolean shouldBeLoaded(Structure structure, DataRepository dataRepository) { return true; } }
Fix with reading the proper buffer. git-svn-id: f9411aee4f13664f2fc428a5b3e824fe43a079a3@7943 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
engine/src/blender/com/jme3/scene/plugins/blender/helpers/v249/ModifierHelper.java
Fix with reading the proper buffer.
Java
mit
c7195e5ba959fe81216c05290d2b627fbe73afcb
0
erikeelde/Granter,erikeelde/Granter
package se.eelde.granter; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import pub.devrel.easypermissions.AppSettingsDialog; import pub.devrel.easypermissions.EasyPermissions; public class GranterFragment extends Fragment implements EasyPermissions.PermissionCallbacks { private static final String ARGUMENT_PERMISSIONS_ARRAY = "argument_permissions_array"; private static final String ARGUMENT_REQUEST_CODE = "argument_request_code"; private static final String ARGUMENT_RATIONALE = "argument_rationale"; private static final String ARGUMENT_SEND_USER_TO_SETTINGS = "argument_send_user_to_settings"; private String[] requestedPermissions; private int requestCode; private String rationale; private boolean sendUserToSettings = true; static GranterFragment newInstance(ArrayList<String> permissions, int requestCode, String rationale, boolean sendUserToSettings) { Bundle args = new Bundle(); args.putStringArrayList(ARGUMENT_PERMISSIONS_ARRAY, permissions); args.putInt(ARGUMENT_REQUEST_CODE, requestCode); args.putString(ARGUMENT_RATIONALE, rationale); args.putBoolean(ARGUMENT_SEND_USER_TO_SETTINGS, sendUserToSettings); GranterFragment fragment = new GranterFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayList<String> stringArrayList = getArguments().getStringArrayList(ARGUMENT_PERMISSIONS_ARRAY); //noinspection ConstantConditions requestedPermissions = new String[stringArrayList.size()]; stringArrayList.toArray(requestedPermissions); requestCode = getArguments().getInt(ARGUMENT_REQUEST_CODE); rationale = getArguments().getString(ARGUMENT_RATIONALE, getString(R.string.permission_rationale_message)); sendUserToSettings = getArguments().getBoolean(ARGUMENT_SEND_USER_TO_SETTINGS, true); if (!EasyPermissions.hasPermissions(getContext(), requestedPermissions)) { EasyPermissions.requestPermissions(this, rationale, requestCode, requestedPermissions); } else { int[] ints = new int[requestedPermissions.length]; Arrays.fill(ints, PackageManager.PERMISSION_GRANTED); callback(requestCode, requestedPermissions, ints); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); callback(requestCode, permissions, grantResults); } @Override public void onPermissionsGranted(int requestCode, List<String> perms) { } @Override public void onPermissionsDenied(int requestCode, List<String> perms) { if (sendUserToSettings && EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { new AppSettingsDialog.Builder(this).build().show(); } } private void callback(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (getParentFragment() != null) { EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this, getParentFragment()); } else if (getActivity() != null) { EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this, getActivity()); } } }
granter/src/main/java/se/eelde/granter/GranterFragment.java
package se.eelde.granter; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import pub.devrel.easypermissions.AppSettingsDialog; import pub.devrel.easypermissions.EasyPermissions; public class GranterFragment extends Fragment implements EasyPermissions.PermissionCallbacks { private static final String ARGUMENT_PERMISSIONS_ARRAY = "argument_permissions_array"; private static final String ARGUMENT_REQUEST_CODE = "argument_request_code"; private static final String ARGUMENT_RATIONALE = "argument_rationale"; private static final String ARGUMENT_SEND_USER_TO_SETTINGS = "argument_send_user_to_settings"; private String[] requestedPermissions; private int requestCode; private String rationale; private boolean sendUserToSettings = true; static GranterFragment newInstance(ArrayList<String> permissions, int requestCode, String rationale, boolean sendUserToSettings) { Bundle args = new Bundle(); args.putStringArrayList(ARGUMENT_PERMISSIONS_ARRAY, permissions); args.putInt(ARGUMENT_REQUEST_CODE, requestCode); args.putString(ARGUMENT_RATIONALE, rationale); args.putBoolean(ARGUMENT_SEND_USER_TO_SETTINGS, sendUserToSettings); GranterFragment fragment = new GranterFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayList<String> stringArrayList = getArguments().getStringArrayList(ARGUMENT_PERMISSIONS_ARRAY); //noinspection ConstantConditions requestedPermissions = new String[stringArrayList.size()]; stringArrayList.toArray(requestedPermissions); requestCode = getArguments().getInt(ARGUMENT_REQUEST_CODE); rationale = getArguments().getString(ARGUMENT_RATIONALE, getString(R.string.permission_rationale_message)); sendUserToSettings = getArguments().getBoolean(ARGUMENT_SEND_USER_TO_SETTINGS, true); checkPermission(); } private void checkPermission() { if (!EasyPermissions.hasPermissions(getContext(), requestedPermissions)) { EasyPermissions.requestPermissions(this, rationale, requestCode, requestedPermissions); } else { int[] ints = new int[requestedPermissions.length]; Arrays.fill(ints, PackageManager.PERMISSION_GRANTED); callback(requestCode, requestedPermissions, ints); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); callback(requestCode, permissions, grantResults); } @Override public void onPermissionsGranted(int requestCode, List<String> perms) { } @Override public void onPermissionsDenied(int requestCode, List<String> perms) { if (sendUserToSettings && EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { new AppSettingsDialog.Builder(this).build().show(); } } private void callback(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (getParentFragment() != null) { EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this, getParentFragment()); } else if (getActivity() != null) { EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this, getActivity()); } } }
inline check for permission
granter/src/main/java/se/eelde/granter/GranterFragment.java
inline check for permission
Java
mit
c678993418d528c19169dad262d8568458f6642d
0
jongerrish/robolectric,jongerrish/robolectric,jongerrish/robolectric,spotify/robolectric,spotify/robolectric,spotify/robolectric,jongerrish/robolectric
package org.robolectric.shadows; import static android.content.pm.PackageManager.PERMISSION_DENIED; import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1; import static android.os.Build.VERSION_CODES.M; import static android.os.Build.VERSION_CODES.P; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import android.app.Activity; import android.app.ActivityThread; import android.app.Fragment; import android.app.Instrumentation; import android.app.Instrumentation.ActivityResult; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.Intent.FilterComparison; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.UserHandle; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.shadow.api.Shadow; import org.robolectric.shadows.ShadowActivity.IntentForResult; import org.robolectric.shadows.ShadowApplication.Wrapper; @Implements(value = Instrumentation.class, looseSignatures = true) public class ShadowInstrumentation { private List<Intent> startedActivities = new ArrayList<>(); private List<IntentForResult> startedActivitiesForResults = new ArrayList<>(); private Map<FilterComparison, Integer> intentRequestCodeMap = new HashMap<>(); private List<Intent.FilterComparison> startedServices = new ArrayList<>(); private List<Intent.FilterComparison> stoppedServices = new ArrayList<>(); private List<Intent> broadcastIntents = new ArrayList<>(); private List<ServiceConnection> boundServiceConnections = new ArrayList<>(); private List<ServiceConnection> unboundServiceConnections = new ArrayList<>(); private List<Wrapper> registeredReceivers = new ArrayList<>(); private Set<String> grantedPermissions = new HashSet<>(); private boolean unbindServiceShouldThrowIllegalArgument = false; private Map<Intent.FilterComparison, ServiceConnectionDataWrapper> serviceConnectionDataForIntent = new HashMap<>(); // default values for bindService private ServiceConnectionDataWrapper defaultServiceConnectionData = new ServiceConnectionDataWrapper(null, null); private List<String> unbindableActions = new ArrayList<>(); private Map<String, Intent> stickyIntents = new LinkedHashMap<>(); private Handler mainHandler; private Map<ServiceConnection, ServiceConnectionDataWrapper> serviceConnectionDataForServiceConnection = new HashMap<>(); private boolean checkActivities; @Implementation(minSdk = P) public Activity startActivitySync(Intent intent, Bundle options) { throw new UnsupportedOperationException("Implement me!!"); } @Implementation public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { verifyActivityInManifest(intent); return logStartedActivity(intent, requestCode, options); } @Implementation(maxSdk = LOLLIPOP_MR1) public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Fragment target, Intent intent, int requestCode, Bundle options) { verifyActivityInManifest(intent); return logStartedActivity(intent, requestCode, options); } private ActivityResult logStartedActivity(Intent intent, int requestCode, Bundle options) { startedActivities.add(intent); intentRequestCodeMap.put(new FilterComparison(intent), requestCode); startedActivitiesForResults.add(new IntentForResult(intent, requestCode, options)); return null; } private void verifyActivityInManifest(Intent intent) { if (checkActivities && RuntimeEnvironment.application.getPackageManager().resolveActivity(intent, -1) == null) { throw new ActivityNotFoundException(intent.getAction()); } } @Implementation public void execStartActivities( Context who, IBinder contextThread, IBinder token, Activity target, Intent[] intents, Bundle options) { for (Intent intent : intents) { execStartActivity(who, contextThread, token, target, intent, -1, options); } } @Implementation(minSdk = LOLLIPOP) public void execStartActivityFromAppTask( Context who, IBinder contextThread, Object appTask, Intent intent, Bundle options) { throw new UnsupportedOperationException("Implement me!!"); } @Implementation(minSdk = M) public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, String target, Intent intent, int requestCode, Bundle options) { verifyActivityInManifest(intent); return logStartedActivity(intent, requestCode, options); } @Implementation(minSdk = JELLY_BEAN_MR1) public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, String resultWho, Intent intent, int requestCode, Bundle options, UserHandle user) { throw new UnsupportedOperationException("Implement me!!"); } @Implementation(minSdk = M) public ActivityResult execStartActivityAsCaller( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options, boolean ignoreTargetSecurity, int userId) { throw new UnsupportedOperationException("Implement me!!"); } void sendOrderedBroadcast( Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras, Context context) { List<Wrapper> receivers = getAppropriateWrappers(intent, receiverPermission); sortByPriority(receivers); receivers.add(new Wrapper(resultReceiver, null, context, null, scheduler)); postOrderedToWrappers(receivers, intent, initialCode, initialData, initialExtras, context); } void assertNoBroadcastListenersOfActionRegistered(ContextWrapper context, String action) { for (Wrapper registeredReceiver : registeredReceivers) { if (registeredReceiver.context == context.getBaseContext()) { Iterator<String> actions = registeredReceiver.intentFilter.actionsIterator(); while (actions.hasNext()) { if (actions.next().equals(action)) { RuntimeException e = new IllegalStateException( "Unexpected BroadcastReceiver on " + context + " with action " + action + " " + registeredReceiver.broadcastReceiver + " that was originally registered here:"); e.setStackTrace(registeredReceiver.exception.getStackTrace()); throw e; } } } } } /** Returns the BroadcaseReceivers wrappers, matching intent's action and permissions. */ private List<Wrapper> getAppropriateWrappers(Intent intent, String receiverPermission) { broadcastIntents.add(intent); List<Wrapper> result = new ArrayList<>(); List<Wrapper> copy = new ArrayList<>(); copy.addAll(registeredReceivers); for (Wrapper wrapper : copy) { if (hasMatchingPermission(wrapper.broadcastPermission, receiverPermission) && wrapper.intentFilter.matchAction(intent.getAction())) { final int match = wrapper.intentFilter.matchData(intent.getType(), intent.getScheme(), intent.getData()); if (match != IntentFilter.NO_MATCH_DATA && match != IntentFilter.NO_MATCH_TYPE) { result.add(wrapper); } } } return result; } private void postIntent( Intent intent, Wrapper wrapper, final AtomicBoolean abort, Context context) { final Handler scheduler = (wrapper.scheduler != null) ? wrapper.scheduler : getMainHandler(context); final BroadcastReceiver receiver = wrapper.broadcastReceiver; final ShadowBroadcastReceiver shReceiver = Shadow.extract(receiver); final Intent broadcastIntent = intent; scheduler.post( new Runnable() { @Override public void run() { receiver.setPendingResult(ShadowBroadcastPendingResult.create(0, null, null, false)); shReceiver.onReceive(context, broadcastIntent, abort); } }); } private void postToWrappers(List<Wrapper> wrappers, Intent intent, Context context) { AtomicBoolean abort = new AtomicBoolean(false); // abort state is shared among all broadcast receivers for (Wrapper wrapper : wrappers) { postIntent(intent, wrapper, abort, context); } } private void postOrderedToWrappers( List<Wrapper> wrappers, final Intent intent, int initialCode, String data, Bundle extras, final Context context) { final AtomicBoolean abort = new AtomicBoolean(false); // abort state is shared among all broadcast receivers ListenableFuture<BroadcastResultHolder> future = immediateFuture(new BroadcastResultHolder(initialCode, data, extras)); for (final Wrapper wrapper : wrappers) { future = postIntent(wrapper, intent, future, abort, context); } final ListenableFuture<?> finalFuture = future; future.addListener( new Runnable() { @Override public void run() { getMainHandler(context) .post( new Runnable() { @Override public void run() { try { finalFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } }); } }, directExecutor()); } /** * Enforces that BroadcastReceivers invoked during an ordered broadcast run serially, passing * along their results. */ private ListenableFuture<BroadcastResultHolder> postIntent( final Wrapper wrapper, final Intent intent, ListenableFuture<BroadcastResultHolder> oldResult, final AtomicBoolean abort, final Context context) { final Handler scheduler = (wrapper.scheduler != null) ? wrapper.scheduler : getMainHandler(context); return Futures.transformAsync( oldResult, new AsyncFunction<BroadcastResultHolder, BroadcastResultHolder>() { @Override public ListenableFuture<BroadcastResultHolder> apply( BroadcastResultHolder broadcastResultHolder) throws Exception { final BroadcastReceiver.PendingResult result = ShadowBroadcastPendingResult.create( broadcastResultHolder.resultCode, broadcastResultHolder.resultData, broadcastResultHolder.resultExtras, true /*ordered */); wrapper.broadcastReceiver.setPendingResult(result); scheduler.post( () -> { ShadowBroadcastReceiver shadowBroadcastReceiver = Shadow.extract(wrapper.broadcastReceiver); shadowBroadcastReceiver.onReceive(context, intent, abort); }); return BroadcastResultHolder.transform(result); } }, directExecutor()); } /** * Broadcasts the {@code Intent} by iterating through the registered receivers, invoking their * filters including permissions, and calling {@code onReceive(Application, Intent)} as * appropriate. Does not enqueue the {@code Intent} for later inspection. * * @param context * @param intent the {@code Intent} to broadcast todo: enqueue the Intent for later inspection */ void sendBroadcastWithPermission(Intent intent, String receiverPermission, Context context) { List<Wrapper> wrappers = getAppropriateWrappers(intent, receiverPermission); postToWrappers(wrappers, intent, context); } void sendOrderedBroadcastWithPermission( Intent intent, String receiverPermission, Context context) { List<Wrapper> wrappers = getAppropriateWrappers(intent, receiverPermission); // sort by the decrease of priorities sortByPriority(wrappers); postOrderedToWrappers(wrappers, intent, 0, null, null, context); } private void sortByPriority(List<Wrapper> wrappers) { Collections.sort( wrappers, new Comparator<Wrapper>() { @Override public int compare(Wrapper o1, Wrapper o2) { return Integer.compare( o2.getIntentFilter().getPriority(), o1.getIntentFilter().getPriority()); } }); } List<Intent> getBroadcastIntents() { return broadcastIntents; } Intent getNextStartedActivity() { if (startedActivities.isEmpty()) { return null; } else { return startedActivities.remove(startedActivities.size() - 1); } } Intent peekNextStartedActivity() { if (startedActivities.isEmpty()) { return null; } else { return startedActivities.get(startedActivities.size() - 1); } } IntentForResult getNextStartedActivityForResult() { if (startedActivitiesForResults.isEmpty()) { return null; } else { return startedActivitiesForResults.remove(startedActivitiesForResults.size() - 1); } } IntentForResult peekNextStartedActivityForResult() { if (startedActivitiesForResults.isEmpty()) { return null; } else { return startedActivitiesForResults.get(startedActivitiesForResults.size() - 1); } } void checkActivities(boolean checkActivities) { this.checkActivities = checkActivities; } int getRequestCodeForIntent(Intent requestIntent) { Integer requestCode = intentRequestCodeMap.get(new Intent.FilterComparison(requestIntent)); if (requestCode == null) { throw new RuntimeException( "No intent matches " + requestIntent + " among " + intentRequestCodeMap.keySet()); } return requestCode; } protected ComponentName startService(Intent intent) { startedServices.add(new Intent.FilterComparison(intent)); if (intent.getComponent() != null) { return intent.getComponent(); } return new ComponentName("some.service.package", "SomeServiceName-FIXME"); } boolean stopService(Intent name) { stoppedServices.add(new Intent.FilterComparison(name)); return startedServices.contains(new Intent.FilterComparison(name)); } void setComponentNameAndServiceForBindService(ComponentName name, IBinder service) { defaultServiceConnectionData = new ServiceConnectionDataWrapper(name, service); } void setComponentNameAndServiceForBindServiceForIntent( Intent intent, ComponentName name, IBinder service) { serviceConnectionDataForIntent.put( new Intent.FilterComparison(intent), new ServiceConnectionDataWrapper(name, service)); } protected boolean bindService( final Intent intent, final ServiceConnection serviceConnection, int i) { boundServiceConnections.add(serviceConnection); unboundServiceConnections.remove(serviceConnection); if (unbindableActions.contains(intent.getAction())) { return false; } startedServices.add(new Intent.FilterComparison(intent)); ShadowLooper shadowLooper = Shadow.extract(Looper.getMainLooper()); shadowLooper.post( () -> { final ServiceConnectionDataWrapper serviceConnectionDataWrapper; final Intent.FilterComparison filterComparison = new Intent.FilterComparison(intent); if (serviceConnectionDataForIntent.containsKey(filterComparison)) { serviceConnectionDataWrapper = serviceConnectionDataForIntent.get(filterComparison); } else { serviceConnectionDataWrapper = defaultServiceConnectionData; } serviceConnectionDataForServiceConnection.put( serviceConnection, serviceConnectionDataWrapper); serviceConnection.onServiceConnected( serviceConnectionDataWrapper.componentNameForBindService, serviceConnectionDataWrapper.binderForBindService); }, 0); return true; } protected void unbindService(final ServiceConnection serviceConnection) { if (unbindServiceShouldThrowIllegalArgument) { throw new IllegalArgumentException(); } unboundServiceConnections.add(serviceConnection); boundServiceConnections.remove(serviceConnection); ShadowLooper shadowLooper = Shadow.extract(Looper.getMainLooper()); shadowLooper.post( () -> { final ServiceConnectionDataWrapper serviceConnectionDataWrapper; if (serviceConnectionDataForServiceConnection.containsKey(serviceConnection)) { serviceConnectionDataWrapper = serviceConnectionDataForServiceConnection.get(serviceConnection); } else { serviceConnectionDataWrapper = defaultServiceConnectionData; } serviceConnection.onServiceDisconnected( serviceConnectionDataWrapper.componentNameForBindService); }, 0); } protected List<ServiceConnection> getBoundServiceConnections() { return boundServiceConnections; } void setUnbindServiceShouldThrowIllegalArgument(boolean flag) { unbindServiceShouldThrowIllegalArgument = flag; } protected List<ServiceConnection> getUnboundServiceConnections() { return unboundServiceConnections; } void declareActionUnbindable(String action) { unbindableActions.add(action); } public List<String> getUnbindableActions() { return unbindableActions; } /** * Consumes the most recent {@code Intent} started by {@link * #startService(android.content.Intent)} and returns it. * * @return the most recently started {@code Intent} */ Intent getNextStartedService() { if (startedServices.isEmpty()) { return null; } else { return startedServices.remove(0).getIntent(); } } /** * Returns the most recent {@code Intent} started by {@link #startService(android.content.Intent)} * without consuming it. * * @return the most recently started {@code Intent} */ Intent peekNextStartedService() { if (startedServices.isEmpty()) { return null; } else { return startedServices.get(0).getIntent(); } } /** Clears all {@code Intent} started by {@link #startService(android.content.Intent)}. */ void clearStartedServices() { startedServices.clear(); } /** * Consumes the {@code Intent} requested to stop a service by {@link * #stopService(android.content.Intent)} from the bottom of the stack of stop requests. */ Intent getNextStoppedService() { if (stoppedServices.isEmpty()) { return null; } else { return stoppedServices.remove(0).getIntent(); } } void sendStickyBroadcast(Intent intent, Context context) { stickyIntents.put(intent.getAction(), intent); sendBroadcast(intent, context); } void sendBroadcast(Intent intent, Context context) { sendBroadcastWithPermission(intent, null, context); } Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, Context context) { return registerReceiver(receiver, filter, null, null, context); } Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context) { return registerReceiverWithContext(receiver, filter, broadcastPermission, scheduler, context); } Intent registerReceiverWithContext( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context) { if (receiver != null) { registeredReceivers.add( new Wrapper(receiver, filter, context, broadcastPermission, scheduler)); } return processStickyIntents(filter, receiver, context); } private Intent processStickyIntents( IntentFilter filter, BroadcastReceiver receiver, Context context) { Intent result = null; for (Intent stickyIntent : stickyIntents.values()) { if (filter.matchAction(stickyIntent.getAction())) { if (result == null) { result = stickyIntent; } if (receiver != null) { receiver.setPendingResult(ShadowBroadcastPendingResult.createSticky(stickyIntent)); receiver.onReceive(context, stickyIntent); receiver.setPendingResult(null); } else if (result != null) { break; } } } return result; } void unregisterReceiver(BroadcastReceiver broadcastReceiver) { boolean found = false; Iterator<Wrapper> iterator = registeredReceivers.iterator(); while (iterator.hasNext()) { Wrapper wrapper = iterator.next(); if (wrapper.broadcastReceiver == broadcastReceiver) { iterator.remove(); found = true; } } if (!found) { throw new IllegalArgumentException("Receiver not registered: " + broadcastReceiver); } } /** @deprecated use PackageManager.queryBroadcastReceivers instead */ @Deprecated boolean hasReceiverForIntent(Intent intent) { for (Wrapper wrapper : registeredReceivers) { if (wrapper.intentFilter.matchAction(intent.getAction())) { return true; } } return false; } /** @deprecated use PackageManager.queryBroadcastReceivers instead */ @Deprecated List<BroadcastReceiver> getReceiversForIntent(Intent intent) { ArrayList<BroadcastReceiver> broadcastReceivers = new ArrayList<>(); for (Wrapper wrapper : registeredReceivers) { if (wrapper.intentFilter.matchAction(intent.getAction())) { broadcastReceivers.add(wrapper.getBroadcastReceiver()); } } return broadcastReceivers; } /** @return list of {@link Wrapper}s for registered receivers */ List<Wrapper> getRegisteredReceivers() { return registeredReceivers; } int checkPermission(String permission, int pid, int uid) { return grantedPermissions.contains(permission) ? PERMISSION_GRANTED : PERMISSION_DENIED; } void grantPermissions(String... permissionNames) { Collections.addAll(grantedPermissions, permissionNames); } void denyPermissions(String... permissionNames) { for (String permissionName : permissionNames) { grantedPermissions.remove(permissionName); } } private boolean hasMatchingPermission(String permission1, String permission2) { return permission1 == null ? permission2 == null : permission1.equals(permission2); } private Handler getMainHandler(Context context) { if (mainHandler == null) { mainHandler = new Handler(context.getMainLooper()); } return mainHandler; } private static final class BroadcastResultHolder { private final int resultCode; private final String resultData; private final Bundle resultExtras; private BroadcastResultHolder(int resultCode, String resultData, Bundle resultExtras) { this.resultCode = resultCode; this.resultData = resultData; this.resultExtras = resultExtras; } private static ListenableFuture<BroadcastResultHolder> transform( BroadcastReceiver.PendingResult result) { ShadowBroadcastPendingResult shadowBroadcastPendingResult = Shadow.extract(result); return Futures.transform( shadowBroadcastPendingResult.getFuture(), pendingResult -> new BroadcastResultHolder( pendingResult.getResultCode(), pendingResult.getResultData(), pendingResult.getResultExtras(false)), directExecutor()); } } private static class ServiceConnectionDataWrapper { public final ComponentName componentNameForBindService; public final IBinder binderForBindService; private ServiceConnectionDataWrapper( ComponentName componentNameForBindService, IBinder binderForBindService) { this.componentNameForBindService = componentNameForBindService; this.binderForBindService = binderForBindService; } } public static Instrumentation getInstrumentation() { ActivityThread activityThread = (ActivityThread) RuntimeEnvironment.getActivityThread(); return activityThread.getInstrumentation(); } }
shadows/framework/src/main/java/org/robolectric/shadows/ShadowInstrumentation.java
package org.robolectric.shadows; import static android.content.pm.PackageManager.PERMISSION_DENIED; import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1; import static android.os.Build.VERSION_CODES.M; import static android.os.Build.VERSION_CODES.P; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import android.app.Activity; import android.app.ActivityThread; import android.app.Fragment; import android.app.Instrumentation; import android.app.Instrumentation.ActivityResult; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.Intent.FilterComparison; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.UserHandle; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.shadow.api.Shadow; import org.robolectric.shadows.ShadowActivity.IntentForResult; import org.robolectric.shadows.ShadowApplication.Wrapper; @Implements(value = Instrumentation.class, looseSignatures = true) public class ShadowInstrumentation { private List<Intent> startedActivities = new ArrayList<>(); private List<IntentForResult> startedActivitiesForResults = new ArrayList<>(); private Map<FilterComparison, Integer> intentRequestCodeMap = new HashMap<>(); private List<Intent.FilterComparison> startedServices = new ArrayList<>(); private List<Intent.FilterComparison> stoppedServices = new ArrayList<>(); private List<Intent> broadcastIntents = new ArrayList<>(); private List<ServiceConnection> boundServiceConnections = new ArrayList<>(); private List<ServiceConnection> unboundServiceConnections = new ArrayList<>(); private List<Wrapper> registeredReceivers = new ArrayList<>(); private Set<String> grantedPermissions = new HashSet<>(); private boolean unbindServiceShouldThrowIllegalArgument = false; private Map<Intent.FilterComparison, ServiceConnectionDataWrapper> serviceConnectionDataForIntent = new HashMap<>(); // default values for bindService private ServiceConnectionDataWrapper defaultServiceConnectionData = new ServiceConnectionDataWrapper(null, null); private List<String> unbindableActions = new ArrayList<>(); private Map<String, Intent> stickyIntents = new LinkedHashMap<>(); private Handler mainHandler; private Map<ServiceConnection, ServiceConnectionDataWrapper> serviceConnectionDataForServiceConnection = new HashMap<>(); private boolean checkActivities; @Implementation(minSdk = P) public Activity startActivitySync(Intent intent, Bundle options) { throw new UnsupportedOperationException("Implement me!!"); } @Implementation public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { verifyActivityInManifest(intent); return logStartedActivity(intent, requestCode, options); } @Implementation(maxSdk = LOLLIPOP_MR1) public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Fragment target, Intent intent, int requestCode, Bundle options) { verifyActivityInManifest(intent); return logStartedActivity(intent, requestCode, options); } private ActivityResult logStartedActivity(Intent intent, int requestCode, Bundle options) { startedActivities.add(intent); intentRequestCodeMap.put(new FilterComparison(intent), requestCode); startedActivitiesForResults.add(new IntentForResult(intent, requestCode, options)); return null; } private void verifyActivityInManifest(Intent intent) { if (checkActivities && RuntimeEnvironment.application.getPackageManager().resolveActivity(intent, -1) == null) { throw new ActivityNotFoundException(intent.getAction()); } } @Implementation public void execStartActivities( Context who, IBinder contextThread, IBinder token, Activity target, Intent[] intents, Bundle options) { for (Intent intent : intents) { execStartActivity(who, contextThread, token, target, intent, -1, options); } } @Implementation(minSdk = LOLLIPOP) public void execStartActivityFromAppTask( Context who, IBinder contextThread, Object appTask, Intent intent, Bundle options) { throw new UnsupportedOperationException("Implement me!!"); } @Implementation(minSdk = M) public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, String target, Intent intent, int requestCode, Bundle options) { verifyActivityInManifest(intent); return logStartedActivity(intent, requestCode, options); } @Implementation(minSdk = JELLY_BEAN_MR1) public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, String resultWho, Intent intent, int requestCode, Bundle options, UserHandle user) { throw new UnsupportedOperationException("Implement me!!"); } @Implementation(minSdk = M) public ActivityResult execStartActivityAsCaller( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options, boolean ignoreTargetSecurity, int userId) { throw new UnsupportedOperationException("Implement me!!"); } void sendOrderedBroadcast( Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras, Context context) { List<Wrapper> receivers = getAppropriateWrappers(intent, receiverPermission); sortByPriority(receivers); receivers.add(new Wrapper(resultReceiver, null, context, null, scheduler)); postOrderedToWrappers(receivers, intent, initialCode, initialData, initialExtras, context); } void assertNoBroadcastListenersOfActionRegistered(ContextWrapper context, String action) { for (Wrapper registeredReceiver : registeredReceivers) { if (registeredReceiver.context == context.getBaseContext()) { Iterator<String> actions = registeredReceiver.intentFilter.actionsIterator(); while (actions.hasNext()) { if (actions.next().equals(action)) { RuntimeException e = new IllegalStateException( "Unexpected BroadcastReceiver on " + context + " with action " + action + " " + registeredReceiver.broadcastReceiver + " that was originally registered here:"); e.setStackTrace(registeredReceiver.exception.getStackTrace()); throw e; } } } } } /** Returns the BroadcaseReceivers wrappers, matching intent's action and permissions. */ private List<Wrapper> getAppropriateWrappers(Intent intent, String receiverPermission) { broadcastIntents.add(intent); List<Wrapper> result = new ArrayList<>(); List<Wrapper> copy = new ArrayList<>(); copy.addAll(registeredReceivers); for (Wrapper wrapper : copy) { if (hasMatchingPermission(wrapper.broadcastPermission, receiverPermission) && wrapper.intentFilter.matchAction(intent.getAction())) { final int match = wrapper.intentFilter.matchData(intent.getType(), intent.getScheme(), intent.getData()); if (match != IntentFilter.NO_MATCH_DATA && match != IntentFilter.NO_MATCH_TYPE) { result.add(wrapper); } } } return result; } private void postIntent( Intent intent, Wrapper wrapper, final AtomicBoolean abort, Context context) { final Handler scheduler = (wrapper.scheduler != null) ? wrapper.scheduler : getMainHandler(context); final BroadcastReceiver receiver = wrapper.broadcastReceiver; final ShadowBroadcastReceiver shReceiver = Shadow.extract(receiver); final Intent broadcastIntent = intent; scheduler.post( new Runnable() { @Override public void run() { receiver.setPendingResult(ShadowBroadcastPendingResult.create(0, null, null, false)); shReceiver.onReceive(context, broadcastIntent, abort); } }); } private void postToWrappers(List<Wrapper> wrappers, Intent intent, Context context) { AtomicBoolean abort = new AtomicBoolean(false); // abort state is shared among all broadcast receivers for (Wrapper wrapper : wrappers) { postIntent(intent, wrapper, abort, context); } } private void postOrderedToWrappers( List<Wrapper> wrappers, final Intent intent, int initialCode, String data, Bundle extras, final Context context) { final AtomicBoolean abort = new AtomicBoolean(false); // abort state is shared among all broadcast receivers ListenableFuture<BroadcastResultHolder> future = immediateFuture(new BroadcastResultHolder(initialCode, data, extras)); for (final Wrapper wrapper : wrappers) { future = postIntent(wrapper, intent, future, abort, context); } final ListenableFuture<?> finalFuture = future; future.addListener( new Runnable() { @Override public void run() { getMainHandler(context) .post( new Runnable() { @Override public void run() { try { finalFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } }); } }, directExecutor()); } /** * Enforces that BroadcastReceivers invoked during an ordered broadcast run serially, passing * along their results. */ private ListenableFuture<BroadcastResultHolder> postIntent( final Wrapper wrapper, final Intent intent, ListenableFuture<BroadcastResultHolder> oldResult, final AtomicBoolean abort, final Context context) { final Handler scheduler = (wrapper.scheduler != null) ? wrapper.scheduler : getMainHandler(context); return Futures.transformAsync( oldResult, new AsyncFunction<BroadcastResultHolder, BroadcastResultHolder>() { @Override public ListenableFuture<BroadcastResultHolder> apply( BroadcastResultHolder broadcastResultHolder) throws Exception { final BroadcastReceiver.PendingResult result = ShadowBroadcastPendingResult.create( broadcastResultHolder.resultCode, broadcastResultHolder.resultData, broadcastResultHolder.resultExtras, true /*ordered */); wrapper.broadcastReceiver.setPendingResult(result); scheduler.post( () -> { ShadowBroadcastReceiver shadowBroadcastReceiver = Shadow.extract(wrapper.broadcastReceiver); shadowBroadcastReceiver.onReceive(context, intent, abort); }); return BroadcastResultHolder.transform(result); } }, directExecutor()); } /** * Broadcasts the {@code Intent} by iterating through the registered receivers, invoking their * filters including permissions, and calling {@code onReceive(Application, Intent)} as * appropriate. Does not enqueue the {@code Intent} for later inspection. * * @param context * @param intent the {@code Intent} to broadcast todo: enqueue the Intent for later inspection */ void sendBroadcastWithPermission(Intent intent, String receiverPermission, Context context) { List<Wrapper> wrappers = getAppropriateWrappers(intent, receiverPermission); postToWrappers(wrappers, intent, context); } void sendOrderedBroadcastWithPermission( Intent intent, String receiverPermission, Context context) { List<Wrapper> wrappers = getAppropriateWrappers(intent, receiverPermission); // sort by the decrease of priorities sortByPriority(wrappers); postOrderedToWrappers(wrappers, intent, 0, null, null, context); } private void sortByPriority(List<Wrapper> wrappers) { Collections.sort( wrappers, new Comparator<Wrapper>() { @Override public int compare(Wrapper o1, Wrapper o2) { return Integer.compare( o2.getIntentFilter().getPriority(), o1.getIntentFilter().getPriority()); } }); } List<Intent> getBroadcastIntents() { return broadcastIntents; } Intent getNextStartedActivity() { if (startedActivities.isEmpty()) { return null; } else { return startedActivities.remove(startedActivities.size() - 1); } } Intent peekNextStartedActivity() { if (startedActivities.isEmpty()) { return null; } else { return startedActivities.get(startedActivities.size() - 1); } } IntentForResult getNextStartedActivityForResult() { if (startedActivitiesForResults.isEmpty()) { return null; } else { return startedActivitiesForResults.remove(startedActivitiesForResults.size() - 1); } } IntentForResult peekNextStartedActivityForResult() { if (startedActivitiesForResults.isEmpty()) { return null; } else { return startedActivitiesForResults.get(startedActivitiesForResults.size() - 1); } } void checkActivities(boolean checkActivities) { this.checkActivities = checkActivities; } int getRequestCodeForIntent(Intent requestIntent) { Integer requestCode = intentRequestCodeMap.get(new Intent.FilterComparison(requestIntent)); if (requestCode == null) { throw new RuntimeException( "No intent matches " + requestIntent + " among " + intentRequestCodeMap.keySet()); } return requestCode; } protected ComponentName startService(Intent intent) { startedServices.add(new Intent.FilterComparison(intent)); if (intent.getComponent() != null) { return intent.getComponent(); } return new ComponentName("some.service.package", "SomeServiceName-FIXME"); } boolean stopService(Intent name) { stoppedServices.add(new Intent.FilterComparison(name)); return startedServices.contains(new Intent.FilterComparison(name)); } void setComponentNameAndServiceForBindService(ComponentName name, IBinder service) { defaultServiceConnectionData = new ServiceConnectionDataWrapper(name, service); } void setComponentNameAndServiceForBindServiceForIntent( Intent intent, ComponentName name, IBinder service) { serviceConnectionDataForIntent.put( new Intent.FilterComparison(intent), new ServiceConnectionDataWrapper(name, service)); } boolean bindService(final Intent intent, final ServiceConnection serviceConnection, int i) { boundServiceConnections.add(serviceConnection); unboundServiceConnections.remove(serviceConnection); if (unbindableActions.contains(intent.getAction())) { return false; } startedServices.add(new Intent.FilterComparison(intent)); ShadowLooper shadowLooper = Shadow.extract(Looper.getMainLooper()); shadowLooper.post( () -> { final ServiceConnectionDataWrapper serviceConnectionDataWrapper; final Intent.FilterComparison filterComparison = new Intent.FilterComparison(intent); if (serviceConnectionDataForIntent.containsKey(filterComparison)) { serviceConnectionDataWrapper = serviceConnectionDataForIntent.get(filterComparison); } else { serviceConnectionDataWrapper = defaultServiceConnectionData; } serviceConnectionDataForServiceConnection.put( serviceConnection, serviceConnectionDataWrapper); serviceConnection.onServiceConnected( serviceConnectionDataWrapper.componentNameForBindService, serviceConnectionDataWrapper.binderForBindService); }, 0); return true; } void unbindService(final ServiceConnection serviceConnection) { if (unbindServiceShouldThrowIllegalArgument) { throw new IllegalArgumentException(); } unboundServiceConnections.add(serviceConnection); boundServiceConnections.remove(serviceConnection); ShadowLooper shadowLooper = Shadow.extract(Looper.getMainLooper()); shadowLooper.post( () -> { final ServiceConnectionDataWrapper serviceConnectionDataWrapper; if (serviceConnectionDataForServiceConnection.containsKey(serviceConnection)) { serviceConnectionDataWrapper = serviceConnectionDataForServiceConnection.get(serviceConnection); } else { serviceConnectionDataWrapper = defaultServiceConnectionData; } serviceConnection.onServiceDisconnected( serviceConnectionDataWrapper.componentNameForBindService); }, 0); } List<ServiceConnection> getBoundServiceConnections() { return boundServiceConnections; } void setUnbindServiceShouldThrowIllegalArgument(boolean flag) { unbindServiceShouldThrowIllegalArgument = flag; } List<ServiceConnection> getUnboundServiceConnections() { return unboundServiceConnections; } void declareActionUnbindable(String action) { unbindableActions.add(action); } public List<String> getUnbindableActions() { return unbindableActions; } /** * Consumes the most recent {@code Intent} started by {@link * #startService(android.content.Intent)} and returns it. * * @return the most recently started {@code Intent} */ Intent getNextStartedService() { if (startedServices.isEmpty()) { return null; } else { return startedServices.remove(0).getIntent(); } } /** * Returns the most recent {@code Intent} started by {@link #startService(android.content.Intent)} * without consuming it. * * @return the most recently started {@code Intent} */ Intent peekNextStartedService() { if (startedServices.isEmpty()) { return null; } else { return startedServices.get(0).getIntent(); } } /** Clears all {@code Intent} started by {@link #startService(android.content.Intent)}. */ void clearStartedServices() { startedServices.clear(); } /** * Consumes the {@code Intent} requested to stop a service by {@link * #stopService(android.content.Intent)} from the bottom of the stack of stop requests. */ Intent getNextStoppedService() { if (stoppedServices.isEmpty()) { return null; } else { return stoppedServices.remove(0).getIntent(); } } void sendStickyBroadcast(Intent intent, Context context) { stickyIntents.put(intent.getAction(), intent); sendBroadcast(intent, context); } void sendBroadcast(Intent intent, Context context) { sendBroadcastWithPermission(intent, null, context); } Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, Context context) { return registerReceiver(receiver, filter, null, null, context); } Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context) { return registerReceiverWithContext(receiver, filter, broadcastPermission, scheduler, context); } Intent registerReceiverWithContext( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context) { if (receiver != null) { registeredReceivers.add( new Wrapper(receiver, filter, context, broadcastPermission, scheduler)); } return processStickyIntents(filter, receiver, context); } private Intent processStickyIntents( IntentFilter filter, BroadcastReceiver receiver, Context context) { Intent result = null; for (Intent stickyIntent : stickyIntents.values()) { if (filter.matchAction(stickyIntent.getAction())) { if (result == null) { result = stickyIntent; } if (receiver != null) { receiver.setPendingResult(ShadowBroadcastPendingResult.createSticky(stickyIntent)); receiver.onReceive(context, stickyIntent); receiver.setPendingResult(null); } else if (result != null) { break; } } } return result; } void unregisterReceiver(BroadcastReceiver broadcastReceiver) { boolean found = false; Iterator<Wrapper> iterator = registeredReceivers.iterator(); while (iterator.hasNext()) { Wrapper wrapper = iterator.next(); if (wrapper.broadcastReceiver == broadcastReceiver) { iterator.remove(); found = true; } } if (!found) { throw new IllegalArgumentException("Receiver not registered: " + broadcastReceiver); } } /** @deprecated use PackageManager.queryBroadcastReceivers instead */ @Deprecated boolean hasReceiverForIntent(Intent intent) { for (Wrapper wrapper : registeredReceivers) { if (wrapper.intentFilter.matchAction(intent.getAction())) { return true; } } return false; } /** @deprecated use PackageManager.queryBroadcastReceivers instead */ @Deprecated List<BroadcastReceiver> getReceiversForIntent(Intent intent) { ArrayList<BroadcastReceiver> broadcastReceivers = new ArrayList<>(); for (Wrapper wrapper : registeredReceivers) { if (wrapper.intentFilter.matchAction(intent.getAction())) { broadcastReceivers.add(wrapper.getBroadcastReceiver()); } } return broadcastReceivers; } /** @return list of {@link Wrapper}s for registered receivers */ List<Wrapper> getRegisteredReceivers() { return registeredReceivers; } int checkPermission(String permission, int pid, int uid) { return grantedPermissions.contains(permission) ? PERMISSION_GRANTED : PERMISSION_DENIED; } void grantPermissions(String... permissionNames) { Collections.addAll(grantedPermissions, permissionNames); } void denyPermissions(String... permissionNames) { for (String permissionName : permissionNames) { grantedPermissions.remove(permissionName); } } private boolean hasMatchingPermission(String permission1, String permission2) { return permission1 == null ? permission2 == null : permission1.equals(permission2); } private Handler getMainHandler(Context context) { if (mainHandler == null) { mainHandler = new Handler(context.getMainLooper()); } return mainHandler; } private static final class BroadcastResultHolder { private final int resultCode; private final String resultData; private final Bundle resultExtras; private BroadcastResultHolder(int resultCode, String resultData, Bundle resultExtras) { this.resultCode = resultCode; this.resultData = resultData; this.resultExtras = resultExtras; } private static ListenableFuture<BroadcastResultHolder> transform( BroadcastReceiver.PendingResult result) { ShadowBroadcastPendingResult shadowBroadcastPendingResult = Shadow.extract(result); return Futures.transform( shadowBroadcastPendingResult.getFuture(), pendingResult -> new BroadcastResultHolder( pendingResult.getResultCode(), pendingResult.getResultData(), pendingResult.getResultExtras(false)), directExecutor()); } } private static class ServiceConnectionDataWrapper { public final ComponentName componentNameForBindService; public final IBinder binderForBindService; private ServiceConnectionDataWrapper( ComponentName componentNameForBindService, IBinder binderForBindService) { this.componentNameForBindService = componentNameForBindService; this.binderForBindService = binderForBindService; } } public static Instrumentation getInstrumentation() { ActivityThread activityThread = (ActivityThread) RuntimeEnvironment.getActivityThread(); return activityThread.getInstrumentation(); } }
Mark {un,}bindService in ShadowInstrumentation protected This provides a way for tests to override the binding logic with custom behaviors. PiperOrigin-RevId: 203863917
shadows/framework/src/main/java/org/robolectric/shadows/ShadowInstrumentation.java
Mark {un,}bindService in ShadowInstrumentation protected
Java
mit
2cb9c9919ebcd4e005aaefd3b800ac8f2da811c8
0
ryan-williams/Hadoop-BAM,cmnbroad/Hadoop-BAM,tomwhite/Hadoop-BAM,fnothaft/Hadoop-BAM,fnothaft/Hadoop-BAM,tkrishp/Hadoop-BAM,ryan-williams/Hadoop-BAM,fnothaft/Hadoop-BAM,cmnbroad/Hadoop-BAM,HadoopGenomics/Hadoop-BAM,HadoopGenomics/Hadoop-BAM,HadoopGenomics/Hadoop-BAM
// File created: 2010-08-09 13:06:32 package fi.tkk.ics.hadoop.bam; import java.io.DataOutput; import java.io.DataInput; import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.InputSplit; public class FileVirtualSplit extends InputSplit implements Writable { private Path file; private long vStart; private long vEnd; private final String[] locations; public FileVirtualSplit() { locations = null; } public FileVirtualSplit(Path f, long vs, long ve, String[] locs) { file = f; vStart = vs; vEnd = ve; locations = locs; } @Override public String[] getLocations() { return locations; } @Override public long getLength() { // Approximate: we don't know here how many blocks are in between two // file offsets, so just use the differences between the file offsets // (unless it's zero, in which case the beginning and end are in the same // block and we can actually give an exact answer). final long vsHi = vStart & ~0xffff; final long veHi = vEnd & ~0xffff; final long hiDiff = veHi - vsHi; return hiDiff == 0 ? ((vEnd & 0xffff) - (vStart & 0xffff)) : hiDiff; } public Path getPath() { return file; } public long getStartVirtualOffset() { return vStart; } public long getEndVirtualOffset() { return vEnd; } @Override public void write(DataOutput out) throws IOException { Text.writeString(out, file.toString()); out.writeLong(vStart); out.writeLong(vEnd); } @Override public void readFields(DataInput in) throws IOException { file = new Path(Text.readString(in)); vStart = in.readLong(); vEnd = in.readLong(); } }
src/fi/tkk/ics/hadoop/bam/FileVirtualSplit.java
// File created: 2010-08-09 13:06:32 package fi.tkk.ics.hadoop.bam; import java.io.DataOutput; import java.io.DataInput; import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.InputSplit; public class FileVirtualSplit extends InputSplit implements Writable { private Path file; private long vStart; private long vEnd; private final String[] locations; public FileVirtualSplit() { locations = null; } public FileVirtualSplit(Path f, long vs, long ve, String[] locs) { file = f; vStart = vs; vEnd = ve; locations = locs; } @Override public String[] getLocations() { return locations; } @Override public long getLength() { // Approximate: we don't know here how many blocks are in between two // file offsets, so just use the differences between the file offsets // (unless it's zero, in which case the beginning aend are in the same // block and we can actually give an exact answer). final long vsHi = vStart & ~0xffff; final long veHi = vEnd & ~0xffff; final long hiDiff = veHi - vsHi; return hiDiff == 0 ? ((vEnd & 0xffff) - (vStart & 0xffff)) : hiDiff; } public Path getPath() { return file; } public long getStartVirtualOffset() { return vStart; } public long getEndVirtualOffset() { return vEnd; } @Override public void write(DataOutput out) throws IOException { Text.writeString(out, file.toString()); out.writeLong(vStart); out.writeLong(vEnd); } @Override public void readFields(DataInput in) throws IOException { file = new Path(Text.readString(in)); vStart = in.readLong(); vEnd = in.readLong(); } }
Fix typo in comment.
src/fi/tkk/ics/hadoop/bam/FileVirtualSplit.java
Fix typo in comment.
Java
mit
aa85b13dab2aa35fafec1346feaab2cb4994b26c
0
CamioCam/Opentok-Java-SDK,Kwasniewski/Opentok-Java-SDK,drahot/Opentok-Java-SDK,opentok/Opentok-Java-SDK,drahot/Opentok-Java-SDK,opentok/Opentok-Java-SDK,mukesh-kum/Opentok-Java-SDK,CamioCam/Opentok-Java-SDK,Kwasniewski/Opentok-Java-SDK,mukesh-kum/Opentok-Java-SDK
/*! * OpenTok Java Library * http://www.tokbox.com/ * * Copyright 2010, TokBox, Inc. * */ package com.opentok.api; public class API_Config { public static final int API_KEY = 4317; public static final String API_SECRET = "91e6f7609074be23b40747a4651ba5a7"; public static final String API_URL = "https://api.opentok.com"; }
src/main/java/com/opentok/api/API_Config.java
/*! * OpenTok Java Library * http://www.tokbox.com/ * * Copyright 2010, TokBox, Inc. * */ package com.opentok.api; public class API_Config { public static final int API_KEY = 4317; public static final String API_SECRET = "91e6f7609074be23b40747a4651ba5a7"; public static final String API_URL = "http://staging.tokbox.com/hl"; // Uncomment this line when you launch your app // public static final String API_URL = "https://api.opentok.com/hl"; }
Remove reference to staging from SDK
src/main/java/com/opentok/api/API_Config.java
Remove reference to staging from SDK
Java
epl-1.0
b88c482a4d89859634b57a0958cc67e1e98a640a
0
tassadarius/crypto,jcryptool/crypto,tassadarius/crypto,jcryptool/crypto
//-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2017 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.analysis.friedman.ui; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.jcryptool.analysis.graphtools.Bar; import org.jcryptool.analysis.graphtools.Graph; import org.jcryptool.analysis.graphtools.MColor; import org.jcryptool.analysis.graphtools.derivates.OverlayBar; import org.jcryptool.analysis.graphtools.derivates.OverlayLabelBar; /** * @author SLeischnig * This custom Graph is not restricted to display all bars only at once, but can zoom in and out, and shift the graph. */ public class FriedmanGraph extends Graph { int overlayTranspHighest, overlayTranspLowest; MColor overlayBarColor; double overlayBarWidth = 1.0; double maxValue = 0; private int currentShift = 0; private int savedShift = 0; private double lowestValue = 999999.0; private int barCount = 0; private double zoomFactor = 1.628; private Rectangle barDrawingRect; private Rectangle descDrawingRect; /** * Change the standard settings from the super class */ private void iniSettings() { overlayTranspHighest = 230; overlayTranspLowest = 0; distTop = 30; distBottom = 16; distLeft = 34; distRight = 0; marginTop = 0; marginBottom = 0; marginLeft = 4; marginRight = 4; calcAreas(); descTopFontColor = new MColor("0095C9", 255); //$NON-NLS-1$ descBottomFontColor = new MColor("FFFFFF", 255); //$NON-NLS-1$ descTopBGColor = new MColor("306A90", 255); //$NON-NLS-1$ descBottomBGColor = new MColor("B60000", 255); //$NON-NLS-1$ descLeftBGColor = new MColor("B60000", 255); //$NON-NLS-1$ descRightBGColor = new MColor("B60000", 255); //$NON-NLS-1$ barAreaBGColor = new MColor("306A90", 255); //$NON-NLS-1$ overlayBarColor = new MColor("006AB0", 255); //$NON-NLS-1$ } public FriedmanGraph(final GC gc, final int areaWidth, final int areaHeight) { super(gc, areaWidth, areaHeight); iniSettings(); } /** * Calculate which space a bar label can fill * * @param textSpace * the whole bar description area * @param thisIndex * the bar's index * @return the actual space reserved for the label */ private Rectangle calculateTextContainer(final Rectangle textSpace, final int thisIndex) { int myIndex = (thisIndex - currentShift); double rectWidth = (double) textSpace.width / (double) (getBarCount()); double dRX = textSpace.x + rectWidth * myIndex; double dRW = textSpace.x + rectWidth * (myIndex + 1) - dRX; int RX = (int) Math.round(dRX); int RW = (int) Math.round(dRW); int RY = textSpace.y; int RH = textSpace.height; return new Rectangle(RX, RY, RW, RH); } /** * calculates the whole space a bar can fill, integrating the offset value field * * @param barSpace * the space that is reserved for bars * @param thisIndex * the x-axis value of the bar you want to calculate * @return */ protected final Rectangle calculateBarContainer(final Rectangle barSpace, final int thisIndex) { int myIndex = (thisIndex - currentShift); double rectWidth = (double) barSpace.width / (double) (getBarCount()); double dRX = barSpace.x + rectWidth * myIndex; double dRW = barSpace.x + rectWidth * (myIndex + 1) - dRX; int RX = (int) Math.round(dRX); int RW = (int) Math.round(dRW); int RY = barSpace.y; int RH = barSpace.height; return new Rectangle(RX, RY, RW, RH); } @Override protected final void paintBarArea(final Rectangle thisArea, final MColor thisBGColor) { //The bar drawing rectangle without margins barDrawingRect = new Rectangle(barAreaRect.x + marginLeft + distLeft, barAreaRect.y + marginTop, barAreaRect.width - marginLeft - marginRight + distLeft, barAreaRect.height - marginTop - marginBottom); //actual bar box Rectangle barBox; //calculate the biggest bar Index biggestBarIndex = calcBiggestBarIndex(); //Draw the background thisBGColor.setColor(gc); thisBGColor.setBGColor(gc); gc.fillRectangle(thisArea); if (bars.size() > 0) { for (int i = currentShift; i < currentShift + barCount; i++) { //Only shift when the bar is no overlay bar. barBox = calculateBarContainer(barDrawingRect, bars.get(i).getIndex()); //barBox = calculateBarContainer(barDrawingRect, ((Bar)bars.get(i)).getIndex(), biggestBarIndex); bars.get(i).setBox(barBox); bars.get(i).setGC(gc); bars.get(i).drawBar(); } } } @Override protected void paintDescLeftArea(Rectangle thisArea, MColor thisBGColor) { thisArea.width = distLeft; thisArea.y = 0; thisArea.height += distTop; barAreaBGColor.setColor(gc); gc.setLineWidth(2); gc.fillRectangle(thisArea); drawYAxis(thisBGColor); } @Override protected final void paintDescTopArea(final Rectangle thisArea, final MColor thisBGColor, final MColor thisFontColor) { //thisArea.height = 150; //thisArea.width = 0; super.paintDescTopArea(thisArea, thisBGColor, thisFontColor); //Old function body // thisBGColor.setColor(gc); // thisBGColor.setBGColor(gc); // gc.fillRectangle(thisArea); // thisFontColor.setColor(gc); } @Override protected final void paintDescBottomArea(final Rectangle thisArea, final MColor thisBGColor, final MColor thisFontColor) { // The bar drawing rectangle without margins descDrawingRect = new Rectangle(barAreaRect.x + marginLeft + distLeft, descBottomRect.y, barAreaRect.width - marginLeft - marginRight + distLeft, descBottomRect.height); // actual bar box Rectangle textBox; thisBGColor.setColor(gc); thisBGColor.setBGColor(gc); gc.fillRectangle(thisArea); int numberCounter = calculateNumberingSpaces(thisArea.width); thisFontColor.setColor(gc); for (int i = currentShift, index; i < currentShift + barCount; i++) { index = bars.get(i).getIndex(); if (numberCounter == 1 || (i >= 2 && (index + 1) % numberCounter == 0)) { textBox = calculateTextContainer(descDrawingRect, index); bars.get(i).drawLowerLabel(textBox, gc); } } } @Override protected final Bar setBarStandardSettings(final Bar rawBar) { //set OVERLAY BAR Standards - they override standard bar settings (because they're specialised bars) if (rawBar instanceof OverlayBar || rawBar instanceof OverlayLabelBar) { if ((rawBar).getWidth() == -1.0) { (rawBar).setWidth(overlayBarWidth); } if ((rawBar).getColorMainBar() == null) { (rawBar).setColorMainBar(overlayBarColor); } } rawBar.setGC(gc); if (rawBar.getColorMainBar() == null) { rawBar.setColorMainBar(barColor); } if (rawBar.getWidth() == -1) { rawBar.setWidth(barWidth); } //Set Transparency if (rawBar instanceof OverlayBar) { if (((OverlayBar) rawBar).getTransparencyHighest() == -1) { ((OverlayBar) rawBar).setTransparencyHighest(overlayTranspHighest); } if (((OverlayBar) rawBar).getTransparencyLowest() == -1) { ((OverlayBar) rawBar).setTransparencyLowest(overlayTranspLowest); } } if (rawBar instanceof OverlayLabelBar) { if (((OverlayLabelBar) rawBar).getTransparencyHighest() == -1) { ((OverlayLabelBar) rawBar).setTransparencyHighest(overlayTranspHighest); } if (((OverlayLabelBar) rawBar).getTransparencyLowest() == -1) { ((OverlayLabelBar) rawBar).setTransparencyLowest(overlayTranspLowest); } } return rawBar; } @Override public final void addBar(Bar myBar) { // before which bar should this bar be inserted? -1, if it is the lat index. myBar = setBarStandardSettings(myBar); int beforeWhich = -1; for (int i = 0; i < bars.size(); i++) { if (compareBarOrder(myBar, bars.get(i)) && beforeWhich == -1) { beforeWhich = i; } } bars.setSize(bars.size() + 1); if (beforeWhich > -1) { for (int i = bars.size() - 1; i > beforeWhich; i--) { bars.set(i, bars.get(i - 1)); } bars.set(beforeWhich, myBar); } else { bars.set(bars.size() - 1, myBar); } if (myBar.getHeight() < lowestValue) { lowestValue = myBar.getHeight(); } } /** * optimizes the displaying of the bars by relativating their displayed heights: The function seeks the bar with the lowest * value, and cuts every bar by a percentage of this value. * * @param cutPercentage * the cutting percentage. Range: 0..1. 1 would mean, you cut the bars such, the lowest bar would not be displayed. */ public final void optimizeBarHeights(final double cutPercentage) { double subtractHeight = cutPercentage * lowestValue; for (int i = 0; i < bars.size(); i++) { bars.get(i).setHeight(bars.get(i).getHeight() - subtractHeight); } for (int i = 0; i < bars.size(); i++) { bars.get(i).setHeight(bars.get(i).getHeight() / (1 - subtractHeight)); } } /** * @return the max. horizontal space available for a bar in pixel. */ protected final double calculateBarHorizSpace() { return (double) (areaWidth - descLeftRect.width - descRightRect.width) / (double) (barCount); } /** * if the Frequency Graph is dragged, this method determines whether a shifting of bars will happen, and if, of which offset. * <br /> * Current Policy is, to not shift the Graph by the exact pixel value; the bars will rather snap to the raster positions * * @param myPixelsDifference * is the difference in horizontal pixels in the dragging procedure. * @param isMouseButtonHold * if the mouseButton is held pressed. * @return if a shifting occured (for redraw) */ public final boolean setDraggedPixels(final int myPixelsDifference, final boolean isMouseButtonHold) { if (calcBiggestBarIndex() > 0) { int myShift = (-1) * (int) Math.round(myPixelsDifference / calculateBarHorizSpace()); boolean changed = savedShift + myShift != getCurrentShift(); setCurrentShift(Math.max(savedShift + myShift, 0)); //setCurrentShift(modulo(getCurrentShift(), calcBiggestBarIndex())); if (!isMouseButtonHold) { savedShift = getCurrentShift(); } if (changed) { return true; } //Wenn sich was verändert hat, zeichnen! return false; } else { setCurrentShift(0); savedShift = 0; return true; } } /** * reset the shift of the graph * * @param myBarCount * sets the amount of bars to be displayed */ public final void resetDrag(final int myBarCount) { setCurrentShift(0); setBarCount(myBarCount); savedShift = 0; } /** * @param currentShift * sets the shift */ public final void setCurrentShift(final int currentShift) { if (bars.size() > 0) { this.currentShift = Math.min(currentShift, bars.size() - barCount - 1); this.currentShift = Math.max(this.currentShift, 0); } } /** * zoom in by the zoomFactor value * * @return whether the zoom has affected something or not. */ public final boolean zoomin() { int oldShift = currentShift; boolean changed = false; if (bars.size() > 0) { double newBarCount = barCount / zoomFactor; int newCount = (int) Math.round(newBarCount); if (newCount <= 1) barCount = 1; else if (newCount >= barCount) { newCount = barCount - 1; } if (barCount != newCount || currentShift != oldShift) { changed = true; } if (barCount != newCount) { barCount = newCount; } } if (changed) { return true; } else { return false; } } /** * zoom out by the zoomFactor value * * @return whether the zoom has affected something or not. */ public final boolean zoomout() { int oldShift = currentShift; boolean changed = false; if (bars.size() > 0) { double newBarCount = barCount * zoomFactor; int newCount = (int) Math.round(newBarCount); if (newCount > bars.size()) return false; if (newCount <= barCount) { newCount = barCount + 1; } if (currentShift + newCount > bars.size()) { currentShift = bars.size() - newCount; currentShift = Math.max(0, currentShift); newCount = bars.size() - currentShift; } if (barCount != newCount || currentShift != oldShift) { changed = true; } if (barCount != newCount) { barCount = newCount; } } if (changed) { return true; } else { return false; } } public final int getCurrentShift() { return currentShift; } public final void setBarCount(final int barCount) { if (bars.size() > 0) { this.barCount = Math.min(bars.size() - currentShift, barCount); } } public final int getBarCount() { return barCount; } public final void setZoomFactor(final double zoomFactor) { this.zoomFactor = zoomFactor; } public final double getZoomFactor() { return zoomFactor; } public final void setMaxHeight(double maxValue) { this.maxValue = maxValue; } private void drawYAxis(MColor thisBGColor) { MColor thisColor = new MColor("FFFFFF"); thisBGColor.setBGColor(gc); double ySpacingUnround; int ySpacing; int virtualScale = (int) Math.round(barDrawingRect.height / (maxValue * 10)); ySpacingUnround = virtualScale / 10D; ySpacing = (int) Math.floor(ySpacingUnround); org.eclipse.swt.graphics.Point textSize = gc.stringExtent("0.05"); int textHeight = textSize.y; if (bars.size() > 0) { if (ySpacing > textHeight + 5) { for (int i = 0; ySpacing * i + ySpacing < barDrawingRect.height; ++i) { gc.drawLine(3, barDrawingRect.y + barDrawingRect.height - (ySpacing * i) - 1, 3 + distLeft, barDrawingRect.y + barDrawingRect.height - (ySpacing * i) - 1); } gc.drawLine(3, distTop, distLeft, distTop); thisColor.setColor(gc); gc.drawString(String.format("%.3f", maxValue), 3, distTop - textHeight - 2 - 2); double scale = 0.0; String scaleText; for (int i = 0; /*i <= 9 &&*/ ySpacing * i + ySpacing < barDrawingRect.height; ++i, scale += 0.01) { scaleText = String.format("%.2f", scale); gc.drawText(scaleText, 3, barDrawingRect.y + barDrawingRect.height - (ySpacing * i) - textHeight - 5); } return; } else { ySpacingUnround = virtualScale / 4D; ySpacing = (int) Math.floor(ySpacingUnround); for (int i = 0; i <= 3; ++i) { gc.drawLine(3, barDrawingRect.y + barDrawingRect.height - (ySpacing * i) - 1, 3 + distLeft, barDrawingRect.y + barDrawingRect.height - (ySpacing * i) - 1); } } if (ySpacing > textHeight + 5) { gc.drawLine(3, distTop, distLeft, distTop); thisColor.setColor(gc); gc.drawString(String.format("%.3f", maxValue), 3, distTop - textHeight - 2 - 2); thisColor.setColor(gc); double scale = 0.0; String scaleText; for (int i = 0; i <= 3 && (ySpacing * i) + (textHeight + 10) < barDrawingRect.height; ++i, scale += 0.025) { scaleText = String.format("%.3f", scale); gc.drawText(scaleText, 3, barDrawingRect.y + barDrawingRect.height - (ySpacing * i) - textHeight - 5); } } } } private int calculateNumberingSpaces(int availableSpace) { // Following constructs count the number of digits which should be printed to avoid overlapping int multiplier = 1, digitCounter = 1, decimalPower = 10, digitsPerNumber = 1; // this simple loops determines how many digits the current leftmost number in the graph // has and sets digitsPerNumber and (next bigger) decimalPower for (int i = 10; i < currentShift; i *= 10, ++digitsPerNumber, decimalPower *= 10) ; boolean fitting = false; while (!fitting) { // This inner loop counts the number indexes the graph would show depending on the multiplier // e.g. an multiplier of 1 displays it for every bar, 5 would display for every 5th bar. for (int i = digitsPerNumber; i < barCount; i += multiplier) { if (i % decimalPower == 0) { digitsPerNumber++; decimalPower *= 10; } digitCounter += digitsPerNumber; } //if it doesn't fit the multiplier is increased to 5, 50 or 500 and the loop run again if (digitCounter * 10 > availableSpace) { multiplier = multiplier == 1 ? 5 : multiplier * 10; digitCounter = multiplier; } else fitting = true; } return multiplier; } }
org.jcryptool.analysis.friedman/src/org/jcryptool/analysis/friedman/ui/FriedmanGraph.java
//-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2017 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.analysis.friedman.ui; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.jcryptool.analysis.graphtools.Bar; import org.jcryptool.analysis.graphtools.Graph; import org.jcryptool.analysis.graphtools.MColor; import org.jcryptool.analysis.graphtools.derivates.OverlayBar; import org.jcryptool.analysis.graphtools.derivates.OverlayLabelBar; /** * @author SLeischnig * This custom Graph is not restricted to display all bars only at once, but can zoom in and out, and shift the graph. */ public class FriedmanGraph extends Graph { int overlayTranspHighest, overlayTranspLowest; MColor overlayBarColor; double overlayBarWidth = 1.0; private int currentShift = 0; private int savedShift = 0; private double lowestValue = 999999.0; private int barCount = 0; private double zoomFactor = 1.628; /** * Change the standard settings from the super class */ private void iniSettings() { overlayTranspHighest = 230; overlayTranspLowest = 0; distTop = 3; distBottom = 16; distLeft = 0; distRight = 0; marginTop = 0; marginBottom = 0; marginLeft = 4; marginRight = 4; calcAreas(); descTopFontColor = new MColor("0095C9", 255); //$NON-NLS-1$ descBottomFontColor = new MColor("FFFFFF", 255); //$NON-NLS-1$ descTopBGColor = new MColor("306A90", 255); //$NON-NLS-1$ descBottomBGColor = new MColor("B60000", 255); //$NON-NLS-1$ descLeftBGColor = new MColor("B60000", 255); //$NON-NLS-1$ descRightBGColor = new MColor("B60000", 255); //$NON-NLS-1$ barAreaBGColor = new MColor("306A90", 255); //$NON-NLS-1$ overlayBarColor = new MColor("006AB0", 255); //$NON-NLS-1$ } public FriedmanGraph(final GC gc, final int areaWidth, final int areaHeight) { super(gc, areaWidth, areaHeight); iniSettings(); } /** * Calculate which space a bar label can fill * * @param textSpace * the whole bar description area * @param thisIndex * the bar's index * @return the actual space reserved for the label */ private Rectangle calculateTextContainer(final Rectangle textSpace, final int thisIndex) { int myIndex = (thisIndex - currentShift); double rectWidth = (double) textSpace.width / (double) (getBarCount()); double dRX = textSpace.x + rectWidth * myIndex; double dRW = textSpace.x + rectWidth * (myIndex + 1) - dRX; int RX = (int) Math.round(dRX); int RW = (int) Math.round(dRW); int RY = textSpace.y; int RH = textSpace.height; return new Rectangle(RX, RY, RW, RH); } /** * calculates the whole space a bar can fill, integrating the offset value field * * @param barSpace * the space that is reserved for bars * @param thisIndex * the x-axis value of the bar you want to calculate * @return */ protected final Rectangle calculateBarContainer(final Rectangle barSpace, final int thisIndex) { int myIndex = (thisIndex - currentShift); double rectWidth = (double) barSpace.width / (double) (getBarCount()); double dRX = barSpace.x + rectWidth * myIndex; double dRW = barSpace.x + rectWidth * (myIndex + 1) - dRX; int RX = (int) Math.round(dRX); int RW = (int) Math.round(dRW); int RY = barSpace.y; int RH = barSpace.height; return new Rectangle(RX, RY, RW, RH); } @Override protected final void paintBarArea(final Rectangle thisArea, final MColor thisBGColor) { //The bar drawing rectangle without margins Rectangle barDrawingRect = new Rectangle(barAreaRect.x + marginLeft, barAreaRect.y + marginTop, barAreaRect.width - marginLeft - marginRight, barAreaRect.height - marginTop - marginBottom); //actual bar box Rectangle barBox; //calculate the biggest bar Index biggestBarIndex = calcBiggestBarIndex(); //Draw the background thisBGColor.setColor(gc); thisBGColor.setBGColor(gc); gc.fillRectangle(thisArea); if (bars.size() > 0) { for (int i = currentShift; i < currentShift + barCount; i++) { //Only shift when the bar is no overlay bar. barBox = calculateBarContainer(barDrawingRect, bars.get(i).getIndex()); //barBox = calculateBarContainer(barDrawingRect, ((Bar)bars.get(i)).getIndex(), biggestBarIndex); bars.get(i).setBox(barBox); bars.get(i).setGC(gc); bars.get(i).drawBar(); } } } @Override protected final void paintDescTopArea(final Rectangle thisArea, final MColor thisBGColor, final MColor thisFontColor) { thisBGColor.setColor(gc); thisBGColor.setBGColor(gc); gc.fillRectangle(thisArea); thisFontColor.setColor(gc); } @Override protected final void paintDescBottomArea(final Rectangle thisArea, final MColor thisBGColor, final MColor thisFontColor) { // The bar drawing rectangle without margins Rectangle descDrawingRect = new Rectangle(barAreaRect.x + marginLeft, descBottomRect.y, barAreaRect.width - marginLeft - marginRight, descBottomRect.height); // actual bar box Rectangle textBox; thisBGColor.setColor(gc); thisBGColor.setBGColor(gc); gc.fillRectangle(thisArea); // Following constructs count the number of digits which should be printed to avoid overlapping int multiplier = 1, digitCounter = 1, decimalPower = 10, digitsPerNumber = 1; // this simple loops determines how many digits the current leftmost number in the graph // has and sets digitsPerNumber and (next bigger) decimalPower for (int i = 10; i < currentShift; i *= 10, ++digitsPerNumber, decimalPower *= 10) ; boolean fitting = false; while (!fitting) { // This inner loop counts the number indexes the graph would show depending on the multiplier // e.g. an multiplier of 1 displays it for every bar, 5 would display for every 5th bar. for (int i = digitsPerNumber; i < barCount; i += multiplier) { if (i % decimalPower == 0) { digitsPerNumber++; decimalPower *= 10; } digitCounter += digitsPerNumber; } //if it doesn't fit the multiplier is increased to 5, 50 or 500 and the loop run again if (digitCounter * 10 > thisArea.width) { multiplier = multiplier == 1 ? 5 : multiplier * 10; digitCounter = multiplier; } else fitting = true; } thisFontColor.setColor(gc); for (int i = currentShift, index; i < currentShift + barCount; i++) { index = bars.get(i).getIndex(); if (multiplier == 1 || (i >= 2 && (index + 1) % multiplier == 0)) { textBox = calculateTextContainer(descDrawingRect, index); bars.get(i).drawLowerLabel(textBox, gc); } } } @Override protected final Bar setBarStandardSettings(final Bar rawBar) { //set OVERLAY BAR Standards - they override standard bar settings (because they're specialised bars) if (rawBar instanceof OverlayBar || rawBar instanceof OverlayLabelBar) { if ((rawBar).getWidth() == -1.0) { (rawBar).setWidth(overlayBarWidth); } if ((rawBar).getColorMainBar() == null) { (rawBar).setColorMainBar(overlayBarColor); } } rawBar.setGC(gc); if (rawBar.getColorMainBar() == null) { rawBar.setColorMainBar(barColor); } if (rawBar.getWidth() == -1) { rawBar.setWidth(barWidth); } //Set Transparency if (rawBar instanceof OverlayBar) { if (((OverlayBar) rawBar).getTransparencyHighest() == -1) { ((OverlayBar) rawBar).setTransparencyHighest(overlayTranspHighest); } if (((OverlayBar) rawBar).getTransparencyLowest() == -1) { ((OverlayBar) rawBar).setTransparencyLowest(overlayTranspLowest); } } if (rawBar instanceof OverlayLabelBar) { if (((OverlayLabelBar) rawBar).getTransparencyHighest() == -1) { ((OverlayLabelBar) rawBar).setTransparencyHighest(overlayTranspHighest); } if (((OverlayLabelBar) rawBar).getTransparencyLowest() == -1) { ((OverlayLabelBar) rawBar).setTransparencyLowest(overlayTranspLowest); } } return rawBar; } @Override public final void addBar(Bar myBar) { // before which bar should this bar be inserted? -1, if it is the lat index. myBar = setBarStandardSettings(myBar); int beforeWhich = -1; for (int i = 0; i < bars.size(); i++) { if (compareBarOrder(myBar, bars.get(i)) && beforeWhich == -1) { beforeWhich = i; } } bars.setSize(bars.size() + 1); if (beforeWhich > -1) { for (int i = bars.size() - 1; i > beforeWhich; i--) { bars.set(i, bars.get(i - 1)); } bars.set(beforeWhich, myBar); } else { bars.set(bars.size() - 1, myBar); } if (myBar.getHeight() < lowestValue) { lowestValue = myBar.getHeight(); } } /** * optimizes the displaying of the bars by relativating their displayed heights: The function seeks the bar with the lowest * value, and cuts every bar by a percentage of this value. * * @param cutPercentage * the cutting percentage. Range: 0..1. 1 would mean, you cut the bars such, the lowest bar would not be displayed. */ public final void optimizeBarHeights(final double cutPercentage) { double subtractHeight = cutPercentage * lowestValue; for (int i = 0; i < bars.size(); i++) { bars.get(i).setHeight(bars.get(i).getHeight() - subtractHeight); } for (int i = 0; i < bars.size(); i++) { bars.get(i).setHeight(bars.get(i).getHeight() / (1 - subtractHeight)); } } /** * @return the max. horizontal space available for a bar in pixel. */ protected final double calculateBarHorizSpace() { return (double) (areaWidth - descLeftRect.width - descRightRect.width) / (double) (barCount); } /** * if the Frequency Graph is dragged, this method determines whether a shifting of bars will happen, and if, of which offset. * <br /> * Current Policy is, to not shift the Graph by the exact pixel value; the bars will rather snap to the raster positions * * @param myPixelsDifference * is the difference in horizontal pixels in the dragging procedure. * @param isMouseButtonHold * if the mouseButton is held pressed. * @return if a shifting occured (for redraw) */ public final boolean setDraggedPixels(final int myPixelsDifference, final boolean isMouseButtonHold) { if (calcBiggestBarIndex() > 0) { int myShift = (-1) * (int) Math.round(myPixelsDifference / calculateBarHorizSpace()); boolean changed = savedShift + myShift != getCurrentShift(); setCurrentShift(Math.max(savedShift + myShift, 0)); //setCurrentShift(modulo(getCurrentShift(), calcBiggestBarIndex())); if (!isMouseButtonHold) { savedShift = getCurrentShift(); } if (changed) { return true; } //Wenn sich was verändert hat, zeichnen! return false; } else { setCurrentShift(0); savedShift = 0; return true; } } /** * reset the shift of the graph * * @param myBarCount * sets the amount of bars to be displayed */ public final void resetDrag(final int myBarCount) { setCurrentShift(0); setBarCount(myBarCount); savedShift = 0; } /** * @param currentShift * sets the shift */ public final void setCurrentShift(final int currentShift) { if (bars.size() > 0) { this.currentShift = Math.min(currentShift, bars.size() - barCount - 1); } } /** * zoom in by the zoomFactor value * * @return whether the zoom has affected something or not. */ public final boolean zoomin() { int oldShift = currentShift; boolean changed = false; if (bars.size() > 0) { double newBarCount = barCount / zoomFactor; int newCount = (int) Math.round(newBarCount); if (newCount <= 1) barCount = 1; else if (newCount >= barCount) { newCount = barCount - 1; } if (barCount != newCount || currentShift != oldShift) { changed = true; } if (barCount != newCount) { barCount = newCount; } } if (changed) { return true; } else { return false; } } /** * zoom out by the zoomFactor value * * @return whether the zoom has affected something or not. */ public final boolean zoomout() { int oldShift = currentShift; boolean changed = false; if (bars.size() > 0) { double newBarCount = barCount * zoomFactor; int newCount = (int) Math.round(newBarCount); if (newCount > bars.size()) return false; if (newCount <= barCount) { newCount = barCount + 1; } if (currentShift + newCount > bars.size()) { currentShift = bars.size() - newCount; currentShift = Math.max(0, currentShift); newCount = bars.size() - currentShift; } if (barCount != newCount || currentShift != oldShift) { changed = true; } if (barCount != newCount) { barCount = newCount; } } if (changed) { return true; } else { return false; } } public final int getCurrentShift() { return currentShift; } public final void setBarCount(final int barCount) { if (bars.size() > 0) { this.barCount = Math.min(bars.size() - currentShift, barCount); } } public final int getBarCount() { return barCount; } public final void setZoomFactor(final double zoomFactor) { this.zoomFactor = zoomFactor; } public final double getZoomFactor() { return zoomFactor; } }
UI changes to analysis.friedman - Added y-axis description Added a y-axis description going in 0.1 or 0.25 steps. It also shows the highest values and scales with the graph size. BUGS: This is an in-between commit. The 0.25 values don't scale correctly and there are some hardcoded values which may be replaced by function-determined values.
org.jcryptool.analysis.friedman/src/org/jcryptool/analysis/friedman/ui/FriedmanGraph.java
UI changes to analysis.friedman - Added y-axis description
Java
epl-1.0
cbfd56df903da17929a5c318fc09790b8b0d6977
0
usethesource/rascal-value
/******************************************************************************* * Copyright (c) 2013-2014 CWI * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI *******************************************************************************/ package io.usethesource.vallang.impl.persistent; import java.util.Arrays; import java.util.Iterator; import java.util.Map.Entry; import io.usethesource.capsule.Map; import io.usethesource.capsule.util.EqualityComparator; import io.usethesource.vallang.IMap; import io.usethesource.vallang.IMapWriter; import io.usethesource.vallang.ITuple; import io.usethesource.vallang.IValue; import io.usethesource.vallang.exceptions.UnexpectedElementTypeException; import io.usethesource.vallang.type.Type; import io.usethesource.vallang.util.AbstractTypeBag; import io.usethesource.vallang.util.EqualityUtils; final class MapWriter implements IMapWriter { private static final EqualityComparator<Object> equivalenceComparator = EqualityUtils.getEquivalenceComparator(); private AbstractTypeBag keyTypeBag; private AbstractTypeBag valTypeBag; private final Map.Transient<IValue, IValue> mapContent; private final boolean checkUpperBound; private final Type upperBoundKeyType; private final Type upperBoundValType; private IMap constructedMap; MapWriter() { super(); this.checkUpperBound = false; this.upperBoundKeyType = null; this.upperBoundValType = null; keyTypeBag = AbstractTypeBag.of(); valTypeBag = AbstractTypeBag.of(); mapContent = Map.Transient.of(); constructedMap = null; } @Override @SuppressWarnings("deprecation") public void put(IValue key, IValue value) { checkMutation(); final Type keyType = key.getType(); final Type valType = value.getType(); if (checkUpperBound) { if (!keyType.isSubtypeOf(upperBoundKeyType)) { throw new UnexpectedElementTypeException(upperBoundKeyType, keyType); } if (!valType.isSubtypeOf(upperBoundValType)) { throw new UnexpectedElementTypeException(upperBoundValType, valType); } } final IValue replaced = mapContent.__putEquivalent(key, value, equivalenceComparator); keyTypeBag = keyTypeBag.increase(keyType); valTypeBag = valTypeBag.increase(valType); if (replaced != null) { final Type replacedType = replaced.getType(); valTypeBag = valTypeBag.decrease(replacedType); } } @Override public void putAll(IMap map) { putAll(map.entryIterator()); } @Override public void putAll(java.util.Map<IValue, IValue> map) { putAll(map.entrySet().iterator()); } private void putAll(Iterator<Entry<IValue, IValue>> entryIterator) { checkMutation(); while (entryIterator.hasNext()) { Entry<IValue, IValue> entry = entryIterator.next(); IValue key = entry.getKey(); IValue value = entry.getValue(); this.put(key, value); } } @Override public void insert(IValue... values) { insertAll(Arrays.asList(values)); } @Override public void insertAll(Iterable<? extends IValue> collection) { checkMutation(); Iterator<? extends IValue> collectionIterator = collection.iterator(); while (collectionIterator.hasNext()) { final Object item = collectionIterator.next(); if (!(item instanceof ITuple)) { throw new IllegalArgumentException("Argument must be of ITuple type."); } final ITuple tuple = (ITuple) item; if (tuple.arity() != 2) { throw new IllegalArgumentException("Tuple must have an arity of 2."); } put(tuple.get(0), tuple.get(1)); } } protected void checkMutation() { if (constructedMap != null) { throw new UnsupportedOperationException("Mutation of a finalized map is not supported."); } } @Override public IMap done() { if (constructedMap == null) { constructedMap = new PersistentHashMap(keyTypeBag, valTypeBag, mapContent.freeze()); } return constructedMap; } @Override public void insertTuple(IValue... fields) { insert(ValueFactory.getInstance().tuple(fields)); } @Override public Iterator<IValue> iterator() { return mapContent.keyIterator(); } @Override public IValue get(IValue key) { return mapContent.get(key); } }
src/main/java/io/usethesource/vallang/impl/persistent/MapWriter.java
/******************************************************************************* * Copyright (c) 2013-2014 CWI * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI *******************************************************************************/ package io.usethesource.vallang.impl.persistent; import java.util.Arrays; import java.util.Iterator; import java.util.Map.Entry; import io.usethesource.capsule.Map; import io.usethesource.capsule.util.EqualityComparator; import io.usethesource.vallang.IMap; import io.usethesource.vallang.IMapWriter; import io.usethesource.vallang.ITuple; import io.usethesource.vallang.IValue; import io.usethesource.vallang.exceptions.UnexpectedElementTypeException; import io.usethesource.vallang.type.Type; import io.usethesource.vallang.util.AbstractTypeBag; import io.usethesource.vallang.util.EqualityUtils; final class MapWriter implements IMapWriter { private static final EqualityComparator<Object> equivalenceComparator = EqualityUtils.getEquivalenceComparator(); protected AbstractTypeBag keyTypeBag; protected AbstractTypeBag valTypeBag; protected final Map.Transient<IValue, IValue> mapContent; protected final boolean checkUpperBound; protected final Type upperBoundKeyType; protected final Type upperBoundValType; protected IMap constructedMap; MapWriter() { super(); this.checkUpperBound = false; this.upperBoundKeyType = null; this.upperBoundValType = null; keyTypeBag = AbstractTypeBag.of(); valTypeBag = AbstractTypeBag.of(); mapContent = Map.Transient.of(); constructedMap = null; } @Override @SuppressWarnings("deprecation") public void put(IValue key, IValue value) { checkMutation(); final Type keyType = key.getType(); final Type valType = value.getType(); if (checkUpperBound) { if (!keyType.isSubtypeOf(upperBoundKeyType)) { throw new UnexpectedElementTypeException(upperBoundKeyType, keyType); } if (!valType.isSubtypeOf(upperBoundValType)) { throw new UnexpectedElementTypeException(upperBoundValType, valType); } } final IValue replaced = mapContent.__putEquivalent(key, value, equivalenceComparator); keyTypeBag = keyTypeBag.increase(keyType); valTypeBag = valTypeBag.increase(valType); if (replaced != null) { final Type replacedType = replaced.getType(); valTypeBag = valTypeBag.decrease(replacedType); } } @Override public void putAll(IMap map) { putAll(map.entryIterator()); } @Override public void putAll(java.util.Map<IValue, IValue> map) { putAll(map.entrySet().iterator()); } private void putAll(Iterator<Entry<IValue, IValue>> entryIterator) { checkMutation(); while (entryIterator.hasNext()) { Entry<IValue, IValue> entry = entryIterator.next(); IValue key = entry.getKey(); IValue value = entry.getValue(); this.put(key, value); } } @Override public void insert(IValue... values) { insertAll(Arrays.asList(values)); } @Override public void insertAll(Iterable<? extends IValue> collection) { checkMutation(); Iterator<? extends IValue> collectionIterator = collection.iterator(); while (collectionIterator.hasNext()) { final Object item = collectionIterator.next(); if (!(item instanceof ITuple)) { throw new IllegalArgumentException("Argument must be of ITuple type."); } final ITuple tuple = (ITuple) item; if (tuple.arity() != 2) { throw new IllegalArgumentException("Tuple must have an arity of 2."); } put(tuple.get(0), tuple.get(1)); } } protected void checkMutation() { if (constructedMap != null) { throw new UnsupportedOperationException("Mutation of a finalized map is not supported."); } } @Override public IMap done() { if (constructedMap == null) { constructedMap = new PersistentHashMap(keyTypeBag, valTypeBag, mapContent.freeze()); } return constructedMap; } @Override public void insertTuple(IValue... fields) { insert(ValueFactory.getInstance().tuple(fields)); } @Override public Iterator<IValue> iterator() { return mapContent.keyIterator(); } @Override public IValue get(IValue key) { return mapContent.get(key); } }
made more fields private
src/main/java/io/usethesource/vallang/impl/persistent/MapWriter.java
made more fields private
Java
mpl-2.0
cbafff74be536734528f76a9f00db54b119a876c
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.jhv.plugins.swek.view; import java.util.HashMap; import java.util.Map; import javax.swing.Icon; import javax.swing.ImageIcon; import org.helioviewer.jhv.plugins.swek.SWEKPlugin; /** * An Icon bank for the SWEK plugin. * * @author Bram Bourgoignie (Bram.Bourgoignie@oma.be) * */ public class SWEKIconBank { /** The instance of the SWEK icon bank */ private static SWEKIconBank singletonInstance; /** the icon bank */ private final Map<String, Icon> iconBank; /** * Private default constructor. */ private SWEKIconBank() { iconBank = new HashMap<String, Icon>(); initIconBank(); } /** * Gets the singleton instance of the SWEK icon bank. * * @return the instance of the SWEK icon bank */ public static SWEKIconBank getSingletonInstance() { if (singletonInstance == null) { singletonInstance = new SWEKIconBank(); } return singletonInstance; } /** * Adds a new Icon to the icon bank. * * @param eventType * the event type for which an icon was added * @param icon * the icon corresponding to the event */ public void addIcon(String eventType, ImageIcon icon) { iconBank.put(eventType, icon); } /** * Gets the Icon for the given icon name. * * @param iconName * the name of the icon. * @return the icon corresponding with the given name or the "other" icon if * the name was not known. */ public Icon getIcon(String iconName) { Icon tempIcon = iconBank.get(iconName); if (tempIcon == null) { return iconBank.get("Other"); } else { return tempIcon; } } /** * Initializes the icon bank. Adds all the standard icons to the iconbank. */ private void initIconBank() { iconBank.put("ActiveRegion", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ar_icon.png"))); iconBank.put("CoronalDimming", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/cd_icon.png"))); iconBank.put("CME", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ce_icon.png"))); iconBank.put("CoronalHole", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ch_icon.png"))); iconBank.put("CoronalWave", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/cw_icon.png"))); iconBank.put("EmergingFlux", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ef_icon.png"))); iconBank.put("Eruption", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/er_small.gif"))); iconBank.put("FilamentActivation", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fa_icon.png"))); iconBank.put("FilamentEruption", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fe_icon.png"))); iconBank.put("Filament", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fi_icon.png"))); iconBank.put("Flare", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fl_icon.png"))); iconBank.put("Loop", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/lp_icon.png"))); iconBank.put("NothingReported", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/nr_icon.png"))); iconBank.put("Oscillation", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/os_icon.png"))); iconBank.put("Other", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ot_icon.png"))); iconBank.put("Plage", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/pg_icon.png"))); iconBank.put("Sigmoid", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/sg_icon.png"))); iconBank.put("SpraySurge", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/sp_icon.png"))); iconBank.put("SunSpot", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ss_icon.png"))); } }
src/plugins/swhv-swek/src/org/helioviewer/jhv/plugins/swek/view/SWEKIconBank.java
package org.helioviewer.jhv.plugins.swek.view; import java.util.HashMap; import java.util.Map; import javax.swing.Icon; import javax.swing.ImageIcon; import org.helioviewer.jhv.plugins.swek.SWEKPlugin; /** * An Icon bank for the SWEK plugin. * * @author Bram Bourgoignie (Bram.Bourgoignie@oma.be) * */ public class SWEKIconBank { /** The instance of the SWEK icon bank */ private static SWEKIconBank singletonInstance; /** the icon bank */ private final Map<String, Icon> iconBank; /** * Private default constructor. */ private SWEKIconBank() { iconBank = new HashMap<String, Icon>(); initIconBank(); } /** * Gets the singleton instance of the SWEK icon bank. * * @return the instance of the SWEK icon bank */ public static SWEKIconBank getSingletonInstance() { if (singletonInstance == null) { singletonInstance = new SWEKIconBank(); } return singletonInstance; } /** * Adds a new Icon to the icon bank. * * @param eventType * the event type for which an icon was added * @param icon * the icon corresponding to the event */ public void addIcon(String eventType, ImageIcon icon) { iconBank.put(eventType, icon); } /** * Initializes the icon bank. Adds all the standard icons to the iconbank. */ private void initIconBank() { iconBank.put("ActiveRegion", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ar_icon.png"))); iconBank.put("CoronalDimming", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/cd_icon.png"))); iconBank.put("CME", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ce_icon.png"))); iconBank.put("CoronalHole", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ch_icon.png"))); iconBank.put("CoronalWave", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/cw_icon.png"))); iconBank.put("EmergingFlux", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ef_icon.png"))); iconBank.put("FilamentActivation", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fa_icon.png"))); iconBank.put("FilamentEruption", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fe_icon.png"))); iconBank.put("Filament", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fi_icon.png"))); iconBank.put("Flare", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/fl_icon.png"))); iconBank.put("Loop", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/lp_icon.png"))); iconBank.put("NothingReported", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/nr_icon.png"))); iconBank.put("Oscillation", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/os_icon.png"))); iconBank.put("Other", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ot_icon.png"))); iconBank.put("Sigmoid", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/sg_icon.png"))); iconBank.put("SpraySurge", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/sp_icon.png"))); iconBank.put("SunSpot", new ImageIcon(SWEKPlugin.class.getResource("/images/EventIcons/ss_icon.png"))); } }
Added eruption icon and get method git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@1938 b4e469a2-07ce-4b26-9273-4d7d95a670c7
src/plugins/swhv-swek/src/org/helioviewer/jhv/plugins/swek/view/SWEKIconBank.java
Added eruption icon and get method
Java
agpl-3.0
43efd25dd36a18efbcaa93ca17f7b7e98b617390
0
jrnold/rstudio,jrnold/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jrnold/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,jrnold/rstudio,jar1karp/rstudio,jar1karp/rstudio,jrnold/rstudio,jrnold/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jrnold/rstudio,jar1karp/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jrnold/rstudio,jrnold/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,jar1karp/rstudio,JanMarvin/rstudio
/* * DependencyManager.java * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.common.dependencies; import java.util.ArrayList; import org.rstudio.core.client.CommandWith2Args; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.console.ConsoleProcess; import org.rstudio.studio.client.common.console.ProcessExitEvent; import org.rstudio.studio.client.common.dependencies.events.InstallShinyEvent; import org.rstudio.studio.client.common.dependencies.model.Dependency; import org.rstudio.studio.client.common.dependencies.model.DependencyServerOperations; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.workbench.views.vcs.common.ConsoleProgressDialog; import com.google.gwt.core.client.JsArray; import com.google.gwt.user.client.Command; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class DependencyManager implements InstallShinyEvent.Handler { @Inject public DependencyManager(GlobalDisplay globalDisplay, DependencyServerOperations server, EventBus eventBus) { globalDisplay_ = globalDisplay; server_ = server; eventBus.addHandler(InstallShinyEvent.TYPE, this); } public void withDependencies(String progressCaption, CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, boolean silentEmbeddedUpdate, CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, null, userPrompt, dependencies, silentEmbeddedUpdate, onComplete); } public void withDependencies(String progressCaption, String userAction, Dependency[] dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, userAction, null, dependencies, silentEmbeddedUpdate, onComplete); } public void withPackrat(String userAction, final Command command) { withDependencies( "Packrat", userAction, new Dependency[] { Dependency.cranPackage("packrat", "0.4.6", true) }, false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } }); } public void withRSConnect(String userAction, boolean requiresRmarkdown, CommandWith2Args<String, Command> userPrompt, final CommandWithArg<Boolean> onCompleted) { // build dependency array ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("RCurl", "1.95")); deps.add(Dependency.cranPackage("RJSONIO", "1.0")); deps.add(Dependency.cranPackage("PKI", "0.1")); deps.add(Dependency.cranPackage("rstudioapi", "0.2")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); if (requiresRmarkdown) deps.addAll(rmarkdownDependencies()); deps.add(Dependency.cranPackage("packrat", "0.4.6", true)); deps.add(Dependency.embeddedPackage("rsconnect")); withDependencies( "Publishing", userAction, userPrompt, deps.toArray(new Dependency[deps.size()]), true, // we want the embedded rsconnect package to be updated if needed onCompleted ); } public void withRMarkdown(String userAction, final Command command) { withDependencies( "R Markdown", userAction, rmarkdownDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> rmarkdownDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("evaluate", "0.7.2")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("formatR", "1.1")); deps.add(Dependency.cranPackage("highr", "0.3")); deps.add(Dependency.cranPackage("markdown", "0.7")); deps.add(Dependency.cranPackage("stringr", "0.6")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); deps.add(Dependency.cranPackage("htmltools", "0.2.4")); deps.add(Dependency.cranPackage("caTools", "1.14")); deps.add(Dependency.cranPackage("bitops", "1.0-6")); deps.add(Dependency.cranPackage("knitr", "1.11", true)); deps.add(Dependency.cranPackage("rmarkdown", "0.9.2", true)); return deps; } private Dependency[] rmarkdownDependenciesArray() { ArrayList<Dependency> deps = rmarkdownDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withShiny(final String userAction, final Command command) { // create user prompt command CommandWith2Args<String, Command> userPrompt = new CommandWith2Args<String, Command>() { @Override public void execute(final String unmetDeps, final Command yesCommand) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Shiny Package", userAction + " requires installation of an updated version " + "of the shiny package.\n\nDo you want to install shiny now?", new Operation() { @Override public void execute() { yesCommand.execute(); } }, true); } }; // perform dependency resolution withDependencies( "Checking installed packages", userPrompt, shinyDependenciesArray( "0.11.0", // shiny version "0.2.6"), // htmltools version true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } public void withShinyAddins(final Command command) { // define dependencies ArrayList<Dependency> deps = shinyDependencies( "0.13", // shiny version "0.3"); // htmltools version deps.add(Dependency.cranPackage("miniUI", "0.1.1", true)); deps.add(Dependency.cranPackage("rstudioapi", "0.4", true)); withDependencies( "Checking installed packages", "Executing addins", deps.toArray(new Dependency[deps.size()]), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private Dependency[] shinyDependenciesArray(String shinyVersion, String htmltoolsVersion) { ArrayList<Dependency> deps = shinyDependencies(shinyVersion, htmltoolsVersion); return deps.toArray(new Dependency[deps.size()]); } private ArrayList<Dependency> shinyDependencies(String shinyVersion, String htmltoolsVersion) { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("httpuv", "1.3.3")); deps.add(Dependency.cranPackage("mime", "0.3")); deps.add(Dependency.cranPackage("jsonlite", "0.9.16")); deps.add(Dependency.cranPackage("xtable", "1.7")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("R6", "2.0")); deps.add(Dependency.cranPackage("htmltools", htmltoolsVersion)); deps.add(Dependency.cranPackage("shiny", shinyVersion, true)); return deps; } @Override public void onInstallShiny(InstallShinyEvent event) { withShiny(event.getUserAction(), new Command() { public void execute() {}}); } public void withDataImportCSV(String userAction, final Command command) { withDependencies( "Preparing Import from CSV", userAction, dataImportCsvDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportCsvDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readr", "0.2.2")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportCsvDependenciesArray() { ArrayList<Dependency> deps = dataImportCsvDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportSAV(String userAction, final Command command) { withDependencies( "Preparing Import from SPSS, SAS and Stata", userAction, dataImportSavDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportSavDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("haven", "0.2.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.4")); return deps; } private Dependency[] dataImportSavDependenciesArray() { ArrayList<Dependency> deps = dataImportSavDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXLS(String userAction, final Command command) { withDependencies( "Preparing Import from Excel", userAction, dataImportXlsDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXlsDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readxl", "0.1.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportXlsDependenciesArray() { ArrayList<Dependency> deps = dataImportXlsDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXML(String userAction, final Command command) { withDependencies( "Preparing Import from XML", userAction, dataImportXmlDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXmlDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("xml2", "0.1.2")); return deps; } private Dependency[] dataImportXmlDependenciesArray() { ArrayList<Dependency> deps = dataImportXmlDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJSON(String userAction, final Command command) { withDependencies( "Preparing Import from JSON", userAction, dataImportJsonDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJsonDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); return deps; } private Dependency[] dataImportJsonDependenciesArray() { ArrayList<Dependency> deps = dataImportJsonDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJDBC(String userAction, final Command command) { withDependencies( "Preparing Import from JDBC", userAction, dataImportJdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RJDBC", "0.2-5")); deps.add(Dependency.cranPackage("rJava", "0.4-15")); return deps; } private Dependency[] dataImportJdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportJdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportODBC(String userAction, final Command command) { withDependencies( "Preparing Import from ODBC", userAction, dataImportOdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportOdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RODBC", "1.3-12")); return deps; } private Dependency[] dataImportOdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportOdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportMongo(String userAction, final Command command) { withDependencies( "Preparing Import from Mongo DB", userAction, dataImportMongoDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportMongoDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("mongolite", "0.8")); deps.add(Dependency.cranPackage("jsonlite", "0.9.16")); return deps; } private Dependency[] dataImportMongoDependenciesArray() { ArrayList<Dependency> deps = dataImportMongoDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withProfvis(String userAction, final Command command) { withDependencies( "Preparing Profiler", userAction, new Dependency[] { Dependency.embeddedPackage("profvis"), Dependency.cranPackage("htmlwidgets", "0.6"), Dependency.cranPackage("stringr", "0.6") }, false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private void withDependencies(String progressCaption, final String userAction, final CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { // convert dependencies to JsArray JsArray<Dependency> deps = JsArray.createArray().cast(); deps.setLength(dependencies.length); for (int i = 0; i<deps.length(); i++) deps.set(i, dependencies[i]); // create progress indicator final ProgressIndicator progress = new GlobalProgressDelayer( globalDisplay_, 250, progressCaption + "...").getIndicator(); // query for unsatisfied dependencies server_.unsatisfiedDependencies( deps, silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived( final JsArray<Dependency> unsatisfiedDeps) { progress.onCompleted(); // if we've satisfied all dependencies then execute the command if (unsatisfiedDeps.length() == 0) { onComplete.execute(true); return; } // check to see if we can satisfy the version requirement for all // dependencies String unsatisfiedVersions = ""; for (int i = 0; i < unsatisfiedDeps.length(); i++) { if (!unsatisfiedDeps.get(i).getVersionSatisfied()) { unsatisfiedVersions += unsatisfiedDeps.get(i).getName() + " " + unsatisfiedDeps.get(i).getVersion(); String version = unsatisfiedDeps.get(i).getAvailableVersion(); if (version.isEmpty()) unsatisfiedVersions += " is not available\n"; else unsatisfiedVersions += " is required but " + version + " is available\n"; } } if (!unsatisfiedVersions.isEmpty()) { // error if we can't satisfy requirements globalDisplay_.showErrorMessage(userAction, "Required package versions could not be found:\n\n" + unsatisfiedVersions + "\n" + "Check that getOption(\"repos\") refers to a CRAN " + "repository that contains the needed package versions."); onComplete.execute(false); } else { // otherwise ask the user if they want to install the // unsatisifed dependencies final CommandWithArg<Boolean> installCommand = new CommandWithArg<Boolean>() { @Override public void execute(Boolean confirmed) { // bail if if (!confirmed) { onComplete.execute(false); return; } // the incoming JsArray from the server may not serialize // as expected when this code is executed from a satellite // (see RemoteServer.sendRequestViaMainWorkbench), so we // clone it before passing to the dependency installer JsArray<Dependency> newArray = JsArray.createArray().cast(); newArray.setLength(unsatisfiedDeps.length()); for (int i = 0; i < unsatisfiedDeps.length(); i++) { newArray.set(i, unsatisfiedDeps.get(i)); } installDependencies( newArray, silentEmbeddedUpdate, onComplete); } }; if (userPrompt != null) { userPrompt.execute(describeDepPkgs(unsatisfiedDeps), new Command() { @Override public void execute() { installCommand.execute(true); } }); } else { confirmPackageInstallation(userAction, unsatisfiedDeps, installCommand); } } } @Override public void onError(ServerError error) { progress.onError(error.getUserMessage()); onComplete.execute(false); } }); } private void installDependencies(final JsArray<Dependency> dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.installDependencies( dependencies, new ServerRequestCallback<ConsoleProcess>() { @Override public void onResponseReceived(ConsoleProcess proc) { final ConsoleProgressDialog dialog = new ConsoleProgressDialog(proc, server_); dialog.showModal(); proc.addProcessExitHandler( new ProcessExitEvent.Handler() { @Override public void onProcessExit(ProcessExitEvent event) { ifDependenciesSatisifed(dependencies, silentEmbeddedUpdate, new CommandWithArg<Boolean>(){ @Override public void execute(Boolean succeeded) { dialog.hide(); onComplete.execute(succeeded); } }); } }); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Dependency installation failed", error.getUserMessage()); onComplete.execute(false); } }); } private void ifDependenciesSatisifed(JsArray<Dependency> dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.unsatisfiedDependencies( dependencies, silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived(JsArray<Dependency> dependencies) { onComplete.execute(dependencies.length() == 0); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Could not determine available packages", error.getUserMessage()); onComplete.execute(false); } }); } private void confirmPackageInstallation( String userAction, final JsArray<Dependency> dependencies, final CommandWithArg<Boolean> onComplete) { String msg = null; if (dependencies.length() == 1) { msg = "requires an updated version of the " + dependencies.get(0).getName() + " package. " + "\n\nDo you want to install this package now?"; } else { msg = "requires updated versions of the following packages: " + describeDepPkgs(dependencies) + ". " + "\n\nDo you want to install these packages now?"; } if (userAction != null) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Required Packages", userAction + " " + msg, false, new Operation() { @Override public void execute() { onComplete.execute(true); } }, new Operation() { @Override public void execute() { onComplete.execute(false); } }, true); } else { onComplete.execute(true); } } private String describeDepPkgs(JsArray<Dependency> dependencies) { ArrayList<String> deps = new ArrayList<String>(); for (int i = 0; i < dependencies.length(); i++) deps.add(dependencies.get(i).getName()); return StringUtil.join(deps, ", "); } private final GlobalDisplay globalDisplay_; private final DependencyServerOperations server_; }
src/gwt/src/org/rstudio/studio/client/common/dependencies/DependencyManager.java
/* * DependencyManager.java * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.common.dependencies; import java.util.ArrayList; import org.rstudio.core.client.CommandWith2Args; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.console.ConsoleProcess; import org.rstudio.studio.client.common.console.ProcessExitEvent; import org.rstudio.studio.client.common.dependencies.events.InstallShinyEvent; import org.rstudio.studio.client.common.dependencies.model.Dependency; import org.rstudio.studio.client.common.dependencies.model.DependencyServerOperations; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.workbench.views.vcs.common.ConsoleProgressDialog; import com.google.gwt.core.client.JsArray; import com.google.gwt.user.client.Command; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class DependencyManager implements InstallShinyEvent.Handler { @Inject public DependencyManager(GlobalDisplay globalDisplay, DependencyServerOperations server, EventBus eventBus) { globalDisplay_ = globalDisplay; server_ = server; eventBus.addHandler(InstallShinyEvent.TYPE, this); } public void withDependencies(String progressCaption, CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, boolean silentEmbeddedUpdate, CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, null, userPrompt, dependencies, silentEmbeddedUpdate, onComplete); } public void withDependencies(String progressCaption, String userAction, Dependency[] dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, userAction, null, dependencies, silentEmbeddedUpdate, onComplete); } public void withPackrat(String userAction, final Command command) { withDependencies( "Packrat", userAction, new Dependency[] { Dependency.cranPackage("packrat", "0.4.6", true) }, false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } }); } public void withRSConnect(String userAction, boolean requiresRmarkdown, CommandWith2Args<String, Command> userPrompt, final CommandWithArg<Boolean> onCompleted) { // build dependency array ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("RCurl", "1.95")); deps.add(Dependency.cranPackage("RJSONIO", "1.0")); deps.add(Dependency.cranPackage("PKI", "0.1")); deps.add(Dependency.cranPackage("rstudioapi", "0.2")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); if (requiresRmarkdown) deps.addAll(rmarkdownDependencies()); deps.add(Dependency.cranPackage("packrat", "0.4.6", true)); deps.add(Dependency.embeddedPackage("rsconnect")); withDependencies( "Publishing", userAction, userPrompt, deps.toArray(new Dependency[deps.size()]), true, // we want the embedded rsconnect package to be updated if needed onCompleted ); } public void withRMarkdown(String userAction, final Command command) { withDependencies( "R Markdown", userAction, rmarkdownDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> rmarkdownDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("evaluate", "0.7.2")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("formatR", "1.1")); deps.add(Dependency.cranPackage("highr", "0.3")); deps.add(Dependency.cranPackage("markdown", "0.7")); deps.add(Dependency.cranPackage("stringr", "0.6")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); deps.add(Dependency.cranPackage("htmltools", "0.2.4")); deps.add(Dependency.cranPackage("caTools", "1.14")); deps.add(Dependency.cranPackage("bitops", "1.0-6")); deps.add(Dependency.cranPackage("knitr", "1.11", true)); deps.add(Dependency.cranPackage("rmarkdown", "0.9.2", true)); return deps; } private Dependency[] rmarkdownDependenciesArray() { ArrayList<Dependency> deps = rmarkdownDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withShiny(final String userAction, final Command command) { // create user prompt command CommandWith2Args<String, Command> userPrompt = new CommandWith2Args<String, Command>() { @Override public void execute(final String unmetDeps, final Command yesCommand) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Shiny Package", userAction + " requires installation of an updated version " + "of the shiny package.\n\nDo you want to install shiny now?", new Operation() { @Override public void execute() { yesCommand.execute(); } }, true); } }; // perform dependency resolution withDependencies( "Checking installed packages", userPrompt, shinyDependenciesArray( "0.11.0", // shiny version "0.2.6"), // htmltools version true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } public void withShinyAddins(final Command command) { // define dependencies ArrayList<Dependency> deps = shinyDependencies( "0.13", // shiny version "0.3"); // htmltools version deps.add(Dependency.cranPackage("miniUI", "0.1.1", true)); deps.add(Dependency.cranPackage("rstudioapi", "0.4", true)); withDependencies( "Checking installed packages", "Executing addins", deps.toArray(new Dependency[deps.size()]), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private Dependency[] shinyDependenciesArray(String shinyVersion, String htmltoolsVersion) { ArrayList<Dependency> deps = shinyDependencies(shinyVersion, htmltoolsVersion); return deps.toArray(new Dependency[deps.size()]); } private ArrayList<Dependency> shinyDependencies(String shinyVersion, String htmltoolsVersion) { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("httpuv", "1.3.3")); deps.add(Dependency.cranPackage("mime", "0.3")); deps.add(Dependency.cranPackage("jsonlite", "0.9.16")); deps.add(Dependency.cranPackage("xtable", "1.7")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("R6", "2.0")); deps.add(Dependency.cranPackage("htmltools", htmltoolsVersion)); deps.add(Dependency.cranPackage("shiny", shinyVersion, true)); return deps; } @Override public void onInstallShiny(InstallShinyEvent event) { withShiny(event.getUserAction(), new Command() { public void execute() {}}); } public void withDataImportCSV(String userAction, final Command command) { withDependencies( "Preparing Import from CSV", userAction, dataImportCsvDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportCsvDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readr", "0.2.2")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportCsvDependenciesArray() { ArrayList<Dependency> deps = dataImportCsvDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportSAV(String userAction, final Command command) { withDependencies( "Preparing Import from SPSS, SAS and Stata", userAction, dataImportSavDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportSavDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("haven", "0.2.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.4")); return deps; } private Dependency[] dataImportSavDependenciesArray() { ArrayList<Dependency> deps = dataImportSavDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXLS(String userAction, final Command command) { withDependencies( "Preparing Import from Excel", userAction, dataImportXlsDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXlsDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readxl", "0.1.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportXlsDependenciesArray() { ArrayList<Dependency> deps = dataImportXlsDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXML(String userAction, final Command command) { withDependencies( "Preparing Import from XML", userAction, dataImportXmlDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXmlDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("xml2", "0.1.2")); return deps; } private Dependency[] dataImportXmlDependenciesArray() { ArrayList<Dependency> deps = dataImportXmlDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJSON(String userAction, final Command command) { withDependencies( "Preparing Import from JSON", userAction, dataImportJsonDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJsonDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); return deps; } private Dependency[] dataImportJsonDependenciesArray() { ArrayList<Dependency> deps = dataImportJsonDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJDBC(String userAction, final Command command) { withDependencies( "Preparing Import from JDBC", userAction, dataImportJdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RJDBC", "0.2-5")); deps.add(Dependency.cranPackage("rJava", "0.4-15")); return deps; } private Dependency[] dataImportJdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportJdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportODBC(String userAction, final Command command) { withDependencies( "Preparing Import from ODBC", userAction, dataImportOdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportOdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RODBC", "1.3-12")); return deps; } private Dependency[] dataImportOdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportOdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportMongo(String userAction, final Command command) { withDependencies( "Preparing Import from Mongo DB", userAction, dataImportMongoDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportMongoDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("mongolite", "0.8")); deps.add(Dependency.cranPackage("jsonlite", "0.9.16")); return deps; } private Dependency[] dataImportMongoDependenciesArray() { ArrayList<Dependency> deps = dataImportMongoDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withProfvis(String userAction, final Command command) { withDependencies( "Preparing Profiler", userAction, new Dependency[] { Dependency.embeddedPackage("profvis") }, false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private void withDependencies(String progressCaption, final String userAction, final CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { // convert dependencies to JsArray JsArray<Dependency> deps = JsArray.createArray().cast(); deps.setLength(dependencies.length); for (int i = 0; i<deps.length(); i++) deps.set(i, dependencies[i]); // create progress indicator final ProgressIndicator progress = new GlobalProgressDelayer( globalDisplay_, 250, progressCaption + "...").getIndicator(); // query for unsatisfied dependencies server_.unsatisfiedDependencies( deps, silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived( final JsArray<Dependency> unsatisfiedDeps) { progress.onCompleted(); // if we've satisfied all dependencies then execute the command if (unsatisfiedDeps.length() == 0) { onComplete.execute(true); return; } // check to see if we can satisfy the version requirement for all // dependencies String unsatisfiedVersions = ""; for (int i = 0; i < unsatisfiedDeps.length(); i++) { if (!unsatisfiedDeps.get(i).getVersionSatisfied()) { unsatisfiedVersions += unsatisfiedDeps.get(i).getName() + " " + unsatisfiedDeps.get(i).getVersion(); String version = unsatisfiedDeps.get(i).getAvailableVersion(); if (version.isEmpty()) unsatisfiedVersions += " is not available\n"; else unsatisfiedVersions += " is required but " + version + " is available\n"; } } if (!unsatisfiedVersions.isEmpty()) { // error if we can't satisfy requirements globalDisplay_.showErrorMessage(userAction, "Required package versions could not be found:\n\n" + unsatisfiedVersions + "\n" + "Check that getOption(\"repos\") refers to a CRAN " + "repository that contains the needed package versions."); onComplete.execute(false); } else { // otherwise ask the user if they want to install the // unsatisifed dependencies final CommandWithArg<Boolean> installCommand = new CommandWithArg<Boolean>() { @Override public void execute(Boolean confirmed) { // bail if if (!confirmed) { onComplete.execute(false); return; } // the incoming JsArray from the server may not serialize // as expected when this code is executed from a satellite // (see RemoteServer.sendRequestViaMainWorkbench), so we // clone it before passing to the dependency installer JsArray<Dependency> newArray = JsArray.createArray().cast(); newArray.setLength(unsatisfiedDeps.length()); for (int i = 0; i < unsatisfiedDeps.length(); i++) { newArray.set(i, unsatisfiedDeps.get(i)); } installDependencies( newArray, silentEmbeddedUpdate, onComplete); } }; if (userPrompt != null) { userPrompt.execute(describeDepPkgs(unsatisfiedDeps), new Command() { @Override public void execute() { installCommand.execute(true); } }); } else { confirmPackageInstallation(userAction, unsatisfiedDeps, installCommand); } } } @Override public void onError(ServerError error) { progress.onError(error.getUserMessage()); onComplete.execute(false); } }); } private void installDependencies(final JsArray<Dependency> dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.installDependencies( dependencies, new ServerRequestCallback<ConsoleProcess>() { @Override public void onResponseReceived(ConsoleProcess proc) { final ConsoleProgressDialog dialog = new ConsoleProgressDialog(proc, server_); dialog.showModal(); proc.addProcessExitHandler( new ProcessExitEvent.Handler() { @Override public void onProcessExit(ProcessExitEvent event) { ifDependenciesSatisifed(dependencies, silentEmbeddedUpdate, new CommandWithArg<Boolean>(){ @Override public void execute(Boolean succeeded) { dialog.hide(); onComplete.execute(succeeded); } }); } }); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Dependency installation failed", error.getUserMessage()); onComplete.execute(false); } }); } private void ifDependenciesSatisifed(JsArray<Dependency> dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.unsatisfiedDependencies( dependencies, silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived(JsArray<Dependency> dependencies) { onComplete.execute(dependencies.length() == 0); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Could not determine available packages", error.getUserMessage()); onComplete.execute(false); } }); } private void confirmPackageInstallation( String userAction, final JsArray<Dependency> dependencies, final CommandWithArg<Boolean> onComplete) { String msg = null; if (dependencies.length() == 1) { msg = "requires an updated version of the " + dependencies.get(0).getName() + " package. " + "\n\nDo you want to install this package now?"; } else { msg = "requires updated versions of the following packages: " + describeDepPkgs(dependencies) + ". " + "\n\nDo you want to install these packages now?"; } if (userAction != null) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Required Packages", userAction + " " + msg, false, new Operation() { @Override public void execute() { onComplete.execute(true); } }, new Operation() { @Override public void execute() { onComplete.execute(false); } }, true); } else { onComplete.execute(true); } } private String describeDepPkgs(JsArray<Dependency> dependencies) { ArrayList<String> deps = new ArrayList<String>(); for (int i = 0; i < dependencies.length(); i++) deps.add(dependencies.get(i).getName()); return StringUtil.join(deps, ", "); } private final GlobalDisplay globalDisplay_; private final DependencyServerOperations server_; }
add additional dependencies required by profvis (htmlwidgets and stringr)
src/gwt/src/org/rstudio/studio/client/common/dependencies/DependencyManager.java
add additional dependencies required by profvis (htmlwidgets and stringr)
Java
agpl-3.0
d8fa40d7d5a9211aaa048010143c002173c5ab3a
0
subshare/subshare,subshare/subshare,subshare/subshare
package org.subshare.local; import static co.codewizards.cloudstore.core.util.AssertUtil.*; import static co.codewizards.cloudstore.core.util.StringUtil.*; import static org.subshare.local.CryptreeNodeUtil.*; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import javax.jdo.JDOHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subshare.core.AccessDeniedException; import org.subshare.core.DataKey; import org.subshare.core.GrantAccessDeniedException; import org.subshare.core.ReadAccessDeniedException; import org.subshare.core.ReadUserIdentityAccessDeniedException; import org.subshare.core.WriteAccessDeniedException; import org.subshare.core.crypto.CryptoConfigUtil; import org.subshare.core.dto.CollisionPrivateDto; import org.subshare.core.dto.CryptoKeyPart; import org.subshare.core.dto.CryptoKeyRole; import org.subshare.core.dto.PermissionType; import org.subshare.core.dto.PlainHistoCryptoRepoFileDto; import org.subshare.core.dto.SignatureDto; import org.subshare.core.dto.SsRepoFileDto; import org.subshare.core.repo.local.CollisionFilter; import org.subshare.core.sign.Signable; import org.subshare.core.sign.WriteProtected; import org.subshare.core.user.UserRepoKey; import org.subshare.core.user.UserRepoKey.PublicKey; import org.subshare.crypto.CipherOperationMode; import org.subshare.local.dto.CollisionDtoConverter; import org.subshare.local.dto.CollisionPrivateDtoConverter; import org.subshare.local.dto.HistoCryptoRepoFileDtoConverter; import org.subshare.local.persistence.Collision; import org.subshare.local.persistence.CollisionDao; import org.subshare.local.persistence.CollisionPrivate; import org.subshare.local.persistence.CollisionPrivateDao; import org.subshare.local.persistence.CryptoConfigPropSet; import org.subshare.local.persistence.CryptoConfigPropSetDao; import org.subshare.local.persistence.CryptoKey; import org.subshare.local.persistence.CryptoKeyDao; import org.subshare.local.persistence.CryptoKeyDeactivation; import org.subshare.local.persistence.CryptoLink; import org.subshare.local.persistence.CryptoLinkDao; import org.subshare.local.persistence.CryptoRepoFile; import org.subshare.local.persistence.CryptoRepoFileDao; import org.subshare.local.persistence.CurrentHistoCryptoRepoFile; import org.subshare.local.persistence.CurrentHistoCryptoRepoFileDao; import org.subshare.local.persistence.HistoCryptoRepoFile; import org.subshare.local.persistence.HistoCryptoRepoFileDao; import org.subshare.local.persistence.HistoFrame; import org.subshare.local.persistence.HistoFrameDao; import org.subshare.local.persistence.InvitationUserRepoKeyPublicKey; import org.subshare.local.persistence.Permission; import org.subshare.local.persistence.PermissionDao; import org.subshare.local.persistence.PermissionSet; import org.subshare.local.persistence.PermissionSetDao; import org.subshare.local.persistence.PermissionSetInheritance; import org.subshare.local.persistence.PlainHistoCryptoRepoFile; import org.subshare.local.persistence.PlainHistoCryptoRepoFileDao; import org.subshare.local.persistence.PreliminaryDeletion; import org.subshare.local.persistence.PreliminaryDeletionDao; import org.subshare.local.persistence.RepositoryOwner; import org.subshare.local.persistence.UserIdentityLink; import org.subshare.local.persistence.UserIdentityLinkDao; import org.subshare.local.persistence.UserRepoKeyPublicKey; import org.subshare.local.persistence.UserRepoKeyPublicKeyDao; import org.subshare.local.persistence.UserRepoKeyPublicKeyReplacementRequestDao; import co.codewizards.cloudstore.core.Uid; import co.codewizards.cloudstore.core.auth.SignatureException; import co.codewizards.cloudstore.core.config.Config; import co.codewizards.cloudstore.core.dto.ConfigPropSetDto; import co.codewizards.cloudstore.core.dto.RepoFileDto; import co.codewizards.cloudstore.core.dto.jaxb.ConfigPropSetDtoIo; import co.codewizards.cloudstore.core.oio.File; import co.codewizards.cloudstore.core.repo.local.LocalRepoTransaction; import co.codewizards.cloudstore.core.util.ISO8601; import co.codewizards.cloudstore.core.util.PropertiesUtil; import co.codewizards.cloudstore.local.dto.RepoFileDtoConverter; import co.codewizards.cloudstore.local.persistence.Directory; import co.codewizards.cloudstore.local.persistence.RemoteRepository; import co.codewizards.cloudstore.local.persistence.RemoteRepositoryDao; import co.codewizards.cloudstore.local.persistence.RepoFile; import co.codewizards.cloudstore.local.persistence.RepoFileDao; public class CryptreeNode { private static final Logger logger = LoggerFactory.getLogger(CryptreeNode.class); private static final Map<CryptoKeyRole, Class<? extends PlainCryptoKeyFactory>> cryptoKeyRole2PlainCryptoKeyFactory; static { final Map<CryptoKeyRole, Class<? extends PlainCryptoKeyFactory>> m = new HashMap<>(5); m.put(CryptoKeyRole.clearanceKey, PlainCryptoKeyFactory.ClearanceKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.subdirKey, PlainCryptoKeyFactory.SubdirKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.fileKey, PlainCryptoKeyFactory.FileKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.backlinkKey, PlainCryptoKeyFactory.BacklinkKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.dataKey, PlainCryptoKeyFactory.DataKeyPlainCryptoKeyFactory.class); cryptoKeyRole2PlainCryptoKeyFactory = Collections.unmodifiableMap(m); } private final CryptreeContext context; private CryptreeNode parent; // maybe null - lazily loaded, if there is one private RepoFile repoFile; // maybe null - lazily loaded private CryptoRepoFile cryptoRepoFile; // maybe null - lazily loaded private PermissionSet permissionSet; // maybe null - lazily loaded, if there is one private RepoFileDtoConverter repoFileDtoConverter; // maybe null - lazily loaded private final List<CryptreeNode> children = new ArrayList<CryptreeNode>(0); private boolean childrenLoaded = false; private final Set<Permission> permissionsBeingCheckedNow = new HashSet<Permission>(); private final Set<Permission> permissionsAlreadyCheckedOk = new HashSet<Permission>(); public CryptreeNode(final CryptreeContext context, final RepoFile repoFile) { this(context, repoFile, null); } public CryptreeNode(final CryptreeContext context, final CryptoRepoFile cryptoRepoFile) { this(context, null, cryptoRepoFile); } private CryptreeNode(final CryptreeContext context, final RepoFile repoFile, final CryptoRepoFile cryptoRepoFile) { this(null, null, context, repoFile, cryptoRepoFile); } public CryptreeNode(final CryptreeNode parent, final CryptreeNode child, final CryptreeContext context, final RepoFile repoFile, final CryptoRepoFile cryptoRepoFile) { if (parent == null && child == null && context == null) throw new IllegalArgumentException("parent == null && child == null && context == null"); if (repoFile == null && cryptoRepoFile == null) throw new IllegalArgumentException("repoFile == null && cryptoRepoFile == null"); this.parent = parent; this.context = context != null ? context : (parent != null ? parent.getContext() : child.getContext()); this.repoFile = repoFile != null ? repoFile : cryptoRepoFile.getRepoFile(); this.cryptoRepoFile = cryptoRepoFile; if (child != null) children.add(child); } public CryptreeContext getContext() { return context; } public RepoFile getRepoFile() { if (repoFile == null) { repoFile = getCryptoRepoFile().getRepoFile(); if (repoFile == null) { getRepoFileDto(); // We expect the line above to throw an AccessDeniedException, if the user is not allowed to access it. // But if we checked out a sub-directory, it's a valid state that the parent-RepoFile objects do *not* // exist (because we don't have local file representations) and still we can decrypt the RepoFileDto // of the parent directories. // This RepoFile is therefore clearly optional! } else context.registerCryptreeNode(repoFile, this); } return repoFile; } /** * Gets the RepoFileDto containing meta-data only (the current version of it). * @return the DTO or <code>null</code>, if there is no CryptoRepoFile (i.e. {@link #getCryptoRepoFile()} returns <code>null</code>. * @throws AccessDeniedException */ public RepoFileDto getRepoFileDto() throws AccessDeniedException { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null) return null; final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(cryptoRepoFile.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The CryptoRepoFile with cryptoRepoFileId=%s could not be decrypted! Access rights missing?!", cryptoRepoFile.getCryptoRepoFileId())); final byte[] plainRepoFileDtoData = assertNotNull(decrypt(cryptoRepoFile.getRepoFileDtoData(), plainCryptoKey), "decrypt(...)"); final RepoFileDto repoFileDto = context.repoFileDtoIo.deserializeWithGz(plainRepoFileDtoData); return repoFileDto; } public RepoFileDto getHistoCryptoRepoFileRepoFileDto(final HistoCryptoRepoFile histoCryptoRepoFile) throws AccessDeniedException { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(histoCryptoRepoFile.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The HistoCryptoRepoFile with histoCryptoRepoFileId=%s could not be decrypted! Access rights missing?!", histoCryptoRepoFile.getHistoCryptoRepoFileId())); final byte[] plainRepoFileDtoData = assertNotNull(decrypt(histoCryptoRepoFile.getRepoFileDtoData(), plainCryptoKey), "decrypt(...)"); final RepoFileDto repoFileDto = context.repoFileDtoIo.deserializeWithGz(plainRepoFileDtoData); return repoFileDto; } public RepoFileDto getRepoFileDtoOnServer() throws AccessDeniedException { final CurrentHistoCryptoRepoFile currentHistoCryptoRepoFile = getCurrentHistoCryptoRepoFile(); if (currentHistoCryptoRepoFile == null) return null; final HistoCryptoRepoFile histoCryptoRepoFile = currentHistoCryptoRepoFile.getHistoCryptoRepoFile(); assertNotNull(histoCryptoRepoFile, "currentHistoCryptoRepoFile.histoCryptoRepoFile"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(histoCryptoRepoFile.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The HistoCryptoRepoFile with cryptoRepoFileId=%s could not be decrypted! Access rights missing?!", histoCryptoRepoFile.getCryptoRepoFile().getCryptoRepoFileId())); final byte[] plainRepoFileDtoData = assertNotNull(decrypt(histoCryptoRepoFile.getRepoFileDtoData(), plainCryptoKey), "decrypt(...)"); final RepoFileDto repoFileDto = context.repoFileDtoIo.deserializeWithGz(plainRepoFileDtoData); return repoFileDto; } public CryptoRepoFile getCryptoRepoFile() { if (cryptoRepoFile == null) { if (repoFile == null) // at least one of them must be there! throw new IllegalStateException("repoFile == null && cryptoRepoFile == null"); final CryptoRepoFileDao cryptoRepoFileDao = context.transaction.getDao(CryptoRepoFileDao.class); cryptoRepoFile = cryptoRepoFileDao.getCryptoRepoFile(repoFile); // may be null! final CryptreeNode parent = getParent(); if (parent != null && cryptoRepoFile == null) { cryptoRepoFile = cryptoRepoFileDao.getChildCryptoRepoFile(parent.getCryptoRepoFile(), repoFile.getName()); } if (cryptoRepoFile != null) context.registerCryptreeNode(cryptoRepoFile, this); } return cryptoRepoFile; } public CryptoRepoFile getCryptoRepoFileOrCreate(final boolean update) { CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null || update) { final CryptoRepoFileDao cryptoRepoFileDao = context.transaction.getDao(CryptoRepoFileDao.class); if (cryptoRepoFile == null) { cryptoRepoFile = new CryptoRepoFile(); // We sign *after* we persist below in this *same* *method*, hence we store this // dummy value temporarily to avoid allowing NULL. It's set to the real value in // the same transaction, anyway. Hence we should never end up with this in the DB. cryptoRepoFile.setSignature(new SignatureDto(new Date(0), new Uid(0, 0), new byte[] { 7 })); } else { cryptoRepoFile.setDeleted(null); cryptoRepoFile.setDeletedByIgnoreRule(false); deletePreliminaryDeletions(); } cryptoRepoFile.setRepoFile(assertNotNull(repoFile, "repoFile")); // repoFile is guaranteed to be *not* null, because of getCryptoRepoFile() above. cryptoRepoFile.setDirectory(repoFile instanceof Directory); // getPlainCryptoKeyOrCreate(...) causes this method to be called again. We thus must prevent // an eternal recursion by already assigning it to the field *now*. // Furthermore, CryptoKey has a reference to this object and will thus persist it, anyway. // Thus we explicitly persist it already here. this.cryptoRepoFile = cryptoRepoFile = cryptoRepoFileDao.makePersistent(cryptoRepoFile); final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); cryptoRepoFile.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); final CryptreeNode parent = getParent(); cryptoRepoFile.setParent(parent == null ? null : parent.getCryptoRepoFile()); final byte[] repoFileDtoData = createRepoFileDtoDataForCryptoRepoFile(false); cryptoRepoFile.setRepoFileDtoData(assertNotNull(encrypt(repoFileDtoData, plainCryptoKey), "encrypt(...)")); cryptoRepoFile.setLastSyncFromRepositoryId(null); sign(cryptoRepoFile); context.transaction.flush(); // we want an early failure - not later during commit. updateCryptoConfigPropSetIfConfigFile(); } return cryptoRepoFile; } public CryptoConfigPropSet updateCryptoConfigPropSetIfConfigFile() { final CryptoRepoFile cryptoRepoFile = assertNotNull(getCryptoRepoFile(), "cryptoRepoFile"); final String localName = cryptoRepoFile.getLocalName(); if (! Config.PROPERTIES_FILE_NAME_FOR_DIRECTORY.equals(localName)) { return null; } final CryptreeNode parent = assertNotNull(getParent(), "parent"); final CryptoRepoFile parentCrf = parent.getCryptoRepoFileOrCreate(false); final CryptoConfigPropSetDao ccpsDao = context.transaction.getDao(CryptoConfigPropSetDao.class); CryptoConfigPropSet cryptoConfigPropSet = ccpsDao.getCryptoConfigPropSet(parentCrf); if (cryptoConfigPropSet == null) cryptoConfigPropSet = new CryptoConfigPropSet(parentCrf); final PlainCryptoKey plainCryptoKey = parent.getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); cryptoConfigPropSet.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); final byte[] plainData = createConfigPropSetDtoDataFromFile(); cryptoConfigPropSet.setConfigPropSetDtoData(plainData == null ? null : encrypt(plainData, plainCryptoKey)); cryptoConfigPropSet.setLastSyncFromRepositoryId(null); parent.sign(cryptoConfigPropSet); cryptoConfigPropSet = ccpsDao.makePersistent(cryptoConfigPropSet); context.transaction.flush(); // we want an early failure - not later during commit. return cryptoConfigPropSet; } private byte[] createConfigPropSetDtoDataFromFile() { final ConfigPropSetDto configPropSetDto = createConfigPropSetDtoFromFile(); if (configPropSetDto == null) return null; return new ConfigPropSetDtoIo().serializeWithGz(configPropSetDto); } private ConfigPropSetDto createConfigPropSetDtoFromFile() { if (getCryptoRepoFile().getDeleted() != null) return null; final RepoFile repoFile = assertNotNull(getRepoFile(), "repoFile"); final File configFile = repoFile.getFile(context.transaction.getLocalRepoManager().getLocalRoot()); if (! configFile.isFile()) { logger.warn("createConfigPropSetDtoFromFile: configFile not existing (deleted after local-sync?!): {}", configFile); return null; } final Properties properties; try { properties = PropertiesUtil.load(configFile); } catch (IOException e) { throw new RuntimeException(e); } return new ConfigPropSetDto(properties); } public CurrentHistoCryptoRepoFile getCurrentHistoCryptoRepoFile() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null) return null; final CurrentHistoCryptoRepoFileDao chcrfDao = context.transaction.getDao(CurrentHistoCryptoRepoFileDao.class); final CurrentHistoCryptoRepoFile currentHistoCryptoRepoFile = chcrfDao.getCurrentHistoCryptoRepoFile(cryptoRepoFile); return currentHistoCryptoRepoFile; } /** * Creates a new current {@link HistoCryptoRepoFile} and assigns it as the current one. */ public HistoCryptoRepoFile createHistoCryptoRepoFileIfNeeded() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFileOrCreate(false); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); final CurrentHistoCryptoRepoFileDao chcrfDao = context.transaction.getDao(CurrentHistoCryptoRepoFileDao.class); final HistoCryptoRepoFileDao hcrfDao = context.transaction.getDao(HistoCryptoRepoFileDao.class); final HistoFrameDao hfDao = context.transaction.getDao(HistoFrameDao.class); final HistoFrame histoFrame = hfDao.getUnsealedHistoFrameOrFail(context.localRepositoryId); CurrentHistoCryptoRepoFile currentHistoCryptoRepoFile = chcrfDao.getCurrentHistoCryptoRepoFile(cryptoRepoFile); if (currentHistoCryptoRepoFile == null) { currentHistoCryptoRepoFile = new CurrentHistoCryptoRepoFile(); currentHistoCryptoRepoFile.setCryptoRepoFile(cryptoRepoFile); } final HistoCryptoRepoFile previousHistoCryptoRepoFile = currentHistoCryptoRepoFile.getHistoCryptoRepoFile(); HistoCryptoRepoFile histoCryptoRepoFile = null; Collection<HistoCryptoRepoFile> histoCryptoRepoFiles = hcrfDao.getHistoCryptoRepoFiles(cryptoRepoFile); for (HistoCryptoRepoFile hcrf : histoCryptoRepoFiles) { if (histoFrame.equals(hcrf.getHistoFrame())) { // createCollisionIfNeeded(histoCryptoRepoFile); // throw new IllegalStateException("xxx"); histoCryptoRepoFile = hcrf; // TODO is this the right strategy? Or should we better delete and recreate? I encountered this situation when aborting an up-sync and resuming later. // ... if https://github.com/subshare/subshare/issues/45 is fixed, now, then it can't be so wrong ;-) } } if (histoCryptoRepoFile == null) { histoCryptoRepoFile = new HistoCryptoRepoFile(); histoCryptoRepoFile.setCryptoRepoFile(cryptoRepoFile); histoCryptoRepoFile.setPreviousHistoCryptoRepoFile(previousHistoCryptoRepoFile); histoCryptoRepoFile.setHistoFrame(histoFrame); final Date deleted = cryptoRepoFile.getDeleted(); histoCryptoRepoFile.setDeleted(deleted); histoCryptoRepoFile.setDeletedByIgnoreRule(cryptoRepoFile.isDeletedByIgnoreRule()); final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); histoCryptoRepoFile.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); if (! cryptoKey.equals(cryptoRepoFile.getCryptoKey())) // sanity check: the key should not have changed inbetween! otherwise we might need a new CryptoChangeSet-upload to the server!!! throw new IllegalStateException(String.format("cryptoKey != cryptoRepoFile.cryptoKey :: %s != %s", cryptoKey, cryptoRepoFile.getCryptoKey())); final byte[] repoFileDtoData; if (deleted != null) // repoFileDtoData = getRepoFileDtoDataForDeletedCryptoRepoFile(previousHistoCryptoRepoFile); repoFileDtoData = context.repoFileDtoIo.serializeWithGz(assertNotNull(getRepoFileDto(), "getRepoFileDto()")); else repoFileDtoData = createRepoFileDtoDataForCryptoRepoFile(true); histoCryptoRepoFile.setRepoFileDtoData(assertNotNull(encrypt(repoFileDtoData, plainCryptoKey), "encrypt(...)")); histoCryptoRepoFile.setLastSyncFromRepositoryId(null); sign(histoCryptoRepoFile); histoCryptoRepoFile = hcrfDao.makePersistent(histoCryptoRepoFile); } currentHistoCryptoRepoFile.setHistoCryptoRepoFile(histoCryptoRepoFile); currentHistoCryptoRepoFile.setLastSyncFromRepositoryId(null); sign(currentHistoCryptoRepoFile); chcrfDao.makePersistent(currentHistoCryptoRepoFile); updatePlainHistoCryptoRepoFile(histoCryptoRepoFile); // createCollisionIfNeeded(histoCryptoRepoFile); context.transaction.flush(); // for early detection of an error return histoCryptoRepoFile; } public Collision createCollisionIfNeeded(final CryptoRepoFile duplicateCryptoRepoFile, final String localPath, boolean expectedSealedStatus) { final LocalRepoTransaction tx = context.transaction; final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); final CollisionDao cDao = tx.getDao(CollisionDao.class); final HistoCryptoRepoFileDao hcrfDao = tx.getDao(HistoCryptoRepoFileDao.class); final Collection<HistoCryptoRepoFile> histoCryptoRepoFiles = hcrfDao.getHistoCryptoRepoFiles(cryptoRepoFile); final HistoCryptoRepoFile localHistoCryptoRepoFile = getLastHistoCryptoRepoFile(histoCryptoRepoFiles, false); final HistoCryptoRepoFile remoteHistoCryptoRepoFile = getLastHistoCryptoRepoFile(histoCryptoRepoFiles, true); if (localHistoCryptoRepoFile != null) { if (localHistoCryptoRepoFile.getHistoFrame().getSealed() != null && expectedSealedStatus == false) { // https://github.com/subshare/subshare/issues/52 // Converted blocking error to warning, because this actually happened -- and I have no idea why :-( // ...and it isn't a serious problem, hence a warning is fine. IllegalStateException x = new IllegalStateException(String.format("Why is the local HistoFrame already sealed?!???!!! cryptoRepoFile=%s duplicateCryptoRepoFile=%s localPath=%s localHistoCryptoRepoFile=%s remoteHistoCryptoRepoFile=%s", cryptoRepoFile, duplicateCryptoRepoFile, localPath, localHistoCryptoRepoFile, remoteHistoCryptoRepoFile)); logger.warn("createCollisionIfNeeded: " + x.toString(), x); } if (localHistoCryptoRepoFile.getHistoFrame().getSealed() == null && expectedSealedStatus == true) throw new IllegalStateException("Why is the local HistoFrame not yet sealed?!???!!!"); } HistoCryptoRepoFile histoCryptoRepoFile1 = localHistoCryptoRepoFile; HistoCryptoRepoFile histoCryptoRepoFile2 = remoteHistoCryptoRepoFile; if (histoCryptoRepoFile1 == null) { histoCryptoRepoFile1 = histoCryptoRepoFile2; histoCryptoRepoFile2 = null; } assertNotNull(histoCryptoRepoFile1, "histoCryptoRepoFile1", "cryptoRepoFile=%s duplicateCryptoRepoFile=%s localPath=%s localHistoCryptoRepoFile=%s remoteHistoCryptoRepoFile=%s", cryptoRepoFile, duplicateCryptoRepoFile, localPath, localHistoCryptoRepoFile, remoteHistoCryptoRepoFile); if (duplicateCryptoRepoFile != null) { if (duplicateCryptoRepoFile.getCryptoRepoFileId().equals(getCryptoRepoFileId(histoCryptoRepoFile1))) { histoCryptoRepoFile1 = histoCryptoRepoFile2; histoCryptoRepoFile2 = null; } else if (histoCryptoRepoFile2 == null || duplicateCryptoRepoFile.getCryptoRepoFileId().equals(getCryptoRepoFileId(histoCryptoRepoFile2))) histoCryptoRepoFile2 = null; else { // throw new IllegalStateException("duplicateCryptoRepoFile neither matches histoCryptoRepoFile1 nor histoCryptoRepoFile2!\nduplicateCryptoRepoFile=" + duplicateCryptoRepoFile + "\nhistoCryptoRepoFile1=" + histoCryptoRepoFile1 + "\nhistoCryptoRepoFile2=" + histoCryptoRepoFile2); // https://github.com/subshare/subshare/issues/21 :: I think the above exception is nonsense. Instead we should just make sure // that histoCryptoRepoFile1 is the newer one, so that we use the newest. This scenario happens, if this sync+deduplication is // done on a computer that is *not* involved in any of the changes having caused the collision - which is a perfectly legal situation. if (histoCryptoRepoFile1.getSignature().getSignatureCreated().before(histoCryptoRepoFile2.getSignature().getSignatureCreated())) histoCryptoRepoFile1 = histoCryptoRepoFile2; histoCryptoRepoFile2 = null; } if (duplicateCryptoRepoFile.getCryptoRepoFileId().equals(getCryptoRepoFileId(histoCryptoRepoFile1))) throw new IllegalStateException("duplicateCryptoRepoFile matches histoCryptoRepoFile1!\nduplicateCryptoRepoFile=" + duplicateCryptoRepoFile + "\nhistoCryptoRepoFile1=" + histoCryptoRepoFile1 + "\nhistoCryptoRepoFile2=" + histoCryptoRepoFile2); } else { // assertNotNull(histoCryptoRepoFile2, "histoCryptoRepoFile2"); if (histoCryptoRepoFile2 == null) { IllegalStateException x = new IllegalStateException(String.format("duplicateCryptoRepoFile and histoCryptoRepoFile2 are both null!!! cryptoRepoFile=%s localPath=%s localHistoCryptoRepoFile=%s remoteHistoCryptoRepoFile=%s", cryptoRepoFile, localPath, localHistoCryptoRepoFile, remoteHistoCryptoRepoFile)); logger.warn("createCollisionIfNeeded: " + x.toString(), x); return null; } } assertNotNull(histoCryptoRepoFile1, "histoCryptoRepoFile1"); final Uid duplicateCryptoRepoFileId = duplicateCryptoRepoFile == null ? null : duplicateCryptoRepoFile.getCryptoRepoFileId(); Collision collision = cDao.getCollision(histoCryptoRepoFile1, histoCryptoRepoFile2, duplicateCryptoRepoFileId); if (collision == null) { collision = new Collision(); collision.setHistoCryptoRepoFile1(histoCryptoRepoFile1); collision.setHistoCryptoRepoFile2(histoCryptoRepoFile2); collision.setDuplicateCryptoRepoFileId(duplicateCryptoRepoFileId); putCollisionPrivateDto(collision, new CollisionPrivateDto()); // signs the Collision collision = cDao.makePersistent(collision); logger.info("createCollisionIfNeeded: localPath='{}' histoCryptoRepoFile1={} histoCryptoRepoFile2={} duplicateCryptoRepoFileId={} localRevision={}", localPath, histoCryptoRepoFile1, histoCryptoRepoFile2, duplicateCryptoRepoFileId, collision.getLocalRevision()); } updateCollisionPrivate(collision); context.transaction.flush(); // for early detection of an error return collision; } public void putCollisionPrivateDto(final Collision collision, final CollisionPrivateDto collisionPrivateDto) { assertNotNull(collision, "collision"); assertNotNull(collisionPrivateDto, "collisionPrivateDto"); if (collisionPrivateDto.getCollisionId() == null) collisionPrivateDto.setCollisionId(collision.getCollisionId()); else if (! collisionPrivateDto.getCollisionId().equals(collision.getCollisionId())) throw new IllegalArgumentException("collisionPrivateDto.collisionId != collision.collisionId"); final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); collision.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); final byte[] data = context.collisionPrivateDtoIo.serializeWithGz(collisionPrivateDto); collision.setCollisionPrivateDtoData(assertNotNull(encrypt(data, plainCryptoKey), "encrypt(...)")); sign(collision); updateCollisionPrivate(collision); } public CollisionPrivateDto getCollisionPrivateDto(final Collision collision) { assertNotNull(collision, "collision"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(collision.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The Collision with collisionId=%s could not be decrypted! Access rights missing?!", collision.getCollisionId())); final byte[] plainDtoData = assertNotNull(decrypt(collision.getCollisionPrivateDtoData(), plainCryptoKey), "decrypt(...)"); CollisionPrivateDto collisionPrivateDto = context.collisionPrivateDtoIo.deserializeWithGz(plainDtoData); return collisionPrivateDto; } private static Uid getCryptoRepoFileId(final HistoCryptoRepoFile histoCryptoRepoFile) { if (histoCryptoRepoFile == null) return null; return histoCryptoRepoFile.getCryptoRepoFile().getCryptoRepoFileId(); } // TODO replace this method by a specific, optimized query! private HistoCryptoRepoFile getLastHistoCryptoRepoFile(final Collection<HistoCryptoRepoFile> histoCryptoRepoFiles, boolean remote) { assertNotNull(histoCryptoRepoFiles, "histoCryptoRepoFiles"); final UUID localRepositoryId = context.transaction.getLocalRepoManager().getRepositoryId(); HistoCryptoRepoFile result = null; for (HistoCryptoRepoFile histoCryptoRepoFile : histoCryptoRepoFiles) { final HistoFrame histoFrame = histoCryptoRepoFile.getHistoFrame(); if (remote) { if (localRepositoryId.equals(histoFrame.getFromRepositoryId())) continue; } else { if (! localRepositoryId.equals(histoFrame.getFromRepositoryId())) continue; } if (result == null || result.getSignature().getSignatureCreated().compareTo(histoCryptoRepoFile.getSignature().getSignatureCreated()) < 0) result = histoCryptoRepoFile; } // if (result == null) // throw new IllegalStateException("No matching HistoCryptoRepoFile found!"); return result; } public CollisionPrivate updateCollisionPrivate(final Collision collision) { assertNotNull(collision, "collision"); if (! getCryptoRepoFile().equals(collision.getHistoCryptoRepoFile1().getCryptoRepoFile())) throw new IllegalArgumentException("this.cryptoRepoFile != collision.histoCryptoRepoFile1.cryptoRepoFile"); final CollisionPrivateDao cpDao = getContext().transaction.getDao(CollisionPrivateDao.class); CollisionPrivate cp = cpDao.getCollisionPrivate(collision); final CollisionPrivateDto collisionPrivateDto = tryDecryptCollisionPrivateDto(collision); if (collisionPrivateDto == null) { if (cp != null) cpDao.deletePersistent(cp); } else cp = CollisionPrivateDtoConverter.create(getContext().transaction).putCollisionPrivateDto(collision, collisionPrivateDto); updatePlainHistoCryptoRepoFile(collision.getHistoCryptoRepoFile1()); if (collision.getHistoCryptoRepoFile2() != null) { getContext().getCryptreeNodeOrCreate(collision.getHistoCryptoRepoFile2().getCryptoRepoFile().getCryptoRepoFileId()) .updatePlainHistoCryptoRepoFile(collision.getHistoCryptoRepoFile2()); } return cp; } public PlainHistoCryptoRepoFile updatePlainHistoCryptoRepoFile(final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final PlainHistoCryptoRepoFileDao phcrfDao = getContext().transaction.getDao(PlainHistoCryptoRepoFileDao.class); PlainHistoCryptoRepoFile phcrf = phcrfDao.getPlainHistoCryptoRepoFile(histoCryptoRepoFile); if (phcrf == null) { phcrf = new PlainHistoCryptoRepoFile(); phcrf.setHistoCryptoRepoFile(histoCryptoRepoFile); } phcrf.setPlainHistoCryptoRepoFileDto(createPlainHistoCryptoRepoFileDto(histoCryptoRepoFile)); phcrf = phcrfDao.makePersistent(phcrf); return phcrf; } /** * Creates a {@link PlainHistoCryptoRepoFileDto} which is then stored (as gzipped XML) in a {@link PlainHistoCryptoRepoFile}. * This allows for very fast loading of the history (there might be *many* items especially in the first HistoFrame). * @param histoCryptoRepoFile the {@link HistoCryptoRepoFile} to read and (try to) decrypt. Must not be <code>null</code>. * @return the {@link PlainHistoCryptoRepoFileDto} - never <code>null</code>. */ private PlainHistoCryptoRepoFileDto createPlainHistoCryptoRepoFileDto(final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final HistoCryptoRepoFileDtoConverter converter = HistoCryptoRepoFileDtoConverter.create(getContext().transaction); final PlainHistoCryptoRepoFileDto plainHistoCryptoRepoFileDto = new PlainHistoCryptoRepoFileDto(); plainHistoCryptoRepoFileDto.setHistoCryptoRepoFileDto(converter.toHistoCryptoRepoFileDto(histoCryptoRepoFile)); final Uid cryptoRepoFileId = histoCryptoRepoFile.getCryptoRepoFile().getCryptoRepoFileId(); plainHistoCryptoRepoFileDto.setCryptoRepoFileId(cryptoRepoFileId); final CryptoRepoFile parentCryptoRepoFile = histoCryptoRepoFile.getCryptoRepoFile().getParent(); plainHistoCryptoRepoFileDto.setParentCryptoRepoFileId(parentCryptoRepoFile == null ? null : parentCryptoRepoFile.getCryptoRepoFileId()); final RepoFileDto repoFileDto = tryDecryptHistoCryptoRepoFile(histoCryptoRepoFile); // if (repoFileDto instanceof SsNormalFileDto) // no need to store these *LARGE* details in the PlainHistoCryptoRepoFile. // ((SsNormalFileDto) repoFileDto).getFileChunkDtos().clear(); // YES, they ARE NEEDED! for the history export! plainHistoCryptoRepoFileDto.setRepoFileDto(repoFileDto); if (histoCryptoRepoFile.getDeleted() != null) plainHistoCryptoRepoFileDto.setAction(PlainHistoCryptoRepoFileDto.Action.DELETE); else if (histoCryptoRepoFile.getPreviousHistoCryptoRepoFile() == null || histoCryptoRepoFile.getPreviousHistoCryptoRepoFile().getDeleted() != null) plainHistoCryptoRepoFileDto.setAction(PlainHistoCryptoRepoFileDto.Action.ADD); else plainHistoCryptoRepoFileDto.setAction(PlainHistoCryptoRepoFileDto.Action.MODIFY); populateCollisionDtos(plainHistoCryptoRepoFileDto, histoCryptoRepoFile); return plainHistoCryptoRepoFileDto; } private void populateCollisionDtos(final PlainHistoCryptoRepoFileDto plainHistoCryptoRepoFileDto, final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final CollisionDao cDao = getContext().transaction.getDao(CollisionDao.class); final CollisionPrivateDao cpDao = getContext().transaction.getDao(CollisionPrivateDao.class); final CollisionDtoConverter collisionDtoConverter = CollisionDtoConverter.create(getContext().transaction); final CollisionPrivateDtoConverter cpDtoConverter = CollisionPrivateDtoConverter.create(getContext().transaction); final CollisionFilter collisionFilter = new CollisionFilter(); collisionFilter.setHistoCryptoRepoFileId(histoCryptoRepoFile.getHistoCryptoRepoFileId()); final Collection<Collision> collisions = cDao.getCollisions(collisionFilter); for (final Collision collision : collisions) { plainHistoCryptoRepoFileDto.getCollisionDtos().add(collisionDtoConverter.toCollisionDto(collision)); final CollisionPrivate collisionPrivate = cpDao.getCollisionPrivate(collision); if (collisionPrivate != null) plainHistoCryptoRepoFileDto.getCollisionPrivateDtos().add(cpDtoConverter.toCollisionPrivateDto(collisionPrivate)); } } private RepoFileDto tryDecryptHistoCryptoRepoFile(final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); RepoFileDto repoFileDto = null; try { repoFileDto = getHistoCryptoRepoFileRepoFileDto(histoCryptoRepoFile); } catch (ReadAccessDeniedException x) { if (logger.isDebugEnabled()) logger.info("tryDecryptHistoCryptoRepoFile: " + x, x); else logger.info("tryDecryptHistoCryptoRepoFile: " + x); } return repoFileDto; } private CollisionPrivateDto tryDecryptCollisionPrivateDto(final Collision collision) { assertNotNull(collision, "collision"); CollisionPrivateDto collisionPrivateDto = null; try { collisionPrivateDto = getCollisionPrivateDto(collision); } catch (ReadAccessDeniedException x) { if (logger.isDebugEnabled()) logger.info("tryDecryptCollisionPrivateDto: " + x, x); else logger.info("tryDecryptCollisionPrivateDto: " + x); } return collisionPrivateDto; } // private byte[] getRepoFileDtoDataForDeletedCryptoRepoFile(final HistoCryptoRepoFile previousHistoCryptoRepoFile) { // // previousHistoCryptoRepoFile may be null, if it was never completely uploaded - hmmmm... why don't we *always* use the info from getRepoFileDto()?! // // final RepoFileDto repoFileDto = previousHistoCryptoRepoFile == null ? getRepoFileDto() : getHistoCryptoRepoFileRepoFileDto(previousHistoCryptoRepoFile); // if (repoFileDto instanceof SsDirectoryDto) // ; // nothing to do // else if (repoFileDto instanceof SsNormalFileDto) { // SsNormalFileDto normalFileDto = (SsNormalFileDto) repoFileDto; // normalFileDto.setFileChunkDtos(null); // normalFileDto.setTempFileChunkDtos(null); // they should always be null, anyway. // } // else if (repoFileDto instanceof SsSymlinkDto) // ; // nothing to do // else // throw new IllegalStateException("Unexpected repoFileDto type: " + repoFileDto); // // return serializeRepoFileDto(repoFileDto); // } private void grantReadPermission(final UserRepoKey.PublicKey publicKey) { assertNotNull(publicKey, "publicKey"); // TODO Make sure previously invisible sub-directories & files pop up in the client repositories! // If we grant access to a sub-directory later (either by (re)enabling the inheritance here or by // explicitly granting read access), the sub-directory (and all files) are not modified and therefore // are normally not synced (again). We somehow need to make sure that they indeed are re-synced. final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks( getCryptoRepoFileOrCreate(false), CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey); if (containsFromUserRepoKeyId(cryptoLinks, Collections.singleton(publicKey.getUserRepoKeyId()))) return; // There is already an active key which is accessible to the given user. Thus no need to generate a new crypto-link. final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.clearanceKey, CipherOperationMode.DECRYPT); createCryptoLink(this, getUserRepoKeyPublicKeyOrCreate(publicKey), plainCryptoKey); } private RepoFileDtoConverter getRepoFileDtoConverter() { if (repoFileDtoConverter == null) repoFileDtoConverter = RepoFileDtoConverter.create(context.transaction); repoFileDtoConverter.setExcludeLocalIds(false); repoFileDtoConverter.setExcludeMutableData(false); return repoFileDtoConverter; } private byte[] createRepoFileDtoDataForCryptoRepoFile(final boolean forHisto) { // TODO can we assert here, that this code is invoked on the client-side with the plain-text RepoFile?! final RepoFileDtoConverter repoFileDtoConverter = getRepoFileDtoConverter(); // No need for local IDs. Because this DTO is shared across all repositories, local IDs make no sense. repoFileDtoConverter.setExcludeLocalIds(true); // Erase information like last-modified, hash and length, if not used in HistoCryptoRepoFile! repoFileDtoConverter.setExcludeMutableData(! forHisto); final RepoFileDto repoFileDto = repoFileDtoConverter.toRepoFileDto(repoFile, forHisto ? Integer.MAX_VALUE : 0); ((SsRepoFileDto) repoFileDto).setParentName(null); // only needed for uploading to the server. if (((SsRepoFileDto) repoFileDto).getSignature() != null) // must be null on the client - and this method is never called on the server. throw new IllegalStateException("repoFileDto.signature != null"); // Prevent overriding the real name with "", if we checked out a sub-directory. In this case, we cannot // change the localName locally and must make sure, it is preserved. if (cryptoRepoFile.getLocalName() == null || repoFile.getParent() != null) cryptoRepoFile.setLocalName(repoFileDto.getName()); else repoFileDto.setName(cryptoRepoFile.getLocalName()); return context.repoFileDtoIo.serializeWithGz(repoFileDto); } private void revokeReadPermission(final Set<Uid> userRepoKeyIds) { assertNotNull(userRepoKeyIds, "userRepoKeyIds"); if (userRepoKeyIds.isEmpty()) return; final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null) return; // There is no CryptoRepoFile, thus there can be no read-access which could be revoked. final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks( cryptoRepoFile, CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey); if (! containsFromUserRepoKeyId(cryptoLinks, userRepoKeyIds)) return; // There is no active key which is accessible to any of the given users. Thus no need to generate a new key. // There should be only one single *active* key, but due to collisions (multiple repos grant the same user // access), it might happen, that there are multiple. We therefore de-activate all we find. final Set<CryptoKey> processedCryptoKeys = new HashSet<CryptoKey>(); for (final CryptoLink cryptoLink : cryptoLinks) deactivateCryptoKeyAndDescendants(cryptoLink.getToCryptoKey(), processedCryptoKeys); // likely the same CryptoKey for all cryptoLinks => deduplicate via Set // Make sure the changes are written to the DB, so that a new active clearance key is generated in the following. context.transaction.flush(); // Create a *new* clearance key *immediately*, but only if needed. PlainCryptoKey clearanceKeyPlainCryptoKey = null; // And grant read access to everyone except for the users that should be removed. for (final CryptoLink cryptoLink : cryptoLinks) { final UserRepoKeyPublicKey fromUserRepoKeyPublicKey = cryptoLink.getFromUserRepoKeyPublicKey(); final Uid fromUserRepoKeyId = fromUserRepoKeyPublicKey == null ? null : fromUserRepoKeyPublicKey.getUserRepoKeyId(); if (fromUserRepoKeyId == null || userRepoKeyIds.contains(fromUserRepoKeyId)) continue; if (clearanceKeyPlainCryptoKey == null) clearanceKeyPlainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.clearanceKey, CipherOperationMode.DECRYPT); // The current user is already granted access when the clearing key was created above. // We thus need to check, if the current fromUserRepoKeyPublicKey still needs a CryptoLink. if (fromUserRepoKeyPublicKey != null && ! cryptoLinkDao.getActiveCryptoLinks( cryptoRepoFile, CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey, fromUserRepoKeyPublicKey).isEmpty()) continue; createCryptoLink(this, fromUserRepoKeyPublicKey, clearanceKeyPlainCryptoKey); } if (clearanceKeyPlainCryptoKey != null) createBacklinkKeyForFile(); createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively(); // createBacklinkKeyIfNeededParentsRecursively(); } private void createBacklinkKeyForFile() { if (! isDirectory()) getActivePlainCryptoKeyOrCreate(CryptoKeyRole.backlinkKey, CipherOperationMode.DECRYPT); } private void deactivateCryptoKeyAndDescendants(final CryptoKey cryptoKey, final Set<CryptoKey> processedCryptoKeys) { if (! processedCryptoKeys.add(cryptoKey)) return; if (cryptoKey.getCryptoKeyDeactivation() == null) deactivateCryptoKey(cryptoKey); for (final CryptoLink cryptoLink : cryptoKey.getOutCryptoLinks()) deactivateCryptoKeyAndDescendants(cryptoLink.getToCryptoKey(), processedCryptoKeys); } private void deactivateCryptoKey(final CryptoKey cryptoKey) { final CryptoKeyDeactivation cryptoKeyDeactivation = new CryptoKeyDeactivation(); cryptoKeyDeactivation.setCryptoKey(cryptoKey); sign(cryptoKeyDeactivation); cryptoKey.setCryptoKeyDeactivation(cryptoKeyDeactivation); cryptoKey.setLastSyncFromRepositoryId(null); } private void createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively() { // Only directories have a subdirKey (and further children). The backlinkKeys of the files // are optional and didn't get dirty, because they are not in the CryptoLink-chain of the parent. // The backlinkKey only got dirty, if this is a file. We handle this separately in // createBacklinkKeyIfNeededFile(). if (! isDirectory()) return; getActivePlainCryptoKeyOrCreate(CryptoKeyRole.subdirKey, CipherOperationMode.DECRYPT); getActivePlainCryptoKeyOrCreate(CryptoKeyRole.backlinkKey, CipherOperationMode.DECRYPT); for (final CryptreeNode child : getChildren()) child.createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively(); } // private void createBacklinkKeyIfNeededParentsRecursively() { // // If this is a file, the backlinkKey is optional - and created in createBacklinkKeyIfNeededFile(). // if (isDirectory()) // getActivePlainCryptoKeyOrCreate(CryptoKeyRole.backlinkKey, CryptoKeyPart.sharedSecret); // // final CryptreeNode parent = getParent(); // if (parent != null) // parent.createBacklinkKeyIfNeededParentsRecursively(); // } private boolean containsFromUserRepoKeyId(final Collection<CryptoLink> cryptoLinks, final Set<Uid> fromUserRepoKeyIds) { assertNotNull(cryptoLinks, "cryptoLinks"); assertNotNull(fromUserRepoKeyIds, "fromUserRepoKeyIds"); for (final CryptoLink cryptoLink : cryptoLinks) { final UserRepoKeyPublicKey fromUserRepoKeyPublicKey = cryptoLink.getFromUserRepoKeyPublicKey(); final Uid fromUserRepoKeyId = fromUserRepoKeyPublicKey == null ? null : fromUserRepoKeyPublicKey.getUserRepoKeyId(); if (fromUserRepoKeyId != null && fromUserRepoKeyIds.contains(fromUserRepoKeyId)) return true; } return false; } public Collection<CryptreeNode> getChildren() { if (! childrenLoaded) { if (cryptoRepoFile != null) { final CryptoRepoFileDao dao = context.transaction.getDao(CryptoRepoFileDao.class); final Collection<CryptoRepoFile> childCryptoRepoFiles = dao.getChildCryptoRepoFiles(cryptoRepoFile); for (final CryptoRepoFile childCryptoRepoFile : childCryptoRepoFiles) children.add(context.getCryptreeNodeOrCreate(this, null, null, childCryptoRepoFile)); } else if (repoFile != null) { final RepoFileDao dao = context.transaction.getDao(RepoFileDao.class); final Collection<RepoFile> childRepoFiles = dao.getChildRepoFiles(repoFile); for (final RepoFile childRepoFile : childRepoFiles) children.add(context.getCryptreeNodeOrCreate(this, null, childRepoFile, null)); } else throw new IllegalStateException("repoFile == null && cryptoRepoFile == null"); childrenLoaded = true; } return Collections.unmodifiableList(children); } protected boolean isDirectory() { if (repoFile != null) return repoFile instanceof Directory; return cryptoRepoFile.isDirectory(); } protected PlainCryptoKey getActivePlainCryptoKey(final CryptoKeyRole toCryptoKeyRole, final CipherOperationMode cipherOperationMode) { assertNotNull(toCryptoKeyRole, "toCryptoKeyRole"); assertNotNull(cipherOperationMode, "cipherOperationMode"); logger.debug("getActivePlainCryptoKey: cryptoRepoFile={} repoFile={} toCryptoKeyRole={} cipherOperationMode={}", cryptoRepoFile, repoFile, toCryptoKeyRole, cipherOperationMode); final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final CryptoKeyPart[] toCryptoKeyParts = toCryptoKeyRole.getCryptoKeyParts(cipherOperationMode); for (final CryptoKeyPart toCryptoKeyPart : toCryptoKeyParts) { final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks(getCryptoRepoFile(), toCryptoKeyRole, toCryptoKeyPart); final PlainCryptoKey plainCryptoKey = getPlainCryptoKey(cryptoLinks, toCryptoKeyPart); if (plainCryptoKey != null) return plainCryptoKey; } return null; } public PlainCryptoKey getPlainCryptoKeyForDecrypting(final CryptoKey cryptoKey) { assertNotNull(cryptoKey, "cryptoKey"); logger.debug("getPlainCryptoKeyForDecrypting: cryptoRepoFile={} repoFile={} cryptoKey={}", cryptoRepoFile, repoFile, cryptoKey); final PlainCryptoKey plainCryptoKey = getPlainCryptoKey(cryptoKey.getInCryptoLinks(), getCryptoKeyPartForDecrypting(cryptoKey)); return plainCryptoKey; // may be null! } private PlainCryptoKey getPlainCryptoKey(final Collection<CryptoLink> cryptoLinks, final CryptoKeyPart toCryptoKeyPart) { assertNotNull(cryptoLinks, "cryptoLinks"); assertNotNull(toCryptoKeyPart, "toCryptoKeyPart"); for (final CryptoLink cryptoLink : cryptoLinks) { if (toCryptoKeyPart != cryptoLink.getToCryptoKeyPart()) continue; final UserRepoKeyPublicKey fromUserRepoKeyPublicKey = cryptoLink.getFromUserRepoKeyPublicKey(); if (fromUserRepoKeyPublicKey != null) { logger.debug("getPlainCryptoKey: >>> cryptoRepoFile={} repoFile={} cryptoLink={} fromUserRepoKeyPublicKey={}", cryptoRepoFile, repoFile, cryptoLink, fromUserRepoKeyPublicKey); final Uid userRepoKeyId = fromUserRepoKeyPublicKey.getUserRepoKeyId(); final UserRepoKey userRepoKey = context.userRepoKeyRing.getUserRepoKey(userRepoKeyId); if (userRepoKey != null) { logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromUserRepoKeyPublicKey={}: DECRYPTED!", cryptoRepoFile, repoFile, cryptoLink, fromUserRepoKeyPublicKey); final byte[] plain = decryptLarge(cryptoLink.getToCryptoKeyData(), userRepoKey); return new PlainCryptoKey(cryptoLink.getToCryptoKey(), cryptoLink.getToCryptoKeyPart(), plain); } else logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromUserRepoKeyPublicKey={}: FAILED TO DECRYPT!", cryptoRepoFile, repoFile, cryptoLink, fromUserRepoKeyPublicKey); } else if (cryptoLink.getFromCryptoKey() == null) { // *not* encrypted logger.debug("getPlainCryptoKey: *** cryptoRepoFile={} repoFile={} cryptoLink={}: PLAIN!", cryptoRepoFile, repoFile, cryptoLink); return new PlainCryptoKey(cryptoLink.getToCryptoKey(), cryptoLink.getToCryptoKeyPart(), cryptoLink.getToCryptoKeyData()); } } for (final CryptoLink cryptoLink : cryptoLinks) { if (toCryptoKeyPart != cryptoLink.getToCryptoKeyPart()) continue; final CryptoKey fromCryptoKey = cryptoLink.getFromCryptoKey(); if (fromCryptoKey != null) { logger.debug("getPlainCryptoKey: >>> cryptoRepoFile={} repoFile={} cryptoLink={} fromCryptoKey={}", cryptoRepoFile, repoFile, cryptoLink, fromCryptoKey); final PlainCryptoKey plainFromCryptoKey = getPlainCryptoKey( fromCryptoKey.getInCryptoLinks(), getCryptoKeyPartForDecrypting(fromCryptoKey)); if (plainFromCryptoKey != null) { logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromCryptoKey={}: DECRYPTED!", cryptoRepoFile, repoFile, cryptoLink, fromCryptoKey); final byte[] plain = decrypt( cryptoLink.getToCryptoKeyData(), plainFromCryptoKey); return new PlainCryptoKey(cryptoLink.getToCryptoKey(), cryptoLink.getToCryptoKeyPart(), plain); } else logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromCryptoKey={}: FAILED TO DECRYPT!", cryptoRepoFile, repoFile, cryptoLink, fromCryptoKey); } } return null; } private CryptoKeyPart getCryptoKeyPartForDecrypting(final CryptoKey cryptoKey) { switch (cryptoKey.getCryptoKeyType()) { case asymmetric: return CryptoKeyPart.privateKey; case symmetric: return CryptoKeyPart.sharedSecret; default: throw new IllegalStateException("Unknown cryptoKey.cryptoKeyType: " + cryptoKey.getCryptoKeyType()); } } protected PlainCryptoKey getActivePlainCryptoKeyOrCreate(final CryptoKeyRole toCryptoKeyRole, final CipherOperationMode cipherOperationMode) { assertNotNull(toCryptoKeyRole, "toCryptoKeyRole"); assertNotNull(cipherOperationMode, "cipherOperationMode"); PlainCryptoKey plainCryptoKey = getActivePlainCryptoKey(toCryptoKeyRole, cipherOperationMode); if (plainCryptoKey == null) { final Class<? extends PlainCryptoKeyFactory> clazz = cryptoKeyRole2PlainCryptoKeyFactory.get(toCryptoKeyRole); assertNotNull(clazz, String.format("cryptoKeyRole2PlainCryptoKeyFactory[%s]", toCryptoKeyRole)); final PlainCryptoKeyFactory factory; try { factory = clazz.newInstance(); } catch (final Exception e) { throw new RuntimeException(String.format("Creating new instance of class %s failed: %s", clazz.getName(), e), e); } factory.setCryptreeNode(this); factory.setCipherOperationMode(cipherOperationMode); plainCryptoKey = factory.createPlainCryptoKey(); assertNotNull(plainCryptoKey, clazz.getName() + ".createPlainCryptoKey()"); if (plainCryptoKey.getCryptoKey().getCryptoKeyRole() != toCryptoKeyRole) throw new IllegalStateException(String.format("plainCryptoKey.cryptoKey.cryptoKeyRole != toCryptoKeyRole :: %s != %s", plainCryptoKey.getCryptoKey().getCryptoKeyRole(), toCryptoKeyRole)); final CryptoKeyDao cryptoKeyDao = context.transaction.getDao(CryptoKeyDao.class); final CryptoKey cryptoKey = cryptoKeyDao.makePersistent(plainCryptoKey.getCryptoKey()); plainCryptoKey = new PlainCryptoKey(cryptoKey, plainCryptoKey.getCryptoKeyPart(), plainCryptoKey.getCipherParameters()); } return plainCryptoKey; } /** * Gets the current data key as indicated by {@link CryptoRepoFile#getCryptoKey()}. * @return the current data key. Never <code>null</code>. */ public DataKey getDataKeyOrFail() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); return getDataKeyOrFail(cryptoRepoFile.getCryptoKey()); } /** * Gets the data key identified by the given {@ code cryptoKeyId}. * @param cryptoKeyId the unique ID of the {@link CryptoKey} from which to extract the plain key material. * @return the data key. Never <code>null</code>. */ public DataKey getDataKeyOrFail(final Uid cryptoKeyId) { assertNotNull(cryptoKeyId, "cryptoKeyId"); final CryptoKeyDao cryptoKeyDao = context.transaction.getDao(CryptoKeyDao.class); final CryptoKey cryptoKey = cryptoKeyDao.getCryptoKeyOrFail(cryptoKeyId); return getDataKeyOrFail(cryptoKey); } protected DataKey getDataKeyOrFail(final CryptoKey cryptoKey) { assertNotNull(cryptoKey, "cryptoKey"); // We can use the following method, because it's *symmetric* - thus it works for both decrypting and encrypting! final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(cryptoKey); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("Cannot decrypt dataKey for cryptoKeyID=%s (cryptoRepoFileId=%s)!", cryptoKey.getCryptoKeyId(), cryptoKey.getCryptoRepoFile().getCryptoRepoFileId())); assertNotNull(plainCryptoKey.getCryptoKey(), "plainCryptoKey.cryptoKey"); if (CryptoKeyRole.dataKey != plainCryptoKey.getCryptoKey().getCryptoKeyRole()) throw new IllegalStateException("CryptoKeyRole.dataKey != plainCryptoKey.getCryptoKey().getCryptoKeyRole()"); if (CryptoKeyPart.sharedSecret != plainCryptoKey.getCryptoKeyPart()) throw new IllegalStateException("CryptoKeyPart.sharedSecret != plainCryptoKey.getCryptoKeyPart()"); return new DataKey(cryptoKey.getCryptoKeyId(), plainCryptoKey.getKeyParameterOrFail()); } public CryptreeNode getParent() { if (parent == null) { if (repoFile != null && JDOHelper.isDeleted(repoFile)) { getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); } final RepoFile parentRepoFile = repoFile == null || JDOHelper.isDeleted(repoFile) ? null : repoFile.getParent(); final CryptoRepoFile parentCryptoRepoFile = cryptoRepoFile == null ? null : cryptoRepoFile.getParent(); if (parentRepoFile != null || parentCryptoRepoFile != null) parent = context.getCryptreeNodeOrCreate(null, this, parentRepoFile, parentCryptoRepoFile); } return parent; } public UserRepoKeyPublicKey getUserRepoKeyPublicKeyOrCreate(final UserRepoKey userRepoKey) { assertNotNull(userRepoKey, "userRepoKey"); return getUserRepoKeyPublicKeyOrCreate(userRepoKey.getPublicKey()); } public UserRepoKeyPublicKey getUserRepoKeyPublicKeyOrCreate(final UserRepoKey.PublicKey publicKey) { assertNotNull(publicKey, "publicKey"); return new UserRepoKeyPublicKeyHelper(getContext()).getUserRepoKeyPublicKeyOrCreate(publicKey); } /** * Grant a permission on the directory/file represented by this node. * <p> * <p> * If there is nothing to be granted, this method is a noop. * <p> * Or in other words: * If the user (more specifically, his repository-dependent {@code publicKey}) already has the permission * which is to be granted, this method returns silently without any effect. * @param permissionType the type of the permission to be granted. Must not be <code>null</code>. * @param publicKey the user's repository-dependent public-key. Must not be <code>null</code>. * @see #getGrantedPermissionTypes(Uid) * @see #revokePermission(PermissionType, Set) */ public void grantPermission(final PermissionType permissionType, final UserRepoKey.PublicKey publicKey) { assertNotNull(permissionType, "permissionType"); assertNotNull(publicKey, "publicKey"); if (isOwner(publicKey.getUserRepoKeyId())) return; // the owner always has all permissions - no need to grant anything! if (PermissionType.readUserIdentity == permissionType) { final CryptreeNode parent = getParent(); if (parent != null) { parent.grantPermission(permissionType, publicKey); return; } } // It is technically required to have read permission, when having write or grant permission. Therefore, // we simply grant it here. if (permissionType == PermissionType.read || permissionType == PermissionType.write || permissionType == PermissionType.grant) grantReadPermission(publicKey); if (PermissionType.read == permissionType) return; final Uid ownerUserRepoKeyId = context.getRepositoryOwnerOrFail().getUserRepoKeyPublicKey().getUserRepoKeyId(); if (ownerUserRepoKeyId.equals(publicKey.getUserRepoKeyId())) return; // It is technically required to have write permission, when having grant permission. Therefore, we // grant it here, too. Additionally, we grant readUserIdentity permission, as it makes no sense to manage // users, i.e. grant access to them, without seeing them ;-) if (PermissionType.grant == permissionType) { grantPermission(PermissionType.write, publicKey); grantPermission(PermissionType.readUserIdentity, publicKey); } final PermissionSet permissionSet = getPermissionSetOrCreate(); final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final UserRepoKeyPublicKey userRepoKeyPublicKey = getUserRepoKeyPublicKeyOrCreate(publicKey); final Collection<Permission> permissions = dao.getNonRevokedPermissions(permissionSet, permissionType, userRepoKeyPublicKey); if (permissions.isEmpty()) { Permission permission = new Permission(); permission.setPermissionSet(permissionSet); permission.setPermissionType(permissionType); permission.setUserRepoKeyPublicKey(userRepoKeyPublicKey); sign(permission); permission = dao.makePersistent(permission); assertPermissionOk(permission); } if (PermissionType.grant == permissionType) ensureParentHasAsymmetricActiveSubdirKey(); if (PermissionType.readUserIdentity == permissionType) createUserIdentityLinksVisibleFor(userRepoKeyPublicKey); } public void setPermissionsInherited(final boolean inherited) { if (inherited == isPermissionsInherited()) return; final PermissionSet permissionSet = getPermissionSetOrCreate(); if (inherited) { // TODO Make sure previously invisible sub-directories & files pop up in the client repositories! // If we grant access to a sub-directory later (either by (re)enabling the inheritance here or by // explicitly granting read access), the sub-directory (and all files) are not modified and therefore // are normally not synced (again). We somehow need to make sure that they indeed are re-synced. final PermissionSetInheritance permissionSetInheritance = new PermissionSetInheritance(); permissionSetInheritance.setPermissionSet(permissionSet); sign(permissionSetInheritance); permissionSet.getPermissionSetInheritances().add(permissionSetInheritance); } else { final RepositoryOwner repositoryOwner = context.getRepositoryOwnerOrFail(); final PublicKey ownerPublicKey = repositoryOwner.getUserRepoKeyPublicKey().getPublicKey(); grantReadPermission(ownerPublicKey); final boolean currentUserIsOwner = context.userRepoKeyRing.getUserRepoKey(ownerPublicKey.getUserRepoKeyId()) != null; if (! currentUserIsOwner) { // TODO since the inheritance is interrupted, the current user does not have grant access anymore. // We need to either extend the grant access chain (better) or make this operation only available to the owner. logger.warn("This is not yet cleanly implemented and likely causes an error.", new UnsupportedOperationException("NYI")); } for (final PermissionSetInheritance permissionSetInheritance : permissionSet.getPermissionSetInheritances()) { if (permissionSetInheritance.getRevoked() == null) { permissionSetInheritance.setRevoked(new Date()); sign(permissionSetInheritance); } } // There should be only one single *active* key, but due to collisions (multiple repos grant the same user // access), it might happen, that there are multiple. We therefore de-activate all we find. final Set<CryptoKey> processedCryptoKeys = new HashSet<CryptoKey>(); final Collection<CryptoKey> subdirKeys = context.transaction.getDao(CryptoKeyDao.class).getActiveCryptoKeys(getCryptoRepoFileOrCreate(false), CryptoKeyRole.subdirKey); for (final CryptoKey subdirKey : subdirKeys) deactivateCryptoKeyAndDescendants(subdirKey, processedCryptoKeys); // createBacklinkKeyForFile(); // TODO do we need this - especially for the children? createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively(); } } public boolean isPermissionsInherited() { final PermissionSet permissionSet = getPermissionSet(); if (permissionSet == null) return true; // This method is for the UI, hence we use the revoked state - not the validTo. for (final PermissionSetInheritance permissionSetInheritance : permissionSet.getPermissionSetInheritances()) { if (permissionSetInheritance.getRevoked() == null) return true; } return false; } private void ensureParentHasAsymmetricActiveSubdirKey() { final CryptreeNode parent = getParent(); final CryptoRepoFile parentCryptoRepoFile = parent == null ? null : parent.getCryptoRepoFileOrCreate(false); if (parentCryptoRepoFile == null) return; final CryptoKeyDao cryptoKeyDao = context.transaction.getDao(CryptoKeyDao.class); final Collection<CryptoKey> activeSubdirKeys = cryptoKeyDao.getActiveCryptoKeys(parentCryptoRepoFile, CryptoKeyRole.subdirKey); boolean hasAsymmetryActiveSubdirKey = false; for (final CryptoKey activeSubdirKey : activeSubdirKeys) { switch (activeSubdirKey.getCryptoKeyType()) { case asymmetric: hasAsymmetryActiveSubdirKey = true; break; case symmetric: deactivateCryptoKey(activeSubdirKey); break; default: throw new IllegalStateException("Unknown CryptoKeyType: " + activeSubdirKey.getCryptoKeyType()); } } if (! hasAsymmetryActiveSubdirKey) parent.getActivePlainCryptoKeyOrCreate(CryptoKeyRole.subdirKey, CipherOperationMode.DECRYPT); } /** * Revoke a permission on the directory/file represented by this node. * <p> * If there is nothing to be revoked, this method is a noop. * <p> * Or in other words: * If none of the users (more specifically, their repository-dependent keys) have the permission which is * to be revoked, this method returns silently without any effect. The same happens when the {@code userRepoKeyIds} * is empty. * @param permissionType the type of the permission to be revoked. Must not be <code>null</code>. * @param userRepoKeyIds identifiers of all those keys from which to revoke the permission. Must not be <code>null</code>. * May be empty, which causes this method to return without any effect. * @see #getGrantedPermissionTypes(Uid) * @see #grantPermission(PermissionType, PublicKey) */ public void revokePermission(final PermissionType permissionType, final Set<Uid> userRepoKeyIds) { assertNotNull(permissionType, "permissionType"); assertNotNull(userRepoKeyIds, "userRepoKeyIds"); if (PermissionType.readUserIdentity == permissionType) { final CryptreeNode parent = getParent(); if (parent != null) { parent.revokePermission(permissionType, userRepoKeyIds); return; } // Revoke grant permission - technically not really needed but it makes no sense to manage invisible/unknown users. revokeGrantPermissionOfAllCryptoRepoFiles(userRepoKeyIds); } if (PermissionType.read == permissionType) { // Since it is technically required to have read permission, when having write or grant permission, we // revoke grant and write permission, too. revokePermission(PermissionType.write, userRepoKeyIds); // revokePermission(PermissionType.grant, userRepoKeyIds); // is implicitly done by revoking 'write' permission. revokeReadPermission(userRepoKeyIds); return; } if (PermissionType.write == permissionType) { // grant requires write, hence we must revoke grant, too, if we want to revoke write. revokePermission(PermissionType.grant, userRepoKeyIds); } final PermissionSet permissionSet = getPermissionSet(); if (permissionSet == null) return; final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final Collection<Permission> permissions = dao.getNonRevokedPermissions(permissionSet, permissionType, userRepoKeyIds); for (final Permission permission : permissions) { permissionsAlreadyCheckedOk.remove(permission); permission.setRevoked(new Date()); sign(permission); assertPermissionOk(permission); } if (PermissionType.readUserIdentity == permissionType) { if (existsAtLeastOneUserIdentityLinkFor(userRepoKeyIds)) new UserRepoKeyPublicKeyHelper(getContext()).removeUserIdentityLinksAfterRevokingReadUserIdentityPermission(); } } /** * Gets the {@link PermissionType}s granted to the directory/file represented by this node. * <p> * <b>Important:</b> In contrast to {@link #assertHasPermission(boolean, Uid, PermissionType, Date) assertHasPermission(...)} this * method operates on the current node, only! It does not take parents / inheritance into account. * <p> * <b>Important:</b> If the specified user has {@link PermissionType#readUserIdentity readUserIdentity}, this * {@code PermissionType} is always part of the result, no matter on which node this method is invoked! This is, * because {@code readUserIdentity} is not associated with a directory - it's global! Technically, it is assigned * to the root (at least right now - this might change later), but semantically, it is not associated with any. * * @param userRepoKeyId the user-key's identifier for which to determine the permissions granted. * @return the {@link PermissionType}s assigned to this node. Never <code>null</code>, but maybe empty! * @see #grantPermission(PermissionType, PublicKey) * @see #revokePermission(PermissionType, Set) * @see #assertHasPermission(boolean, Uid, PermissionType, Date) */ public Set<PermissionType> getGrantedPermissionTypes(final Uid userRepoKeyId) { assertNotNull(userRepoKeyId, "userRepoKeyId"); final Set<PermissionType> result = EnumSet.noneOf(PermissionType.class); if (isOwner(userRepoKeyId)) // the owner has *all* permissions - always! result.addAll(Arrays.asList(PermissionType.values())); else { final PermissionDao pDao = context.transaction.getDao(PermissionDao.class); if (! pDao.getNonRevokedPermissions(PermissionType.readUserIdentity, userRepoKeyId).isEmpty()) result.add(PermissionType.readUserIdentity); final PermissionSet permissionSet = getPermissionSet(); if (permissionSet != null) { if (! pDao.getNonRevokedPermissions(permissionSet, PermissionType.grant, userRepoKeyId).isEmpty()) result.add(PermissionType.grant); if (! pDao.getNonRevokedPermissions(permissionSet, PermissionType.write, userRepoKeyId).isEmpty()) result.add(PermissionType.write); } if (hasReadPermissionHere(userRepoKeyId)) result.add(PermissionType.read); } return result; } private boolean hasReadPermissionHereOrInherited(final Uid userRepoKeyId) { if (hasReadPermissionHere(userRepoKeyId)) return true; if (isPermissionsInherited()) { final CryptreeNode parent = getParent(); if (parent != null) return parent.hasReadPermissionHereOrInherited(userRepoKeyId); } return false; } private boolean hasReadPermissionHere(final Uid userRepoKeyId) { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile != null) { // If there is no CryptoRepoFile, there can be no read-access. final UserRepoKeyPublicKeyDao urkpkDao = context.transaction.getDao(UserRepoKeyPublicKeyDao.class); final UserRepoKeyPublicKey userRepoKeyPublicKey = urkpkDao.getUserRepoKeyPublicKey(userRepoKeyId); if (userRepoKeyPublicKey != null) { // if there is no UserRepoKeyPublicKey, there can be no read-access! final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks( cryptoRepoFile, CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey, userRepoKeyPublicKey); if (! cryptoLinks.isEmpty()) return true; } } return false; } private void createUserIdentityLinksVisibleFor(final UserRepoKeyPublicKey userRepoKeyPublicKey) { // Not necessary, because UserRepoKeyPublicKeyHelper.createMissingUserIdentities() is invoked in every sync. } private boolean existsAtLeastOneUserIdentityLinkFor(final Set<Uid> userRepoKeyIds) { assertNotNull(userRepoKeyIds, "userRepoKeyIds"); final UserRepoKeyPublicKeyDao urkpkDao = getContext().transaction.getDao(UserRepoKeyPublicKeyDao.class); final UserIdentityLinkDao uilDao = getContext().transaction.getDao(UserIdentityLinkDao.class); for (Uid userRepoKeyId : userRepoKeyIds) { final UserRepoKeyPublicKey forUserRepoKeyPublicKey = urkpkDao.getUserRepoKeyPublicKeyOrFail(userRepoKeyId); final Collection<UserIdentityLink> userIdentityLinks = uilDao.getUserIdentityLinksFor(forUserRepoKeyPublicKey); if (! userIdentityLinks.isEmpty()) return true; } return false; } private void revokeGrantPermissionOfAllCryptoRepoFiles(final Set<Uid> userRepoKeyIds) { assertNotNull(userRepoKeyIds, "userRepoKeyIds"); final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final Set<CryptoRepoFile> cryptoRepoFiles = new HashSet<>(); final Collection<Permission> permissions = dao.getNonRevokedPermissions(PermissionType.grant, userRepoKeyIds); for (final Permission permission : permissions) cryptoRepoFiles.add(permission.getPermissionSet().getCryptoRepoFile()); for (final CryptoRepoFile cryptoRepoFile : cryptoRepoFiles) getContext().getCryptreeNodeOrCreate(cryptoRepoFile.getCryptoRepoFileId()).revokePermission(PermissionType.grant, userRepoKeyIds); } /** * @param anyCryptoRepoFile <code>true</code> to indicate that the {@link Permission} does not need to be available on the * level of this node's {@link CryptoRepoFile} (it is thus independent from this context); <code>false</code> to indicate * that is must be available here on this level (i.e. granted directly or inherited from a parent). * @param userRepoKeyId * @param permissionType * @param timestamp */ public void assertHasPermission( final boolean anyCryptoRepoFile, final Uid userRepoKeyId, final PermissionType permissionType, final Date timestamp ) throws AccessDeniedException { assertNotNull(userRepoKeyId, "userRepoKeyId"); assertNotNull(permissionType, "permissionType"); assertNotNull(timestamp, "timestamp"); if (isOwner(userRepoKeyId)) return; // The owner always has all permissions. String additionalExceptionMsg = null; final UserRepoKeyPublicKey userRepoKeyPublicKey = context.transaction.getDao(UserRepoKeyPublicKeyDao.class).getUserRepoKeyPublicKeyOrFail(userRepoKeyId); if (userRepoKeyPublicKey instanceof InvitationUserRepoKeyPublicKey) { final InvitationUserRepoKeyPublicKey invUserRepoKeyPublicKey = (InvitationUserRepoKeyPublicKey) userRepoKeyPublicKey; if (timestamp.compareTo(invUserRepoKeyPublicKey.getValidTo()) <= 0) { // Using a delegation via the invitiation-key is only allowed, if there is a corresponding replacement-request! // This reduces the potential to abuse this possibility (to grant access to other people). final UserRepoKeyPublicKeyReplacementRequestDao dao = context.transaction.getDao(UserRepoKeyPublicKeyReplacementRequestDao.class); if (dao.getUserRepoKeyPublicKeyReplacementRequestsForOldKey(invUserRepoKeyPublicKey).isEmpty()) throwAccessDeniedException(permissionType, "There is no UserRepoKeyPublicKeyReplacementRequest for " + invUserRepoKeyPublicKey); final Uid signingUserRepoKeyId = invUserRepoKeyPublicKey.getSignature().getSigningUserRepoKeyId(); assertHasPermission(anyCryptoRepoFile, signingUserRepoKeyId, permissionType, invUserRepoKeyPublicKey.getSignature().getSignatureCreated()); // Using 'timestamp' here means the signing user must still have permissions, when the invitation was consumed. // This is maybe not perfect, but maybe it's exactly what we want... at least it should be OK. Or should be better // to use the timestamp of the invitation? This is what we do now. return; } else additionalExceptionMsg = String.format( "userRepoKeyPublicKey is an InvitationUserRepoKeyPublicKey, but it expired on '%s', which is before the given timestamp '%s'!", ISO8601.formatDate(invUserRepoKeyPublicKey.getValidTo()), ISO8601.formatDate(timestamp)); } final Set<Permission> permissions = new HashSet<Permission>(); if (PermissionType.read == permissionType) { long timeDifferenceToNow = Math.abs(System.currentTimeMillis() - timestamp.getTime()); if (timeDifferenceToNow > 5 * 60 * 1000) throw new UnsupportedOperationException("assertHasPermission(...) does not yet support permissionType 'read' combined with a timestamp that is not *now*!"); if (hasReadPermissionHereOrInherited(userRepoKeyId)) return; } else { collectPermissions(permissions, anyCryptoRepoFile, permissionType, userRepoKeyId, timestamp); final Set<Permission> permissionsIndicatingBackdatedSignature = extractPermissionsIndicatingBackdatedSignature(permissions); if (! permissions.isEmpty()) return; // all is fine => silently return. if (! permissionsIndicatingBackdatedSignature.isEmpty()) { final String exceptionMsg = String.format("Found '%s' permission(s) for userRepoKeyId=%s and timestamp=%s, but it (or they) indicates backdating outside of allowed range!", permissionType, userRepoKeyId, timestamp); throwAccessDeniedException(permissionType, exceptionMsg); } } final String exceptionMsg = String.format("No '%s' permission found for userRepoKeyId=%s and timestamp=%s!", permissionType, userRepoKeyId, ISO8601.formatDate(timestamp)) + (isEmpty(additionalExceptionMsg) ? "" : (" " + additionalExceptionMsg)); throwAccessDeniedException(permissionType, exceptionMsg); } private void throwAccessDeniedException(final PermissionType permissionType, final String exceptionMessage) throws AccessDeniedException { switch (permissionType) { case grant: throw new GrantAccessDeniedException(exceptionMessage); case write: throw new WriteAccessDeniedException(exceptionMessage); case read: throw new ReadAccessDeniedException(exceptionMessage); case readUserIdentity: throw new ReadUserIdentityAccessDeniedException(exceptionMessage); default: throw new IllegalArgumentException("Unknown permissionType: " + permissionType); } } private boolean isOwner(final Uid userRepoKeyId) { assertNotNull(userRepoKeyId, "userRepoKeyId"); return userRepoKeyId.equals(context.getRepositoryOwnerOrFail().getUserRepoKeyPublicKey().getUserRepoKeyId()); } /** * @param anyCryptoRepoFile <code>true</code> to indicate that the {@link Permission} does not need to be available on the * level of this node's {@link CryptoRepoFile} (it is thus independent from this context); <code>false</code> to indicate * that is must be available here on this level (i.e. granted directly or inherited from a parent). * @param permissionType * @param userRepoKeyId * @param timestamp * @return */ private void collectPermissions(final Set<Permission> permissions, boolean anyCryptoRepoFile, final PermissionType permissionType, final Uid userRepoKeyId, final Date timestamp) { assertNotNull(permissionType, "permissionType"); assertNotNull(userRepoKeyId, "userRepoKeyId"); assertNotNull(timestamp, "timestamp"); // There is no Permission object with *read* permission. Hence, if we ever need to check this // here, we have to check it differently (=> tracing back the cryptree's crypto-links)! switch (permissionType) { case grant: case write: break; case readUserIdentity: anyCryptoRepoFile = true; // it's global!!! it cannot be assigned on a directory/file level! break; default: throw new IllegalArgumentException("PermissionType unknown or not allowed here: " + permissionType); } // final UserRepoKeyPublicKey userRepoKeyPublicKey = context.transaction.getDao(UserRepoKeyPublicKeyDao.class).getUserRepoKeyPublicKeyOrFail(userRepoKeyId); // if (userRepoKeyPublicKey instanceof InvitationUserRepoKeyPublicKey) { // final InvitationUserRepoKeyPublicKey invUserRepoKeyPublicKey = (InvitationUserRepoKeyPublicKey) userRepoKeyPublicKey; // if (timestamp.compareTo(invUserRepoKeyPublicKey.getValidTo()) <= 0) { // final Uid signingUserRepoKeyId = invUserRepoKeyPublicKey.getSignature().getSigningUserRepoKeyId(); // collectPermissions(permissions, anyCryptoRepoFile, permissionType, signingUserRepoKeyId, invUserRepoKeyPublicKey.getSignature().getSignatureCreated()); // // Using 'timestamp' here means the signing user must still have permissions, when the invitation was consumed. // // This is maybe not perfect, but maybe it's exactly what we want... at least it should be OK. Or should be better // // use the timestamp of the invitation? // } // } final PermissionSet permissionSet = anyCryptoRepoFile ? null : getPermissionSet(); if (anyCryptoRepoFile || permissionSet != null) { final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final Set<Permission> ps = anyCryptoRepoFile ? new HashSet<>(dao.getValidPermissions(permissionType, userRepoKeyId, timestamp)) : new HashSet<>(dao.getValidPermissions(permissionSet, permissionType, userRepoKeyId, timestamp)); ps.removeAll(permissionsBeingCheckedNow); if (!ps.isEmpty()) { for (final Permission permission : ps) assertPermissionOk(permission); // TODO is this necessary? isn't it sufficient to check when it's written into the DB? } permissions.addAll(ps); } if (! anyCryptoRepoFile && (permissionSet == null || permissionSet.isPermissionsInherited(timestamp))) { final CryptreeNode parent = getParent(); if (parent != null) parent.collectPermissions(permissions, anyCryptoRepoFile, permissionType, userRepoKeyId, timestamp); } } private Set<Permission> extractPermissionsIndicatingBackdatedSignature(final Set<Permission> permissions) { final Set<Permission> result = new HashSet<Permission>(permissions); Date backdatingOldestPermissionValidTo = null; if (getContext().isOnServer) { // We prevent backdating only on the server, because it is likely that a client didn't sync for ages // TODO not sure, if this is the best location for this test. but I think this code here is only called, if a new thingy is *written* on the server (never on read). for (final Iterator<Permission> it = permissions.iterator(); it.hasNext(); ) { final Permission permission = it.next(); if (permission.getValidTo() != null) { if (backdatingOldestPermissionValidTo == null) { // We make it configurable per repository - not (yet) per subdir/file. final File file = getContext().transaction.getLocalRepoManager().getLocalRoot(); backdatingOldestPermissionValidTo = new Date(System.currentTimeMillis() - CryptoConfigUtil.getBackdatingMaxPermissionValidToAge(file)); } if (permission.getValidTo().before(backdatingOldestPermissionValidTo)) { result.add(permission); it.remove(); } } } } return result; } private void assertPermissionOk(final Permission permission) throws SignatureException, AccessDeniedException { assertNotNull(permission, "permission"); if (permissionsAlreadyCheckedOk.contains(permission)) return; if (! permissionsBeingCheckedNow.add(permission)) throw new IllegalStateException("Circular permission check! " + permission); try { assertSignatureOk(permission); permissionsAlreadyCheckedOk.add(permission); } finally { permissionsBeingCheckedNow.remove(permission); } } public void assertSignatureOk(final WriteProtected entity) throws SignatureException, AccessDeniedException { assertNotNull(entity, "entity"); final Uid crfIdControllingPermissions = entity.getCryptoRepoFileIdControllingPermissions(); if (crfIdControllingPermissions == null) this.assertSignatureOk(entity, true, entity.getPermissionTypeRequiredForWrite()); else if (crfIdControllingPermissions.equals(this.getCryptoRepoFile().getCryptoRepoFileId())) this.assertSignatureOk(entity, false, entity.getPermissionTypeRequiredForWrite()); else { final CryptreeNode cryptreeNode = context.getCryptreeNodeOrCreate(crfIdControllingPermissions); cryptreeNode.assertSignatureOk(entity, false, entity.getPermissionTypeRequiredForWrite()); } } public void assertSignatureOk( final Signable signable, final boolean anyCryptoRepoFile, final PermissionType requiredPermissionType ) throws SignatureException, AccessDeniedException { assertNotNull(signable, "signable"); // requiredPermissionType may be null, because a write-protected entity may not require any permission-type, but only behave like an ordinary Signable. // *always* verify signature! context.signableVerifier.verify(signable); if (requiredPermissionType != null) { // only check, if a requiredPermissionType was given. final Uid signingUserRepoKeyId = signable.getSignature().getSigningUserRepoKeyId(); assertHasPermission(anyCryptoRepoFile, signingUserRepoKeyId, requiredPermissionType, signable.getSignature().getSignatureCreated()); } } public PermissionSet getPermissionSet() { if (permissionSet == null) { final PermissionSetDao dao = context.transaction.getDao(PermissionSetDao.class); permissionSet = dao.getPermissionSet(getCryptoRepoFileOrCreate(false)); if (permissionSet != null) assertSignatureOk(permissionSet); } return permissionSet; } public PermissionSet getPermissionSetOrCreate() { PermissionSet permissionSet = getPermissionSet(); if (permissionSet == null) { permissionSet = new PermissionSet(); permissionSet.setCryptoRepoFile(assertNotNull(getCryptoRepoFile(), "getCryptoRepoFile()")); sign(permissionSet); final PermissionSetDao dao = context.transaction.getDao(PermissionSetDao.class); this.permissionSet = permissionSet = dao.makePersistent(permissionSet); setPermissionsInherited(true); // this should be the default for a new PermissionSet } return permissionSet; } public void sign(final WriteProtected writeProtected) throws AccessDeniedException { assertNotNull(writeProtected, "writeProtectedEntity"); final Uid crfIdControllingPermissions = writeProtected.getCryptoRepoFileIdControllingPermissions(); final UserRepoKey userRepoKey; if (crfIdControllingPermissions == null) userRepoKey = this.getUserRepoKeyOrFail(true, writeProtected.getPermissionTypeRequiredForWrite()); else if (crfIdControllingPermissions.equals(this.getCryptoRepoFile().getCryptoRepoFileId())) userRepoKey = this.getUserRepoKeyOrFail(false, writeProtected.getPermissionTypeRequiredForWrite()); else { final CryptreeNode cryptreeNode = context.getCryptreeNodeOrCreate(crfIdControllingPermissions); userRepoKey = cryptreeNode.getUserRepoKeyOrFail(false, writeProtected.getPermissionTypeRequiredForWrite()); } context.getSignableSigner(userRepoKey).sign(writeProtected); } /** * @param anyCryptoRepoFile <code>true</code> to indicate that the {@link Permission} does not need to be available on the * level of this node's {@link CryptoRepoFile} (it is thus independent from this context); <code>false</code> to indicate * that is must be available here on this level (i.e. granted directly or inherited from a parent). * @param permissionType * @return */ public UserRepoKey getUserRepoKey(final boolean anyCryptoRepoFile, final PermissionType permissionType) { assertNotNull(permissionType, "permissionType"); // There is no Permission object with *read* permission. Hence, if we ever need to check this // here, we have to check it differently (=> tracing back the cryptree's crypto-links)! switch (permissionType) { case grant: case write: break; default: throw new IllegalArgumentException("PermissionType unknown or not allowed here: " + permissionType); } final Date now = new Date(); for (final UserRepoKey userRepoKey : context.userRepoKeyRing.getPermanentUserRepoKeys(context.serverRepositoryId)) { final boolean owner = isOwner(userRepoKey.getUserRepoKeyId()); final Set<Permission> permissions = new HashSet<Permission>(); if (! owner) collectPermissions(permissions, anyCryptoRepoFile, permissionType, userRepoKey.getUserRepoKeyId(), now); if (owner || ! permissions.isEmpty()) { getUserRepoKeyPublicKeyOrCreate(userRepoKey); // Make sure it is persisted in the DB. return userRepoKey; } } return null; } private UserRepoKey getUserRepoKeyOrFail(final boolean anyCryptoRepoFile, final PermissionType permissionType) { final UserRepoKey userRepoKey = getUserRepoKey(anyCryptoRepoFile, permissionType); if (userRepoKey == null) { final String message = String.format("No '%s' permission for any UserRepoKey of the current UserRepoKeyRing for: %s", permissionType, (repoFile != null ? repoFile.getPath() : cryptoRepoFile)); switch (permissionType) { case grant: throw new GrantAccessDeniedException(message); case read: throw new ReadAccessDeniedException(message); case write: throw new WriteAccessDeniedException(message); default: throw new IllegalArgumentException("Unknown PermissionType: " + permissionType); } } return userRepoKey; } public void clearCryptoRepoFileDeleted() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); deletePreliminaryDeletions(); if (cryptoRepoFile.getDeleted() != null) { cryptoRepoFile.setDeleted(null); cryptoRepoFile.setDeletedByIgnoreRule(false); cryptoRepoFile.setLastSyncFromRepositoryId(null); sign(cryptoRepoFile); updateCryptoConfigPropSetIfConfigFile(); } } protected void deletePreliminaryDeletions() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); PreliminaryDeletionDao pdDao = getContext().transaction.getDao(PreliminaryDeletionDao.class); PreliminaryDeletion preliminaryDeletion = pdDao.getPreliminaryDeletion(cryptoRepoFile); if (preliminaryDeletion != null) pdDao.deletePersistent(preliminaryDeletion); } public ConfigPropSetDto getParentConfigPropSetDtoIfNeeded() { final Uid id = context.getCryptoRepoFileIdForRemotePathPrefixOrFail(); if (! id.equals(getCryptoRepoFile().getCryptoRepoFileId())) throw new IllegalStateException("cryptoRepoFileIdForRemotePathPrefix != cryptoRepoFile.cryptoRepoFileId :: " + id + " != " + getCryptoRepoFile().getCryptoRepoFileId()); final List<CryptoConfigPropSet> cryptoConfigPropSets = getCryptoConfigPropSetsAbove(); if (! isCryptoConfigPropSetModifiedAfterLastSync(cryptoConfigPropSets)) return null; Properties mergedProperties = null; for (final CryptoConfigPropSet cryptoConfigPropSet : cryptoConfigPropSets) { final ConfigPropSetDto configPropSetDto = getConfigPropSetDto(cryptoConfigPropSet); if (configPropSetDto == null) continue; final Properties properties = configPropSetDto.toProperties(); if (mergedProperties == null) mergedProperties = properties; else mergedProperties.putAll(properties); } // We must not return null, if there was a modification. Returning null means to *not* // overwrite the parent.properties. But it must be rewritten. return mergedProperties == null ? new ConfigPropSetDto() : new ConfigPropSetDto(mergedProperties); } private ConfigPropSetDto getConfigPropSetDto(CryptoConfigPropSet cryptoConfigPropSet) { assertNotNull(cryptoConfigPropSet, "cryptoConfigPropSet"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(cryptoConfigPropSet.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The CryptoConfigPropSet with cryptoRepoFileId=%s could not be decrypted! Access rights missing?!", cryptoConfigPropSet.getCryptoRepoFileId())); final byte[] encryptedData = cryptoConfigPropSet.getConfigPropSetDtoData(); if (encryptedData == null || encryptedData.length == 0) return null; final byte[] plainData = decrypt(encryptedData, plainCryptoKey); return new ConfigPropSetDtoIo().deserializeWithGz(plainData); } private boolean isCryptoConfigPropSetModifiedAfterLastSync(final List<CryptoConfigPropSet> cryptoConfigPropSets) { assertNotNull(cryptoConfigPropSets, "cryptoConfigPropSets"); final RemoteRepository remoteRepository = context.transaction.getDao(RemoteRepositoryDao.class).getRemoteRepositoryOrFail(context.remoteRepositoryId); for (final CryptoConfigPropSet cryptoConfigPropSet : cryptoConfigPropSets) { if (cryptoConfigPropSet.getLocalRevision() > remoteRepository.getLocalRevision()) return true; } return false; } private List<CryptoConfigPropSet> getCryptoConfigPropSetsAbove() { final CryptoConfigPropSetDao ccpsDao = context.transaction.getDao(CryptoConfigPropSetDao.class); final List<CryptoConfigPropSet> result = new ArrayList<>(); CryptoRepoFile cryptoRepoFile = assertNotNull(getCryptoRepoFile(), "cryptoRepoFile"); while (true) { cryptoRepoFile = cryptoRepoFile.getParent(); if (cryptoRepoFile == null) break; final CryptoConfigPropSet cryptoConfigPropSet = ccpsDao.getCryptoConfigPropSet(cryptoRepoFile); if (cryptoConfigPropSet != null) result.add(cryptoConfigPropSet); } Collections.reverse(result); return result; } }
org.subshare/org.subshare.local/src/main/java/org/subshare/local/CryptreeNode.java
package org.subshare.local; import static co.codewizards.cloudstore.core.util.AssertUtil.*; import static co.codewizards.cloudstore.core.util.StringUtil.*; import static org.subshare.local.CryptreeNodeUtil.*; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import javax.jdo.JDOHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subshare.core.AccessDeniedException; import org.subshare.core.DataKey; import org.subshare.core.GrantAccessDeniedException; import org.subshare.core.ReadAccessDeniedException; import org.subshare.core.ReadUserIdentityAccessDeniedException; import org.subshare.core.WriteAccessDeniedException; import org.subshare.core.crypto.CryptoConfigUtil; import org.subshare.core.dto.CollisionPrivateDto; import org.subshare.core.dto.CryptoKeyPart; import org.subshare.core.dto.CryptoKeyRole; import org.subshare.core.dto.PermissionType; import org.subshare.core.dto.PlainHistoCryptoRepoFileDto; import org.subshare.core.dto.SignatureDto; import org.subshare.core.dto.SsRepoFileDto; import org.subshare.core.repo.local.CollisionFilter; import org.subshare.core.sign.Signable; import org.subshare.core.sign.WriteProtected; import org.subshare.core.user.UserRepoKey; import org.subshare.core.user.UserRepoKey.PublicKey; import org.subshare.crypto.CipherOperationMode; import org.subshare.local.dto.CollisionDtoConverter; import org.subshare.local.dto.CollisionPrivateDtoConverter; import org.subshare.local.dto.HistoCryptoRepoFileDtoConverter; import org.subshare.local.persistence.Collision; import org.subshare.local.persistence.CollisionDao; import org.subshare.local.persistence.CollisionPrivate; import org.subshare.local.persistence.CollisionPrivateDao; import org.subshare.local.persistence.CryptoConfigPropSet; import org.subshare.local.persistence.CryptoConfigPropSetDao; import org.subshare.local.persistence.CryptoKey; import org.subshare.local.persistence.CryptoKeyDao; import org.subshare.local.persistence.CryptoKeyDeactivation; import org.subshare.local.persistence.CryptoLink; import org.subshare.local.persistence.CryptoLinkDao; import org.subshare.local.persistence.CryptoRepoFile; import org.subshare.local.persistence.CryptoRepoFileDao; import org.subshare.local.persistence.CurrentHistoCryptoRepoFile; import org.subshare.local.persistence.CurrentHistoCryptoRepoFileDao; import org.subshare.local.persistence.HistoCryptoRepoFile; import org.subshare.local.persistence.HistoCryptoRepoFileDao; import org.subshare.local.persistence.HistoFrame; import org.subshare.local.persistence.HistoFrameDao; import org.subshare.local.persistence.InvitationUserRepoKeyPublicKey; import org.subshare.local.persistence.Permission; import org.subshare.local.persistence.PermissionDao; import org.subshare.local.persistence.PermissionSet; import org.subshare.local.persistence.PermissionSetDao; import org.subshare.local.persistence.PermissionSetInheritance; import org.subshare.local.persistence.PlainHistoCryptoRepoFile; import org.subshare.local.persistence.PlainHistoCryptoRepoFileDao; import org.subshare.local.persistence.PreliminaryDeletion; import org.subshare.local.persistence.PreliminaryDeletionDao; import org.subshare.local.persistence.RepositoryOwner; import org.subshare.local.persistence.UserIdentityLink; import org.subshare.local.persistence.UserIdentityLinkDao; import org.subshare.local.persistence.UserRepoKeyPublicKey; import org.subshare.local.persistence.UserRepoKeyPublicKeyDao; import org.subshare.local.persistence.UserRepoKeyPublicKeyReplacementRequestDao; import co.codewizards.cloudstore.core.Uid; import co.codewizards.cloudstore.core.auth.SignatureException; import co.codewizards.cloudstore.core.config.Config; import co.codewizards.cloudstore.core.dto.ConfigPropSetDto; import co.codewizards.cloudstore.core.dto.RepoFileDto; import co.codewizards.cloudstore.core.dto.jaxb.ConfigPropSetDtoIo; import co.codewizards.cloudstore.core.oio.File; import co.codewizards.cloudstore.core.repo.local.LocalRepoTransaction; import co.codewizards.cloudstore.core.util.ISO8601; import co.codewizards.cloudstore.core.util.PropertiesUtil; import co.codewizards.cloudstore.local.dto.RepoFileDtoConverter; import co.codewizards.cloudstore.local.persistence.Directory; import co.codewizards.cloudstore.local.persistence.RemoteRepository; import co.codewizards.cloudstore.local.persistence.RemoteRepositoryDao; import co.codewizards.cloudstore.local.persistence.RepoFile; import co.codewizards.cloudstore.local.persistence.RepoFileDao; public class CryptreeNode { private static final Logger logger = LoggerFactory.getLogger(CryptreeNode.class); private static final Map<CryptoKeyRole, Class<? extends PlainCryptoKeyFactory>> cryptoKeyRole2PlainCryptoKeyFactory; static { final Map<CryptoKeyRole, Class<? extends PlainCryptoKeyFactory>> m = new HashMap<>(5); m.put(CryptoKeyRole.clearanceKey, PlainCryptoKeyFactory.ClearanceKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.subdirKey, PlainCryptoKeyFactory.SubdirKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.fileKey, PlainCryptoKeyFactory.FileKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.backlinkKey, PlainCryptoKeyFactory.BacklinkKeyPlainCryptoKeyFactory.class); m.put(CryptoKeyRole.dataKey, PlainCryptoKeyFactory.DataKeyPlainCryptoKeyFactory.class); cryptoKeyRole2PlainCryptoKeyFactory = Collections.unmodifiableMap(m); } private final CryptreeContext context; private CryptreeNode parent; // maybe null - lazily loaded, if there is one private RepoFile repoFile; // maybe null - lazily loaded private CryptoRepoFile cryptoRepoFile; // maybe null - lazily loaded private PermissionSet permissionSet; // maybe null - lazily loaded, if there is one private RepoFileDtoConverter repoFileDtoConverter; // maybe null - lazily loaded private final List<CryptreeNode> children = new ArrayList<CryptreeNode>(0); private boolean childrenLoaded = false; private final Set<Permission> permissionsBeingCheckedNow = new HashSet<Permission>(); private final Set<Permission> permissionsAlreadyCheckedOk = new HashSet<Permission>(); public CryptreeNode(final CryptreeContext context, final RepoFile repoFile) { this(context, repoFile, null); } public CryptreeNode(final CryptreeContext context, final CryptoRepoFile cryptoRepoFile) { this(context, null, cryptoRepoFile); } private CryptreeNode(final CryptreeContext context, final RepoFile repoFile, final CryptoRepoFile cryptoRepoFile) { this(null, null, context, repoFile, cryptoRepoFile); } public CryptreeNode(final CryptreeNode parent, final CryptreeNode child, final CryptreeContext context, final RepoFile repoFile, final CryptoRepoFile cryptoRepoFile) { if (parent == null && child == null && context == null) throw new IllegalArgumentException("parent == null && child == null && context == null"); if (repoFile == null && cryptoRepoFile == null) throw new IllegalArgumentException("repoFile == null && cryptoRepoFile == null"); this.parent = parent; this.context = context != null ? context : (parent != null ? parent.getContext() : child.getContext()); this.repoFile = repoFile != null ? repoFile : cryptoRepoFile.getRepoFile(); this.cryptoRepoFile = cryptoRepoFile; if (child != null) children.add(child); } public CryptreeContext getContext() { return context; } public RepoFile getRepoFile() { if (repoFile == null) { repoFile = getCryptoRepoFile().getRepoFile(); if (repoFile == null) { getRepoFileDto(); // We expect the line above to throw an AccessDeniedException, if the user is not allowed to access it. // But if we checked out a sub-directory, it's a valid state that the parent-RepoFile objects do *not* // exist (because we don't have local file representations) and still we can decrypt the RepoFileDto // of the parent directories. // This RepoFile is therefore clearly optional! } else context.registerCryptreeNode(repoFile, this); } return repoFile; } /** * Gets the RepoFileDto containing meta-data only (the current version of it). * @return the DTO or <code>null</code>, if there is no CryptoRepoFile (i.e. {@link #getCryptoRepoFile()} returns <code>null</code>. * @throws AccessDeniedException */ public RepoFileDto getRepoFileDto() throws AccessDeniedException { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null) return null; final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(cryptoRepoFile.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The CryptoRepoFile with cryptoRepoFileId=%s could not be decrypted! Access rights missing?!", cryptoRepoFile.getCryptoRepoFileId())); final byte[] plainRepoFileDtoData = assertNotNull(decrypt(cryptoRepoFile.getRepoFileDtoData(), plainCryptoKey), "decrypt(...)"); final RepoFileDto repoFileDto = context.repoFileDtoIo.deserializeWithGz(plainRepoFileDtoData); return repoFileDto; } public RepoFileDto getHistoCryptoRepoFileRepoFileDto(final HistoCryptoRepoFile histoCryptoRepoFile) throws AccessDeniedException { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(histoCryptoRepoFile.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The HistoCryptoRepoFile with histoCryptoRepoFileId=%s could not be decrypted! Access rights missing?!", histoCryptoRepoFile.getHistoCryptoRepoFileId())); final byte[] plainRepoFileDtoData = assertNotNull(decrypt(histoCryptoRepoFile.getRepoFileDtoData(), plainCryptoKey), "decrypt(...)"); final RepoFileDto repoFileDto = context.repoFileDtoIo.deserializeWithGz(plainRepoFileDtoData); return repoFileDto; } public RepoFileDto getRepoFileDtoOnServer() throws AccessDeniedException { final CurrentHistoCryptoRepoFile currentHistoCryptoRepoFile = getCurrentHistoCryptoRepoFile(); if (currentHistoCryptoRepoFile == null) return null; final HistoCryptoRepoFile histoCryptoRepoFile = currentHistoCryptoRepoFile.getHistoCryptoRepoFile(); assertNotNull(histoCryptoRepoFile, "currentHistoCryptoRepoFile.histoCryptoRepoFile"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(histoCryptoRepoFile.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The HistoCryptoRepoFile with cryptoRepoFileId=%s could not be decrypted! Access rights missing?!", histoCryptoRepoFile.getCryptoRepoFile().getCryptoRepoFileId())); final byte[] plainRepoFileDtoData = assertNotNull(decrypt(histoCryptoRepoFile.getRepoFileDtoData(), plainCryptoKey), "decrypt(...)"); final RepoFileDto repoFileDto = context.repoFileDtoIo.deserializeWithGz(plainRepoFileDtoData); return repoFileDto; } public CryptoRepoFile getCryptoRepoFile() { if (cryptoRepoFile == null) { if (repoFile == null) // at least one of them must be there! throw new IllegalStateException("repoFile == null && cryptoRepoFile == null"); final CryptoRepoFileDao cryptoRepoFileDao = context.transaction.getDao(CryptoRepoFileDao.class); cryptoRepoFile = cryptoRepoFileDao.getCryptoRepoFile(repoFile); // may be null! final CryptreeNode parent = getParent(); if (parent != null && cryptoRepoFile == null) { cryptoRepoFile = cryptoRepoFileDao.getChildCryptoRepoFile(parent.getCryptoRepoFile(), repoFile.getName()); } if (cryptoRepoFile != null) context.registerCryptreeNode(cryptoRepoFile, this); } return cryptoRepoFile; } public CryptoRepoFile getCryptoRepoFileOrCreate(final boolean update) { CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null || update) { final CryptoRepoFileDao cryptoRepoFileDao = context.transaction.getDao(CryptoRepoFileDao.class); if (cryptoRepoFile == null) { cryptoRepoFile = new CryptoRepoFile(); // We sign *after* we persist below in this *same* *method*, hence we store this // dummy value temporarily to avoid allowing NULL. It's set to the real value in // the same transaction, anyway. Hence we should never end up with this in the DB. cryptoRepoFile.setSignature(new SignatureDto(new Date(0), new Uid(0, 0), new byte[] { 7 })); } else { cryptoRepoFile.setDeleted(null); cryptoRepoFile.setDeletedByIgnoreRule(false); deletePreliminaryDeletions(); } cryptoRepoFile.setRepoFile(assertNotNull(repoFile, "repoFile")); // repoFile is guaranteed to be *not* null, because of getCryptoRepoFile() above. cryptoRepoFile.setDirectory(repoFile instanceof Directory); // getPlainCryptoKeyOrCreate(...) causes this method to be called again. We thus must prevent // an eternal recursion by already assigning it to the field *now*. // Furthermore, CryptoKey has a reference to this object and will thus persist it, anyway. // Thus we explicitly persist it already here. this.cryptoRepoFile = cryptoRepoFile = cryptoRepoFileDao.makePersistent(cryptoRepoFile); final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); cryptoRepoFile.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); final CryptreeNode parent = getParent(); cryptoRepoFile.setParent(parent == null ? null : parent.getCryptoRepoFile()); final byte[] repoFileDtoData = createRepoFileDtoDataForCryptoRepoFile(false); cryptoRepoFile.setRepoFileDtoData(assertNotNull(encrypt(repoFileDtoData, plainCryptoKey), "encrypt(...)")); cryptoRepoFile.setLastSyncFromRepositoryId(null); sign(cryptoRepoFile); context.transaction.flush(); // we want an early failure - not later during commit. updateCryptoConfigPropSetIfConfigFile(); } return cryptoRepoFile; } public CryptoConfigPropSet updateCryptoConfigPropSetIfConfigFile() { final CryptoRepoFile cryptoRepoFile = assertNotNull(getCryptoRepoFile(), "cryptoRepoFile"); final String localName = cryptoRepoFile.getLocalName(); if (! Config.PROPERTIES_FILE_NAME_FOR_DIRECTORY.equals(localName)) { return null; } final CryptreeNode parent = assertNotNull(getParent(), "parent"); final CryptoRepoFile parentCrf = parent.getCryptoRepoFileOrCreate(false); final CryptoConfigPropSetDao ccpsDao = context.transaction.getDao(CryptoConfigPropSetDao.class); CryptoConfigPropSet cryptoConfigPropSet = ccpsDao.getCryptoConfigPropSet(parentCrf); if (cryptoConfigPropSet == null) cryptoConfigPropSet = new CryptoConfigPropSet(parentCrf); final PlainCryptoKey plainCryptoKey = parent.getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); cryptoConfigPropSet.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); final byte[] plainData = createConfigPropSetDtoDataFromFile(); cryptoConfigPropSet.setConfigPropSetDtoData(plainData == null ? null : encrypt(plainData, plainCryptoKey)); cryptoConfigPropSet.setLastSyncFromRepositoryId(null); parent.sign(cryptoConfigPropSet); cryptoConfigPropSet = ccpsDao.makePersistent(cryptoConfigPropSet); context.transaction.flush(); // we want an early failure - not later during commit. return cryptoConfigPropSet; } private byte[] createConfigPropSetDtoDataFromFile() { final ConfigPropSetDto configPropSetDto = createConfigPropSetDtoFromFile(); if (configPropSetDto == null) return null; return new ConfigPropSetDtoIo().serializeWithGz(configPropSetDto); } private ConfigPropSetDto createConfigPropSetDtoFromFile() { if (getCryptoRepoFile().getDeleted() != null) return null; final RepoFile repoFile = assertNotNull(getRepoFile(), "repoFile"); final File configFile = repoFile.getFile(context.transaction.getLocalRepoManager().getLocalRoot()); if (! configFile.isFile()) { logger.warn("createConfigPropSetDtoFromFile: configFile not existing (deleted after local-sync?!): {}", configFile); return null; } final Properties properties; try { properties = PropertiesUtil.load(configFile); } catch (IOException e) { throw new RuntimeException(e); } return new ConfigPropSetDto(properties); } public CurrentHistoCryptoRepoFile getCurrentHistoCryptoRepoFile() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null) return null; final CurrentHistoCryptoRepoFileDao chcrfDao = context.transaction.getDao(CurrentHistoCryptoRepoFileDao.class); final CurrentHistoCryptoRepoFile currentHistoCryptoRepoFile = chcrfDao.getCurrentHistoCryptoRepoFile(cryptoRepoFile); return currentHistoCryptoRepoFile; } /** * Creates a new current {@link HistoCryptoRepoFile} and assigns it as the current one. */ public HistoCryptoRepoFile createHistoCryptoRepoFileIfNeeded() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFileOrCreate(false); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); final CurrentHistoCryptoRepoFileDao chcrfDao = context.transaction.getDao(CurrentHistoCryptoRepoFileDao.class); final HistoCryptoRepoFileDao hcrfDao = context.transaction.getDao(HistoCryptoRepoFileDao.class); final HistoFrameDao hfDao = context.transaction.getDao(HistoFrameDao.class); final HistoFrame histoFrame = hfDao.getUnsealedHistoFrameOrFail(context.localRepositoryId); CurrentHistoCryptoRepoFile currentHistoCryptoRepoFile = chcrfDao.getCurrentHistoCryptoRepoFile(cryptoRepoFile); if (currentHistoCryptoRepoFile == null) { currentHistoCryptoRepoFile = new CurrentHistoCryptoRepoFile(); currentHistoCryptoRepoFile.setCryptoRepoFile(cryptoRepoFile); } final HistoCryptoRepoFile previousHistoCryptoRepoFile = currentHistoCryptoRepoFile.getHistoCryptoRepoFile(); HistoCryptoRepoFile histoCryptoRepoFile = null; Collection<HistoCryptoRepoFile> histoCryptoRepoFiles = hcrfDao.getHistoCryptoRepoFiles(cryptoRepoFile); for (HistoCryptoRepoFile hcrf : histoCryptoRepoFiles) { if (histoFrame.equals(hcrf.getHistoFrame())) { // createCollisionIfNeeded(histoCryptoRepoFile); // throw new IllegalStateException("xxx"); histoCryptoRepoFile = hcrf; // TODO is this the right strategy? Or should we better delete and recreate? I encountered this situation when aborting an up-sync and resuming later. // ... if https://github.com/subshare/subshare/issues/45 is fixed, now, then it can't be so wrong ;-) } } if (histoCryptoRepoFile == null) { histoCryptoRepoFile = new HistoCryptoRepoFile(); histoCryptoRepoFile.setCryptoRepoFile(cryptoRepoFile); histoCryptoRepoFile.setPreviousHistoCryptoRepoFile(previousHistoCryptoRepoFile); histoCryptoRepoFile.setHistoFrame(histoFrame); final Date deleted = cryptoRepoFile.getDeleted(); histoCryptoRepoFile.setDeleted(deleted); histoCryptoRepoFile.setDeletedByIgnoreRule(cryptoRepoFile.isDeletedByIgnoreRule()); final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); histoCryptoRepoFile.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); if (! cryptoKey.equals(cryptoRepoFile.getCryptoKey())) // sanity check: the key should not have changed inbetween! otherwise we might need a new CryptoChangeSet-upload to the server!!! throw new IllegalStateException(String.format("cryptoKey != cryptoRepoFile.cryptoKey :: %s != %s", cryptoKey, cryptoRepoFile.getCryptoKey())); final byte[] repoFileDtoData; if (deleted != null) // repoFileDtoData = getRepoFileDtoDataForDeletedCryptoRepoFile(previousHistoCryptoRepoFile); repoFileDtoData = context.repoFileDtoIo.serializeWithGz(assertNotNull(getRepoFileDto(), "getRepoFileDto()")); else repoFileDtoData = createRepoFileDtoDataForCryptoRepoFile(true); histoCryptoRepoFile.setRepoFileDtoData(assertNotNull(encrypt(repoFileDtoData, plainCryptoKey), "encrypt(...)")); histoCryptoRepoFile.setLastSyncFromRepositoryId(null); sign(histoCryptoRepoFile); histoCryptoRepoFile = hcrfDao.makePersistent(histoCryptoRepoFile); } currentHistoCryptoRepoFile.setHistoCryptoRepoFile(histoCryptoRepoFile); currentHistoCryptoRepoFile.setLastSyncFromRepositoryId(null); sign(currentHistoCryptoRepoFile); chcrfDao.makePersistent(currentHistoCryptoRepoFile); updatePlainHistoCryptoRepoFile(histoCryptoRepoFile); // createCollisionIfNeeded(histoCryptoRepoFile); context.transaction.flush(); // for early detection of an error return histoCryptoRepoFile; } public Collision createCollisionIfNeeded(final CryptoRepoFile duplicateCryptoRepoFile, final String localPath, boolean expectedSealedStatus) { final LocalRepoTransaction tx = context.transaction; final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); final CollisionDao cDao = tx.getDao(CollisionDao.class); final HistoCryptoRepoFileDao hcrfDao = tx.getDao(HistoCryptoRepoFileDao.class); final Collection<HistoCryptoRepoFile> histoCryptoRepoFiles = hcrfDao.getHistoCryptoRepoFiles(cryptoRepoFile); final HistoCryptoRepoFile localHistoCryptoRepoFile = getLastHistoCryptoRepoFile(histoCryptoRepoFiles, false); final HistoCryptoRepoFile remoteHistoCryptoRepoFile = getLastHistoCryptoRepoFile(histoCryptoRepoFiles, true); if (localHistoCryptoRepoFile != null) { if (localHistoCryptoRepoFile.getHistoFrame().getSealed() != null && expectedSealedStatus == false) { // https://github.com/subshare/subshare/issues/52 // Converted blocking error to warning, because this actually happened -- and I have no idea why :-( // ...and it isn't a serious problem, hence a warning is fine. IllegalStateException x = new IllegalStateException(String.format("Why is the local HistoFrame already sealed?!???!!! cryptoRepoFile=%s duplicateCryptoRepoFile=%s localPath=%s localHistoCryptoRepoFile=%s remoteHistoCryptoRepoFile=%s", cryptoRepoFile, duplicateCryptoRepoFile, localPath, localHistoCryptoRepoFile, remoteHistoCryptoRepoFile)); logger.warn("createCollisionIfNeeded: " + x.toString(), x); } if (localHistoCryptoRepoFile.getHistoFrame().getSealed() == null && expectedSealedStatus == true) throw new IllegalStateException("Why is the local HistoFrame not yet sealed?!???!!!"); } HistoCryptoRepoFile histoCryptoRepoFile1 = localHistoCryptoRepoFile; HistoCryptoRepoFile histoCryptoRepoFile2 = remoteHistoCryptoRepoFile; if (histoCryptoRepoFile1 == null) { histoCryptoRepoFile1 = histoCryptoRepoFile2; histoCryptoRepoFile2 = null; } assertNotNull(histoCryptoRepoFile1, "histoCryptoRepoFile1", "cryptoRepoFile=%s duplicateCryptoRepoFile=%s localPath=%s localHistoCryptoRepoFile=%s remoteHistoCryptoRepoFile=%s", cryptoRepoFile, duplicateCryptoRepoFile, localPath, localHistoCryptoRepoFile, remoteHistoCryptoRepoFile); if (duplicateCryptoRepoFile != null) { if (duplicateCryptoRepoFile.getCryptoRepoFileId().equals(getCryptoRepoFileId(histoCryptoRepoFile1))) { histoCryptoRepoFile1 = histoCryptoRepoFile2; histoCryptoRepoFile2 = null; } else if (histoCryptoRepoFile2 == null || duplicateCryptoRepoFile.getCryptoRepoFileId().equals(getCryptoRepoFileId(histoCryptoRepoFile2))) histoCryptoRepoFile2 = null; else { // throw new IllegalStateException("duplicateCryptoRepoFile neither matches histoCryptoRepoFile1 nor histoCryptoRepoFile2!\nduplicateCryptoRepoFile=" + duplicateCryptoRepoFile + "\nhistoCryptoRepoFile1=" + histoCryptoRepoFile1 + "\nhistoCryptoRepoFile2=" + histoCryptoRepoFile2); // https://github.com/subshare/subshare/issues/21 :: I think the above exception is nonsense. Instead we should just make sure // that histoCryptoRepoFile1 is the newer one, so that we use the newest. This scenario happens, if this sync+deduplication is // done on a computer that is *not* involved in any of the changes having caused the collision - which is a perfectly legal situation. if (histoCryptoRepoFile1.getSignature().getSignatureCreated().before(histoCryptoRepoFile2.getSignature().getSignatureCreated())) histoCryptoRepoFile1 = histoCryptoRepoFile2; histoCryptoRepoFile2 = null; } if (duplicateCryptoRepoFile.getCryptoRepoFileId().equals(getCryptoRepoFileId(histoCryptoRepoFile1))) throw new IllegalStateException("duplicateCryptoRepoFile matches histoCryptoRepoFile1!\nduplicateCryptoRepoFile=" + duplicateCryptoRepoFile + "\nhistoCryptoRepoFile1=" + histoCryptoRepoFile1 + "\nhistoCryptoRepoFile2=" + histoCryptoRepoFile2); } else { // assertNotNull(histoCryptoRepoFile2, "histoCryptoRepoFile2"); IllegalStateException x = new IllegalStateException(String.format("duplicateCryptoRepoFile and histoCryptoRepoFile2 are both null!!! cryptoRepoFile=%s localPath=%s localHistoCryptoRepoFile=%s remoteHistoCryptoRepoFile=%s", cryptoRepoFile, localPath, localHistoCryptoRepoFile, remoteHistoCryptoRepoFile)); logger.warn("createCollisionIfNeeded: " + x.toString(), x); return null; } assertNotNull(histoCryptoRepoFile1, "histoCryptoRepoFile1"); final Uid duplicateCryptoRepoFileId = duplicateCryptoRepoFile == null ? null : duplicateCryptoRepoFile.getCryptoRepoFileId(); Collision collision = cDao.getCollision(histoCryptoRepoFile1, histoCryptoRepoFile2, duplicateCryptoRepoFileId); if (collision == null) { collision = new Collision(); collision.setHistoCryptoRepoFile1(histoCryptoRepoFile1); collision.setHistoCryptoRepoFile2(histoCryptoRepoFile2); collision.setDuplicateCryptoRepoFileId(duplicateCryptoRepoFileId); putCollisionPrivateDto(collision, new CollisionPrivateDto()); // signs the Collision collision = cDao.makePersistent(collision); logger.info("createCollisionIfNeeded: localPath='{}' histoCryptoRepoFile1={} histoCryptoRepoFile2={} duplicateCryptoRepoFileId={} localRevision={}", localPath, histoCryptoRepoFile1, histoCryptoRepoFile2, duplicateCryptoRepoFileId, collision.getLocalRevision()); } updateCollisionPrivate(collision); context.transaction.flush(); // for early detection of an error return collision; } public void putCollisionPrivateDto(final Collision collision, final CollisionPrivateDto collisionPrivateDto) { assertNotNull(collision, "collision"); assertNotNull(collisionPrivateDto, "collisionPrivateDto"); if (collisionPrivateDto.getCollisionId() == null) collisionPrivateDto.setCollisionId(collision.getCollisionId()); else if (! collisionPrivateDto.getCollisionId().equals(collision.getCollisionId())) throw new IllegalArgumentException("collisionPrivateDto.collisionId != collision.collisionId"); final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.dataKey, CipherOperationMode.ENCRYPT); final CryptoKey cryptoKey = assertNotNull(plainCryptoKey, "plainCryptoKey").getCryptoKey(); collision.setCryptoKey(assertNotNull(cryptoKey, "plainCryptoKey.cryptoKey")); final byte[] data = context.collisionPrivateDtoIo.serializeWithGz(collisionPrivateDto); collision.setCollisionPrivateDtoData(assertNotNull(encrypt(data, plainCryptoKey), "encrypt(...)")); sign(collision); updateCollisionPrivate(collision); } public CollisionPrivateDto getCollisionPrivateDto(final Collision collision) { assertNotNull(collision, "collision"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(collision.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The Collision with collisionId=%s could not be decrypted! Access rights missing?!", collision.getCollisionId())); final byte[] plainDtoData = assertNotNull(decrypt(collision.getCollisionPrivateDtoData(), plainCryptoKey), "decrypt(...)"); CollisionPrivateDto collisionPrivateDto = context.collisionPrivateDtoIo.deserializeWithGz(plainDtoData); return collisionPrivateDto; } private static Uid getCryptoRepoFileId(final HistoCryptoRepoFile histoCryptoRepoFile) { if (histoCryptoRepoFile == null) return null; return histoCryptoRepoFile.getCryptoRepoFile().getCryptoRepoFileId(); } // TODO replace this method by a specific, optimized query! private HistoCryptoRepoFile getLastHistoCryptoRepoFile(final Collection<HistoCryptoRepoFile> histoCryptoRepoFiles, boolean remote) { assertNotNull(histoCryptoRepoFiles, "histoCryptoRepoFiles"); final UUID localRepositoryId = context.transaction.getLocalRepoManager().getRepositoryId(); HistoCryptoRepoFile result = null; for (HistoCryptoRepoFile histoCryptoRepoFile : histoCryptoRepoFiles) { final HistoFrame histoFrame = histoCryptoRepoFile.getHistoFrame(); if (remote) { if (localRepositoryId.equals(histoFrame.getFromRepositoryId())) continue; } else { if (! localRepositoryId.equals(histoFrame.getFromRepositoryId())) continue; } if (result == null || result.getSignature().getSignatureCreated().compareTo(histoCryptoRepoFile.getSignature().getSignatureCreated()) < 0) result = histoCryptoRepoFile; } // if (result == null) // throw new IllegalStateException("No matching HistoCryptoRepoFile found!"); return result; } public CollisionPrivate updateCollisionPrivate(final Collision collision) { assertNotNull(collision, "collision"); if (! getCryptoRepoFile().equals(collision.getHistoCryptoRepoFile1().getCryptoRepoFile())) throw new IllegalArgumentException("this.cryptoRepoFile != collision.histoCryptoRepoFile1.cryptoRepoFile"); final CollisionPrivateDao cpDao = getContext().transaction.getDao(CollisionPrivateDao.class); CollisionPrivate cp = cpDao.getCollisionPrivate(collision); final CollisionPrivateDto collisionPrivateDto = tryDecryptCollisionPrivateDto(collision); if (collisionPrivateDto == null) { if (cp != null) cpDao.deletePersistent(cp); } else cp = CollisionPrivateDtoConverter.create(getContext().transaction).putCollisionPrivateDto(collision, collisionPrivateDto); updatePlainHistoCryptoRepoFile(collision.getHistoCryptoRepoFile1()); if (collision.getHistoCryptoRepoFile2() != null) { getContext().getCryptreeNodeOrCreate(collision.getHistoCryptoRepoFile2().getCryptoRepoFile().getCryptoRepoFileId()) .updatePlainHistoCryptoRepoFile(collision.getHistoCryptoRepoFile2()); } return cp; } public PlainHistoCryptoRepoFile updatePlainHistoCryptoRepoFile(final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final PlainHistoCryptoRepoFileDao phcrfDao = getContext().transaction.getDao(PlainHistoCryptoRepoFileDao.class); PlainHistoCryptoRepoFile phcrf = phcrfDao.getPlainHistoCryptoRepoFile(histoCryptoRepoFile); if (phcrf == null) { phcrf = new PlainHistoCryptoRepoFile(); phcrf.setHistoCryptoRepoFile(histoCryptoRepoFile); } phcrf.setPlainHistoCryptoRepoFileDto(createPlainHistoCryptoRepoFileDto(histoCryptoRepoFile)); phcrf = phcrfDao.makePersistent(phcrf); return phcrf; } /** * Creates a {@link PlainHistoCryptoRepoFileDto} which is then stored (as gzipped XML) in a {@link PlainHistoCryptoRepoFile}. * This allows for very fast loading of the history (there might be *many* items especially in the first HistoFrame). * @param histoCryptoRepoFile the {@link HistoCryptoRepoFile} to read and (try to) decrypt. Must not be <code>null</code>. * @return the {@link PlainHistoCryptoRepoFileDto} - never <code>null</code>. */ private PlainHistoCryptoRepoFileDto createPlainHistoCryptoRepoFileDto(final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final HistoCryptoRepoFileDtoConverter converter = HistoCryptoRepoFileDtoConverter.create(getContext().transaction); final PlainHistoCryptoRepoFileDto plainHistoCryptoRepoFileDto = new PlainHistoCryptoRepoFileDto(); plainHistoCryptoRepoFileDto.setHistoCryptoRepoFileDto(converter.toHistoCryptoRepoFileDto(histoCryptoRepoFile)); final Uid cryptoRepoFileId = histoCryptoRepoFile.getCryptoRepoFile().getCryptoRepoFileId(); plainHistoCryptoRepoFileDto.setCryptoRepoFileId(cryptoRepoFileId); final CryptoRepoFile parentCryptoRepoFile = histoCryptoRepoFile.getCryptoRepoFile().getParent(); plainHistoCryptoRepoFileDto.setParentCryptoRepoFileId(parentCryptoRepoFile == null ? null : parentCryptoRepoFile.getCryptoRepoFileId()); final RepoFileDto repoFileDto = tryDecryptHistoCryptoRepoFile(histoCryptoRepoFile); // if (repoFileDto instanceof SsNormalFileDto) // no need to store these *LARGE* details in the PlainHistoCryptoRepoFile. // ((SsNormalFileDto) repoFileDto).getFileChunkDtos().clear(); // YES, they ARE NEEDED! for the history export! plainHistoCryptoRepoFileDto.setRepoFileDto(repoFileDto); if (histoCryptoRepoFile.getDeleted() != null) plainHistoCryptoRepoFileDto.setAction(PlainHistoCryptoRepoFileDto.Action.DELETE); else if (histoCryptoRepoFile.getPreviousHistoCryptoRepoFile() == null || histoCryptoRepoFile.getPreviousHistoCryptoRepoFile().getDeleted() != null) plainHistoCryptoRepoFileDto.setAction(PlainHistoCryptoRepoFileDto.Action.ADD); else plainHistoCryptoRepoFileDto.setAction(PlainHistoCryptoRepoFileDto.Action.MODIFY); populateCollisionDtos(plainHistoCryptoRepoFileDto, histoCryptoRepoFile); return plainHistoCryptoRepoFileDto; } private void populateCollisionDtos(final PlainHistoCryptoRepoFileDto plainHistoCryptoRepoFileDto, final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); final CollisionDao cDao = getContext().transaction.getDao(CollisionDao.class); final CollisionPrivateDao cpDao = getContext().transaction.getDao(CollisionPrivateDao.class); final CollisionDtoConverter collisionDtoConverter = CollisionDtoConverter.create(getContext().transaction); final CollisionPrivateDtoConverter cpDtoConverter = CollisionPrivateDtoConverter.create(getContext().transaction); final CollisionFilter collisionFilter = new CollisionFilter(); collisionFilter.setHistoCryptoRepoFileId(histoCryptoRepoFile.getHistoCryptoRepoFileId()); final Collection<Collision> collisions = cDao.getCollisions(collisionFilter); for (final Collision collision : collisions) { plainHistoCryptoRepoFileDto.getCollisionDtos().add(collisionDtoConverter.toCollisionDto(collision)); final CollisionPrivate collisionPrivate = cpDao.getCollisionPrivate(collision); if (collisionPrivate != null) plainHistoCryptoRepoFileDto.getCollisionPrivateDtos().add(cpDtoConverter.toCollisionPrivateDto(collisionPrivate)); } } private RepoFileDto tryDecryptHistoCryptoRepoFile(final HistoCryptoRepoFile histoCryptoRepoFile) { assertNotNull(histoCryptoRepoFile, "histoCryptoRepoFile"); RepoFileDto repoFileDto = null; try { repoFileDto = getHistoCryptoRepoFileRepoFileDto(histoCryptoRepoFile); } catch (ReadAccessDeniedException x) { if (logger.isDebugEnabled()) logger.info("tryDecryptHistoCryptoRepoFile: " + x, x); else logger.info("tryDecryptHistoCryptoRepoFile: " + x); } return repoFileDto; } private CollisionPrivateDto tryDecryptCollisionPrivateDto(final Collision collision) { assertNotNull(collision, "collision"); CollisionPrivateDto collisionPrivateDto = null; try { collisionPrivateDto = getCollisionPrivateDto(collision); } catch (ReadAccessDeniedException x) { if (logger.isDebugEnabled()) logger.info("tryDecryptCollisionPrivateDto: " + x, x); else logger.info("tryDecryptCollisionPrivateDto: " + x); } return collisionPrivateDto; } // private byte[] getRepoFileDtoDataForDeletedCryptoRepoFile(final HistoCryptoRepoFile previousHistoCryptoRepoFile) { // // previousHistoCryptoRepoFile may be null, if it was never completely uploaded - hmmmm... why don't we *always* use the info from getRepoFileDto()?! // // final RepoFileDto repoFileDto = previousHistoCryptoRepoFile == null ? getRepoFileDto() : getHistoCryptoRepoFileRepoFileDto(previousHistoCryptoRepoFile); // if (repoFileDto instanceof SsDirectoryDto) // ; // nothing to do // else if (repoFileDto instanceof SsNormalFileDto) { // SsNormalFileDto normalFileDto = (SsNormalFileDto) repoFileDto; // normalFileDto.setFileChunkDtos(null); // normalFileDto.setTempFileChunkDtos(null); // they should always be null, anyway. // } // else if (repoFileDto instanceof SsSymlinkDto) // ; // nothing to do // else // throw new IllegalStateException("Unexpected repoFileDto type: " + repoFileDto); // // return serializeRepoFileDto(repoFileDto); // } private void grantReadPermission(final UserRepoKey.PublicKey publicKey) { assertNotNull(publicKey, "publicKey"); // TODO Make sure previously invisible sub-directories & files pop up in the client repositories! // If we grant access to a sub-directory later (either by (re)enabling the inheritance here or by // explicitly granting read access), the sub-directory (and all files) are not modified and therefore // are normally not synced (again). We somehow need to make sure that they indeed are re-synced. final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks( getCryptoRepoFileOrCreate(false), CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey); if (containsFromUserRepoKeyId(cryptoLinks, Collections.singleton(publicKey.getUserRepoKeyId()))) return; // There is already an active key which is accessible to the given user. Thus no need to generate a new crypto-link. final PlainCryptoKey plainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.clearanceKey, CipherOperationMode.DECRYPT); createCryptoLink(this, getUserRepoKeyPublicKeyOrCreate(publicKey), plainCryptoKey); } private RepoFileDtoConverter getRepoFileDtoConverter() { if (repoFileDtoConverter == null) repoFileDtoConverter = RepoFileDtoConverter.create(context.transaction); repoFileDtoConverter.setExcludeLocalIds(false); repoFileDtoConverter.setExcludeMutableData(false); return repoFileDtoConverter; } private byte[] createRepoFileDtoDataForCryptoRepoFile(final boolean forHisto) { // TODO can we assert here, that this code is invoked on the client-side with the plain-text RepoFile?! final RepoFileDtoConverter repoFileDtoConverter = getRepoFileDtoConverter(); // No need for local IDs. Because this DTO is shared across all repositories, local IDs make no sense. repoFileDtoConverter.setExcludeLocalIds(true); // Erase information like last-modified, hash and length, if not used in HistoCryptoRepoFile! repoFileDtoConverter.setExcludeMutableData(! forHisto); final RepoFileDto repoFileDto = repoFileDtoConverter.toRepoFileDto(repoFile, forHisto ? Integer.MAX_VALUE : 0); ((SsRepoFileDto) repoFileDto).setParentName(null); // only needed for uploading to the server. if (((SsRepoFileDto) repoFileDto).getSignature() != null) // must be null on the client - and this method is never called on the server. throw new IllegalStateException("repoFileDto.signature != null"); // Prevent overriding the real name with "", if we checked out a sub-directory. In this case, we cannot // change the localName locally and must make sure, it is preserved. if (cryptoRepoFile.getLocalName() == null || repoFile.getParent() != null) cryptoRepoFile.setLocalName(repoFileDto.getName()); else repoFileDto.setName(cryptoRepoFile.getLocalName()); return context.repoFileDtoIo.serializeWithGz(repoFileDto); } private void revokeReadPermission(final Set<Uid> userRepoKeyIds) { assertNotNull(userRepoKeyIds, "userRepoKeyIds"); if (userRepoKeyIds.isEmpty()) return; final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile == null) return; // There is no CryptoRepoFile, thus there can be no read-access which could be revoked. final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks( cryptoRepoFile, CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey); if (! containsFromUserRepoKeyId(cryptoLinks, userRepoKeyIds)) return; // There is no active key which is accessible to any of the given users. Thus no need to generate a new key. // There should be only one single *active* key, but due to collisions (multiple repos grant the same user // access), it might happen, that there are multiple. We therefore de-activate all we find. final Set<CryptoKey> processedCryptoKeys = new HashSet<CryptoKey>(); for (final CryptoLink cryptoLink : cryptoLinks) deactivateCryptoKeyAndDescendants(cryptoLink.getToCryptoKey(), processedCryptoKeys); // likely the same CryptoKey for all cryptoLinks => deduplicate via Set // Make sure the changes are written to the DB, so that a new active clearance key is generated in the following. context.transaction.flush(); // Create a *new* clearance key *immediately*, but only if needed. PlainCryptoKey clearanceKeyPlainCryptoKey = null; // And grant read access to everyone except for the users that should be removed. for (final CryptoLink cryptoLink : cryptoLinks) { final UserRepoKeyPublicKey fromUserRepoKeyPublicKey = cryptoLink.getFromUserRepoKeyPublicKey(); final Uid fromUserRepoKeyId = fromUserRepoKeyPublicKey == null ? null : fromUserRepoKeyPublicKey.getUserRepoKeyId(); if (fromUserRepoKeyId == null || userRepoKeyIds.contains(fromUserRepoKeyId)) continue; if (clearanceKeyPlainCryptoKey == null) clearanceKeyPlainCryptoKey = getActivePlainCryptoKeyOrCreate(CryptoKeyRole.clearanceKey, CipherOperationMode.DECRYPT); // The current user is already granted access when the clearing key was created above. // We thus need to check, if the current fromUserRepoKeyPublicKey still needs a CryptoLink. if (fromUserRepoKeyPublicKey != null && ! cryptoLinkDao.getActiveCryptoLinks( cryptoRepoFile, CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey, fromUserRepoKeyPublicKey).isEmpty()) continue; createCryptoLink(this, fromUserRepoKeyPublicKey, clearanceKeyPlainCryptoKey); } if (clearanceKeyPlainCryptoKey != null) createBacklinkKeyForFile(); createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively(); // createBacklinkKeyIfNeededParentsRecursively(); } private void createBacklinkKeyForFile() { if (! isDirectory()) getActivePlainCryptoKeyOrCreate(CryptoKeyRole.backlinkKey, CipherOperationMode.DECRYPT); } private void deactivateCryptoKeyAndDescendants(final CryptoKey cryptoKey, final Set<CryptoKey> processedCryptoKeys) { if (! processedCryptoKeys.add(cryptoKey)) return; if (cryptoKey.getCryptoKeyDeactivation() == null) deactivateCryptoKey(cryptoKey); for (final CryptoLink cryptoLink : cryptoKey.getOutCryptoLinks()) deactivateCryptoKeyAndDescendants(cryptoLink.getToCryptoKey(), processedCryptoKeys); } private void deactivateCryptoKey(final CryptoKey cryptoKey) { final CryptoKeyDeactivation cryptoKeyDeactivation = new CryptoKeyDeactivation(); cryptoKeyDeactivation.setCryptoKey(cryptoKey); sign(cryptoKeyDeactivation); cryptoKey.setCryptoKeyDeactivation(cryptoKeyDeactivation); cryptoKey.setLastSyncFromRepositoryId(null); } private void createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively() { // Only directories have a subdirKey (and further children). The backlinkKeys of the files // are optional and didn't get dirty, because they are not in the CryptoLink-chain of the parent. // The backlinkKey only got dirty, if this is a file. We handle this separately in // createBacklinkKeyIfNeededFile(). if (! isDirectory()) return; getActivePlainCryptoKeyOrCreate(CryptoKeyRole.subdirKey, CipherOperationMode.DECRYPT); getActivePlainCryptoKeyOrCreate(CryptoKeyRole.backlinkKey, CipherOperationMode.DECRYPT); for (final CryptreeNode child : getChildren()) child.createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively(); } // private void createBacklinkKeyIfNeededParentsRecursively() { // // If this is a file, the backlinkKey is optional - and created in createBacklinkKeyIfNeededFile(). // if (isDirectory()) // getActivePlainCryptoKeyOrCreate(CryptoKeyRole.backlinkKey, CryptoKeyPart.sharedSecret); // // final CryptreeNode parent = getParent(); // if (parent != null) // parent.createBacklinkKeyIfNeededParentsRecursively(); // } private boolean containsFromUserRepoKeyId(final Collection<CryptoLink> cryptoLinks, final Set<Uid> fromUserRepoKeyIds) { assertNotNull(cryptoLinks, "cryptoLinks"); assertNotNull(fromUserRepoKeyIds, "fromUserRepoKeyIds"); for (final CryptoLink cryptoLink : cryptoLinks) { final UserRepoKeyPublicKey fromUserRepoKeyPublicKey = cryptoLink.getFromUserRepoKeyPublicKey(); final Uid fromUserRepoKeyId = fromUserRepoKeyPublicKey == null ? null : fromUserRepoKeyPublicKey.getUserRepoKeyId(); if (fromUserRepoKeyId != null && fromUserRepoKeyIds.contains(fromUserRepoKeyId)) return true; } return false; } public Collection<CryptreeNode> getChildren() { if (! childrenLoaded) { if (cryptoRepoFile != null) { final CryptoRepoFileDao dao = context.transaction.getDao(CryptoRepoFileDao.class); final Collection<CryptoRepoFile> childCryptoRepoFiles = dao.getChildCryptoRepoFiles(cryptoRepoFile); for (final CryptoRepoFile childCryptoRepoFile : childCryptoRepoFiles) children.add(context.getCryptreeNodeOrCreate(this, null, null, childCryptoRepoFile)); } else if (repoFile != null) { final RepoFileDao dao = context.transaction.getDao(RepoFileDao.class); final Collection<RepoFile> childRepoFiles = dao.getChildRepoFiles(repoFile); for (final RepoFile childRepoFile : childRepoFiles) children.add(context.getCryptreeNodeOrCreate(this, null, childRepoFile, null)); } else throw new IllegalStateException("repoFile == null && cryptoRepoFile == null"); childrenLoaded = true; } return Collections.unmodifiableList(children); } protected boolean isDirectory() { if (repoFile != null) return repoFile instanceof Directory; return cryptoRepoFile.isDirectory(); } protected PlainCryptoKey getActivePlainCryptoKey(final CryptoKeyRole toCryptoKeyRole, final CipherOperationMode cipherOperationMode) { assertNotNull(toCryptoKeyRole, "toCryptoKeyRole"); assertNotNull(cipherOperationMode, "cipherOperationMode"); logger.debug("getActivePlainCryptoKey: cryptoRepoFile={} repoFile={} toCryptoKeyRole={} cipherOperationMode={}", cryptoRepoFile, repoFile, toCryptoKeyRole, cipherOperationMode); final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final CryptoKeyPart[] toCryptoKeyParts = toCryptoKeyRole.getCryptoKeyParts(cipherOperationMode); for (final CryptoKeyPart toCryptoKeyPart : toCryptoKeyParts) { final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks(getCryptoRepoFile(), toCryptoKeyRole, toCryptoKeyPart); final PlainCryptoKey plainCryptoKey = getPlainCryptoKey(cryptoLinks, toCryptoKeyPart); if (plainCryptoKey != null) return plainCryptoKey; } return null; } public PlainCryptoKey getPlainCryptoKeyForDecrypting(final CryptoKey cryptoKey) { assertNotNull(cryptoKey, "cryptoKey"); logger.debug("getPlainCryptoKeyForDecrypting: cryptoRepoFile={} repoFile={} cryptoKey={}", cryptoRepoFile, repoFile, cryptoKey); final PlainCryptoKey plainCryptoKey = getPlainCryptoKey(cryptoKey.getInCryptoLinks(), getCryptoKeyPartForDecrypting(cryptoKey)); return plainCryptoKey; // may be null! } private PlainCryptoKey getPlainCryptoKey(final Collection<CryptoLink> cryptoLinks, final CryptoKeyPart toCryptoKeyPart) { assertNotNull(cryptoLinks, "cryptoLinks"); assertNotNull(toCryptoKeyPart, "toCryptoKeyPart"); for (final CryptoLink cryptoLink : cryptoLinks) { if (toCryptoKeyPart != cryptoLink.getToCryptoKeyPart()) continue; final UserRepoKeyPublicKey fromUserRepoKeyPublicKey = cryptoLink.getFromUserRepoKeyPublicKey(); if (fromUserRepoKeyPublicKey != null) { logger.debug("getPlainCryptoKey: >>> cryptoRepoFile={} repoFile={} cryptoLink={} fromUserRepoKeyPublicKey={}", cryptoRepoFile, repoFile, cryptoLink, fromUserRepoKeyPublicKey); final Uid userRepoKeyId = fromUserRepoKeyPublicKey.getUserRepoKeyId(); final UserRepoKey userRepoKey = context.userRepoKeyRing.getUserRepoKey(userRepoKeyId); if (userRepoKey != null) { logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromUserRepoKeyPublicKey={}: DECRYPTED!", cryptoRepoFile, repoFile, cryptoLink, fromUserRepoKeyPublicKey); final byte[] plain = decryptLarge(cryptoLink.getToCryptoKeyData(), userRepoKey); return new PlainCryptoKey(cryptoLink.getToCryptoKey(), cryptoLink.getToCryptoKeyPart(), plain); } else logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromUserRepoKeyPublicKey={}: FAILED TO DECRYPT!", cryptoRepoFile, repoFile, cryptoLink, fromUserRepoKeyPublicKey); } else if (cryptoLink.getFromCryptoKey() == null) { // *not* encrypted logger.debug("getPlainCryptoKey: *** cryptoRepoFile={} repoFile={} cryptoLink={}: PLAIN!", cryptoRepoFile, repoFile, cryptoLink); return new PlainCryptoKey(cryptoLink.getToCryptoKey(), cryptoLink.getToCryptoKeyPart(), cryptoLink.getToCryptoKeyData()); } } for (final CryptoLink cryptoLink : cryptoLinks) { if (toCryptoKeyPart != cryptoLink.getToCryptoKeyPart()) continue; final CryptoKey fromCryptoKey = cryptoLink.getFromCryptoKey(); if (fromCryptoKey != null) { logger.debug("getPlainCryptoKey: >>> cryptoRepoFile={} repoFile={} cryptoLink={} fromCryptoKey={}", cryptoRepoFile, repoFile, cryptoLink, fromCryptoKey); final PlainCryptoKey plainFromCryptoKey = getPlainCryptoKey( fromCryptoKey.getInCryptoLinks(), getCryptoKeyPartForDecrypting(fromCryptoKey)); if (plainFromCryptoKey != null) { logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromCryptoKey={}: DECRYPTED!", cryptoRepoFile, repoFile, cryptoLink, fromCryptoKey); final byte[] plain = decrypt( cryptoLink.getToCryptoKeyData(), plainFromCryptoKey); return new PlainCryptoKey(cryptoLink.getToCryptoKey(), cryptoLink.getToCryptoKeyPart(), plain); } else logger.debug("getPlainCryptoKey: <<< cryptoRepoFile={} repoFile={} cryptoLink={} fromCryptoKey={}: FAILED TO DECRYPT!", cryptoRepoFile, repoFile, cryptoLink, fromCryptoKey); } } return null; } private CryptoKeyPart getCryptoKeyPartForDecrypting(final CryptoKey cryptoKey) { switch (cryptoKey.getCryptoKeyType()) { case asymmetric: return CryptoKeyPart.privateKey; case symmetric: return CryptoKeyPart.sharedSecret; default: throw new IllegalStateException("Unknown cryptoKey.cryptoKeyType: " + cryptoKey.getCryptoKeyType()); } } protected PlainCryptoKey getActivePlainCryptoKeyOrCreate(final CryptoKeyRole toCryptoKeyRole, final CipherOperationMode cipherOperationMode) { assertNotNull(toCryptoKeyRole, "toCryptoKeyRole"); assertNotNull(cipherOperationMode, "cipherOperationMode"); PlainCryptoKey plainCryptoKey = getActivePlainCryptoKey(toCryptoKeyRole, cipherOperationMode); if (plainCryptoKey == null) { final Class<? extends PlainCryptoKeyFactory> clazz = cryptoKeyRole2PlainCryptoKeyFactory.get(toCryptoKeyRole); assertNotNull(clazz, String.format("cryptoKeyRole2PlainCryptoKeyFactory[%s]", toCryptoKeyRole)); final PlainCryptoKeyFactory factory; try { factory = clazz.newInstance(); } catch (final Exception e) { throw new RuntimeException(String.format("Creating new instance of class %s failed: %s", clazz.getName(), e), e); } factory.setCryptreeNode(this); factory.setCipherOperationMode(cipherOperationMode); plainCryptoKey = factory.createPlainCryptoKey(); assertNotNull(plainCryptoKey, clazz.getName() + ".createPlainCryptoKey()"); if (plainCryptoKey.getCryptoKey().getCryptoKeyRole() != toCryptoKeyRole) throw new IllegalStateException(String.format("plainCryptoKey.cryptoKey.cryptoKeyRole != toCryptoKeyRole :: %s != %s", plainCryptoKey.getCryptoKey().getCryptoKeyRole(), toCryptoKeyRole)); final CryptoKeyDao cryptoKeyDao = context.transaction.getDao(CryptoKeyDao.class); final CryptoKey cryptoKey = cryptoKeyDao.makePersistent(plainCryptoKey.getCryptoKey()); plainCryptoKey = new PlainCryptoKey(cryptoKey, plainCryptoKey.getCryptoKeyPart(), plainCryptoKey.getCipherParameters()); } return plainCryptoKey; } /** * Gets the current data key as indicated by {@link CryptoRepoFile#getCryptoKey()}. * @return the current data key. Never <code>null</code>. */ public DataKey getDataKeyOrFail() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); return getDataKeyOrFail(cryptoRepoFile.getCryptoKey()); } /** * Gets the data key identified by the given {@ code cryptoKeyId}. * @param cryptoKeyId the unique ID of the {@link CryptoKey} from which to extract the plain key material. * @return the data key. Never <code>null</code>. */ public DataKey getDataKeyOrFail(final Uid cryptoKeyId) { assertNotNull(cryptoKeyId, "cryptoKeyId"); final CryptoKeyDao cryptoKeyDao = context.transaction.getDao(CryptoKeyDao.class); final CryptoKey cryptoKey = cryptoKeyDao.getCryptoKeyOrFail(cryptoKeyId); return getDataKeyOrFail(cryptoKey); } protected DataKey getDataKeyOrFail(final CryptoKey cryptoKey) { assertNotNull(cryptoKey, "cryptoKey"); // We can use the following method, because it's *symmetric* - thus it works for both decrypting and encrypting! final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(cryptoKey); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("Cannot decrypt dataKey for cryptoKeyID=%s (cryptoRepoFileId=%s)!", cryptoKey.getCryptoKeyId(), cryptoKey.getCryptoRepoFile().getCryptoRepoFileId())); assertNotNull(plainCryptoKey.getCryptoKey(), "plainCryptoKey.cryptoKey"); if (CryptoKeyRole.dataKey != plainCryptoKey.getCryptoKey().getCryptoKeyRole()) throw new IllegalStateException("CryptoKeyRole.dataKey != plainCryptoKey.getCryptoKey().getCryptoKeyRole()"); if (CryptoKeyPart.sharedSecret != plainCryptoKey.getCryptoKeyPart()) throw new IllegalStateException("CryptoKeyPart.sharedSecret != plainCryptoKey.getCryptoKeyPart()"); return new DataKey(cryptoKey.getCryptoKeyId(), plainCryptoKey.getKeyParameterOrFail()); } public CryptreeNode getParent() { if (parent == null) { if (repoFile != null && JDOHelper.isDeleted(repoFile)) { getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); } final RepoFile parentRepoFile = repoFile == null || JDOHelper.isDeleted(repoFile) ? null : repoFile.getParent(); final CryptoRepoFile parentCryptoRepoFile = cryptoRepoFile == null ? null : cryptoRepoFile.getParent(); if (parentRepoFile != null || parentCryptoRepoFile != null) parent = context.getCryptreeNodeOrCreate(null, this, parentRepoFile, parentCryptoRepoFile); } return parent; } public UserRepoKeyPublicKey getUserRepoKeyPublicKeyOrCreate(final UserRepoKey userRepoKey) { assertNotNull(userRepoKey, "userRepoKey"); return getUserRepoKeyPublicKeyOrCreate(userRepoKey.getPublicKey()); } public UserRepoKeyPublicKey getUserRepoKeyPublicKeyOrCreate(final UserRepoKey.PublicKey publicKey) { assertNotNull(publicKey, "publicKey"); return new UserRepoKeyPublicKeyHelper(getContext()).getUserRepoKeyPublicKeyOrCreate(publicKey); } /** * Grant a permission on the directory/file represented by this node. * <p> * <p> * If there is nothing to be granted, this method is a noop. * <p> * Or in other words: * If the user (more specifically, his repository-dependent {@code publicKey}) already has the permission * which is to be granted, this method returns silently without any effect. * @param permissionType the type of the permission to be granted. Must not be <code>null</code>. * @param publicKey the user's repository-dependent public-key. Must not be <code>null</code>. * @see #getGrantedPermissionTypes(Uid) * @see #revokePermission(PermissionType, Set) */ public void grantPermission(final PermissionType permissionType, final UserRepoKey.PublicKey publicKey) { assertNotNull(permissionType, "permissionType"); assertNotNull(publicKey, "publicKey"); if (isOwner(publicKey.getUserRepoKeyId())) return; // the owner always has all permissions - no need to grant anything! if (PermissionType.readUserIdentity == permissionType) { final CryptreeNode parent = getParent(); if (parent != null) { parent.grantPermission(permissionType, publicKey); return; } } // It is technically required to have read permission, when having write or grant permission. Therefore, // we simply grant it here. if (permissionType == PermissionType.read || permissionType == PermissionType.write || permissionType == PermissionType.grant) grantReadPermission(publicKey); if (PermissionType.read == permissionType) return; final Uid ownerUserRepoKeyId = context.getRepositoryOwnerOrFail().getUserRepoKeyPublicKey().getUserRepoKeyId(); if (ownerUserRepoKeyId.equals(publicKey.getUserRepoKeyId())) return; // It is technically required to have write permission, when having grant permission. Therefore, we // grant it here, too. Additionally, we grant readUserIdentity permission, as it makes no sense to manage // users, i.e. grant access to them, without seeing them ;-) if (PermissionType.grant == permissionType) { grantPermission(PermissionType.write, publicKey); grantPermission(PermissionType.readUserIdentity, publicKey); } final PermissionSet permissionSet = getPermissionSetOrCreate(); final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final UserRepoKeyPublicKey userRepoKeyPublicKey = getUserRepoKeyPublicKeyOrCreate(publicKey); final Collection<Permission> permissions = dao.getNonRevokedPermissions(permissionSet, permissionType, userRepoKeyPublicKey); if (permissions.isEmpty()) { Permission permission = new Permission(); permission.setPermissionSet(permissionSet); permission.setPermissionType(permissionType); permission.setUserRepoKeyPublicKey(userRepoKeyPublicKey); sign(permission); permission = dao.makePersistent(permission); assertPermissionOk(permission); } if (PermissionType.grant == permissionType) ensureParentHasAsymmetricActiveSubdirKey(); if (PermissionType.readUserIdentity == permissionType) createUserIdentityLinksVisibleFor(userRepoKeyPublicKey); } public void setPermissionsInherited(final boolean inherited) { if (inherited == isPermissionsInherited()) return; final PermissionSet permissionSet = getPermissionSetOrCreate(); if (inherited) { // TODO Make sure previously invisible sub-directories & files pop up in the client repositories! // If we grant access to a sub-directory later (either by (re)enabling the inheritance here or by // explicitly granting read access), the sub-directory (and all files) are not modified and therefore // are normally not synced (again). We somehow need to make sure that they indeed are re-synced. final PermissionSetInheritance permissionSetInheritance = new PermissionSetInheritance(); permissionSetInheritance.setPermissionSet(permissionSet); sign(permissionSetInheritance); permissionSet.getPermissionSetInheritances().add(permissionSetInheritance); } else { final RepositoryOwner repositoryOwner = context.getRepositoryOwnerOrFail(); final PublicKey ownerPublicKey = repositoryOwner.getUserRepoKeyPublicKey().getPublicKey(); grantReadPermission(ownerPublicKey); final boolean currentUserIsOwner = context.userRepoKeyRing.getUserRepoKey(ownerPublicKey.getUserRepoKeyId()) != null; if (! currentUserIsOwner) { // TODO since the inheritance is interrupted, the current user does not have grant access anymore. // We need to either extend the grant access chain (better) or make this operation only available to the owner. logger.warn("This is not yet cleanly implemented and likely causes an error.", new UnsupportedOperationException("NYI")); } for (final PermissionSetInheritance permissionSetInheritance : permissionSet.getPermissionSetInheritances()) { if (permissionSetInheritance.getRevoked() == null) { permissionSetInheritance.setRevoked(new Date()); sign(permissionSetInheritance); } } // There should be only one single *active* key, but due to collisions (multiple repos grant the same user // access), it might happen, that there are multiple. We therefore de-activate all we find. final Set<CryptoKey> processedCryptoKeys = new HashSet<CryptoKey>(); final Collection<CryptoKey> subdirKeys = context.transaction.getDao(CryptoKeyDao.class).getActiveCryptoKeys(getCryptoRepoFileOrCreate(false), CryptoKeyRole.subdirKey); for (final CryptoKey subdirKey : subdirKeys) deactivateCryptoKeyAndDescendants(subdirKey, processedCryptoKeys); // createBacklinkKeyForFile(); // TODO do we need this - especially for the children? createSubdirKeyAndBacklinkKeyIfNeededChildrenRecursively(); } } public boolean isPermissionsInherited() { final PermissionSet permissionSet = getPermissionSet(); if (permissionSet == null) return true; // This method is for the UI, hence we use the revoked state - not the validTo. for (final PermissionSetInheritance permissionSetInheritance : permissionSet.getPermissionSetInheritances()) { if (permissionSetInheritance.getRevoked() == null) return true; } return false; } private void ensureParentHasAsymmetricActiveSubdirKey() { final CryptreeNode parent = getParent(); final CryptoRepoFile parentCryptoRepoFile = parent == null ? null : parent.getCryptoRepoFileOrCreate(false); if (parentCryptoRepoFile == null) return; final CryptoKeyDao cryptoKeyDao = context.transaction.getDao(CryptoKeyDao.class); final Collection<CryptoKey> activeSubdirKeys = cryptoKeyDao.getActiveCryptoKeys(parentCryptoRepoFile, CryptoKeyRole.subdirKey); boolean hasAsymmetryActiveSubdirKey = false; for (final CryptoKey activeSubdirKey : activeSubdirKeys) { switch (activeSubdirKey.getCryptoKeyType()) { case asymmetric: hasAsymmetryActiveSubdirKey = true; break; case symmetric: deactivateCryptoKey(activeSubdirKey); break; default: throw new IllegalStateException("Unknown CryptoKeyType: " + activeSubdirKey.getCryptoKeyType()); } } if (! hasAsymmetryActiveSubdirKey) parent.getActivePlainCryptoKeyOrCreate(CryptoKeyRole.subdirKey, CipherOperationMode.DECRYPT); } /** * Revoke a permission on the directory/file represented by this node. * <p> * If there is nothing to be revoked, this method is a noop. * <p> * Or in other words: * If none of the users (more specifically, their repository-dependent keys) have the permission which is * to be revoked, this method returns silently without any effect. The same happens when the {@code userRepoKeyIds} * is empty. * @param permissionType the type of the permission to be revoked. Must not be <code>null</code>. * @param userRepoKeyIds identifiers of all those keys from which to revoke the permission. Must not be <code>null</code>. * May be empty, which causes this method to return without any effect. * @see #getGrantedPermissionTypes(Uid) * @see #grantPermission(PermissionType, PublicKey) */ public void revokePermission(final PermissionType permissionType, final Set<Uid> userRepoKeyIds) { assertNotNull(permissionType, "permissionType"); assertNotNull(userRepoKeyIds, "userRepoKeyIds"); if (PermissionType.readUserIdentity == permissionType) { final CryptreeNode parent = getParent(); if (parent != null) { parent.revokePermission(permissionType, userRepoKeyIds); return; } // Revoke grant permission - technically not really needed but it makes no sense to manage invisible/unknown users. revokeGrantPermissionOfAllCryptoRepoFiles(userRepoKeyIds); } if (PermissionType.read == permissionType) { // Since it is technically required to have read permission, when having write or grant permission, we // revoke grant and write permission, too. revokePermission(PermissionType.write, userRepoKeyIds); // revokePermission(PermissionType.grant, userRepoKeyIds); // is implicitly done by revoking 'write' permission. revokeReadPermission(userRepoKeyIds); return; } if (PermissionType.write == permissionType) { // grant requires write, hence we must revoke grant, too, if we want to revoke write. revokePermission(PermissionType.grant, userRepoKeyIds); } final PermissionSet permissionSet = getPermissionSet(); if (permissionSet == null) return; final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final Collection<Permission> permissions = dao.getNonRevokedPermissions(permissionSet, permissionType, userRepoKeyIds); for (final Permission permission : permissions) { permissionsAlreadyCheckedOk.remove(permission); permission.setRevoked(new Date()); sign(permission); assertPermissionOk(permission); } if (PermissionType.readUserIdentity == permissionType) { if (existsAtLeastOneUserIdentityLinkFor(userRepoKeyIds)) new UserRepoKeyPublicKeyHelper(getContext()).removeUserIdentityLinksAfterRevokingReadUserIdentityPermission(); } } /** * Gets the {@link PermissionType}s granted to the directory/file represented by this node. * <p> * <b>Important:</b> In contrast to {@link #assertHasPermission(boolean, Uid, PermissionType, Date) assertHasPermission(...)} this * method operates on the current node, only! It does not take parents / inheritance into account. * <p> * <b>Important:</b> If the specified user has {@link PermissionType#readUserIdentity readUserIdentity}, this * {@code PermissionType} is always part of the result, no matter on which node this method is invoked! This is, * because {@code readUserIdentity} is not associated with a directory - it's global! Technically, it is assigned * to the root (at least right now - this might change later), but semantically, it is not associated with any. * * @param userRepoKeyId the user-key's identifier for which to determine the permissions granted. * @return the {@link PermissionType}s assigned to this node. Never <code>null</code>, but maybe empty! * @see #grantPermission(PermissionType, PublicKey) * @see #revokePermission(PermissionType, Set) * @see #assertHasPermission(boolean, Uid, PermissionType, Date) */ public Set<PermissionType> getGrantedPermissionTypes(final Uid userRepoKeyId) { assertNotNull(userRepoKeyId, "userRepoKeyId"); final Set<PermissionType> result = EnumSet.noneOf(PermissionType.class); if (isOwner(userRepoKeyId)) // the owner has *all* permissions - always! result.addAll(Arrays.asList(PermissionType.values())); else { final PermissionDao pDao = context.transaction.getDao(PermissionDao.class); if (! pDao.getNonRevokedPermissions(PermissionType.readUserIdentity, userRepoKeyId).isEmpty()) result.add(PermissionType.readUserIdentity); final PermissionSet permissionSet = getPermissionSet(); if (permissionSet != null) { if (! pDao.getNonRevokedPermissions(permissionSet, PermissionType.grant, userRepoKeyId).isEmpty()) result.add(PermissionType.grant); if (! pDao.getNonRevokedPermissions(permissionSet, PermissionType.write, userRepoKeyId).isEmpty()) result.add(PermissionType.write); } if (hasReadPermissionHere(userRepoKeyId)) result.add(PermissionType.read); } return result; } private boolean hasReadPermissionHereOrInherited(final Uid userRepoKeyId) { if (hasReadPermissionHere(userRepoKeyId)) return true; if (isPermissionsInherited()) { final CryptreeNode parent = getParent(); if (parent != null) return parent.hasReadPermissionHereOrInherited(userRepoKeyId); } return false; } private boolean hasReadPermissionHere(final Uid userRepoKeyId) { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); if (cryptoRepoFile != null) { // If there is no CryptoRepoFile, there can be no read-access. final UserRepoKeyPublicKeyDao urkpkDao = context.transaction.getDao(UserRepoKeyPublicKeyDao.class); final UserRepoKeyPublicKey userRepoKeyPublicKey = urkpkDao.getUserRepoKeyPublicKey(userRepoKeyId); if (userRepoKeyPublicKey != null) { // if there is no UserRepoKeyPublicKey, there can be no read-access! final CryptoLinkDao cryptoLinkDao = context.transaction.getDao(CryptoLinkDao.class); final Collection<CryptoLink> cryptoLinks = cryptoLinkDao.getActiveCryptoLinks( cryptoRepoFile, CryptoKeyRole.clearanceKey, CryptoKeyPart.privateKey, userRepoKeyPublicKey); if (! cryptoLinks.isEmpty()) return true; } } return false; } private void createUserIdentityLinksVisibleFor(final UserRepoKeyPublicKey userRepoKeyPublicKey) { // Not necessary, because UserRepoKeyPublicKeyHelper.createMissingUserIdentities() is invoked in every sync. } private boolean existsAtLeastOneUserIdentityLinkFor(final Set<Uid> userRepoKeyIds) { assertNotNull(userRepoKeyIds, "userRepoKeyIds"); final UserRepoKeyPublicKeyDao urkpkDao = getContext().transaction.getDao(UserRepoKeyPublicKeyDao.class); final UserIdentityLinkDao uilDao = getContext().transaction.getDao(UserIdentityLinkDao.class); for (Uid userRepoKeyId : userRepoKeyIds) { final UserRepoKeyPublicKey forUserRepoKeyPublicKey = urkpkDao.getUserRepoKeyPublicKeyOrFail(userRepoKeyId); final Collection<UserIdentityLink> userIdentityLinks = uilDao.getUserIdentityLinksFor(forUserRepoKeyPublicKey); if (! userIdentityLinks.isEmpty()) return true; } return false; } private void revokeGrantPermissionOfAllCryptoRepoFiles(final Set<Uid> userRepoKeyIds) { assertNotNull(userRepoKeyIds, "userRepoKeyIds"); final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final Set<CryptoRepoFile> cryptoRepoFiles = new HashSet<>(); final Collection<Permission> permissions = dao.getNonRevokedPermissions(PermissionType.grant, userRepoKeyIds); for (final Permission permission : permissions) cryptoRepoFiles.add(permission.getPermissionSet().getCryptoRepoFile()); for (final CryptoRepoFile cryptoRepoFile : cryptoRepoFiles) getContext().getCryptreeNodeOrCreate(cryptoRepoFile.getCryptoRepoFileId()).revokePermission(PermissionType.grant, userRepoKeyIds); } /** * @param anyCryptoRepoFile <code>true</code> to indicate that the {@link Permission} does not need to be available on the * level of this node's {@link CryptoRepoFile} (it is thus independent from this context); <code>false</code> to indicate * that is must be available here on this level (i.e. granted directly or inherited from a parent). * @param userRepoKeyId * @param permissionType * @param timestamp */ public void assertHasPermission( final boolean anyCryptoRepoFile, final Uid userRepoKeyId, final PermissionType permissionType, final Date timestamp ) throws AccessDeniedException { assertNotNull(userRepoKeyId, "userRepoKeyId"); assertNotNull(permissionType, "permissionType"); assertNotNull(timestamp, "timestamp"); if (isOwner(userRepoKeyId)) return; // The owner always has all permissions. String additionalExceptionMsg = null; final UserRepoKeyPublicKey userRepoKeyPublicKey = context.transaction.getDao(UserRepoKeyPublicKeyDao.class).getUserRepoKeyPublicKeyOrFail(userRepoKeyId); if (userRepoKeyPublicKey instanceof InvitationUserRepoKeyPublicKey) { final InvitationUserRepoKeyPublicKey invUserRepoKeyPublicKey = (InvitationUserRepoKeyPublicKey) userRepoKeyPublicKey; if (timestamp.compareTo(invUserRepoKeyPublicKey.getValidTo()) <= 0) { // Using a delegation via the invitiation-key is only allowed, if there is a corresponding replacement-request! // This reduces the potential to abuse this possibility (to grant access to other people). final UserRepoKeyPublicKeyReplacementRequestDao dao = context.transaction.getDao(UserRepoKeyPublicKeyReplacementRequestDao.class); if (dao.getUserRepoKeyPublicKeyReplacementRequestsForOldKey(invUserRepoKeyPublicKey).isEmpty()) throwAccessDeniedException(permissionType, "There is no UserRepoKeyPublicKeyReplacementRequest for " + invUserRepoKeyPublicKey); final Uid signingUserRepoKeyId = invUserRepoKeyPublicKey.getSignature().getSigningUserRepoKeyId(); assertHasPermission(anyCryptoRepoFile, signingUserRepoKeyId, permissionType, invUserRepoKeyPublicKey.getSignature().getSignatureCreated()); // Using 'timestamp' here means the signing user must still have permissions, when the invitation was consumed. // This is maybe not perfect, but maybe it's exactly what we want... at least it should be OK. Or should be better // to use the timestamp of the invitation? This is what we do now. return; } else additionalExceptionMsg = String.format( "userRepoKeyPublicKey is an InvitationUserRepoKeyPublicKey, but it expired on '%s', which is before the given timestamp '%s'!", ISO8601.formatDate(invUserRepoKeyPublicKey.getValidTo()), ISO8601.formatDate(timestamp)); } final Set<Permission> permissions = new HashSet<Permission>(); if (PermissionType.read == permissionType) { long timeDifferenceToNow = Math.abs(System.currentTimeMillis() - timestamp.getTime()); if (timeDifferenceToNow > 5 * 60 * 1000) throw new UnsupportedOperationException("assertHasPermission(...) does not yet support permissionType 'read' combined with a timestamp that is not *now*!"); if (hasReadPermissionHereOrInherited(userRepoKeyId)) return; } else { collectPermissions(permissions, anyCryptoRepoFile, permissionType, userRepoKeyId, timestamp); final Set<Permission> permissionsIndicatingBackdatedSignature = extractPermissionsIndicatingBackdatedSignature(permissions); if (! permissions.isEmpty()) return; // all is fine => silently return. if (! permissionsIndicatingBackdatedSignature.isEmpty()) { final String exceptionMsg = String.format("Found '%s' permission(s) for userRepoKeyId=%s and timestamp=%s, but it (or they) indicates backdating outside of allowed range!", permissionType, userRepoKeyId, timestamp); throwAccessDeniedException(permissionType, exceptionMsg); } } final String exceptionMsg = String.format("No '%s' permission found for userRepoKeyId=%s and timestamp=%s!", permissionType, userRepoKeyId, ISO8601.formatDate(timestamp)) + (isEmpty(additionalExceptionMsg) ? "" : (" " + additionalExceptionMsg)); throwAccessDeniedException(permissionType, exceptionMsg); } private void throwAccessDeniedException(final PermissionType permissionType, final String exceptionMessage) throws AccessDeniedException { switch (permissionType) { case grant: throw new GrantAccessDeniedException(exceptionMessage); case write: throw new WriteAccessDeniedException(exceptionMessage); case read: throw new ReadAccessDeniedException(exceptionMessage); case readUserIdentity: throw new ReadUserIdentityAccessDeniedException(exceptionMessage); default: throw new IllegalArgumentException("Unknown permissionType: " + permissionType); } } private boolean isOwner(final Uid userRepoKeyId) { assertNotNull(userRepoKeyId, "userRepoKeyId"); return userRepoKeyId.equals(context.getRepositoryOwnerOrFail().getUserRepoKeyPublicKey().getUserRepoKeyId()); } /** * @param anyCryptoRepoFile <code>true</code> to indicate that the {@link Permission} does not need to be available on the * level of this node's {@link CryptoRepoFile} (it is thus independent from this context); <code>false</code> to indicate * that is must be available here on this level (i.e. granted directly or inherited from a parent). * @param permissionType * @param userRepoKeyId * @param timestamp * @return */ private void collectPermissions(final Set<Permission> permissions, boolean anyCryptoRepoFile, final PermissionType permissionType, final Uid userRepoKeyId, final Date timestamp) { assertNotNull(permissionType, "permissionType"); assertNotNull(userRepoKeyId, "userRepoKeyId"); assertNotNull(timestamp, "timestamp"); // There is no Permission object with *read* permission. Hence, if we ever need to check this // here, we have to check it differently (=> tracing back the cryptree's crypto-links)! switch (permissionType) { case grant: case write: break; case readUserIdentity: anyCryptoRepoFile = true; // it's global!!! it cannot be assigned on a directory/file level! break; default: throw new IllegalArgumentException("PermissionType unknown or not allowed here: " + permissionType); } // final UserRepoKeyPublicKey userRepoKeyPublicKey = context.transaction.getDao(UserRepoKeyPublicKeyDao.class).getUserRepoKeyPublicKeyOrFail(userRepoKeyId); // if (userRepoKeyPublicKey instanceof InvitationUserRepoKeyPublicKey) { // final InvitationUserRepoKeyPublicKey invUserRepoKeyPublicKey = (InvitationUserRepoKeyPublicKey) userRepoKeyPublicKey; // if (timestamp.compareTo(invUserRepoKeyPublicKey.getValidTo()) <= 0) { // final Uid signingUserRepoKeyId = invUserRepoKeyPublicKey.getSignature().getSigningUserRepoKeyId(); // collectPermissions(permissions, anyCryptoRepoFile, permissionType, signingUserRepoKeyId, invUserRepoKeyPublicKey.getSignature().getSignatureCreated()); // // Using 'timestamp' here means the signing user must still have permissions, when the invitation was consumed. // // This is maybe not perfect, but maybe it's exactly what we want... at least it should be OK. Or should be better // // use the timestamp of the invitation? // } // } final PermissionSet permissionSet = anyCryptoRepoFile ? null : getPermissionSet(); if (anyCryptoRepoFile || permissionSet != null) { final PermissionDao dao = context.transaction.getDao(PermissionDao.class); final Set<Permission> ps = anyCryptoRepoFile ? new HashSet<>(dao.getValidPermissions(permissionType, userRepoKeyId, timestamp)) : new HashSet<>(dao.getValidPermissions(permissionSet, permissionType, userRepoKeyId, timestamp)); ps.removeAll(permissionsBeingCheckedNow); if (!ps.isEmpty()) { for (final Permission permission : ps) assertPermissionOk(permission); // TODO is this necessary? isn't it sufficient to check when it's written into the DB? } permissions.addAll(ps); } if (! anyCryptoRepoFile && (permissionSet == null || permissionSet.isPermissionsInherited(timestamp))) { final CryptreeNode parent = getParent(); if (parent != null) parent.collectPermissions(permissions, anyCryptoRepoFile, permissionType, userRepoKeyId, timestamp); } } private Set<Permission> extractPermissionsIndicatingBackdatedSignature(final Set<Permission> permissions) { final Set<Permission> result = new HashSet<Permission>(permissions); Date backdatingOldestPermissionValidTo = null; if (getContext().isOnServer) { // We prevent backdating only on the server, because it is likely that a client didn't sync for ages // TODO not sure, if this is the best location for this test. but I think this code here is only called, if a new thingy is *written* on the server (never on read). for (final Iterator<Permission> it = permissions.iterator(); it.hasNext(); ) { final Permission permission = it.next(); if (permission.getValidTo() != null) { if (backdatingOldestPermissionValidTo == null) { // We make it configurable per repository - not (yet) per subdir/file. final File file = getContext().transaction.getLocalRepoManager().getLocalRoot(); backdatingOldestPermissionValidTo = new Date(System.currentTimeMillis() - CryptoConfigUtil.getBackdatingMaxPermissionValidToAge(file)); } if (permission.getValidTo().before(backdatingOldestPermissionValidTo)) { result.add(permission); it.remove(); } } } } return result; } private void assertPermissionOk(final Permission permission) throws SignatureException, AccessDeniedException { assertNotNull(permission, "permission"); if (permissionsAlreadyCheckedOk.contains(permission)) return; if (! permissionsBeingCheckedNow.add(permission)) throw new IllegalStateException("Circular permission check! " + permission); try { assertSignatureOk(permission); permissionsAlreadyCheckedOk.add(permission); } finally { permissionsBeingCheckedNow.remove(permission); } } public void assertSignatureOk(final WriteProtected entity) throws SignatureException, AccessDeniedException { assertNotNull(entity, "entity"); final Uid crfIdControllingPermissions = entity.getCryptoRepoFileIdControllingPermissions(); if (crfIdControllingPermissions == null) this.assertSignatureOk(entity, true, entity.getPermissionTypeRequiredForWrite()); else if (crfIdControllingPermissions.equals(this.getCryptoRepoFile().getCryptoRepoFileId())) this.assertSignatureOk(entity, false, entity.getPermissionTypeRequiredForWrite()); else { final CryptreeNode cryptreeNode = context.getCryptreeNodeOrCreate(crfIdControllingPermissions); cryptreeNode.assertSignatureOk(entity, false, entity.getPermissionTypeRequiredForWrite()); } } public void assertSignatureOk( final Signable signable, final boolean anyCryptoRepoFile, final PermissionType requiredPermissionType ) throws SignatureException, AccessDeniedException { assertNotNull(signable, "signable"); // requiredPermissionType may be null, because a write-protected entity may not require any permission-type, but only behave like an ordinary Signable. // *always* verify signature! context.signableVerifier.verify(signable); if (requiredPermissionType != null) { // only check, if a requiredPermissionType was given. final Uid signingUserRepoKeyId = signable.getSignature().getSigningUserRepoKeyId(); assertHasPermission(anyCryptoRepoFile, signingUserRepoKeyId, requiredPermissionType, signable.getSignature().getSignatureCreated()); } } public PermissionSet getPermissionSet() { if (permissionSet == null) { final PermissionSetDao dao = context.transaction.getDao(PermissionSetDao.class); permissionSet = dao.getPermissionSet(getCryptoRepoFileOrCreate(false)); if (permissionSet != null) assertSignatureOk(permissionSet); } return permissionSet; } public PermissionSet getPermissionSetOrCreate() { PermissionSet permissionSet = getPermissionSet(); if (permissionSet == null) { permissionSet = new PermissionSet(); permissionSet.setCryptoRepoFile(assertNotNull(getCryptoRepoFile(), "getCryptoRepoFile()")); sign(permissionSet); final PermissionSetDao dao = context.transaction.getDao(PermissionSetDao.class); this.permissionSet = permissionSet = dao.makePersistent(permissionSet); setPermissionsInherited(true); // this should be the default for a new PermissionSet } return permissionSet; } public void sign(final WriteProtected writeProtected) throws AccessDeniedException { assertNotNull(writeProtected, "writeProtectedEntity"); final Uid crfIdControllingPermissions = writeProtected.getCryptoRepoFileIdControllingPermissions(); final UserRepoKey userRepoKey; if (crfIdControllingPermissions == null) userRepoKey = this.getUserRepoKeyOrFail(true, writeProtected.getPermissionTypeRequiredForWrite()); else if (crfIdControllingPermissions.equals(this.getCryptoRepoFile().getCryptoRepoFileId())) userRepoKey = this.getUserRepoKeyOrFail(false, writeProtected.getPermissionTypeRequiredForWrite()); else { final CryptreeNode cryptreeNode = context.getCryptreeNodeOrCreate(crfIdControllingPermissions); userRepoKey = cryptreeNode.getUserRepoKeyOrFail(false, writeProtected.getPermissionTypeRequiredForWrite()); } context.getSignableSigner(userRepoKey).sign(writeProtected); } /** * @param anyCryptoRepoFile <code>true</code> to indicate that the {@link Permission} does not need to be available on the * level of this node's {@link CryptoRepoFile} (it is thus independent from this context); <code>false</code> to indicate * that is must be available here on this level (i.e. granted directly or inherited from a parent). * @param permissionType * @return */ public UserRepoKey getUserRepoKey(final boolean anyCryptoRepoFile, final PermissionType permissionType) { assertNotNull(permissionType, "permissionType"); // There is no Permission object with *read* permission. Hence, if we ever need to check this // here, we have to check it differently (=> tracing back the cryptree's crypto-links)! switch (permissionType) { case grant: case write: break; default: throw new IllegalArgumentException("PermissionType unknown or not allowed here: " + permissionType); } final Date now = new Date(); for (final UserRepoKey userRepoKey : context.userRepoKeyRing.getPermanentUserRepoKeys(context.serverRepositoryId)) { final boolean owner = isOwner(userRepoKey.getUserRepoKeyId()); final Set<Permission> permissions = new HashSet<Permission>(); if (! owner) collectPermissions(permissions, anyCryptoRepoFile, permissionType, userRepoKey.getUserRepoKeyId(), now); if (owner || ! permissions.isEmpty()) { getUserRepoKeyPublicKeyOrCreate(userRepoKey); // Make sure it is persisted in the DB. return userRepoKey; } } return null; } private UserRepoKey getUserRepoKeyOrFail(final boolean anyCryptoRepoFile, final PermissionType permissionType) { final UserRepoKey userRepoKey = getUserRepoKey(anyCryptoRepoFile, permissionType); if (userRepoKey == null) { final String message = String.format("No '%s' permission for any UserRepoKey of the current UserRepoKeyRing for: %s", permissionType, (repoFile != null ? repoFile.getPath() : cryptoRepoFile)); switch (permissionType) { case grant: throw new GrantAccessDeniedException(message); case read: throw new ReadAccessDeniedException(message); case write: throw new WriteAccessDeniedException(message); default: throw new IllegalArgumentException("Unknown PermissionType: " + permissionType); } } return userRepoKey; } public void clearCryptoRepoFileDeleted() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); deletePreliminaryDeletions(); if (cryptoRepoFile.getDeleted() != null) { cryptoRepoFile.setDeleted(null); cryptoRepoFile.setDeletedByIgnoreRule(false); cryptoRepoFile.setLastSyncFromRepositoryId(null); sign(cryptoRepoFile); updateCryptoConfigPropSetIfConfigFile(); } } protected void deletePreliminaryDeletions() { final CryptoRepoFile cryptoRepoFile = getCryptoRepoFile(); assertNotNull(cryptoRepoFile, "cryptoRepoFile"); PreliminaryDeletionDao pdDao = getContext().transaction.getDao(PreliminaryDeletionDao.class); PreliminaryDeletion preliminaryDeletion = pdDao.getPreliminaryDeletion(cryptoRepoFile); if (preliminaryDeletion != null) pdDao.deletePersistent(preliminaryDeletion); } public ConfigPropSetDto getParentConfigPropSetDtoIfNeeded() { final Uid id = context.getCryptoRepoFileIdForRemotePathPrefixOrFail(); if (! id.equals(getCryptoRepoFile().getCryptoRepoFileId())) throw new IllegalStateException("cryptoRepoFileIdForRemotePathPrefix != cryptoRepoFile.cryptoRepoFileId :: " + id + " != " + getCryptoRepoFile().getCryptoRepoFileId()); final List<CryptoConfigPropSet> cryptoConfigPropSets = getCryptoConfigPropSetsAbove(); if (! isCryptoConfigPropSetModifiedAfterLastSync(cryptoConfigPropSets)) return null; Properties mergedProperties = null; for (final CryptoConfigPropSet cryptoConfigPropSet : cryptoConfigPropSets) { final ConfigPropSetDto configPropSetDto = getConfigPropSetDto(cryptoConfigPropSet); if (configPropSetDto == null) continue; final Properties properties = configPropSetDto.toProperties(); if (mergedProperties == null) mergedProperties = properties; else mergedProperties.putAll(properties); } // We must not return null, if there was a modification. Returning null means to *not* // overwrite the parent.properties. But it must be rewritten. return mergedProperties == null ? new ConfigPropSetDto() : new ConfigPropSetDto(mergedProperties); } private ConfigPropSetDto getConfigPropSetDto(CryptoConfigPropSet cryptoConfigPropSet) { assertNotNull(cryptoConfigPropSet, "cryptoConfigPropSet"); final PlainCryptoKey plainCryptoKey = getPlainCryptoKeyForDecrypting(cryptoConfigPropSet.getCryptoKey()); if (plainCryptoKey == null) throw new ReadAccessDeniedException(String.format("The CryptoConfigPropSet with cryptoRepoFileId=%s could not be decrypted! Access rights missing?!", cryptoConfigPropSet.getCryptoRepoFileId())); final byte[] encryptedData = cryptoConfigPropSet.getConfigPropSetDtoData(); if (encryptedData == null || encryptedData.length == 0) return null; final byte[] plainData = decrypt(encryptedData, plainCryptoKey); return new ConfigPropSetDtoIo().deserializeWithGz(plainData); } private boolean isCryptoConfigPropSetModifiedAfterLastSync(final List<CryptoConfigPropSet> cryptoConfigPropSets) { assertNotNull(cryptoConfigPropSets, "cryptoConfigPropSets"); final RemoteRepository remoteRepository = context.transaction.getDao(RemoteRepositoryDao.class).getRemoteRepositoryOrFail(context.remoteRepositoryId); for (final CryptoConfigPropSet cryptoConfigPropSet : cryptoConfigPropSets) { if (cryptoConfigPropSet.getLocalRevision() > remoteRepository.getLocalRevision()) return true; } return false; } private List<CryptoConfigPropSet> getCryptoConfigPropSetsAbove() { final CryptoConfigPropSetDao ccpsDao = context.transaction.getDao(CryptoConfigPropSetDao.class); final List<CryptoConfigPropSet> result = new ArrayList<>(); CryptoRepoFile cryptoRepoFile = assertNotNull(getCryptoRepoFile(), "cryptoRepoFile"); while (true) { cryptoRepoFile = cryptoRepoFile.getParent(); if (cryptoRepoFile == null) break; final CryptoConfigPropSet cryptoConfigPropSet = ccpsDao.getCryptoConfigPropSet(cryptoRepoFile); if (cryptoConfigPropSet != null) result.add(cryptoConfigPropSet); } Collections.reverse(result); return result; } }
https://github.com/subshare/subshare/issues/52 Added missing null-check. Warning was always logged and operation always aborted :-(
org.subshare/org.subshare.local/src/main/java/org/subshare/local/CryptreeNode.java
https://github.com/subshare/subshare/issues/52
Java
lgpl-2.1
e296fe58e9a2d83f91c7d098e0140fd3bc96742b
0
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2007 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.HashMap; import java.util.Map; import org.intermine.dataconversion.DBConverter; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.sql.Database; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.ItemHelper; /** * A DBConverter with helper methods for bio sources. * @author Kim Rutherford */ public abstract class BioDBConverter extends DBConverter { private Map<String, Item> chromosomes = new HashMap<String, Item>(); private Item organism; // the DataSet Item for the evidence collection of the new Location private final Item dataSet; // the DataSource for the Synonym objects private final Item dataSource; /** * Create a new BioDBConverter object. * @param database the database to read from * @param tgtModel the Model used by the object store we will write to with the ItemWriter * @param writer an ItemWriter used to handle the resultant Items * @param taxonId organism taxon id to use to create the Organism object for BioEntitys * @param dataSetTitle the title attribute to user when creating the DataSet item * @param dataSourceName the name for the DataSource for this conversion * @throws ObjectStoreException thrown if ItemWriter.store() fails */ public BioDBConverter(Database database, Model tgtModel, ItemWriter writer, int taxonId, String dataSetTitle, String dataSourceName) throws ObjectStoreException { super(database, tgtModel, writer); dataSource = makeItem("DataSource"); dataSource.setAttribute("name", dataSourceName); writer.store(ItemHelper.convert(dataSource)); organism = makeItem("Organism"); organism.setAttribute("taxonId", String.valueOf(taxonId)); writer.store(ItemHelper.convert(organism)); dataSet = makeItem("DataSet"); dataSet.setAttribute("title", dataSetTitle); writer.store(ItemHelper.convert(dataSet)); } /** * Make a Location Relation between a LocatedSequenceFeature and a Chromosome. * @param chromosomeIdentifier Chromosome identifier * @param locatedSequenceFeature the feature * @param start the start position * @param end the end position * @param strand the strand * @return the new Location object * @throws ObjectStoreException if an Item can't be stored */ protected Item makeLocation(String chromosomeIdentifier, Item locatedSequenceFeature, int start, int end, int strand) throws ObjectStoreException { Item chromosome = getChromosome(chromosomeIdentifier); Item location = makeItem("Location"); if (start < end) { location.setAttribute("start", String.valueOf(start)); location.setAttribute("end", String.valueOf(end)); } else { location.setAttribute("start", String.valueOf(end)); location.setAttribute("end", String.valueOf(start)); } location.addAttribute(new Attribute("strand", String.valueOf(strand))); location.setReference("object", chromosome); location.setReference("subject", locatedSequenceFeature); location.addToCollection("evidence", dataSet); getItemWriter().store(ItemHelper.convert(location)); return location; } /** * The Organism item created from the taxon id passed to the constructor. * @return the Organism Item */ public Item getOrganism() { return organism; } /** * The DataSet item created from the dataset title passed to the constructor. * @return the DataSet Item */ public Item getDataSet() { return dataSet; } private Item getChromosome(String identifier) throws ObjectStoreException { Item chromosome = chromosomes.get(identifier); if (chromosome == null) { chromosome = makeItem("Chromosome"); chromosome.setAttribute("identifier", identifier); chromosome.setReference("organism", getOrganism()); chromosomes.put(identifier, chromosome); getItemWriter().store(ItemHelper.convert(chromosome)); } return chromosome; } /** * Create and return a new Synonym, but don't store it. * @param subject the Synonym subject * @param type the Synonym type * @param value the Synonym value * @param evidence the Synonym evidence (eg. a DataSet) * @return the new Synonym */ public Item createSynonym(Item subject, String type, String value, boolean isPrimary, Item evidence) { Item synonym = makeItem("Synonym"); synonym.setAttribute("type", type); synonym.setAttribute("value", value); synonym.setAttribute("isPrimary", String.valueOf(isPrimary)); synonym.setReference("subject", subject); synonym.setReference("source", dataSource); synonym.addToCollection("evidence", evidence); return synonym; } }
bio/core/main/src/org/intermine/bio/dataconversion/BioDBConverter.java
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2007 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.HashMap; import java.util.Map; import org.intermine.dataconversion.DBConverter; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.sql.Database; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.ItemHelper; /** * A DBConverter with helper methods for bio sources. * @author Kim Rutherford */ public abstract class BioDBConverter extends DBConverter { private Map<String, Item> chromosomes = new HashMap<String, Item>(); private Item organism; // the DataSet Item for the evidence collection of the new Location private final Item dataSet; // the DataSource for the Synonym objects private final Item dataSource; /** * Create a new BioDBConverter object. * @param database the database to read from * @param tgtModel the Model used by the object store we will write to with the ItemWriter * @param writer an ItemWriter used to handle the resultant Items * @param taxonId organism taxon id to use to create the Organism object for BioEntitys * @param dataSetTitle the title attribute to user when creating the DataSet item * @param datasource_name * @throws ObjectStoreException thrown if ItemWriter.store() fails */ public BioDBConverter(Database database, Model tgtModel, ItemWriter writer, int taxonId, String dataSetTitle, String dataSourceName) throws ObjectStoreException { super(database, tgtModel, writer); dataSource = makeItem("DataSource"); dataSource.setAttribute("name", dataSourceName); writer.store(ItemHelper.convert(dataSource)); organism = makeItem("Organism"); organism.setAttribute("taxonId", String.valueOf(taxonId)); writer.store(ItemHelper.convert(organism)); dataSet = makeItem("DataSet"); dataSet.setAttribute("title", dataSetTitle); writer.store(ItemHelper.convert(dataSet)); } /** * Make a Location Relation between a LocatedSequenceFeature and a Chromosome. * @param chromosomeIdentifier Chromosome identifier * @param locatedSequenceFeature the feature * @param start the start position * @param end the end position * @param strand the strand * @return the new Location object * @throws ObjectStoreException if an Item can't be stored */ protected Item makeLocation(String chromosomeIdentifier, Item locatedSequenceFeature, int start, int end, int strand) throws ObjectStoreException { Item chromosome = getChromosome(chromosomeIdentifier); Item location = makeItem("Location"); if (start < end) { location.setAttribute("start", String.valueOf(start)); location.setAttribute("end", String.valueOf(end)); } else { location.setAttribute("start", String.valueOf(end)); location.setAttribute("end", String.valueOf(start)); } location.addAttribute(new Attribute("strand", String.valueOf(strand))); location.setReference("object", chromosome); location.setReference("subject", locatedSequenceFeature); location.addToCollection("evidence", dataSet); getItemWriter().store(ItemHelper.convert(location)); return location; } /** * The Organism item created from the taxon id passed to the constructor. * @return the Organism Item */ public Item getOrganism() { return organism; } /** * The DataSet item created from the dataset title passed to the constructor. * @return the DataSet Item */ public Item getDataSet() { return dataSet; } private Item getChromosome(String identifier) throws ObjectStoreException { Item chromosome = chromosomes.get(identifier); if (chromosome == null) { chromosome = makeItem("Chromosome"); chromosome.setAttribute("identifier", identifier); chromosome.setReference("organism", getOrganism()); chromosomes.put(identifier, chromosome); getItemWriter().store(ItemHelper.convert(chromosome)); } return chromosome; } /** * Create and return a new Synonym, but don't store it. * @param subject the Synonym subject * @param type the Synonym type * @param value the Synonym value * @param evidence the Synonym evidence (eg. a DataSet) * @return the new Synonym */ public Item createSynonym(Item subject, String type, String value, boolean isPrimary, Item evidence) { Item synonym = makeItem("Synonym"); synonym.setAttribute("type", type); synonym.setAttribute("value", value); synonym.setAttribute("isPrimary", String.valueOf(isPrimary)); synonym.setReference("subject", subject); synonym.setReference("source", dataSource); synonym.addToCollection("evidence", evidence); return synonym; } }
Checkstyle fix. Former-commit-id: 894079c649c59c3eadd74b8bb5a85995224ecb3b
bio/core/main/src/org/intermine/bio/dataconversion/BioDBConverter.java
Checkstyle fix.
Java
lgpl-2.1
2b4238a4c472cf7c5bb8181e20ccbd527c42f29d
0
levants/lightmare
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); public static final String DATA_SOURCE_PATH_DEF = "./ds"; // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embedded mode) private static final String CONFIG_FILE = "./config/configuration.yaml"; // Configuration keys properties for deployment private static final String HOT_DEPLOYMENT_KEY = "hotDeployment"; private static final String WATCH_STATUS_KEY = "watchStatus"; private static final String LIBRARY_PATH_KEY = "libraryPaths"; // Persistence provider property keys private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig"; private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities"; private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName"; private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; // Configuration properties for deployment private static String ADMIN_USERS_PATH; // Is configuration server or client (default is server) private static boolean server = (Boolean) Config.SERVER.value; private static boolean remote; // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } @SuppressWarnings("unchecked") Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(Config.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(Config.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(Config.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(Config.POOL_PROPERTIES.key); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(Config.POOL_PROVIDER_TYPE.key); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(Config.POOL_PROPERTIES_PATH.key); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(Config.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value); } contains = containsConfigKey(Config.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.PORT.key, Config.PORT.value); } contains = containsConfigKey(Config.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value); } contains = containsConfigKey(Config.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * (Integer) Config.WORKER_POOL.value; String workerProperty = String.valueOf(workers); setConfigValue(Config.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.CONNECTION_TIMEOUT.key, Config.CONNECTION_TIMEOUT.value); } // Sets default values is application on server or client mode Object serverValue = getConfigValue(Config.SERVER.key); if (ObjectUtils.notNull(serverValue)) { if (serverValue instanceof Boolean) { server = (Boolean) serverValue; } else { server = Boolean.valueOf(serverValue.toString()); } } Object remoteValue = getConfigValue(Config.REMOTE.key); if (ObjectUtils.notNull(remoteValue)) { if (remoteValue instanceof Boolean) { remote = (Boolean) remoteValue; } else { remote = Boolean.valueOf(remoteValue.toString()); } } } /** * Merges configuration with default properties */ @SuppressWarnings("unchecked") public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(Config.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = (Set<DeploymentDirectory>) Config.DEMPLOYMENT_PATH.value; setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> innerConfig = (Map<Object, Object>) configuration; configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public boolean isRemote() { return remote; } public void setRemote(boolean remoteValue) { remote = remoteValue; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(Config.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(Config.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(Config.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(Config.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(Config.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(Config.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(Config.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(Config.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(Config.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(Config.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(Config.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(SWAP_DATASOURCE_KEY, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(SCAN_ARCHIVES_KEY, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
src/main/java/org/lightmare/config/Configuration.java
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); public static final String DATA_SOURCE_PATH_DEF = "./ds"; // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embedded mode) private static final String CONFIG_FILE = "./config/configuration.yaml"; // Configuration keys properties for deployment private static final String HOT_DEPLOYMENT_KEY = "hotDeployment"; private static final String WATCH_STATUS_KEY = "watchStatus"; private static final String LIBRARY_PATH_KEY = "libraryPaths"; // Persistence provider property keys private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig"; private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities"; private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName"; private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; // Configuration properties for deployment private static String ADMIN_USERS_PATH; // Is configuration server or client (default is server) private static boolean server = (Boolean) Config.SERVER.value; private static boolean remote; // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } @SuppressWarnings("unchecked") Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(Config.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(Config.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(Config.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(Config.POOL_PROPERTIES.key); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(Config.POOL_PROVIDER_TYPE.key); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(Config.POOL_PROPERTIES_PATH.key); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(Config.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value); } contains = containsConfigKey(Config.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.PORT.key, Config.PORT.value); } contains = containsConfigKey(Config.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value); } contains = containsConfigKey(Config.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * (Integer) Config.WORKER_POOL.value; String workerProperty = String.valueOf(workers); setConfigValue(Config.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.CONNECTION_TIMEOUT.key, Config.CONNECTION_TIMEOUT.value); } // Sets default values is application on server or client mode Object serverValue = getConfigValue(Config.SERVER.key); if (ObjectUtils.notNull(serverValue)) { if (serverValue instanceof Boolean) { server = (Boolean) serverValue; } else { server = Boolean.valueOf(serverValue.toString()); } } Object remoteValue = getConfigValue(Config.REMOTE.key); if (ObjectUtils.notNull(remoteValue)) { if (remoteValue instanceof Boolean) { remote = (Boolean) remoteValue; } else { remote = Boolean.valueOf(remoteValue.toString()); } } } /** * Merges configuration with default properties */ @SuppressWarnings("unchecked") public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(Config.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = (Set<DeploymentDirectory>) Config.DEMPLOYMENT_PATH.value; setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> innerConfig = (Map<Object, Object>) configuration; configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public boolean isRemote() { return remote; } public void setRemote(boolean remoteValue) { remote = remoteValue; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(Config.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(Config.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(Config.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(Config.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(Config.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(Config.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(Config.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(Config.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(Config.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(Config.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(Config.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(SWAP_DATASOURCE_KEY, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(SCAN_ARCHIVES_KEY, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
improved Configuration utilities
src/main/java/org/lightmare/config/Configuration.java
improved Configuration utilities
Java
unlicense
655ed35425059266be20aab82532863f8dec518c
0
charlesmadere/that-lil-hummingbird
package com.charlesmadere.hummingbird.activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.widget.LinearLayout; import com.charlesmadere.hummingbird.R; import com.charlesmadere.hummingbird.models.ErrorInfo; import com.charlesmadere.hummingbird.models.Feed; import com.charlesmadere.hummingbird.models.MediaStory; import com.charlesmadere.hummingbird.networking.ApiResponse; import com.charlesmadere.hummingbird.views.RecyclerViewPaginator; import com.charlesmadere.hummingbird.views.RefreshLayout; import com.charlesmadere.hummingbird.views.SpaceItemDecoration; import java.lang.ref.WeakReference; import butterknife.BindView; public class MediaStoryActivity extends BaseDrawerActivity implements RecyclerViewPaginator.Listeners, SwipeRefreshLayout.OnRefreshListener { private static final String TAG = "MediaStoryActivity"; private static final String CNAME = MediaStoryActivity.class.getCanonicalName(); private static final String EXTRA_MEDIA_STORY = CNAME + ".MediaStory"; private static final String KEY_FEED = "Feed"; private Feed mFeed; private MediaStory mMediaStory; private RecyclerViewPaginator mPaginator; @BindView(R.id.llError) LinearLayout mError; @BindView(R.id.recyclerView) RecyclerView mRecyclerView; @BindView(R.id.refreshLayout) RefreshLayout mRefreshLayout; public static Intent getLaunchIntent(final Context context, final MediaStory mediaStory) { return new Intent(context, MediaStoryActivity.class) .putExtra(EXTRA_MEDIA_STORY, mediaStory); } private void fetchFeed() { mRefreshLayout.setRefreshing(true); // TODO } @Override public String getActivityName() { return TAG; } @Override public boolean isLoading() { // TODO return false; } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_story); final Intent intent = getIntent(); mMediaStory = intent.getParcelableExtra(EXTRA_MEDIA_STORY); if (savedInstanceState != null && !savedInstanceState.isEmpty()) { mFeed = savedInstanceState.getParcelable(KEY_FEED); } if (mFeed == null || !mFeed.hasSubstories()) { fetchFeed(); } else { showFeed(mFeed); } } @Override public void onRefresh() { fetchFeed(); } @Override protected void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); if (mFeed != null && mFeed.hasSubstories()) { outState.putParcelable(KEY_FEED, mFeed); } } @Override protected void onViewsBound() { super.onViewsBound(); mRefreshLayout.setOnRefreshListener(this); SpaceItemDecoration.apply(mRecyclerView, false, R.dimen.root_padding_half); mPaginator = new RecyclerViewPaginator(mRecyclerView, this); } @Override public void paginate() { // TODO } private void paginationComplete() { // TODO } private void paginationNoMore() { // TODO } private void showError() { // TODO } private void showFeed(final Feed feed) { mFeed = feed; // TODO } private static class GetSubstoriesListener implements ApiResponse<Feed> { private final WeakReference<MediaStoryActivity> mActivityReference; private GetSubstoriesListener(final MediaStoryActivity activity) { mActivityReference = new WeakReference<>(activity); } @Override public void failure(@Nullable final ErrorInfo error) { final MediaStoryActivity activity = mActivityReference.get(); if (activity != null && !activity.isDestroyed()) { activity.showError(); } } @Override public void success(final Feed feed) { final MediaStoryActivity activity = mActivityReference.get(); if (activity != null && !activity.isDestroyed()) { if (feed.hasSubstories()) { } else { } } } } private static class PaginateFeedListener implements ApiResponse<Feed> { private final WeakReference<MediaStoryActivity> mActivityReference; private final int mSubstoriesSize; private PaginateFeedListener(final MediaStoryActivity activity) { mActivityReference = new WeakReference<>(activity); mSubstoriesSize = activity.mFeed.getSubstoriesSize(); } @Override public void failure(@Nullable final ErrorInfo error) { final MediaStoryActivity activity = mActivityReference.get(); if (activity != null && !activity.isDestroyed()) { activity.paginationNoMore(); } } @Override public void success(final Feed feed) { final MediaStoryActivity activity = mActivityReference.get(); if (activity != null && !activity.isDestroyed()) { if (feed.getSubstoriesSize() > mSubstoriesSize) { activity.paginationComplete(); } else { activity.paginationNoMore(); } } } } }
project/app/src/main/java/com/charlesmadere/hummingbird/activities/MediaStoryActivity.java
package com.charlesmadere.hummingbird.activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.widget.LinearLayout; import com.charlesmadere.hummingbird.R; import com.charlesmadere.hummingbird.models.Feed; import com.charlesmadere.hummingbird.models.MediaStory; import com.charlesmadere.hummingbird.views.RecyclerViewPaginator; import com.charlesmadere.hummingbird.views.RefreshLayout; import butterknife.BindView; public class MediaStoryActivity extends BaseDrawerActivity implements RecyclerViewPaginator.Listeners, SwipeRefreshLayout.OnRefreshListener { private static final String TAG = "MediaStoryActivity"; private static final String CNAME = MediaStoryActivity.class.getCanonicalName(); private static final String EXTRA_MEDIA_STORY = CNAME + ".MediaStory"; private static final String KEY_FEED = "Feed"; private Feed mFeed; private MediaStory mMediaStory; @BindView(R.id.llError) LinearLayout mError; @BindView(R.id.recyclerView) RecyclerView mRecyclerView; @BindView(R.id.refreshLayout) RefreshLayout mRefreshLayout; public static Intent getLaunchIntent(final Context context, final MediaStory mediaStory) { return new Intent(context, MediaStoryActivity.class) .putExtra(EXTRA_MEDIA_STORY, mediaStory); } private void fetchFeed() { mRefreshLayout.setRefreshing(true); // TODO } @Override public String getActivityName() { return TAG; } @Override public boolean isLoading() { // TODO return false; } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_story); final Intent intent = getIntent(); mMediaStory = intent.getParcelableExtra(EXTRA_MEDIA_STORY); if (savedInstanceState != null && !savedInstanceState.isEmpty()) { mFeed = savedInstanceState.getParcelable(KEY_FEED); } // TODO } @Override public void onRefresh() { fetchFeed(); } @Override protected void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); if (mFeed != null && mFeed.hasSubstories()) { outState.putParcelable(KEY_FEED, mFeed); } } @Override protected void onViewsBound() { super.onViewsBound(); mRefreshLayout.setOnRefreshListener(this); } @Override public void paginate() { // TODO } private void showError() { // TODO } private void showFeed(final Feed feed) { // TODO } }
progress on fetching data
project/app/src/main/java/com/charlesmadere/hummingbird/activities/MediaStoryActivity.java
progress on fetching data
Java
apache-2.0
9f202f6c00dd2c6c046434b86f965e2a8fae8b07
0
ibrahim1hero1/Calccedo
/* * Calccedo Library * hint this code under ApacheLicense */ package com.precious.calccedo.handlers; import com.precious.calccedo.configuration.Configuration; import java.util.ArrayList; /** * * @author Ibrahim Abdsaid Hanna * ibrahim.seniore@gmail.com */ class Eshortuct extends CalccedoHandler{ String leftTemp; char operandType; int leftOperandIndex; int rightOperandIndex; ArrayList<Character> list=new ArrayList<Character>(); public Eshortuct(){ } public Eshortuct(String leftTemp,char operandType,int leftOperandIndex,int rightOperandIndex){ this.leftTemp=leftTemp; this.operandType=operandType; this.leftOperandIndex=leftOperandIndex; this.rightOperandIndex=rightOperandIndex; } // process E shortuct to not conflict with - and + operand public Eshortuct process(String subformula,int Eindex){ String leftTemp="E"; char operandType = 0; int leftOperandIndex = 0; int rightOperandIndex = 0; boolean ignore=false; list.clear(); list.add('/'); list.add('%'); list.add('*'); list.add('^'); for(int i=Eindex;i>=0;i--){ if(!isNumber(subformula.charAt(i))){ if(isMinus(subformula.charAt(i))&&ignore==false){ leftOperandIndex=i; leftTemp=subformula.charAt(i)+leftTemp; break; } else if(isPlus(subformula.charAt(i))){ leftOperandIndex=i; break; } else if(list.contains(subformula.charAt(i))){ leftOperandIndex=i; break; } } else{ leftTemp=subformula.charAt(i)+leftTemp; } } for(int j=Eindex;j<subformula.length();j++){ if(!isNumber(subformula.charAt(j))){ if(isMinus(subformula.charAt(j))&&subformula.charAt(j-1)=='E'&&ignore==false){ leftTemp=leftTemp+'-'; ignore=true; } else if(isPlus(subformula.charAt(j))){ operandType='+'; rightOperandIndex=j; break; } else if(ignore==true&&(isMinus(subformula.charAt(j))||isPlus(subformula.charAt(j)))){ operandType=subformula.charAt(j); rightOperandIndex=j; break; } else if(isMinus(subformula.charAt(j))||isPlus(subformula.charAt(j))){ operandType=subformula.charAt(j); rightOperandIndex=j; break; } else if(list.contains(subformula.charAt(j))){ operandType=subformula.charAt(j); rightOperandIndex=j; break; } } else{ leftTemp=leftTemp+subformula.charAt(j); } } if(Configuration.deepTracing) System.out.println("leftTemp:"+leftTemp+"\noperandType:"+operandType+"\nleftOperandIndex"+leftOperandIndex+"\nrightOperandIndex"+rightOperandIndex+"\n"); return new Eshortuct(leftTemp, operandType,leftOperandIndex,rightOperandIndex); } public boolean isMinus(char c){ return c=='-'; } public boolean isPlus(char c){ return c=='+'; } }
com/precious/calccedo/handlers/Eshortuct.java
/* * Calccedo Library * hint this code under Apache License */ package com.precious.calccedo.handlers; /** * * @author Ibrahim Abdsaid Hanna * ibrahim.seniore@gmail.com */ public class Eshortuct extends CalccedoHandler{ String leftTemp; char operandType; int leftOperandIndex; int rightOperandIndex; public Eshortuct(){ } public Eshortuct(String leftTemp,char operandType,int leftOperandIndex,int rightOperandIndex){ this.leftTemp=leftTemp; this.operandType=operandType; this.leftOperandIndex=leftOperandIndex; this.rightOperandIndex=rightOperandIndex; } // process E shortuct to not conflict with - and + operand public Eshortuct process(String subformula,int Eindex){ String leftTemp="E"; char operandType = 0; int leftOperandIndex = 0; int rightOperandIndex = 0; boolean ignore=false; for(int i=Eindex;i>=0;i--){ if(!isNumber(subformula.charAt(i))){ if(isMinus(subformula.charAt(i))&&ignore==false){ leftOperandIndex=i; leftTemp=subformula.charAt(i)+leftTemp; break; } else if(isPlus(subformula.charAt(i))){ leftOperandIndex=i; break; } } else{ leftTemp=subformula.charAt(i)+leftTemp; } } for(int j=Eindex;j<subformula.length();j++){ if(!isNumber(subformula.charAt(j))){ if(isMinus(subformula.charAt(j))&&Eindex+1=='-'&&ignore==false){ leftTemp=leftTemp+'-'; ignore=true; } else if(isPlus(subformula.charAt(j))){ operandType='+'; rightOperandIndex=j; break; } else if(ignore==true&&(isMinus(subformula.charAt(j))||isPlus(subformula.charAt(j)))){ operandType=subformula.charAt(j); rightOperandIndex=j; break; } else if(isMinus(subformula.charAt(j))||isPlus(subformula.charAt(j))){ operandType=subformula.charAt(j); rightOperandIndex=j; break; } } else{ leftTemp=leftTemp+subformula.charAt(j); } } return new Eshortuct(leftTemp, operandType,leftOperandIndex,rightOperandIndex); } public boolean isMinus(char c){ return c=='-' ? true:false; } public boolean isPlus(char c){ return c=='+' ? true:false; } }
Update Eshortuct.java
com/precious/calccedo/handlers/Eshortuct.java
Update Eshortuct.java
Java
apache-2.0
c5bccb27191415aba1986ba1f12079ba4da832d7
0
burris/dwr,burris/dwr
/* * Copyright 2005 Joe Walker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.directwebremoting; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.directwebremoting.extend.ScriptSessionManager; import org.directwebremoting.io.JavascriptObject; /** * A collection of APIs that manage reverse ajax APIs. * <p>See {@link #withAllSessions} for a menu of the various different with* * methods. * @author Joe Walker [joe at getahead dot ltd dot uk] */ public class Browser { /** * Execute some task (represented by a {@link Runnable}) and aim the output * at all browser window open at all pages in this web application. * It is likely that a more fine-grained broadcast method will be applicable * to most situations. The other with* methods in this class provide extra * ways to filter the set of pages to broadcast to. This option could be * useful if all pages contain an 'update' area, or to broadcast status * information: Window.alert("System reboot in 20mins. Please log off"); * To send UI code to browser windows looking at a specific page, see the * {@link #withPage} method. To send to a custom set of browser windows, * see the {@link #withAllSessionsFiltered} method. To send to a specific * session, use {@link #withSession}. * @param task A code block to execute */ public static void withAllSessions(Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withAllSessions(serverContext, task); } /** * Execute a task an send the output to a subset of the total list of users. * The {@link ScriptSessionFilter} defines which subset. * This method could be used to alert administrators wherever they are on a * site about urgent action that need attention. * @param filter Used to define the set of browser windows which should * receive the update. * @param task A code block to execute */ public static void withAllSessionsFiltered(ScriptSessionFilter filter, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withAllSessionsFiltered(serverContext, filter, task); } /** * Execute a task and aim the output at all the browser windows open at a * given page in this web application. No further filtering is performed. * To send to a subset of the browser windows viewing a page, see the * {@link #withPageFiltered} method. * @param page The page to send to, excluding protocol/host/port specifiers * but including context path and servlet path. For example to send to * <code>http://example.com:8080/webapp/controller/path/index.html</code>, * you should use "/webapp/controller/path/index.html" or since the default * PageNormalizer understands default pages, this is the same as sending to * browsers viewing "/webapp/controller/path/". * To discover the contextPath at runtime you can use * javax.servlet.ServletContext#getContextPath with servlet 2.5, or before * version 2.5 you can also use {@link ServerContext#getContextPath} or * {@link javax.servlet.http.HttpServletRequest#getContextPath}. * @param task A code block to execute */ public static void withPage(String page, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withPage(serverContext, page, task); } /** * Execute a task and aim the output at a subset of the users on a page. * This method is useful when you have a small number of pages that each * have a significant number of functions on them. The filter allows you to * select the set of users that will be interested in the update. * @param page The page to send to. See {@link #withPage} for details * @param filter Used to define the set of browser windows which should * receive the update. * @param task A code block to execute */ public static void withPageFiltered(String page, ScriptSessionFilter filter, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withPageFiltered(serverContext, page, filter, task); } /** * Execute a task and aim the output at all the browser windows open at the * same page as the current request. No further filtering is performed. * This implies that this method is only of use from a DWR created thread. * To send to a subset of the browser windows viewing a page, see the * {@link #withCurrentPageFiltered} method. * @param task A code block to execute */ public static void withCurrentPage(Runnable task) { WebContext webContext = WebContextFactory.get(); String page = webContext.getCurrentPage(); ScriptSessionManager sessionManager = webContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(sessions, task); } /** * Execute a task and aim the output at a subset of the browser windows open * at the same page as the current request. The filter allows you to select * the set of users that will be interested in the update. * This implies that this method is only of use from a DWR created thread. * @param filter Used to define the set of browser windows which should * receive the update. * @param task A code block to execute */ public static void withCurrentPageFiltered(ScriptSessionFilter filter, Runnable task) { WebContext webContext = WebContextFactory.get(); String page = webContext.getCurrentPage(); ScriptSessionManager sessionManager = webContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(filter(sessions, filter), task); } /** * Execute a task and aim the output at a specific script session. This * method is likely to be useful for directed updates that originate away * from a thread started by the browser window in question. Examples include * an instant message, or the results of a slow method invocation. * This method is implicit in anything called from a DWR thread, so should * not need to be used to send UI updates back to an originating browser. * @param sessionId The {@link ScriptSession}.id of the browser window * @param task A code block to execute */ public static void withSession(String sessionId, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withSession(serverContext, sessionId, task); } /** * If a browser passes an object or function to DWR then DWR may need to * release the reference that DWR keeps. If the server-side manifestation of * this object is a proxy implemented interface, then there is no place for * a close method, so this function allows you to close proxy implemented * interfaces. * @param proxy An proxy created interface implementation from a browser * that we no longer need. */ public static void close(Object proxy) { if (proxy instanceof JavascriptObject) { JavascriptObject dproxy = (JavascriptObject) proxy; dproxy.close(); } } /** * This method discovers the sessions that are currently being targeted * by browser updates. * <p> * It will generally only be useful to authors of reverse ajax UI proxy * APIs. Using it directly may cause scaling problems * @return The list of current browser windows. */ protected static Collection<ScriptSession> getTargetSessions() { Collection<ScriptSession> sessions = target.get(); if (sessions != null) { return sessions; } WebContext webContext = WebContextFactory.get(); if (webContext != null) { sessions = new ArrayList<ScriptSession>(); sessions.add(webContext.getScriptSession()); return sessions; } throw new IllegalStateException("No current UI to manipulate. See org.directwebremoting.Browser to set one."); } /** * Execute a task and aim the output at a specific set of users. This method * is private because the filter version is likely to be just as easy to use * and potentially better suited to a clustered environment. * @param sessions The browser window to send the generated scripts to * @param task A code block to execute */ private static void withSessions(Collection<ScriptSession> sessions, Runnable task) { if (sessions.size() > 0) { log.debug("Executing task (" + task.getClass().getSimpleName() + ") against " + sessions.size() + " sessions."); target.set(sessions); task.run(); target.remove(); } } /** * Utility method to run a filter over a set of script sessions. * @param start The un-filtered set of script sessions * @param filter The filter to use to trim this list down * @return The subset of script sessions left by the filter */ private static Collection<ScriptSession> filter(Collection<ScriptSession> start, ScriptSessionFilter filter) { Collection<ScriptSession> use = new ArrayList<ScriptSession>(); for (ScriptSession session : start) { if (filter.match(session)) { use.add(session); } } return use; } /** * As {@link #withAllSessions(Runnable)}, but for use when there is more * than one copy of DWR in the ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ private static void withAllSessions(ServerContext serverContext, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getAllScriptSessions(); withSessions(sessions, task); } /** * As {@link #withAllSessionsFiltered(ScriptSessionFilter, Runnable)}, but * for use when there is more than one copy of DWR in the ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ private static void withAllSessionsFiltered(ServerContext serverContext, ScriptSessionFilter filter, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> all = sessionManager.getAllScriptSessions(); withSessions(filter(all, filter), task); } /** * As {@link #withPage(String, Runnable)}, but for use when there is more * than one copy of DWR in the ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ private static void withPage(ServerContext serverContext, String page, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(sessions, task); } /** * As {@link #withPageFiltered}, but for use when there is more than one copy of DWR * in a ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ private static void withPageFiltered(ServerContext serverContext, String page, ScriptSessionFilter filter, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(filter(sessions, filter), task); } /** * As {@link #withSession(String, Runnable)}, but for use when there is more * than one copy of DWR in a ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ private static void withSession(ServerContext serverContext, String sessionId, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); ScriptSession session = sessionManager.getScriptSession(sessionId, null, null); Collection<ScriptSession> sessions = new ArrayList<ScriptSession>(); if (session != null) { sessions.add(session); } withSessions(sessions, task); } /** * ThreadLocal in which the list of sessions are stored. */ private static final ThreadLocal<Collection<ScriptSession>> target = new ThreadLocal<Collection<ScriptSession>>(); /** * The log stream */ private static final Log log = LogFactory.getLog(Browser.class); }
core/api/main/java/org/directwebremoting/Browser.java
/* * Copyright 2005 Joe Walker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.directwebremoting; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.directwebremoting.extend.ScriptSessionManager; import org.directwebremoting.io.JavascriptObject; /** * A collection of APIs that manage reverse ajax APIs. * <p>See {@link #withAllSessions} for a menu of the various different with* * methods. * @author Joe Walker [joe at getahead dot ltd dot uk] */ public class Browser { /** * Execute some task (represented by a {@link Runnable}) and aim the output * at all browser window open at all pages in this web application. * It is likely that a more fine-grained broadcast method will be applicable * to most situations. The other with* methods in this class provide extra * ways to filter the set of pages to broadcast to. This option could be * useful if all pages contain an 'update' area, or to broadcast status * information: Window.alert("System reboot in 20mins. Please log off"); * To send UI code to browser windows looking at a specific page, see the * {@link #withPage} method. To send to a custom set of browser windows, * see the {@link #withAllSessionsFiltered} method. To send to a specific * session, use {@link #withSession}. * @param task A code block to execute */ public static void withAllSessions(Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withAllSessions(serverContext, task); } /** * As {@link #withAllSessions(Runnable)}, but for use when there is more * than one copy of DWR in the ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ public static void withAllSessions(ServerContext serverContext, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getAllScriptSessions(); withSessions(sessions, task); } /** * Execute a task an send the output to a subset of the total list of users. * The {@link ScriptSessionFilter} defines which subset. * This method could be used to alert administrators wherever they are on a * site about urgent action that need attention. * @param filter Used to define the set of browser windows which should * receive the update. * @param task A code block to execute */ public static void withAllSessionsFiltered(ScriptSessionFilter filter, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withAllSessionsFiltered(serverContext, filter, task); } /** * As {@link #withAllSessionsFiltered(ScriptSessionFilter, Runnable)}, but * for use when there is more than one copy of DWR in the ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ public static void withAllSessionsFiltered(ServerContext serverContext, ScriptSessionFilter filter, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> all = sessionManager.getAllScriptSessions(); withSessions(filter(all, filter), task); } /** * Execute a task and aim the output at all the browser windows open at a * given page in this web application. No further filtering is performed. * To send to a subset of the browser windows viewing a page, see the * {@link #withPageFiltered} method. * @param page The page to send to, excluding protocol/host/port specifiers * but including context path and servlet path. For example to send to * <code>http://example.com:8080/webapp/controller/path/index.html</code>, * you should use "/webapp/controller/path/index.html" or since the default * PageNormalizer understands default pages, this is the same as sending to * browsers viewing "/webapp/controller/path/". * To discover the contextPath at runtime you can use * javax.servlet.ServletContext#getContextPath with servlet 2.5, or before * version 2.5 you can also use {@link ServerContext#getContextPath} or * {@link javax.servlet.http.HttpServletRequest#getContextPath}. * @param task A code block to execute */ public static void withPage(String page, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withPage(serverContext, page, task); } /** * As {@link #withPage(String, Runnable)}, but for use when there is more * than one copy of DWR in the ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ public static void withPage(ServerContext serverContext, String page, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(sessions, task); } /** * Execute a task and aim the output at a subset of the users on a page. * This method is useful when you have a small number of pages that each * have a significant number of functions on them. The filter allows you to * select the set of users that will be interested in the update. * @param page The page to send to. See {@link #withPage} for details * @param filter Used to define the set of browser windows which should * receive the update. * @param task A code block to execute */ public static void withPageFiltered(String page, ScriptSessionFilter filter, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withPageFiltered(serverContext, page, filter, task); } /** * As {@link #withPageFiltered}, but for use when there is more than one copy of DWR * in a ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ public static void withPageFiltered(ServerContext serverContext, String page, ScriptSessionFilter filter, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(filter(sessions, filter), task); } /** * Execute a task and aim the output at all the browser windows open at the * same page as the current request. No further filtering is performed. * This implies that this method is only of use from a DWR created thread. * To send to a subset of the browser windows viewing a page, see the * {@link #withCurrentPageFiltered} method. * @param task A code block to execute */ public static void withCurrentPage(Runnable task) { WebContext webContext = WebContextFactory.get(); String page = webContext.getCurrentPage(); ScriptSessionManager sessionManager = webContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(sessions, task); } /** * Execute a task and aim the output at a subset of the browser windows open * at the same page as the current request. The filter allows you to select * the set of users that will be interested in the update. * This implies that this method is only of use from a DWR created thread. * @param filter Used to define the set of browser windows which should * receive the update. * @param task A code block to execute */ public static void withCurrentPageFiltered(ScriptSessionFilter filter, Runnable task) { WebContext webContext = WebContextFactory.get(); String page = webContext.getCurrentPage(); ScriptSessionManager sessionManager = webContext.getContainer().getBean(ScriptSessionManager.class); Collection<ScriptSession> sessions = sessionManager.getScriptSessionsByPage(page); withSessions(filter(sessions, filter), task); } /** * Execute a task and aim the output at a specific script session. This * method is likely to be useful for directed updates that originate away * from a thread started by the browser window in question. Examples include * an instant message, or the results of a slow method invocation. * This method is implicit in anything called from a DWR thread, so should * not need to be used to send UI updates back to an originating browser. * @param sessionId The {@link ScriptSession}.id of the browser window * @param task A code block to execute */ public static void withSession(String sessionId, Runnable task) { ServerContext serverContext = ServerContextFactory.get(); withSession(serverContext, sessionId, task); } /** * As {@link #withSession(String, Runnable)}, but for use when there is more * than one copy of DWR in a ServletContext. * <p> * For 99% of cases the former method will be much simpler to use. * @param serverContext The specific DWR context in which to execute */ public static void withSession(ServerContext serverContext, String sessionId, Runnable task) { ScriptSessionManager sessionManager = serverContext.getContainer().getBean(ScriptSessionManager.class); ScriptSession session = sessionManager.getScriptSession(sessionId, null, null); Collection<ScriptSession> sessions = new ArrayList<ScriptSession>(); if (session != null) { sessions.add(session); } withSessions(sessions, task); } /** * This method discovers the sessions that are currently being targeted * by browser updates. * <p> * It will generally only be useful to authors of reverse ajax UI proxy * APIs. Using it directly may cause scaling problems * @return The list of current browser windows. */ public static Collection<ScriptSession> getTargetSessions() { Collection<ScriptSession> sessions = target.get(); if (sessions != null) { return sessions; } WebContext webContext = WebContextFactory.get(); if (webContext != null) { sessions = new ArrayList<ScriptSession>(); sessions.add(webContext.getScriptSession()); return sessions; } throw new IllegalStateException("No current UI to manipulate. See org.directwebremoting.Browser to set one."); } /** * Execute a task and aim the output at a specific set of users. This method * is private because the filter version is likely to be just as easy to use * and potentially better suited to a clustered environment. * @param sessions The browser window to send the generated scripts to * @param task A code block to execute */ private static void withSessions(Collection<ScriptSession> sessions, Runnable task) { if (sessions.size() > 0) { log.debug("Executing task (" + task.getClass().getSimpleName() + ") against " + sessions.size() + " sessions."); target.set(sessions); task.run(); target.remove(); } } /** * Utility method to run a filter over a set of script sessions. * @param start The un-filtered set of script sessions * @param filter The filter to use to trim this list down * @return The subset of script sessions left by the filter */ private static Collection<ScriptSession> filter(Collection<ScriptSession> start, ScriptSessionFilter filter) { Collection<ScriptSession> use = new ArrayList<ScriptSession>(); for (ScriptSession session : start) { if (filter.match(session)) { use.add(session); } } return use; } /** * If a browser passes an object or function to DWR then DWR may need to * release the reference that DWR keeps. If the server-side manifestation of * this object is a proxy implemented interface, then there is no place for * a close method, so this function allows you to close proxy implemented * interfaces. * @param proxy An proxy created interface implementation from a browser * that we no longer need. */ public static void close(Object proxy) { if (proxy instanceof JavascriptObject) { JavascriptObject dproxy = (JavascriptObject) proxy; dproxy.close(); } } /** * ThreadLocal in which the list of sessions are stored. */ private static final ThreadLocal<Collection<ScriptSession>> target = new ThreadLocal<Collection<ScriptSession>>(); /** * The log stream */ private static final Log log = LogFactory.getLog(Browser.class); }
remove server context methods from Browser API because they are only rarely going to be of use - we can add them back in more easily that we can remove them git-svn-id: b371d604c7577be4609d70acd88b8a3995ce0a58@2387 3a8262b2-faa5-11dc-8610-ff947880b6b2
core/api/main/java/org/directwebremoting/Browser.java
remove server context methods from Browser API because they are only rarely going to be of use - we can add them back in more easily that we can remove them
Java
apache-2.0
bdd760458d13eefe12a1e8c95dd099ae2697b580
0
Aulust/async-http-client,Aulust/async-http-client
/* * Copyright 2015 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.resolver; import io.netty.util.NetUtil; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import static io.netty.util.internal.ObjectUtil.*; /** * A parser for hosts files. */ public final class HostsFileParser { private static final String WINDOWS_DEFAULT_SYSTEM_ROOT = "C:\\Windows"; private static final String WINDOWS_HOSTS_FILE_RELATIVE_PATH = "\\system32\\drivers\\etc\\hosts"; private static final String X_PLATFORMS_HOSTS_FILE_PATH = "/etc/hosts"; private static final Pattern WHITESPACES = Pattern.compile("[ \t]+"); private static final InternalLogger logger = InternalLoggerFactory.getInstance(HostsFileParser.class); private static File locateHostsFile() { File hostsFile; if (PlatformDependent.isWindows()) { hostsFile = new File(System.getenv("SystemRoot") + WINDOWS_HOSTS_FILE_RELATIVE_PATH); if (!hostsFile.exists()) { hostsFile = new File(WINDOWS_DEFAULT_SYSTEM_ROOT + WINDOWS_HOSTS_FILE_RELATIVE_PATH); } } else { hostsFile = new File(X_PLATFORMS_HOSTS_FILE_PATH); } return hostsFile; } /** * Parse hosts file at standard OS location. * * @return a map of hostname or alias to {@link InetAddress} */ public static Map<String, InetAddress> parseSilently() { File hostsFile = locateHostsFile(); try { return parse(hostsFile); } catch (IOException e) { logger.warn("Failed to load and parse hosts file at " + hostsFile.getPath(), e); return Collections.emptyMap(); } } /** * Parse hosts file at standard OS location. * * @return a map of hostname or alias to {@link InetAddress} * @throws IOException file could not be read */ public static Map<String, InetAddress> parse() throws IOException { return parse(locateHostsFile()); } /** * Parse a hosts file. * * @param file the file to be parsed * @return a map of hostname or alias to {@link InetAddress} * @throws IOException file could not be read */ public static Map<String, InetAddress> parse(File file) throws IOException { checkNotNull(file, "file"); if (file.exists() && file.isFile()) { return parse(new BufferedReader(new FileReader(file))); } else { return Collections.emptyMap(); } } /** * Parse a reader of hosts file format. * * @param reader the file to be parsed * @return a map of hostname or alias to {@link InetAddress} * @throws IOException file could not be read */ public static Map<String, InetAddress> parse(Reader reader) throws IOException { checkNotNull(reader, "reader"); BufferedReader buff = new BufferedReader(reader); try { Map<String, InetAddress> entries = new HashMap<String, InetAddress>(); String line; while ((line = buff.readLine()) != null) { // remove comment int commentPosition = line.indexOf('#'); if (commentPosition != -1) { line = line.substring(0, commentPosition); } // skip empty lines line = line.trim(); if (line.isEmpty()) { continue; } // split List<String> lineParts = new ArrayList<String>(); for (String s: WHITESPACES.split(line)) { if (!s.isEmpty()) { lineParts.add(s); } } // a valid line should be [IP, hostname, alias*] if (lineParts.size() < 2) { // skip invalid line continue; } byte[] ipBytes = NetUtil.createByteArrayFromIpAddressString(lineParts.get(0)); if (ipBytes == null) { // skip invalid IP continue; } // loop over hostname and aliases for (int i = 1; i < lineParts.size(); i ++) { String hostname = lineParts.get(i); if (!entries.containsKey(hostname)) { // trying to map a host to multiple IPs is wrong // only the first entry is honored entries.put(hostname, InetAddress.getByAddress(hostname, ipBytes)); } } } return entries; } finally { try { buff.close(); } catch (IOException e) { logger.warn("Failed to close a reader", e); } } } /** * Can't be instantiated. */ private HostsFileParser() { } }
netty-bp/resolver/src/main/java/io/netty/resolver/HostsFileParser.java
/* * Copyright 2015 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.resolver; import io.netty.util.NetUtil; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.HashMap; import java.util.Map; import static io.netty.util.internal.ObjectUtil.*; /** * A parser for hosts files. */ public final class HostsFileParser { private static final String WINDOWS_DEFAULT_SYSTEM_ROOT = "C:\\Windows"; private static final String WINDOWS_HOSTS_FILE_RELATIVE_PATH = "\\system32\\drivers\\etc\\hosts"; private static final String X_PLATFORMS_HOSTS_FILE_PATH = "/etc/hosts"; private static final InternalLogger logger = InternalLoggerFactory.getInstance(HostsFileParser.class); private static File locateHostsFile() { File hostsFile; if (PlatformDependent.isWindows()) { hostsFile = new File(System.getenv("SystemRoot") + WINDOWS_HOSTS_FILE_RELATIVE_PATH); if (!hostsFile.exists()) { hostsFile = new File(WINDOWS_DEFAULT_SYSTEM_ROOT + WINDOWS_HOSTS_FILE_RELATIVE_PATH); } } else { hostsFile = new File(X_PLATFORMS_HOSTS_FILE_PATH); } return hostsFile; } /** * Parse hosts file at standard OS location. * * @return a map of hostname or alias to {@link InetAddress} */ public static Map<String, InetAddress> parseSilently() { File hostsFile = locateHostsFile(); try { return parse(hostsFile); } catch (IOException e) { logger.warn("Failed to load and parse hosts file at " + hostsFile.getPath(), e); return Collections.emptyMap(); } } /** * Parse hosts file at standard OS location. * * @return a map of hostname or alias to {@link InetAddress} * @throws IOException file could not be read */ public static Map<String, InetAddress> parse() throws IOException { return parse(locateHostsFile()); } /** * Parse a hosts file. * * @param file the file to be parsed * @return a map of hostname or alias to {@link InetAddress} * @throws IOException file could not be read */ public static Map<String, InetAddress> parse(File file) throws IOException { checkNotNull(file, "file"); if (file.exists() && file.isFile()) { return parse(new BufferedReader(new FileReader(file))); } else { return Collections.emptyMap(); } } /** * Parse a reader of hosts file format. * * @param reader the file to be parsed * @return a map of hostname or alias to {@link InetAddress} * @throws IOException file could not be read */ public static Map<String, InetAddress> parse(Reader reader) throws IOException { checkNotNull(reader, "reader"); BufferedReader buff = new BufferedReader(reader); try { Map<String, InetAddress> entries = new HashMap<String, InetAddress>(); String line; while ((line = buff.readLine()) != null) { // remove comment int commentPosition = line.indexOf('#'); if (commentPosition != -1) { line = line.substring(0, commentPosition); } // skip empty lines line = line.trim(); if (line.isEmpty()) { continue; } // split List<String> lineParts = new ArrayList<String>(); for (String s: line.split("[ \t]+")) { if (!s.isEmpty()) { lineParts.add(s); } } // a valid line should be [IP, hostname, alias*] if (lineParts.size() < 2) { // skip invalid line continue; } byte[] ipBytes = NetUtil.createByteArrayFromIpAddressString(lineParts.get(0)); if (ipBytes == null) { // skip invalid IP continue; } InetAddress inetAddress = InetAddress.getByAddress(ipBytes); // loop over hostname and aliases for (int i = 1; i < lineParts.size(); i ++) { String hostname = lineParts.get(i); if (!entries.containsKey(hostname)) { // trying to map a host to multiple IPs is wrong // only the first entry is honored entries.put(hostname, inetAddress); } } } return entries; } finally { buff.close(); } } /** * Can't be instantiated. */ private HostsFileParser() { } }
Backport netty/netty#4837
netty-bp/resolver/src/main/java/io/netty/resolver/HostsFileParser.java
Backport netty/netty#4837
Java
apache-2.0
207d9623be231056a76ba12b090b8b9e2d7aa389
0
adammurdoch/native-platform,adammurdoch/native-platform,adammurdoch/native-platform,adammurdoch/native-platform
/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.file.FileWatchEvent; import net.rubygrapefruit.platform.file.FileWatcher; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * File watcher for macOS. Reports changes to the watched paths and any of their descendants. * * <h3>Remarks:</h3> * * <ul> * <li>Changes are reported as <em>non-canonical</em> paths. This means: * <ul> * <li>When watching a path with a different case, the reported case will match * the one used in starting the watcher.</li> * <li>Symlinks are not canonicalized, and changes are reported against the watched path.</li> * </ul> * </li> * * <li>Events arrive from a single background thread unique to the {@link FileWatcher}. * Calling methods from the {@link FileWatcher} inside the callback method is undefined * behavior and can lead to a deadlock.</li> * </ul> */ public class OsxFileEventFunctions extends AbstractFileEventFunctions { private static final long DEFAULT_LATENCY_IN_MS = 0; @Override public WatcherBuilder newWatcher(BlockingQueue<FileWatchEvent> eventQueue) { return new WatcherBuilder(eventQueue); } public static class WatcherBuilder extends AbstractWatcherBuilder { private long latencyInMillis = DEFAULT_LATENCY_IN_MS; WatcherBuilder(BlockingQueue<FileWatchEvent> eventQueue) { super(eventQueue); } /** * Set the latency for handling events. * The default is {@value DEFAULT_LATENCY_IN_MS} ms. * * @param latency coalesce events for the given amount of time, {@code 0} meaning no coalescing. * @param unit the time unit for {@code latency}. */ public WatcherBuilder withLatency(long latency, TimeUnit unit) { latencyInMillis = unit.toMillis(latency); return this; } @Override protected Object startWatcher(NativeFileWatcherCallback callback) { return startWatcher0(latencyInMillis, callback); } } private static native Object startWatcher0(long latencyInMillis, NativeFileWatcherCallback callback); }
src/main/java/net/rubygrapefruit/platform/internal/jni/OsxFileEventFunctions.java
/* * Copyright 2012 Adam Murdoch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rubygrapefruit.platform.internal.jni; import net.rubygrapefruit.platform.file.FileWatchEvent; import net.rubygrapefruit.platform.file.FileWatcher; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * File watcher for macOS. Reports changes to the watched paths and any of their descendants. * * <h3>Remarks:</h3> * * <ul> * <li>Changes are reported as <em>non-canonical</em> paths. This means: * <ul> * <li>When watching a path with a different case, the reported case will match * the one used in starting the watcher.</li> * <li>Symlinks are not canonicalized, and changes are reported against the watched path.</li> * </ul> * </li> * * <li>Events arrive from a single background thread unique to the {@link FileWatcher}. * Calling methods from the {@link FileWatcher} inside the callback method is undefined * behavior and can lead to a deadlock.</li> * </ul> */ // TODO How to set kFSEventStreamCreateFlagNoDefer when latency is non-zero? public class OsxFileEventFunctions extends AbstractFileEventFunctions { private static final long DEFAULT_LATENCY_IN_MS = 0; @Override public WatcherBuilder newWatcher(BlockingQueue<FileWatchEvent> eventQueue) { return new WatcherBuilder(eventQueue); } public static class WatcherBuilder extends AbstractWatcherBuilder { private long latencyInMillis = DEFAULT_LATENCY_IN_MS; WatcherBuilder(BlockingQueue<FileWatchEvent> eventQueue) { super(eventQueue); } /** * Set the latency for handling events. * The default is {@value DEFAULT_LATENCY_IN_MS} ms. * * @param latency coalesce events for the given amount of time, {@code 0} meaning no coalescing. * @param unit the time unit for {@code latency}. */ public WatcherBuilder withLatency(long latency, TimeUnit unit) { latencyInMillis = unit.toMillis(latency); return this; } @Override protected Object startWatcher(NativeFileWatcherCallback callback) { return startWatcher0(latencyInMillis, callback); } } private static native Object startWatcher0(long latencyInMillis, NativeFileWatcherCallback callback); }
Remove TODO in favor of GitHub issue See https://github.com/gradle/native-platform/issues/208.
src/main/java/net/rubygrapefruit/platform/internal/jni/OsxFileEventFunctions.java
Remove TODO in favor of GitHub issue
Java
apache-2.0
0fd2bebbbae3cfc2868dba4b2d688fd18175d01a
0
symphonyoss/symphony-java-client,symphonyoss/symphony-java-client
/* * * Copyright 2016 The Symphony Software Foundation * * Licensed to The Symphony Software Foundation (SSF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.symphonyoss.symphony.clients.model; import org.symphonyoss.symphony.pod.model.Avatar; import org.symphonyoss.symphony.pod.model.AvatarList; import org.symphonyoss.symphony.pod.model.UserV2; import java.util.ArrayList; import java.util.List; /** * Created by frank.tarsillo on 9/8/2016. */ public class SymUser { private Long id; private String emailAddress; private String firstName; private String lastName; private String displayName; private String title; private String company; private String username; private String location; private List<SymAvatar> avatars; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public List<SymAvatar> getAvatars() { return avatars; } public void setAvatars(List<SymAvatar> avatars) { this.avatars = avatars; } public static UserV2 toUserV2(SymUser symUser) { UserV2 userV2 = new UserV2(); userV2.setCompany(symUser.getCompany()); userV2.setDisplayName(symUser.getDisplayName()); userV2.setEmailAddress(symUser.getEmailAddress()); userV2.setFirstName(symUser.getFirstName()); userV2.setLastName(symUser.getLastName()); userV2.setId(symUser.getId()); userV2.setLocation(symUser.getLocation()); userV2.setTitle(symUser.getTitle()); userV2.setUsername(symUser.getUsername()); AvatarList avatars = new AvatarList(); for (SymAvatar symAvatar : symUser.getAvatars()) { Avatar avatar = new Avatar(); avatar.setSize(symAvatar.getSize()); avatar.setUrl(symAvatar.getUrl()); avatars.add(avatar); } userV2.setAvatars(avatars); return userV2; } public static SymUser toSymUser(UserV2 user) { SymUser symUser = new SymUser(); symUser.setCompany(user.getCompany()); symUser.setDisplayName(user.getDisplayName()); symUser.setEmailAddress(user.getEmailAddress()); symUser.setFirstName(user.getFirstName()); symUser.setLastName(user.getLastName()); symUser.setId(user.getId()); symUser.setLocation(user.getLocation()); symUser.setTitle(user.getTitle()); symUser.setUsername(user.getUsername()); List<SymAvatar> avatars = new ArrayList<>(); for (Avatar avatar : user.getAvatars()) { SymAvatar symAvatar = new SymAvatar(); symAvatar.setSize(avatar.getSize()); symAvatar.setUrl(avatar.getUrl()); avatars.add(symAvatar); } symUser.setAvatars(avatars); return symUser; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof SymUser)) { return false; } SymUser symUser = (SymUser) o; return id.equals(symUser.id) } }
symphony-client/src/main/java/org/symphonyoss/symphony/clients/model/SymUser.java
/* * * Copyright 2016 The Symphony Software Foundation * * Licensed to The Symphony Software Foundation (SSF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.symphonyoss.symphony.clients.model; import org.symphonyoss.symphony.pod.model.Avatar; import org.symphonyoss.symphony.pod.model.AvatarList; import org.symphonyoss.symphony.pod.model.UserV2; import java.util.ArrayList; import java.util.List; /** * Created by frank.tarsillo on 9/8/2016. */ public class SymUser { private Long id; private String emailAddress; private String firstName; private String lastName; private String displayName; private String title; private String company; private String username; private String location; private List<SymAvatar> avatars; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public List<SymAvatar> getAvatars() { return avatars; } public void setAvatars(List<SymAvatar> avatars) { this.avatars = avatars; } public static UserV2 toUserV2(SymUser symUser) { UserV2 userV2 = new UserV2(); userV2.setCompany(symUser.getCompany()); userV2.setDisplayName(symUser.getDisplayName()); userV2.setEmailAddress(symUser.getEmailAddress()); userV2.setFirstName(symUser.getFirstName()); userV2.setLastName(symUser.getLastName()); userV2.setId(symUser.getId()); userV2.setLocation(symUser.getLocation()); userV2.setTitle(symUser.getTitle()); userV2.setUsername(symUser.getUsername()); AvatarList avatars = new AvatarList(); for (SymAvatar symAvatar : symUser.getAvatars()) { Avatar avatar = new Avatar(); avatar.setSize(symAvatar.getSize()); avatar.setUrl(symAvatar.getUrl()); avatars.add(avatar); } userV2.setAvatars(avatars); return userV2; } public static SymUser toSymUser(UserV2 user) { SymUser symUser = new SymUser(); symUser.setCompany(user.getCompany()); symUser.setDisplayName(user.getDisplayName()); symUser.setEmailAddress(user.getEmailAddress()); symUser.setFirstName(user.getFirstName()); symUser.setLastName(user.getLastName()); symUser.setId(user.getId()); symUser.setLocation(user.getLocation()); symUser.setTitle(user.getTitle()); symUser.setUsername(user.getUsername()); List<SymAvatar> avatars = new ArrayList<>(); for (Avatar avatar : user.getAvatars()) { SymAvatar symAvatar = new SymAvatar(); symAvatar.setSize(avatar.getSize()); symAvatar.setUrl(avatar.getUrl()); avatars.add(symAvatar); } symUser.setAvatars(avatars); return symUser; } }
Override equals in SymUser
symphony-client/src/main/java/org/symphonyoss/symphony/clients/model/SymUser.java
Override equals in SymUser
Java
apache-2.0
b99dc6dc9940191adce4b1d7d4477ea9bfbb93f0
0
jeremybrooks/iris
package net.jeremybrooks.iris; import java.awt.*; import java.awt.event.*; import javax.swing.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.imgscalr.Scalr; import java.awt.Canvas; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.io.File; import java.util.Arrays; import java.util.Comparator; import javax.imageio.ImageIO; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JWindow; import javax.swing.ListSelectionModel; import javax.swing.WindowConstants; /** * @author Jeremy Brooks */ public class MainWindow extends JFrame { private GraphicsDevice[] devices; private JWindow imageDisplayWindow; private Logger logger = LogManager.getLogger(); /** * Create the main window and fire off the image load. */ public MainWindow() { devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); logger.info("Found " + devices.length + " graphics devices."); int i = 0; for (GraphicsDevice device : devices) { StringBuilder sb = new StringBuilder("Device " + i + " ID: ").append(device.getIDstring()); int j = 0; for (GraphicsConfiguration configuration : device.getConfigurations()) { sb.append("; Configuration " + j + " bounds: ").append(configuration.getBounds()); j++; } logger.info(sb); } initComponents(); this.setTitle(MainWindow.class.getPackage().getImplementationTitle() + " : " + MainWindow.class.getPackage().getImplementationVersion()); this.imageList.setCellRenderer(new LabelListCellRenderer()); this.loadPlaylist(); } private void menuItemQuitActionPerformed(ActionEvent e) { System.exit(0); } private void menuItemSourceDirectoryActionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setCurrentDirectory(new File(Main.getProperty("source.directory"))); chooser.setMultiSelectionEnabled(false); int result = chooser.showDialog(this, "OK"); if (result == JFileChooser.APPROVE_OPTION) { Main.setProperty("source.directory", chooser.getSelectedFile().getAbsolutePath()); Main.saveProperties(); this.loadPlaylist(); } } /* * Load the images from the source directory. * Warn the user if there is no source directory or if no files were found in the directory. */ private void loadPlaylist() { ImageCache.getInstance().clearCache(); String source = Main.getProperty(Main.PROPERTY_SOURCE_DIRECTORY); if (source.trim().length() == 0) { this.btnHide.setEnabled(false); this.btnShow.setEnabled(false); this.statusBar.setText("No source directory."); JOptionPane.showMessageDialog(this, "No image source directory is selected.\n" + "Go to File -> Image Source Directory to select where your images will come from.", "No Files Loaded", JOptionPane.ERROR_MESSAGE); } else { // list files and sort them File[] files = new File(source).listFiles(); if (files == null) { files = new File[0]; } Arrays.sort(files, new Comparator<File>() { public int compare(File o1, File o2) { int n1 = extractNumber(o1.getName()); int n2 = extractNumber(o2.getName()); return n1 - n2; } private int extractNumber(String name) { int i = 0; try { int s = name.indexOf('_') + 1; int e = name.lastIndexOf('.'); String number = name.substring(s, e); i = Integer.parseInt(number); } catch (Exception e) { i = 0; // if filename does not match the format // then default to 0 } return i; } }); // add files to the model if they are .jpg, .jpeg, or .png DefaultListModel<File> model = new DefaultListModel<File>(); for (File f : files) { String name = f.getName(); if (name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".png")) { File file = new File(Main.getProperty(Main.PROPERTY_SOURCE_DIRECTORY), name); model.addElement(file); } } // update the status bar and put the model on the list this.statusBar.setText(source + ": " + model.size() + " files"); this.imageList.setModel(model); this.imageList.setSelectedIndex(0); if (model.size() == 0) { this.btnHide.setEnabled(false); this.btnShow.setEnabled(false); JOptionPane.showMessageDialog(this, "No valid image files were found in directory " + source + ".\nAdd some files and go to File -> Refresh to reload the list.", "No Files Found", JOptionPane.ERROR_MESSAGE); } else { this.btnHide.setEnabled(true); this.btnShow.setEnabled(true); } } } private void btnPlayActionPerformed(ActionEvent e) { this.displaySelectedImage(); } /* * Display the currently selected image on the monitor that is NOT displaying this window. * If there is only one available monitor, the image will be displayed on that monitor. */ private void displaySelectedImage() { if (this.imageList.getModel().getSize() > 0) { GraphicsDevice currentDevice = this.getGraphicsConfiguration().getDevice(); GraphicsDevice targetDevice = currentDevice; for (GraphicsDevice device : this.devices) { if (!device.equals(currentDevice)) { targetDevice = device; break; } } this.logger.info(String.format("Current device: %s; Target device: %s", currentDevice.getIDstring(), targetDevice.getIDstring())); File f = (File) this.imageList.getSelectedValue(); if (this.imageDisplayWindow != null) { this.imageDisplayWindow.setVisible(false); this.imageDisplayWindow.dispose(); } this.imageDisplayWindow = new JWindow(targetDevice.getDefaultConfiguration()); for (GraphicsConfiguration configuration : targetDevice.getConfigurations()) { Rectangle gcBounds = configuration.getBounds(); int xoffs = gcBounds.x; int yoffs = gcBounds.y; try { BufferedImage img = ImageIO.read(f); int size; Scalr.Mode mode; // scale to fit the shortest of width/height this.logger.info(String.format("Target display size is %d x %d", gcBounds.width, gcBounds.height)); this.logger.info(String.format("Image size is %d x %d", img.getWidth(), img.getHeight())); if (gcBounds.width > gcBounds.height) { size = gcBounds.height; mode = Scalr.Mode.FIT_TO_HEIGHT; } else { size = gcBounds.width; mode = Scalr.Mode.FIT_TO_WIDTH; } this.logger.info(String.format("Scaling to %d pixels for mode %s", size, mode)); Image resized = Scalr.resize(img, mode, size); this.logger.info(String.format("New size is %d x %d", resized.getWidth(null), resized.getHeight(null))); img.flush(); // center based on target display size, add the label, and display the window int xPosition = (gcBounds.width - resized.getWidth(null)) / 2; int yPosition = (gcBounds.height - resized.getHeight(null)) / 2; this.imageDisplayWindow.setLocation(xoffs + xPosition, yoffs + yPosition); this.imageDisplayWindow.add(new JLabel(new ImageIcon(resized))); this.imageDisplayWindow.pack(); this.imageDisplayWindow.setVisible(true); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error displaying image " + f.getAbsolutePath() + "\n\n" + e, "Error Displaying Image", JOptionPane.ERROR_MESSAGE); } } } } private void btnHideActionPerformed(ActionEvent e) { if (this.imageDisplayWindow != null) { this.imageDisplayWindow.setVisible(false); this.imageDisplayWindow.dispose(); this.imageDisplayWindow = null; } } private void menuItemRefreshActionPerformed(ActionEvent e) { this.loadPlaylist(); } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents menuBar1 = new JMenuBar(); menu1 = new JMenu(); menuItemSourceDirectory = new JMenuItem(); menuItemRefresh = new JMenuItem(); menuItemQuit = new JMenuItem(); scrollPane1 = new JScrollPane(); imageList = new JList(); panel1 = new JPanel(); btnShow = new JButton(); btnHide = new JButton(); statusBar = new JLabel(); //======== this ======== setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container contentPane = getContentPane(); contentPane.setLayout(new GridBagLayout()); ((GridBagLayout)contentPane.getLayout()).columnWidths = new int[] {0, 0}; ((GridBagLayout)contentPane.getLayout()).rowHeights = new int[] {0, 0, 0, 0}; ((GridBagLayout)contentPane.getLayout()).columnWeights = new double[] {1.0, 1.0E-4}; ((GridBagLayout)contentPane.getLayout()).rowWeights = new double[] {1.0, 0.0, 0.0, 1.0E-4}; //======== menuBar1 ======== { //======== menu1 ======== { menu1.setText("File"); //---- menuItemSourceDirectory ---- menuItemSourceDirectory.setText("Image Source Directory"); menuItemSourceDirectory.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menuItemSourceDirectory.addActionListener(e -> menuItemSourceDirectoryActionPerformed(e)); menu1.add(menuItemSourceDirectory); //---- menuItemRefresh ---- menuItemRefresh.setText("Refresh"); menuItemRefresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); menuItemRefresh.addActionListener(e -> menuItemRefreshActionPerformed(e)); menu1.add(menuItemRefresh); menu1.addSeparator(); //---- menuItemQuit ---- menuItemQuit.setText("Quit"); menuItemQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menuItemQuit.addActionListener(e -> menuItemQuitActionPerformed(e)); menu1.add(menuItemQuit); } menuBar1.add(menu1); } setJMenuBar(menuBar1); //======== scrollPane1 ======== { //---- imageList ---- imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scrollPane1.setViewportView(imageList); } contentPane.add(scrollPane1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); //======== panel1 ======== { panel1.setLayout(new FlowLayout()); //---- btnShow ---- btnShow.setText("Show"); btnShow.setEnabled(false); btnShow.addActionListener(e -> btnPlayActionPerformed(e)); panel1.add(btnShow); //---- btnHide ---- btnHide.setText("Hide"); btnHide.setEnabled(false); btnHide.addActionListener(e -> btnHideActionPerformed(e)); panel1.add(btnHide); } contentPane.add(panel1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); //---- statusBar ---- statusBar.setText("Loading..."); statusBar.setForeground(Color.black); statusBar.setFont(statusBar.getFont().deriveFont(10f)); contentPane.add(statusBar, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); setSize(700, 400); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables private JMenuBar menuBar1; private JMenu menu1; private JMenuItem menuItemSourceDirectory; private JMenuItem menuItemRefresh; private JMenuItem menuItemQuit; private JScrollPane scrollPane1; private JList imageList; private JPanel panel1; private JButton btnShow; private JButton btnHide; private JLabel statusBar; // JFormDesigner - End of variables declaration //GEN-END:variables }
src/main/java/net/jeremybrooks/iris/MainWindow.java
package net.jeremybrooks.iris; import java.awt.*; import java.awt.event.*; import javax.swing.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.imgscalr.Scalr; import java.awt.Canvas; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.util.Arrays; import java.util.Comparator; import javax.imageio.ImageIO; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JWindow; import javax.swing.ListSelectionModel; import javax.swing.WindowConstants; /** * @author Jeremy Brooks */ public class MainWindow extends JFrame { private GraphicsDevice[] devices; private JWindow window; private Logger logger = LogManager.getLogger(); /** * Create the main window and fire off the image load. */ public MainWindow() { devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); logger.info("Found " + devices.length + " graphics devices."); int i = 0; for (GraphicsDevice device : devices) { StringBuilder sb = new StringBuilder("Device " + i + " ID: ").append(device.getIDstring()); int j = 0; for (GraphicsConfiguration configuration : device.getConfigurations()) { sb.append("; Configuration " + j + " bounds: ").append(configuration.getBounds()); j++; } logger.info(sb); } initComponents(); this.setTitle(MainWindow.class.getPackage().getImplementationTitle() + " : " + MainWindow.class.getPackage().getImplementationVersion()); this.imageList.setCellRenderer(new LabelListCellRenderer()); this.loadPlaylist(); } private void menuItemQuitActionPerformed(ActionEvent e) { System.exit(0); } private void menuItemSourceDirectoryActionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setCurrentDirectory(new File(Main.getProperty("source.directory"))); chooser.setMultiSelectionEnabled(false); int result = chooser.showDialog(this, "OK"); if (result == JFileChooser.APPROVE_OPTION) { Main.setProperty("source.directory", chooser.getSelectedFile().getAbsolutePath()); Main.saveProperties(); this.loadPlaylist(); } } /* * Load the images from the source directory. * Warn the user if there is no source directory or if no files were found in the directory. */ private void loadPlaylist() { ImageCache.getInstance().clearCache(); String source = Main.getProperty(Main.PROPERTY_SOURCE_DIRECTORY); if (source.trim().length() == 0) { this.btnHide.setEnabled(false); this.btnShow.setEnabled(false); this.statusBar.setText("No source directory."); JOptionPane.showMessageDialog(this, "No image source directory is selected.\n" + "Go to File -> Image Source Directory to select where your images will come from.", "No Files Loaded", JOptionPane.ERROR_MESSAGE); } else { // list files and sort them File[] files = new File(source).listFiles(); if (files == null) { files = new File[0]; } Arrays.sort(files, new Comparator<File>() { public int compare(File o1, File o2) { int n1 = extractNumber(o1.getName()); int n2 = extractNumber(o2.getName()); return n1 - n2; } private int extractNumber(String name) { int i = 0; try { int s = name.indexOf('_') + 1; int e = name.lastIndexOf('.'); String number = name.substring(s, e); i = Integer.parseInt(number); } catch (Exception e) { i = 0; // if filename does not match the format // then default to 0 } return i; } }); // add files to the model if they are .jpg, .jpeg, or .png DefaultListModel<File> model = new DefaultListModel<File>(); for (File f : files) { String name = f.getName(); if (name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".png")) { File file = new File(Main.getProperty(Main.PROPERTY_SOURCE_DIRECTORY), name); model.addElement(file); } } // update the status bar and put the model on the list this.statusBar.setText(source + ": " + model.size() + " files"); this.imageList.setModel(model); this.imageList.setSelectedIndex(0); if (model.size() == 0) { this.btnHide.setEnabled(false); this.btnShow.setEnabled(false); JOptionPane.showMessageDialog(this, "No valid image files were found in directory " + source + ".\nAdd some files and go to File -> Refresh to reload the list.", "No Files Found", JOptionPane.ERROR_MESSAGE); } else { this.btnHide.setEnabled(true); this.btnShow.setEnabled(true); } } } private void btnPlayActionPerformed(ActionEvent e) { this.displaySelectedImage(); } /* * Display the currently selected image on the monitor that is NOT displaying this window. * If there is only one available monitor, the image will be displayed on that monitor. */ private void displaySelectedImage() { if (this.imageList.getModel().getSize() > 0) { GraphicsDevice currentDevice = this.getGraphicsConfiguration().getDevice(); GraphicsDevice targetDevice = currentDevice; for (GraphicsDevice device : this.devices) { if (!device.equals(currentDevice)) { targetDevice = device; break; } } File f = (File) this.imageList.getSelectedValue(); if (window != null) { window.setVisible(false); window.dispose(); } window = new JWindow(targetDevice.getDefaultConfiguration()); for (GraphicsConfiguration configuration : targetDevice.getConfigurations()) { Canvas c = new Canvas(configuration); Rectangle gcBounds = configuration.getBounds(); int xoffs = gcBounds.x; int yoffs = gcBounds.y; window.getContentPane().add(c); try { BufferedImage img = ImageIO.read(f); int size; Scalr.Mode mode; // scale to fit the shortest of width/height if (gcBounds.width > gcBounds.height) { size = gcBounds.height; mode = Scalr.Mode.FIT_TO_HEIGHT; } else { size = gcBounds.width; mode = Scalr.Mode.FIT_TO_WIDTH; } Image resized = Scalr.resize(img, mode, size); img.flush(); JLabel lbl = new JLabel(); lbl.setIcon(new ImageIcon(resized)); int xPosition = (gcBounds.width - resized.getWidth(null)) / 2; int yPosition = (gcBounds.height - resized.getHeight(null)) / 2; window.setLocation(xoffs + xPosition, yoffs + yPosition); window.add(lbl); window.pack(); window.setVisible(true); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error displaying image " + f.getAbsolutePath() + "\n\n" + e, "Error Displaying Image", JOptionPane.ERROR_MESSAGE); } } } } private void btnHideActionPerformed(ActionEvent e) { if (this.window != null) { this.window.setVisible(false); this.window.dispose(); this.window = null; } } private void menuItemRefreshActionPerformed(ActionEvent e) { this.loadPlaylist(); } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents menuBar1 = new JMenuBar(); menu1 = new JMenu(); menuItemSourceDirectory = new JMenuItem(); menuItemRefresh = new JMenuItem(); menuItemQuit = new JMenuItem(); scrollPane1 = new JScrollPane(); imageList = new JList(); panel1 = new JPanel(); btnShow = new JButton(); btnHide = new JButton(); statusBar = new JLabel(); //======== this ======== setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container contentPane = getContentPane(); contentPane.setLayout(new GridBagLayout()); ((GridBagLayout)contentPane.getLayout()).columnWidths = new int[] {0, 0}; ((GridBagLayout)contentPane.getLayout()).rowHeights = new int[] {0, 0, 0, 0}; ((GridBagLayout)contentPane.getLayout()).columnWeights = new double[] {1.0, 1.0E-4}; ((GridBagLayout)contentPane.getLayout()).rowWeights = new double[] {1.0, 0.0, 0.0, 1.0E-4}; //======== menuBar1 ======== { //======== menu1 ======== { menu1.setText("File"); //---- menuItemSourceDirectory ---- menuItemSourceDirectory.setText("Image Source Directory"); menuItemSourceDirectory.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menuItemSourceDirectory.addActionListener(e -> menuItemSourceDirectoryActionPerformed(e)); menu1.add(menuItemSourceDirectory); //---- menuItemRefresh ---- menuItemRefresh.setText("Refresh"); menuItemRefresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); menuItemRefresh.addActionListener(e -> menuItemRefreshActionPerformed(e)); menu1.add(menuItemRefresh); menu1.addSeparator(); //---- menuItemQuit ---- menuItemQuit.setText("Quit"); menuItemQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menuItemQuit.addActionListener(e -> menuItemQuitActionPerformed(e)); menu1.add(menuItemQuit); } menuBar1.add(menu1); } setJMenuBar(menuBar1); //======== scrollPane1 ======== { //---- imageList ---- imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scrollPane1.setViewportView(imageList); } contentPane.add(scrollPane1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); //======== panel1 ======== { panel1.setLayout(new FlowLayout()); //---- btnShow ---- btnShow.setText("Show"); btnShow.setEnabled(false); btnShow.addActionListener(e -> btnPlayActionPerformed(e)); panel1.add(btnShow); //---- btnHide ---- btnHide.setText("Hide"); btnHide.setEnabled(false); btnHide.addActionListener(e -> btnHideActionPerformed(e)); panel1.add(btnHide); } contentPane.add(panel1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); //---- statusBar ---- statusBar.setText("Loading..."); statusBar.setForeground(Color.black); statusBar.setFont(statusBar.getFont().deriveFont(10f)); contentPane.add(statusBar, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); setSize(700, 400); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables private JMenuBar menuBar1; private JMenu menu1; private JMenuItem menuItemSourceDirectory; private JMenuItem menuItemRefresh; private JMenuItem menuItemQuit; private JScrollPane scrollPane1; private JList imageList; private JPanel panel1; private JButton btnShow; private JButton btnHide; private JLabel statusBar; // JFormDesigner - End of variables declaration //GEN-END:variables }
Added more logging during image display operation.
src/main/java/net/jeremybrooks/iris/MainWindow.java
Added more logging during image display operation.
Java
apache-2.0
8cdd5f7c13c041b024d53a160bfb385ae789e004
0
jaceksokol/postgres-async-driver
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; import com.github.pgasync.DatabaseConfig.DatabaseConfigBuilder; import com.github.pgasync.impl.PgConnectionPool; import com.github.pgasync.impl.conversion.DataConverter; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.DefaultThreadFactory; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * Builder for creating {@link ConnectionPool} instances. * * @author Antti Laisi */ public class ConnectionPoolBuilder { private static final int DEFAULT_PORT = 5432; private static final int DEFAULT_POOL_SIZE = 4; private final List<Converter<?>> converters = new ArrayList<>(); private DatabaseConfigBuilder configBuilder = DatabaseConfig.builder(); private String hostname; private int port; private int threads; public ConnectionPoolBuilder() { port(DEFAULT_PORT); poolSize(DEFAULT_POOL_SIZE); connectTimeout(30, TimeUnit.SECONDS); poolCloseTimeout(15, TimeUnit.SECONDS); threads(1); } /** * @return Pool ready for use */ public ConnectionPool build() { DatabaseConfig config = configBuilder .address(InetSocketAddress.createUnresolved(hostname, port)) .build(); DataConverter dataConverter = new DataConverter(converters); ThreadFactory threadFactory = new DefaultThreadFactory("PostgresDriverScheduler"); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(threads, threadFactory); return new PgConnectionPool(config, dataConverter, eventLoopGroup); } public ConnectionPoolBuilder hostname(String hostname) { this.hostname = hostname; return this; } public ConnectionPoolBuilder port(int port) { this.port = port; return this; } public ConnectionPoolBuilder username(String username) { configBuilder.username(username); return this; } public ConnectionPoolBuilder password(String password) { configBuilder.password(password); return this; } public ConnectionPoolBuilder database(String database) { configBuilder.database(database); return this; } public ConnectionPoolBuilder poolSize(int poolSize) { configBuilder.poolSize(poolSize); return this; } public ConnectionPoolBuilder converters(Converter<?>... converters) { Collections.addAll(this.converters, converters); return this; } public ConnectionPoolBuilder ssl(boolean ssl) { configBuilder.useSsl(ssl); return this; } public ConnectionPoolBuilder pipeline(boolean pipeline) { configBuilder.pipeline(pipeline); return this; } public ConnectionPoolBuilder connectTimeout(long value, TimeUnit timeUnit) { configBuilder.connectTimeout((int) timeUnit.toMillis(value)); return this; } public ConnectionPoolBuilder statementTimeout(long value, TimeUnit timeUnit) { configBuilder.statementTimeout((int) timeUnit.toMillis(value)); return this; } public ConnectionPoolBuilder poolCloseTimeout(long value, TimeUnit timeUnit) { configBuilder.poolCloseTimeout((int) timeUnit.toMillis(value)); return this; } public ConnectionPoolBuilder threads(int threads) { if (threads < 1) throw new IllegalArgumentException("threads value must be greater than 0"); this.threads = threads; return this; } }
src/main/java/com/github/pgasync/ConnectionPoolBuilder.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; import com.github.pgasync.DatabaseConfig.DatabaseConfigBuilder; import com.github.pgasync.impl.PgConnectionPool; import com.github.pgasync.impl.conversion.DataConverter; import io.netty.channel.nio.NioEventLoopGroup; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; /** * Builder for creating {@link ConnectionPool} instances. * * @author Antti Laisi */ public class ConnectionPoolBuilder { private static final int DEFAULT_PORT = 5432; private static final int DEFAULT_POOL_SIZE = 4; private final List<Converter<?>> converters = new ArrayList<>(); private DatabaseConfigBuilder configBuilder = DatabaseConfig.builder(); private String hostname; private int port; public ConnectionPoolBuilder() { port(DEFAULT_PORT); poolSize(DEFAULT_POOL_SIZE); connectTimeout(30, TimeUnit.SECONDS); poolCloseTimeout(15, TimeUnit.SECONDS); } /** * @return Pool ready for use */ public ConnectionPool build() { DatabaseConfig config = configBuilder .address(InetSocketAddress.createUnresolved(hostname, port)) .build(); DataConverter dataConverter = new DataConverter(converters); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(1); return new PgConnectionPool(config, dataConverter, eventLoopGroup); } public ConnectionPoolBuilder hostname(String hostname) { this.hostname = hostname; return this; } public ConnectionPoolBuilder port(int port) { this.port = port; return this; } public ConnectionPoolBuilder username(String username) { configBuilder.username(username); return this; } public ConnectionPoolBuilder password(String password) { configBuilder.password(password); return this; } public ConnectionPoolBuilder database(String database) { configBuilder.database(database); return this; } public ConnectionPoolBuilder poolSize(int poolSize) { configBuilder.poolSize(poolSize); return this; } public ConnectionPoolBuilder converters(Converter<?>... converters) { Collections.addAll(this.converters, converters); return this; } public ConnectionPoolBuilder ssl(boolean ssl) { configBuilder.useSsl(ssl); return this; } public ConnectionPoolBuilder pipeline(boolean pipeline) { configBuilder.pipeline(pipeline); return this; } public ConnectionPoolBuilder connectTimeout(long value, TimeUnit timeUnit) { configBuilder.connectTimeout((int) timeUnit.toMillis(value)); return this; } public ConnectionPoolBuilder statementTimeout(long value, TimeUnit timeUnit) { configBuilder.statementTimeout((int) timeUnit.toMillis(value)); return this; } public ConnectionPoolBuilder poolCloseTimeout(long value, TimeUnit timeUnit) { configBuilder.poolCloseTimeout((int) timeUnit.toMillis(value)); return this; } }
Add threads number configuration
src/main/java/com/github/pgasync/ConnectionPoolBuilder.java
Add threads number configuration
Java
apache-2.0
0fcb0873c7e7e4a7a16567da488fb4120590894d
0
consulo/consulo-csharp,consulo/consulo-csharp,consulo/consulo-csharp
package org.mustbe.consulo.csharp.ide.debugger; import java.util.List; import java.util.Map; import java.util.Set; import org.consulo.lombok.annotations.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mustbe.consulo.RequiredReadAction; import org.mustbe.consulo.csharp.ide.debugger.expressionEvaluator.Evaluator; import org.mustbe.consulo.csharp.lang.CSharpFileType; import org.mustbe.consulo.csharp.lang.CSharpLanguage; import org.mustbe.consulo.csharp.lang.psi.impl.fragment.CSharpFragmentFactory; import org.mustbe.consulo.csharp.lang.psi.impl.fragment.CSharpFragmentFileImpl; import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpMethodCallExpressionImpl; import org.mustbe.consulo.dotnet.debugger.DotNetDebugContext; import org.mustbe.consulo.dotnet.debugger.DotNetDebuggerProvider; import org.mustbe.consulo.dotnet.debugger.nodes.DotNetFieldOrPropertyMirrorNode; import org.mustbe.consulo.dotnet.debugger.nodes.DotNetStructValueInfo; import org.mustbe.consulo.dotnet.psi.DotNetExpression; import org.mustbe.consulo.dotnet.psi.DotNetLikeMethodDeclaration; import org.mustbe.consulo.dotnet.psi.DotNetReferenceExpression; import com.intellij.lang.Language; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.Consumer; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.evaluation.XDebuggerEvaluator; import com.intellij.xdebugger.frame.XNamedValue; import mono.debugger.FieldOrPropertyMirror; import mono.debugger.InvalidStackFrameException; import mono.debugger.ObjectValueMirror; import mono.debugger.StackFrameMirror; import mono.debugger.StructValueMirror; import mono.debugger.TypeMirror; import mono.debugger.Value; /** * @author VISTALL * @since 10.04.14 */ @Logger public class CSharpDebuggerProvider extends DotNetDebuggerProvider { @NotNull @Override public PsiFile createExpressionCodeFragment(@NotNull Project project, @NotNull PsiElement sourcePosition, @NotNull String text, boolean isPhysical) { return CSharpFragmentFactory.createExpressionFragment(project, text, sourcePosition); } @Override @RequiredReadAction public void evaluate(@NotNull StackFrameMirror frame, @NotNull DotNetDebugContext debuggerContext, @NotNull String expression, @Nullable PsiElement elementAt, @NotNull XDebuggerEvaluator.XEvaluationCallback callback, @Nullable XSourcePosition sourcePosition) { if(elementAt == null) { XDebugSession session = debuggerContext.getSession(); XSourcePosition currentPosition = session.getCurrentPosition(); if(currentPosition == null) { callback.errorOccurred("cant evaluate"); return; } VirtualFile file = currentPosition.getFile(); PsiFile psiFile = PsiManager.getInstance(debuggerContext.getProject()).findFile(file); if(psiFile == null) { callback.errorOccurred("cant evaluate"); return; } elementAt = psiFile.findElementAt(currentPosition.getOffset()); if(elementAt == null) { callback.errorOccurred("cant evaluate"); return; } } CSharpFragmentFileImpl expressionFragment = CSharpFragmentFactory.createExpressionFragment(debuggerContext.getProject(), expression, elementAt); PsiElement[] children = expressionFragment.getChildren(); if(children.length == 0) { callback.errorOccurred("no expression"); return; } PsiElement fragmentElement = children[0]; DotNetExpression expressionPsi = fragmentElement instanceof DotNetExpression ? (DotNetExpression) fragmentElement : null; if(expressionPsi == null) { callback.errorOccurred("no expression"); return; } CSharpExpressionEvaluator expressionEvaluator = new CSharpExpressionEvaluator(); try { expressionPsi.accept(expressionEvaluator); CSharpEvaluateContext evaluateContext = new CSharpEvaluateContext(debuggerContext, frame, elementAt); List<Evaluator> evaluators = expressionEvaluator.getEvaluators(); if(evaluators.isEmpty()) { callback.errorOccurred("cant evaluate expression"); return; } evaluateContext.evaluate(evaluators); Value<?> targetValue = evaluateContext.popValue(); if(targetValue != null) { callback.evaluated(new CSharpWatcherNode(debuggerContext, expression, frame.thread(), targetValue)); } else { callback.errorOccurred("no value"); } } catch(InvalidStackFrameException e) { callback.errorOccurred("invalid stack frame"); } catch(Exception e) { String message = e.getMessage(); if(message == null) { message = e.getClass().getSimpleName() + " was throw"; LOGGER.error("Exception have null message", e); } callback.errorOccurred(message); } } @Override @RequiredReadAction public void evaluate(@NotNull StackFrameMirror frame, @NotNull DotNetDebugContext debuggerContext, @NotNull DotNetReferenceExpression referenceExpression, @NotNull Set<Object> visitedVariables, @NotNull Consumer<XNamedValue> consumer) { PsiElement resolvedElement = referenceExpression.resolve(); if(referenceExpression.getParent() instanceof CSharpMethodCallExpressionImpl || resolvedElement instanceof DotNetLikeMethodDeclaration) { return; } CSharpExpressionEvaluator expressionEvaluator = new CSharpExpressionEvaluator(); try { referenceExpression.accept(expressionEvaluator); CSharpEvaluateContext evaluateContext = new CSharpEvaluateContext(debuggerContext, frame, referenceExpression); List<Evaluator> evaluators = expressionEvaluator.getEvaluators(); if(evaluators.isEmpty()) { return; } evaluateContext.evaluate(evaluators); Pair<Value<?>, Object> objectPair = evaluateContext.pop(); if(objectPair != null && objectPair.getSecond() instanceof FieldOrPropertyMirror) { FieldOrPropertyMirror fieldOrPropertyMirror = (FieldOrPropertyMirror) objectPair.getSecond(); if(visitedVariables.contains(fieldOrPropertyMirror)) { return; } visitedVariables.add(fieldOrPropertyMirror); TypeMirror parent = fieldOrPropertyMirror.parent(); Value thisObjectValue = frame.thisObject(); TypeMirror type = thisObjectValue.type(); if(thisObjectValue instanceof ObjectValueMirror && parent.equals(type)) { consumer.consume(new DotNetFieldOrPropertyMirrorNode(debuggerContext, fieldOrPropertyMirror, frame.thread(), (ObjectValueMirror) thisObjectValue)); } else if(thisObjectValue instanceof StructValueMirror && parent.equals(type)) { StructValueMirror structValueMirror = (StructValueMirror) thisObjectValue; DotNetStructValueInfo valueInfo = new DotNetStructValueInfo(structValueMirror, null, fieldOrPropertyMirror, objectPair.getFirst()); consumer.consume(new DotNetFieldOrPropertyMirrorNode(debuggerContext, fieldOrPropertyMirror, frame.thread(), null, valueInfo)); } else { consumer.consume(new CSharpWatcherNode(debuggerContext, referenceExpression.getText(), frame.thread(), objectPair.getFirst())); } } } catch(Exception e) { // ignored } } @Override public boolean isSupported(@NotNull PsiFile psiFile) { return psiFile.getFileType() == CSharpFileType.INSTANCE; } @Override public Language getEditorLanguage() { return CSharpLanguage.INSTANCE; } }
csharp-impl/src/org/mustbe/consulo/csharp/ide/debugger/CSharpDebuggerProvider.java
package org.mustbe.consulo.csharp.ide.debugger; import java.util.List; import java.util.Set; import org.consulo.lombok.annotations.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mustbe.consulo.RequiredReadAction; import org.mustbe.consulo.csharp.ide.debugger.expressionEvaluator.Evaluator; import org.mustbe.consulo.csharp.lang.CSharpFileType; import org.mustbe.consulo.csharp.lang.CSharpLanguage; import org.mustbe.consulo.csharp.lang.psi.CSharpCallArgumentListOwner; import org.mustbe.consulo.csharp.lang.psi.impl.fragment.CSharpFragmentFactory; import org.mustbe.consulo.csharp.lang.psi.impl.fragment.CSharpFragmentFileImpl; import org.mustbe.consulo.dotnet.debugger.DotNetDebugContext; import org.mustbe.consulo.dotnet.debugger.DotNetDebuggerProvider; import org.mustbe.consulo.dotnet.psi.DotNetExpression; import org.mustbe.consulo.dotnet.psi.DotNetLikeMethodDeclaration; import org.mustbe.consulo.dotnet.psi.DotNetReferenceExpression; import com.intellij.lang.Language; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.Consumer; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.evaluation.XDebuggerEvaluator; import com.intellij.xdebugger.frame.XNamedValue; import mono.debugger.FieldOrPropertyMirror; import mono.debugger.InvalidStackFrameException; import mono.debugger.StackFrameMirror; import mono.debugger.Value; /** * @author VISTALL * @since 10.04.14 */ @Logger public class CSharpDebuggerProvider extends DotNetDebuggerProvider { @NotNull @Override public PsiFile createExpressionCodeFragment(@NotNull Project project, @NotNull PsiElement sourcePosition, @NotNull String text, boolean isPhysical) { return CSharpFragmentFactory.createExpressionFragment(project, text, sourcePosition); } @Override @RequiredReadAction public void evaluate(@NotNull StackFrameMirror frame, @NotNull DotNetDebugContext debuggerContext, @NotNull String expression, @Nullable PsiElement elementAt, @NotNull XDebuggerEvaluator.XEvaluationCallback callback, @Nullable XSourcePosition sourcePosition) { if(elementAt == null) { XDebugSession session = debuggerContext.getSession(); XSourcePosition currentPosition = session.getCurrentPosition(); if(currentPosition == null) { callback.errorOccurred("cant evaluate"); return; } VirtualFile file = currentPosition.getFile(); PsiFile psiFile = PsiManager.getInstance(debuggerContext.getProject()).findFile(file); if(psiFile == null) { callback.errorOccurred("cant evaluate"); return; } elementAt = psiFile.findElementAt(currentPosition.getOffset()); if(elementAt == null) { callback.errorOccurred("cant evaluate"); return; } } CSharpFragmentFileImpl expressionFragment = CSharpFragmentFactory.createExpressionFragment(debuggerContext.getProject(), expression, elementAt); PsiElement[] children = expressionFragment.getChildren(); if(children.length == 0) { callback.errorOccurred("no expression"); return; } PsiElement fragmentElement = children[0]; DotNetExpression expressionPsi = fragmentElement instanceof DotNetExpression ? (DotNetExpression) fragmentElement : null; if(expressionPsi == null) { callback.errorOccurred("no expression"); return; } CSharpExpressionEvaluator expressionEvaluator = new CSharpExpressionEvaluator(); try { expressionPsi.accept(expressionEvaluator); CSharpEvaluateContext evaluateContext = new CSharpEvaluateContext(debuggerContext, frame, elementAt); List<Evaluator> evaluators = expressionEvaluator.getEvaluators(); if(evaluators.isEmpty()) { callback.errorOccurred("cant evaluate expression"); return; } evaluateContext.evaluate(evaluators); Value<?> targetValue = evaluateContext.popValue(); if(targetValue != null) { callback.evaluated(new CSharpWatcherNode(debuggerContext, expression, frame.thread(), targetValue)); } else { callback.errorOccurred("no value"); } } catch(InvalidStackFrameException e) { callback.errorOccurred("invalid stack frame"); } catch(Exception e) { String message = e.getMessage(); if(message == null) { message = e.getClass().getSimpleName() + " was throw"; LOGGER.error("Exception have null message", e); } callback.errorOccurred(message); } } @Override @RequiredReadAction public void evaluate(@NotNull StackFrameMirror frame, @NotNull DotNetDebugContext debuggerContext, @NotNull DotNetReferenceExpression referenceExpression, @NotNull Set<Object> visitedVariables, @NotNull Consumer<XNamedValue> consumer) { PsiElement resolvedElement = referenceExpression.resolve(); if(referenceExpression.getParent() instanceof CSharpCallArgumentListOwner || resolvedElement instanceof DotNetLikeMethodDeclaration) { return; } CSharpExpressionEvaluator expressionEvaluator = new CSharpExpressionEvaluator(); try { referenceExpression.accept(expressionEvaluator); CSharpEvaluateContext evaluateContext = new CSharpEvaluateContext(debuggerContext, frame, referenceExpression); List<Evaluator> evaluators = expressionEvaluator.getEvaluators(); if(evaluators.isEmpty()) { return; } evaluateContext.evaluate(evaluators); Pair<Value<?>, Object> objectPair = evaluateContext.pop(); if(objectPair != null && objectPair.getSecond() instanceof FieldOrPropertyMirror) { FieldOrPropertyMirror fieldOrPropertyMirror = (FieldOrPropertyMirror) objectPair.getSecond(); if(visitedVariables.contains(fieldOrPropertyMirror)) { return; } visitedVariables.add(fieldOrPropertyMirror); consumer.consume(new CSharpWatcherNode(debuggerContext, referenceExpression.getText(), frame.thread(), objectPair.getFirst())); } } catch(Exception e) { // ignored } } @Override public boolean isSupported(@NotNull PsiFile psiFile) { return psiFile.getFileType() == CSharpFileType.INSTANCE; } @Override public Language getEditorLanguage() { return CSharpLanguage.INSTANCE; } }
improved auto-expressions
csharp-impl/src/org/mustbe/consulo/csharp/ide/debugger/CSharpDebuggerProvider.java
improved auto-expressions
Java
apache-2.0
ae54695f58b7e7d445035f95b9cc7a6a1476d794
0
AndreasAbdi/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,joansmith/jackrabbit-oak,alexkli/jackrabbit-oak,kwin/jackrabbit-oak,stillalex/jackrabbit-oak,ieb/jackrabbit-oak,francescomari/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,meggermo/jackrabbit-oak,chetanmeh/jackrabbit-oak,mduerig/jackrabbit-oak,alexparvulescu/jackrabbit-oak,stillalex/jackrabbit-oak,mduerig/jackrabbit-oak,anchela/jackrabbit-oak,meggermo/jackrabbit-oak,catholicon/jackrabbit-oak,kwin/jackrabbit-oak,rombert/jackrabbit-oak,anchela/jackrabbit-oak,kwin/jackrabbit-oak,meggermo/jackrabbit-oak,ieb/jackrabbit-oak,tripodsan/jackrabbit-oak,davidegiannella/jackrabbit-oak,stillalex/jackrabbit-oak,mduerig/jackrabbit-oak,alexparvulescu/jackrabbit-oak,rombert/jackrabbit-oak,chetanmeh/jackrabbit-oak,mduerig/jackrabbit-oak,ieb/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,chetanmeh/jackrabbit-oak,yesil/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,tripodsan/jackrabbit-oak,alexparvulescu/jackrabbit-oak,tripodsan/jackrabbit-oak,bdelacretaz/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,yesil/jackrabbit-oak,francescomari/jackrabbit-oak,joansmith/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,davidegiannella/jackrabbit-oak,chetanmeh/jackrabbit-oak,catholicon/jackrabbit-oak,code-distillery/jackrabbit-oak,yesil/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,rombert/jackrabbit-oak,catholicon/jackrabbit-oak,joansmith/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,afilimonov/jackrabbit-oak,joansmith/jackrabbit-oak,francescomari/jackrabbit-oak,code-distillery/jackrabbit-oak,stillalex/jackrabbit-oak,leftouterjoin/jackrabbit-oak,code-distillery/jackrabbit-oak,tripodsan/jackrabbit-oak,alexkli/jackrabbit-oak,meggermo/jackrabbit-oak,catholicon/jackrabbit-oak,ieb/jackrabbit-oak,stillalex/jackrabbit-oak,kwin/jackrabbit-oak,joansmith/jackrabbit-oak,alexkli/jackrabbit-oak,alexkli/jackrabbit-oak,chetanmeh/jackrabbit-oak,afilimonov/jackrabbit-oak,bdelacretaz/jackrabbit-oak,francescomari/jackrabbit-oak,yesil/jackrabbit-oak,meggermo/jackrabbit-oak,leftouterjoin/jackrabbit-oak,bdelacretaz/jackrabbit-oak,davidegiannella/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,bdelacretaz/jackrabbit-oak,rombert/jackrabbit-oak,leftouterjoin/jackrabbit-oak,afilimonov/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,kwin/jackrabbit-oak,davidegiannella/jackrabbit-oak,anchela/jackrabbit-oak,catholicon/jackrabbit-oak,leftouterjoin/jackrabbit-oak,code-distillery/jackrabbit-oak,francescomari/jackrabbit-oak,davidegiannella/jackrabbit-oak,afilimonov/jackrabbit-oak,mduerig/jackrabbit-oak
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.document; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.Sets; import org.apache.jackrabbit.mk.api.MicroKernelException; import org.apache.jackrabbit.oak.commons.json.JsopStream; import org.apache.jackrabbit.oak.commons.json.JsopWriter; import org.apache.jackrabbit.oak.plugins.document.util.Utils; import org.apache.jackrabbit.oak.commons.PathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES; import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.COLLISIONS; import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.SPLIT_CANDIDATE_THRESHOLD; /** * A higher level object representing a commit. */ public class Commit { private static final Logger LOG = LoggerFactory.getLogger(Commit.class); private final DocumentNodeStore nodeStore; private final Revision baseRevision; private final Revision revision; private HashMap<String, UpdateOp> operations = new LinkedHashMap<String, UpdateOp>(); private JsopWriter diff = new JsopStream(); private List<Revision> collisions = new ArrayList<Revision>(); /** * List of all node paths which have been modified in this commit. In addition to the nodes * which are actually changed it also contains there parent node paths */ private HashSet<String> modifiedNodes = new HashSet<String>(); private HashSet<String> addedNodes = new HashSet<String>(); private HashSet<String> removedNodes = new HashSet<String>(); /** Set of all nodes which have binary properties. **/ private HashSet<String> nodesWithBinaries = Sets.newHashSet(); Commit(DocumentNodeStore nodeStore, Revision baseRevision, Revision revision) { this.baseRevision = baseRevision; this.revision = revision; this.nodeStore = nodeStore; } UpdateOp getUpdateOperationForNode(String path) { UpdateOp op = operations.get(path); if (op == null) { String id = Utils.getIdFromPath(path); op = new UpdateOp(id, false); NodeDocument.setModified(op, revision); operations.put(path, op); } return op; } public static long getModified(long timestamp) { // 5 second resolution return timestamp / 1000 / 5; } /** * The revision for this new commit. That is, the changes within this commit * will be visible with this revision. * * @return the revision for this new commit. */ @Nonnull Revision getRevision() { return revision; } /** * Returns the base revision for this commit. That is, the revision passed * to {@link DocumentMK#commit(String, String, String, String)}. The base * revision may be <code>null</code>, e.g. for the initial commit of the * root node, when there is no base revision. * * @return the base revision of this commit or <code>null</code>. */ @CheckForNull Revision getBaseRevision() { return baseRevision; } void addNodeDiff(DocumentNodeState n) { diff.tag('+').key(n.getPath()); diff.object(); n.append(diff, false); diff.endObject(); diff.newline(); } void updateProperty(String path, String propertyName, String value) { UpdateOp op = getUpdateOperationForNode(path); String key = Utils.escapePropertyName(propertyName); op.setMapEntry(key, revision, value); } void markNodeHavingBinary(String path) { this.nodesWithBinaries.add(path); } void addNode(DocumentNodeState n) { String path = n.getPath(); if (operations.containsKey(path)) { String msg = "Node already added: " + path; LOG.error(msg); throw new MicroKernelException(msg); } operations.put(path, n.asOperation(true)); addedNodes.add(path); } boolean isEmpty() { return operations.isEmpty(); } /** * Applies this commit to the store. * * @return the commit revision. * @throws MicroKernelException if the commit cannot be applied. * TODO: use non-MK exception type */ @Nonnull Revision apply() throws MicroKernelException { boolean success = false; Revision baseRev = getBaseRevision(); boolean isBranch = baseRev != null && baseRev.isBranch(); Revision rev = getRevision(); if (isBranch) { rev = rev.asBranchRevision(); // remember branch commit Branch b = nodeStore.getBranches().getBranch(baseRev); if (b == null) { // baseRev is marker for new branch b = nodeStore.getBranches().create(baseRev.asTrunkRevision(), rev); } else { b.addCommit(rev); } try { // prepare commit prepare(baseRev); success = true; } finally { if (!success) { b.removeCommit(rev); if (!b.hasCommits()) { nodeStore.getBranches().remove(b); } } } } else { applyInternal(); } return rev; } /** * Apply the changes to the document store and the cache. */ private void applyInternal() { if (!operations.isEmpty()) { updateParentChildStatus(); updateBinaryStatus(); applyToDocumentStore(); } } private void prepare(Revision baseRevision) { if (!operations.isEmpty()) { updateParentChildStatus(); updateBinaryStatus(); applyToDocumentStore(baseRevision); } } /** * Update the binary status in the update op. */ private void updateBinaryStatus() { DocumentStore store = this.nodeStore.getDocumentStore(); for (String path : this.nodesWithBinaries) { NodeDocument nd = (NodeDocument) store.getIfCached(Collection.NODES, Utils.getIdFromPath(path)); if ((nd == null) || (nd.hasBinary() != 1)) { UpdateOp updateParentOp = getUpdateOperationForNode(path); NodeDocument.setHasBinary(updateParentOp); } } } /** * Apply the changes to the document store. */ void applyToDocumentStore() { applyToDocumentStore(null); } /** * Apply the changes to the document store. * * @param baseBranchRevision the base revision of this commit. Currently only * used for branch commits. */ private void applyToDocumentStore(Revision baseBranchRevision) { // the value in _revisions.<revision> property of the commit root node // regular commits use "c", which makes the commit visible to // other readers. branch commits use the base revision to indicate // the visibility of the commit String commitValue = baseBranchRevision != null ? baseBranchRevision.toString() : "c"; DocumentStore store = nodeStore.getDocumentStore(); String commitRootPath = null; if (baseBranchRevision != null) { // branch commits always use root node as commit root commitRootPath = "/"; } ArrayList<UpdateOp> newNodes = new ArrayList<UpdateOp>(); ArrayList<UpdateOp> changedNodes = new ArrayList<UpdateOp>(); // operations are added to this list before they are executed, // so that all operations can be rolled back if there is a conflict ArrayList<UpdateOp> opLog = new ArrayList<UpdateOp>(); //Compute the commit root for (String p : operations.keySet()) { markChanged(p); if (commitRootPath == null) { commitRootPath = p; } else { while (!PathUtils.isAncestor(commitRootPath, p)) { commitRootPath = PathUtils.getParentPath(commitRootPath); if (PathUtils.denotesRoot(commitRootPath)) { break; } } } } int commitRootDepth = PathUtils.getDepth(commitRootPath); // create a "root of the commit" if there is none UpdateOp commitRoot = getUpdateOperationForNode(commitRootPath); for (String p : operations.keySet()) { UpdateOp op = operations.get(p); if (op.isNew()) { NodeDocument.setDeleted(op, revision, false); } if (op == commitRoot) { // apply at the end } else { NodeDocument.setCommitRoot(op, revision, commitRootDepth); if (op.isNew()) { if (baseBranchRevision == null) { // for new non-branch nodes we can safely set _lastRev on // insert. for existing nodes the _lastRev is updated by // the background thread to avoid concurrent updates NodeDocument.setLastRev(op, revision); } newNodes.add(op); } else { changedNodes.add(op); } } } if (changedNodes.size() == 0 && commitRoot.isNew()) { // no updates and root of commit is also new. that is, // it is the root of a subtree added in a commit. // so we try to add the root like all other nodes NodeDocument.setRevision(commitRoot, revision, commitValue); newNodes.add(commitRoot); } try { if (newNodes.size() > 0) { // set commit root on new nodes if (!store.create(NODES, newNodes)) { // some of the documents already exist: // try to apply all changes one by one for (UpdateOp op : newNodes) { if (op == commitRoot) { // don't write the commit root just yet // (because there might be a conflict) NodeDocument.unsetRevision(commitRoot, revision); } // setting _lastRev is only safe on insert. now the // background thread needs to take care of it NodeDocument.unsetLastRev(op, revision.getClusterId()); changedNodes.add(op); } newNodes.clear(); } } for (UpdateOp op : changedNodes) { // set commit root on changed nodes unless it's the // commit root itself if (op != commitRoot) { NodeDocument.setCommitRoot(op, revision, commitRootDepth); } opLog.add(op); createOrUpdateNode(store, op); } // finally write the commit root, unless it was already written // with added nodes (the commit root might be written twice, // first to check if there was a conflict, and only then to commit // the revision, with the revision property set) if (changedNodes.size() > 0 || !commitRoot.isNew()) { NodeDocument.setRevision(commitRoot, revision, commitValue); opLog.add(commitRoot); if (baseBranchRevision == null) { // create a clone of the commitRoot in order // to set isNew to false. If we get here the // commitRoot document already exists and // only needs an update UpdateOp commit = commitRoot.shallowCopy(commitRoot.getId()); commit.setNew(false); // only set revision on commit root when there is // no collision for this commit revision commit.containsMapEntry(COLLISIONS, revision, false); NodeDocument before = nodeStore.updateCommitRoot(commit); if (before == null) { String msg = "Conflicting concurrent change. " + "Update operation failed: " + commitRoot; throw new MicroKernelException(msg); } else { // if we get here the commit was successful and // the commit revision is set on the commitRoot // document for this commit. // now check for conflicts/collisions by other commits. // use original commitRoot operation with // correct isNew flag. checkConflicts(commitRoot, before); checkSplitCandidate(before); } } else { // this is a branch commit, do not fail on collisions now // trying to merge the branch will fail later createOrUpdateNode(store, commitRoot); } operations.put(commitRootPath, commitRoot); } } catch (MicroKernelException e) { rollback(newNodes, opLog, commitRoot); throw e; } } private void updateParentChildStatus() { final DocumentStore store = nodeStore.getDocumentStore(); final Set<String> processedParents = Sets.newHashSet(); for (String path : addedNodes) { if (PathUtils.denotesRoot(path)) { continue; } String parentPath = PathUtils.getParentPath(path); if (processedParents.contains(parentPath)) { continue; } processedParents.add(parentPath); final UpdateOp op = operations.get(parentPath); if (op != null) { //Parent node all ready part of modification list //Update it in place if (op.isNew()) { NodeDocument.setChildrenFlag(op, true); } else { NodeDocument nd = store.getIfCached(NODES, Utils.getIdFromPath(parentPath)); if (nd != null && nd.hasChildren()) { continue; } NodeDocument.setChildrenFlag(op, true); } } else { NodeDocument nd = store.getIfCached(NODES, Utils.getIdFromPath(parentPath)); if (nd != null && nd.hasChildren()) { //Flag already set to true. Nothing to do continue; } else { UpdateOp updateParentOp = getUpdateOperationForNode(parentPath); NodeDocument.setChildrenFlag(updateParentOp, true); } } } } private void rollback(List<UpdateOp> newDocuments, List<UpdateOp> changed, UpdateOp commitRoot) { DocumentStore store = nodeStore.getDocumentStore(); for (UpdateOp op : changed) { UpdateOp reverse = op.getReverseOperation(); store.findAndUpdate(NODES, reverse); } for (UpdateOp op : newDocuments) { UpdateOp reverse = op.getReverseOperation(); NodeDocument.unsetLastRev(reverse, revision.getClusterId()); store.findAndUpdate(NODES, reverse); } UpdateOp removeCollision = new UpdateOp(commitRoot.getId(), false); NodeDocument.removeCollision(removeCollision, revision); store.findAndUpdate(NODES, removeCollision); } /** * Try to create or update the node. If there was a conflict, this method * throws an exception, even though the change is still applied. * * @param store the store * @param op the operation */ private void createOrUpdateNode(DocumentStore store, UpdateOp op) { NodeDocument doc = store.createOrUpdate(NODES, op); checkConflicts(op, doc); checkSplitCandidate(doc); } private void checkSplitCandidate(@Nullable NodeDocument doc) { if (doc != null && doc.getMemory() > SPLIT_CANDIDATE_THRESHOLD) { nodeStore.addSplitCandidate(doc.getId()); } } /** * Checks if the update operation introduced any conflicts on the given * document. The document shows the state right before the operation was * applied. * * @param op the update operation. * @param before how the document looked before the update was applied or * {@code null} if it didn't exist before. */ private void checkConflicts(@Nonnull UpdateOp op, @Nullable NodeDocument before) { DocumentStore store = nodeStore.getDocumentStore(); collisions.clear(); if (baseRevision != null) { Revision newestRev = null; if (before != null) { newestRev = before.getNewestRevision(nodeStore, revision, new CollisionHandler() { @Override void concurrentModification(Revision other) { collisions.add(other); } }); } String conflictMessage = null; if (newestRev == null) { if (op.isDelete() || !op.isNew()) { conflictMessage = "The node " + op.getId() + " does not exist or is already deleted"; } } else { if (op.isNew()) { conflictMessage = "The node " + op.getId() + " was already added in revision\n" + newestRev; } else if (nodeStore.isRevisionNewer(newestRev, baseRevision) && (op.isDelete() || isConflicting(before, op))) { conflictMessage = "The node " + op.getId() + " was changed in revision\n" + newestRev + ", which was applied after the base revision\n" + baseRevision; } } if (conflictMessage == null) { // the modification was successful // -> check for collisions and conflict (concurrent updates // on a node are possible if property updates do not overlap) // TODO: unify above conflict detection and isConflicting() if (!collisions.isEmpty() && isConflicting(before, op)) { for (Revision r : collisions) { // mark collisions on commit root Collision c = new Collision(before, r, op, revision, nodeStore); if (c.mark(store).equals(revision)) { // our revision was marked if (baseRevision.isBranch()) { // this is a branch commit. do not fail immediately // merging this branch will fail later. } else { // fail immediately conflictMessage = "The node " + op.getId() + " was changed in revision\n" + r + ", which was applied after the base revision\n" + baseRevision; } } } } } if (conflictMessage != null) { conflictMessage += ", before\n" + revision + "; document:\n" + (before == null ? "" : before.format()) + ",\nrevision order:\n" + nodeStore.getRevisionComparator(); throw new MicroKernelException(conflictMessage); } } } /** * Checks whether the given <code>UpdateOp</code> conflicts with the * existing content in <code>doc</code>. The check is done based on the * {@link #baseRevision} of this commit. An <code>UpdateOp</code> conflicts * when there were changes after {@link #baseRevision} on properties also * contained in <code>UpdateOp</code>. * * @param doc the contents of the nodes before the update. * @param op the update to perform. * @return <code>true</code> if the update conflicts; <code>false</code> * otherwise. */ private boolean isConflicting(@Nullable NodeDocument doc, @Nonnull UpdateOp op) { if (baseRevision == null || doc == null) { // no conflict is possible when there is no baseRevision // or document did not exist before return false; } return doc.isConflicting(op, baseRevision, nodeStore); } /** * Apply the changes to the DocumentNodeStore (to update the cache). * * @param before the revision right before this commit. * @param isBranchCommit whether this is a commit to a branch */ public void applyToCache(Revision before, boolean isBranchCommit) { HashMap<String, ArrayList<String>> nodesWithChangedChildren = new HashMap<String, ArrayList<String>>(); for (String p : modifiedNodes) { if (PathUtils.denotesRoot(p)) { continue; } String parent = PathUtils.getParentPath(p); ArrayList<String> list = nodesWithChangedChildren.get(parent); if (list == null) { list = new ArrayList<String>(); nodesWithChangedChildren.put(parent, list); } list.add(p); } DiffCache.Entry cacheEntry = nodeStore.getDiffCache().newEntry(before, revision); List<String> added = new ArrayList<String>(); List<String> removed = new ArrayList<String>(); List<String> changed = new ArrayList<String>(); for (String path : modifiedNodes) { added.clear(); removed.clear(); changed.clear(); ArrayList<String> changes = nodesWithChangedChildren.get(path); if (changes != null) { for (String s : changes) { if (addedNodes.contains(s)) { added.add(s); } else if (removedNodes.contains(s)) { removed.add(s); } else { changed.add(s); } } } UpdateOp op = operations.get(path); boolean isNew = op != null && op.isNew(); boolean pendingLastRev = op == null || !NodeDocument.hasLastRev(op, revision.getClusterId()); nodeStore.applyChanges(revision, path, isNew, pendingLastRev, isBranchCommit, added, removed, changed, cacheEntry); } cacheEntry.done(); } public void moveNode(String sourcePath, String targetPath) { diff.tag('>').key(sourcePath).value(targetPath); } public void copyNode(String sourcePath, String targetPath) { diff.tag('*').key(sourcePath).value(targetPath); } private void markChanged(String path) { if (!PathUtils.denotesRoot(path) && !PathUtils.isAbsolute(path)) { throw new IllegalArgumentException("path: " + path); } while (true) { if (!modifiedNodes.add(path)) { break; } if (PathUtils.denotesRoot(path)) { break; } path = PathUtils.getParentPath(path); } } public void updatePropertyDiff(String path, String propertyName, String value) { diff.tag('^').key(PathUtils.concat(path, propertyName)).value(value); } public void removeNodeDiff(String path) { diff.tag('-').value(path).newline(); } public void removeNode(String path) { removedNodes.add(path); UpdateOp op = getUpdateOperationForNode(path); op.setDelete(true); NodeDocument.setDeleted(op, revision, true); } }
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/Commit.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.document; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.Sets; import org.apache.jackrabbit.mk.api.MicroKernelException; import org.apache.jackrabbit.oak.commons.json.JsopStream; import org.apache.jackrabbit.oak.commons.json.JsopWriter; import org.apache.jackrabbit.oak.plugins.document.util.Utils; import org.apache.jackrabbit.oak.commons.PathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES; import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.COLLISIONS; import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.SPLIT_CANDIDATE_THRESHOLD; /** * A higher level object representing a commit. */ public class Commit { private static final Logger LOG = LoggerFactory.getLogger(Commit.class); private final DocumentNodeStore nodeStore; private final Revision baseRevision; private final Revision revision; private HashMap<String, UpdateOp> operations = new LinkedHashMap<String, UpdateOp>(); private JsopWriter diff = new JsopStream(); private List<Revision> collisions = new ArrayList<Revision>(); /** * List of all node paths which have been modified in this commit. In addition to the nodes * which are actually changed it also contains there parent node paths */ private HashSet<String> modifiedNodes = new HashSet<String>(); private HashSet<String> addedNodes = new HashSet<String>(); private HashSet<String> removedNodes = new HashSet<String>(); /** Set of all nodes which have binary properties. **/ private HashSet<String> nodesWithBinaries = Sets.newHashSet(); Commit(DocumentNodeStore nodeStore, Revision baseRevision, Revision revision) { this.baseRevision = baseRevision; this.revision = revision; this.nodeStore = nodeStore; } UpdateOp getUpdateOperationForNode(String path) { UpdateOp op = operations.get(path); if (op == null) { String id = Utils.getIdFromPath(path); op = new UpdateOp(id, false); NodeDocument.setModified(op, revision); operations.put(path, op); } return op; } public static long getModified(long timestamp) { // 5 second resolution return timestamp / 1000 / 5; } /** * The revision for this new commit. That is, the changes within this commit * will be visible with this revision. * * @return the revision for this new commit. */ @Nonnull Revision getRevision() { return revision; } /** * Returns the base revision for this commit. That is, the revision passed * to {@link DocumentMK#commit(String, String, String, String)}. The base * revision may be <code>null</code>, e.g. for the initial commit of the * root node, when there is no base revision. * * @return the base revision of this commit or <code>null</code>. */ @CheckForNull Revision getBaseRevision() { return baseRevision; } void addNodeDiff(DocumentNodeState n) { diff.tag('+').key(n.getPath()); diff.object(); n.append(diff, false); diff.endObject(); diff.newline(); } void updateProperty(String path, String propertyName, String value) { UpdateOp op = getUpdateOperationForNode(path); String key = Utils.escapePropertyName(propertyName); op.setMapEntry(key, revision, value); } void markNodeHavingBinary(String path) { this.nodesWithBinaries.add(path); } void addNode(DocumentNodeState n) { String path = n.getPath(); if (operations.containsKey(path)) { String msg = "Node already added: " + path; LOG.error(msg); throw new MicroKernelException(msg); } operations.put(path, n.asOperation(true)); addedNodes.add(path); } boolean isEmpty() { return operations.isEmpty(); } /** * Applies this commit to the store. * * @return the commit revision. * @throws MicroKernelException if the commit cannot be applied. * TODO: use non-MK exception type */ @Nonnull Revision apply() throws MicroKernelException { boolean success = false; Revision baseRev = getBaseRevision(); boolean isBranch = baseRev != null && baseRev.isBranch(); Revision rev = getRevision(); if (isBranch) { rev = rev.asBranchRevision(); // remember branch commit Branch b = nodeStore.getBranches().getBranch(baseRev); if (b == null) { // baseRev is marker for new branch b = nodeStore.getBranches().create(baseRev.asTrunkRevision(), rev); } else { b.addCommit(rev); } try { // prepare commit prepare(baseRev); success = true; } finally { if (!success) { b.removeCommit(rev); if (!b.hasCommits()) { nodeStore.getBranches().remove(b); } } } } else { applyInternal(); } return rev; } /** * Apply the changes to the document store and the cache. */ private void applyInternal() { if (!operations.isEmpty()) { updateParentChildStatus(); updateBinaryStatus(); applyToDocumentStore(); } } private void prepare(Revision baseRevision) { if (!operations.isEmpty()) { updateParentChildStatus(); updateBinaryStatus(); applyToDocumentStore(baseRevision); } } /** * Update the binary status in the update op. */ private void updateBinaryStatus() { DocumentStore store = this.nodeStore.getDocumentStore(); for (String path : this.nodesWithBinaries) { NodeDocument nd = (NodeDocument) store.getIfCached(Collection.NODES, Utils.getIdFromPath(path)); if ((nd == null) || (nd.hasBinary() != 1)) { UpdateOp updateParentOp = getUpdateOperationForNode(path); NodeDocument.setHasBinary(updateParentOp); } } } /** * Apply the changes to the document store. */ void applyToDocumentStore() { applyToDocumentStore(null); } /** * Apply the changes to the document store. * * @param baseBranchRevision the base revision of this commit. Currently only * used for branch commits. */ private void applyToDocumentStore(Revision baseBranchRevision) { // the value in _revisions.<revision> property of the commit root node // regular commits use "c", which makes the commit visible to // other readers. branch commits use the base revision to indicate // the visibility of the commit String commitValue = baseBranchRevision != null ? baseBranchRevision.toString() : "c"; DocumentStore store = nodeStore.getDocumentStore(); String commitRootPath = null; if (baseBranchRevision != null) { // branch commits always use root node as commit root commitRootPath = "/"; } ArrayList<UpdateOp> newNodes = new ArrayList<UpdateOp>(); ArrayList<UpdateOp> changedNodes = new ArrayList<UpdateOp>(); // operations are added to this list before they are executed, // so that all operations can be rolled back if there is a conflict ArrayList<UpdateOp> opLog = new ArrayList<UpdateOp>(); //Compute the commit root for (String p : operations.keySet()) { markChanged(p); if (commitRootPath == null) { commitRootPath = p; } else { while (!PathUtils.isAncestor(commitRootPath, p)) { commitRootPath = PathUtils.getParentPath(commitRootPath); if (PathUtils.denotesRoot(commitRootPath)) { break; } } } } int commitRootDepth = PathUtils.getDepth(commitRootPath); // create a "root of the commit" if there is none UpdateOp commitRoot = getUpdateOperationForNode(commitRootPath); for (String p : operations.keySet()) { UpdateOp op = operations.get(p); if (op.isNew()) { NodeDocument.setDeleted(op, revision, false); } if (op == commitRoot) { // apply at the end } else { NodeDocument.setCommitRoot(op, revision, commitRootDepth); if (op.isNew()) { if (baseBranchRevision == null) { // for new non-branch nodes we can safely set _lastRev on // insert. for existing nodes the _lastRev is updated by // the background thread to avoid concurrent updates NodeDocument.setLastRev(op, revision); } newNodes.add(op); } else { changedNodes.add(op); } } } if (changedNodes.size() == 0 && commitRoot.isNew()) { // no updates and root of commit is also new. that is, // it is the root of a subtree added in a commit. // so we try to add the root like all other nodes NodeDocument.setRevision(commitRoot, revision, commitValue); newNodes.add(commitRoot); } try { if (newNodes.size() > 0) { // set commit root on new nodes if (!store.create(NODES, newNodes)) { // some of the documents already exist: // try to apply all changes one by one for (UpdateOp op : newNodes) { if (op == commitRoot) { // don't write the commit root just yet // (because there might be a conflict) NodeDocument.unsetRevision(commitRoot, revision); } // setting _lastRev is only safe on insert. now the // background thread needs to take care of it NodeDocument.unsetLastRev(op, revision.getClusterId()); changedNodes.add(op); } newNodes.clear(); } } for (UpdateOp op : changedNodes) { // set commit root on changed nodes unless it's the // commit root itself if (op != commitRoot) { NodeDocument.setCommitRoot(op, revision, commitRootDepth); } opLog.add(op); createOrUpdateNode(store, op); } // finally write the commit root, unless it was already written // with added nodes (the commit root might be written twice, // first to check if there was a conflict, and only then to commit // the revision, with the revision property set) if (changedNodes.size() > 0 || !commitRoot.isNew()) { NodeDocument.setRevision(commitRoot, revision, commitValue); opLog.add(commitRoot); if (baseBranchRevision == null) { // create a clone of the commitRoot in order // to set isNew to false. If we get here the // commitRoot document already exists and // only needs an update UpdateOp commit = commitRoot.shallowCopy(commitRoot.getId()); commit.setNew(false); // only set revision on commit root when there is // no collision for this commit revision commit.containsMapEntry(COLLISIONS, revision, false); NodeDocument before = nodeStore.updateCommitRoot(commit); if (before == null) { String msg = "Conflicting concurrent change. " + "Update operation failed: " + commitRoot; throw new MicroKernelException(msg); } else { // if we get here the commit was successful and // the commit revision is set on the commitRoot // document for this commit. // now check for conflicts/collisions by other commits. // use original commitRoot operation with // correct isNew flag. checkConflicts(commitRoot, before); checkSplitCandidate(before); } } else { // this is a branch commit, do not fail on collisions now // trying to merge the branch will fail later createOrUpdateNode(store, commitRoot); } operations.put(commitRootPath, commitRoot); } } catch (MicroKernelException e) { rollback(newNodes, opLog, commitRoot); throw e; } } private void updateParentChildStatus() { final DocumentStore store = nodeStore.getDocumentStore(); final Set<String> processedParents = Sets.newHashSet(); for (String path : addedNodes) { if (PathUtils.denotesRoot(path)) { continue; } String parentPath = PathUtils.getParentPath(path); if (processedParents.contains(parentPath)) { continue; } processedParents.add(parentPath); final UpdateOp op = operations.get(parentPath); if (op != null) { //Parent node all ready part of modification list //Update it in place if (op.isNew()) { NodeDocument.setChildrenFlag(op, true); } else { NodeDocument nd = store.getIfCached(NODES, Utils.getIdFromPath(parentPath)); if (nd != null && nd.hasChildren()) { continue; } NodeDocument.setChildrenFlag(op, true); } } else { NodeDocument nd = store.getIfCached(NODES, Utils.getIdFromPath(parentPath)); if (nd != null && nd.hasChildren()) { //Flag already set to true. Nothing to do continue; } else { UpdateOp updateParentOp = getUpdateOperationForNode(parentPath); NodeDocument.setChildrenFlag(updateParentOp, true); } } } } private void rollback(List<UpdateOp> newDocuments, List<UpdateOp> changed, UpdateOp commitRoot) { DocumentStore store = nodeStore.getDocumentStore(); for (UpdateOp op : changed) { UpdateOp reverse = op.getReverseOperation(); store.createOrUpdate(NODES, reverse); } for (UpdateOp op : newDocuments) { UpdateOp reverse = op.getReverseOperation(); NodeDocument.unsetLastRev(reverse, revision.getClusterId()); store.createOrUpdate(NODES, reverse); } UpdateOp removeCollision = new UpdateOp(commitRoot.getId(), false); NodeDocument.removeCollision(removeCollision, revision); store.createOrUpdate(NODES, removeCollision); } /** * Try to create or update the node. If there was a conflict, this method * throws an exception, even though the change is still applied. * * @param store the store * @param op the operation */ private void createOrUpdateNode(DocumentStore store, UpdateOp op) { NodeDocument doc = store.createOrUpdate(NODES, op); checkConflicts(op, doc); checkSplitCandidate(doc); } private void checkSplitCandidate(@Nullable NodeDocument doc) { if (doc != null && doc.getMemory() > SPLIT_CANDIDATE_THRESHOLD) { nodeStore.addSplitCandidate(doc.getId()); } } /** * Checks if the update operation introduced any conflicts on the given * document. The document shows the state right before the operation was * applied. * * @param op the update operation. * @param before how the document looked before the update was applied or * {@code null} if it didn't exist before. */ private void checkConflicts(@Nonnull UpdateOp op, @Nullable NodeDocument before) { DocumentStore store = nodeStore.getDocumentStore(); collisions.clear(); if (baseRevision != null) { Revision newestRev = null; if (before != null) { newestRev = before.getNewestRevision(nodeStore, revision, new CollisionHandler() { @Override void concurrentModification(Revision other) { collisions.add(other); } }); } String conflictMessage = null; if (newestRev == null) { if (op.isDelete() || !op.isNew()) { conflictMessage = "The node " + op.getId() + " does not exist or is already deleted"; } } else { if (op.isNew()) { conflictMessage = "The node " + op.getId() + " was already added in revision\n" + newestRev; } else if (nodeStore.isRevisionNewer(newestRev, baseRevision) && (op.isDelete() || isConflicting(before, op))) { conflictMessage = "The node " + op.getId() + " was changed in revision\n" + newestRev + ", which was applied after the base revision\n" + baseRevision; } } if (conflictMessage == null) { // the modification was successful // -> check for collisions and conflict (concurrent updates // on a node are possible if property updates do not overlap) // TODO: unify above conflict detection and isConflicting() if (!collisions.isEmpty() && isConflicting(before, op)) { for (Revision r : collisions) { // mark collisions on commit root Collision c = new Collision(before, r, op, revision, nodeStore); if (c.mark(store).equals(revision)) { // our revision was marked if (baseRevision.isBranch()) { // this is a branch commit. do not fail immediately // merging this branch will fail later. } else { // fail immediately conflictMessage = "The node " + op.getId() + " was changed in revision\n" + r + ", which was applied after the base revision\n" + baseRevision; } } } } } if (conflictMessage != null) { conflictMessage += ", before\n" + revision + "; document:\n" + (before == null ? "" : before.format()) + ",\nrevision order:\n" + nodeStore.getRevisionComparator(); throw new MicroKernelException(conflictMessage); } } } /** * Checks whether the given <code>UpdateOp</code> conflicts with the * existing content in <code>doc</code>. The check is done based on the * {@link #baseRevision} of this commit. An <code>UpdateOp</code> conflicts * when there were changes after {@link #baseRevision} on properties also * contained in <code>UpdateOp</code>. * * @param doc the contents of the nodes before the update. * @param op the update to perform. * @return <code>true</code> if the update conflicts; <code>false</code> * otherwise. */ private boolean isConflicting(@Nullable NodeDocument doc, @Nonnull UpdateOp op) { if (baseRevision == null || doc == null) { // no conflict is possible when there is no baseRevision // or document did not exist before return false; } return doc.isConflicting(op, baseRevision, nodeStore); } /** * Apply the changes to the DocumentNodeStore (to update the cache). * * @param before the revision right before this commit. * @param isBranchCommit whether this is a commit to a branch */ public void applyToCache(Revision before, boolean isBranchCommit) { HashMap<String, ArrayList<String>> nodesWithChangedChildren = new HashMap<String, ArrayList<String>>(); for (String p : modifiedNodes) { if (PathUtils.denotesRoot(p)) { continue; } String parent = PathUtils.getParentPath(p); ArrayList<String> list = nodesWithChangedChildren.get(parent); if (list == null) { list = new ArrayList<String>(); nodesWithChangedChildren.put(parent, list); } list.add(p); } DiffCache.Entry cacheEntry = nodeStore.getDiffCache().newEntry(before, revision); List<String> added = new ArrayList<String>(); List<String> removed = new ArrayList<String>(); List<String> changed = new ArrayList<String>(); for (String path : modifiedNodes) { added.clear(); removed.clear(); changed.clear(); ArrayList<String> changes = nodesWithChangedChildren.get(path); if (changes != null) { for (String s : changes) { if (addedNodes.contains(s)) { added.add(s); } else if (removedNodes.contains(s)) { removed.add(s); } else { changed.add(s); } } } UpdateOp op = operations.get(path); boolean isNew = op != null && op.isNew(); boolean pendingLastRev = op == null || !NodeDocument.hasLastRev(op, revision.getClusterId()); nodeStore.applyChanges(revision, path, isNew, pendingLastRev, isBranchCommit, added, removed, changed, cacheEntry); } cacheEntry.done(); } public void moveNode(String sourcePath, String targetPath) { diff.tag('>').key(sourcePath).value(targetPath); } public void copyNode(String sourcePath, String targetPath) { diff.tag('*').key(sourcePath).value(targetPath); } private void markChanged(String path) { if (!PathUtils.denotesRoot(path) && !PathUtils.isAbsolute(path)) { throw new IllegalArgumentException("path: " + path); } while (true) { if (!modifiedNodes.add(path)) { break; } if (PathUtils.denotesRoot(path)) { break; } path = PathUtils.getParentPath(path); } } public void updatePropertyDiff(String path, String propertyName, String value) { diff.tag('^').key(PathUtils.concat(path, propertyName)).value(value); } public void removeNodeDiff(String path) { diff.tag('-').value(path).newline(); } public void removeNode(String path) { removedNodes.add(path); UpdateOp op = getUpdateOperationForNode(path); op.setDelete(true); NodeDocument.setDeleted(op, revision, true); } }
OAK-1585 - rollback logic issues incorrect Updates git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1579973 13f79535-47bb-0310-9956-ffa450edef68
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/Commit.java
OAK-1585 - rollback logic issues incorrect Updates
Java
apache-2.0
b383f056114a72d749485e30d28495e2f40429e5
0
viltgroup/minium,viltgroup/minium,viltgroup/minium
/* * Copyright (C) 2013 The Minium Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vilt.minium.script; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import java.io.File; import java.net.URL; import java.util.List; import org.mozilla.javascript.FunctionObject; import org.mozilla.javascript.NativeFunction; import org.openqa.selenium.Platform; import org.testng.annotations.Test; import com.vilt.minium.prefs.AppPreferences; public class MiniumScriptEngineTest { @Test public void testEngineWebElementDrivers() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(WebElementsDriverFactory.instance()); // when Object firefoxDriver = engine.eval("firefoxDriver"); Object load = engine.eval("load"); // then assertThat(firefoxDriver, instanceOf(NativeFunction.class)); assertThat(load, instanceOf(FunctionObject.class)); } @Test public void testEngineDefaultConst() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); // when Object firefoxDriver = engine.eval("firefoxDriver"); // then assertThat(firefoxDriver, instanceOf(NativeFunction.class)); } @Test public void testEnginePut() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); engine.put("foo", "bar"); // when Object result = engine.eval("foo"); // then assertThat(result, instanceOf(String.class)); assertThat((String) result, equalTo("bar")); } @Test public void testNativeJavaObjects() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); // when Object result = engine.eval("java.lang.Integer.valueOf(1)"); // then assertThat(result, instanceOf(Integer.class)); } @Test public void testRunScript() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); // when URL resource = getClass().getClassLoader().getResource("test.js"); engine.run(new File(resource.getFile())); // then assertThat((String) engine.get("foo"), equalTo("bar")); } @Test public void testModulePathURIs() throws Exception { // given System.setProperty("basedir", Platform.getCurrent().is(Platform.WINDOWS) ? "c:\\minium-app" : "/opt/minium-app"); MiniumScriptEngine engine = new MiniumScriptEngine(WebElementsDriverFactory.instance(), new AppPreferences()); // when List<String> modulePathURIs = engine.getModulePathURIs(); // then String modules = Platform.getCurrent().is(Platform.WINDOWS) ? "file:/c:/minium-app/modules" : "file:/opt/minium-app/modules"; assertThat(modulePathURIs, containsInAnyOrder(modules, "http://www.lodash.com")); } }
minium-script/src/test/java/com/vilt/minium/script/MiniumScriptEngineTest.java
/* * Copyright (C) 2013 The Minium Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vilt.minium.script; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import java.io.File; import java.net.URL; import java.util.List; import org.mozilla.javascript.FunctionObject; import org.mozilla.javascript.NativeFunction; import org.testng.annotations.Test; import com.vilt.minium.prefs.AppPreferences; public class MiniumScriptEngineTest { @Test public void testEngineWebElementDrivers() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(WebElementsDriverFactory.instance()); // when Object firefoxDriver = engine.eval("firefoxDriver"); Object load = engine.eval("load"); // then assertThat(firefoxDriver, instanceOf(NativeFunction.class)); assertThat(load, instanceOf(FunctionObject.class)); } @Test public void testEngineDefaultConst() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); // when Object firefoxDriver = engine.eval("firefoxDriver"); // then assertThat(firefoxDriver, instanceOf(NativeFunction.class)); } @Test public void testEnginePut() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); engine.put("foo", "bar"); // when Object result = engine.eval("foo"); // then assertThat(result, instanceOf(String.class)); assertThat((String) result, equalTo("bar")); } @Test public void testNativeJavaObjects() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); // when Object result = engine.eval("java.lang.Integer.valueOf(1)"); // then assertThat(result, instanceOf(Integer.class)); } @Test public void testRunScript() throws Exception { // given MiniumScriptEngine engine = new MiniumScriptEngine(); // when URL resource = getClass().getClassLoader().getResource("test.js"); engine.run(new File(resource.getFile())); // then assertThat((String) engine.get("foo"), equalTo("bar")); } @Test public void testModulePathURIs() throws Exception { // given System.setProperty("basedir", "c:\\minium-app"); MiniumScriptEngine engine = new MiniumScriptEngine(WebElementsDriverFactory.instance(), new AppPreferences()); // when List<String> modulePathURIs = engine.getModulePathURIs(); // then assertThat(modulePathURIs, containsInAnyOrder("file:/c:/minium-app/modules", "http://www.lodash.com")); } }
Test on Travis failed because of UNIX path, trying to solve it (doesn't affect release)
minium-script/src/test/java/com/vilt/minium/script/MiniumScriptEngineTest.java
Test on Travis failed because of UNIX path, trying to solve it (doesn't affect release)
Java
apache-2.0
4b08c71c2342cf5db8dea1fe215746070e81530a
0
jaeksoft/opensearchserver,jaeksoft/opensearchserver
/** * License Agreement for OpenSearchServer * * Copyright (C) 2013 Emmanuel Keller / Jaeksoft * * http://www.open-search-server.com * * This file is part of OpenSearchServer. * * OpenSearchServer is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenSearchServer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenSearchServer. * If not, see <http://www.gnu.org/licenses/>. **/ package com.jaeksoft.searchlib.crawler.common.process; import com.jaeksoft.searchlib.crawler.FieldMapGeneric; import com.jaeksoft.searchlib.crawler.common.database.CommonFieldTarget; import com.jaeksoft.searchlib.process.ThreadItem; import com.jaeksoft.searchlib.util.map.SourceField; public abstract class FieldMapCrawlItem<I extends FieldMapCrawlItem<I, T, M>, T extends CrawlThreadAbstract<T, M>, M extends CrawlMasterAbstract<M, T>> extends ThreadItem<I, T> { private final FieldMapGeneric<SourceField, CommonFieldTarget> fieldMap; protected FieldMapCrawlItem(M crawlMaster, FieldMapGeneric<SourceField, CommonFieldTarget> fieldMap) { super(crawlMaster); this.fieldMap = fieldMap; } @Override public void copyTo(I crawlItem) { super.copyTo(crawlItem); this.fieldMap.copyTo(crawlItem.getFieldMap()); } /** * @return the fieldMap */ public FieldMapGeneric<SourceField, CommonFieldTarget> getFieldMap() { return fieldMap; } }
src/main/java/com/jaeksoft/searchlib/crawler/common/process/FieldMapCrawlItem.java
/** * License Agreement for OpenSearchServer * * Copyright (C) 2013 Emmanuel Keller / Jaeksoft * * http://www.open-search-server.com * * This file is part of OpenSearchServer. * * OpenSearchServer is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenSearchServer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenSearchServer. * If not, see <http://www.gnu.org/licenses/>. **/ package com.jaeksoft.searchlib.crawler.common.process; import com.jaeksoft.searchlib.crawler.FieldMapGeneric; import com.jaeksoft.searchlib.crawler.common.database.CommonFieldTarget; import com.jaeksoft.searchlib.process.ThreadItem; import com.jaeksoft.searchlib.util.map.SourceField; public abstract class FieldMapCrawlItem<I extends FieldMapCrawlItem<I, T, M>, T extends CrawlThreadAbstract<T, M>, M extends CrawlMasterAbstract<M, T>> extends ThreadItem<I, T> { private final FieldMapGeneric<SourceField, CommonFieldTarget> fieldMap; protected FieldMapCrawlItem(M crawlMaster, FieldMapGeneric<SourceField, CommonFieldTarget> fieldMap) { super(crawlMaster); this.fieldMap = fieldMap; } @Override public void copyTo(I crawlItem) { super.copyTo(crawlItem); this.fieldMap.copyTo(crawlItem.fieldMap); } /** * @return the fieldMap */ public FieldMapGeneric<SourceField, CommonFieldTarget> getFieldMap() { return fieldMap; } }
Fix compilation error
src/main/java/com/jaeksoft/searchlib/crawler/common/process/FieldMapCrawlItem.java
Fix compilation error
Java
apache-2.0
6045c4ece18721b3afea478fb90fc650f7f34d69
0
Water-Cat1/FelisBotus,Water-Cat1/FelisBotus
package com.wc1.felisBotus.irc; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Class to contain information about an IRC server * @author Water_Cat1 * */ public class IRCServer { private Map<String, IRCChannel> channels = new TreeMap<String, IRCChannel>(String.CASE_INSENSITIVE_ORDER); private String serverAddress; /** * Create an instance using a server address and set of saved channels * @param serverAddress Address used to connect to the server * @param channels */ public IRCServer(String serverAddress, Set<IRCChannel> channels) { super(); this.serverAddress = serverAddress; for (IRCChannel currChannel:channels){ this.channels.put(currChannel.getName(), currChannel); } } /** * Create an instance using just a server address * @param serverAddress */ public IRCServer(String serverAddress) { super(); this.serverAddress = serverAddress; this.channels = new HashMap<String,IRCChannel>(); } /** * Get the set of saved channels for this server * @return Set of saved channels */ public Collection<IRCChannel> getChannels() { return Collections.unmodifiableCollection(channels.values()); } /** * Get the IRCChannel object for the channel with channelNAme * @param channelName Name of channel to get object for * @return IRCChannel object */ public IRCChannel getChannel(String channelName){ return channels.get(channelName); } /** * Get the server address * @return Server address */ public String getServerAddress() { return serverAddress; } /** * Add a channel to the set of saved channels * @param newChannel Channel to save * @return Old channel if one is already saved, null otherwise. */ public IRCChannel addChannel(IRCChannel newChannel){ return channels.put(newChannel.getName(), newChannel); } /** * Remove a channel from the saved set * @param oldChannel Channel to remove * @return IRCChannel that was removed */ public IRCChannel removeChannel(String oldChannel){ return channels.remove(oldChannel); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channels == null) ? 0 : channels.hashCode()); result = prime * result + ((serverAddress == null) ? 0 : serverAddress.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof IRCServer)) return false; IRCServer other = (IRCServer) obj; if (channels == null) { if (other.channels != null) return false; } else if (!channels.equals(other.channels)) return false; if (serverAddress == null) { if (other.serverAddress != null) return false; } else if (!serverAddress.equals(other.serverAddress)) return false; return true; } }
FelisBotus/src/com/wc1/felisBotus/irc/IRCServer.java
package com.wc1.felisBotus.irc; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Class to contain information about an IRC server * @author Water_Cat1 * */ public class IRCServer { private Map<String, IRCChannel> channels = new HashMap<String, IRCChannel>(); private String serverAddress; /** * Create an instance using a server address and set of saved channels * @param serverAddress Address used to connect to the server * @param channels */ public IRCServer(String serverAddress, Set<IRCChannel> channels) { super(); this.serverAddress = serverAddress; for (IRCChannel currChannel:channels){ this.channels.put(currChannel.getName(), currChannel); } } /** * Create an instance using just a server address * @param serverAddress */ public IRCServer(String serverAddress) { super(); this.serverAddress = serverAddress; this.channels = new HashMap<String,IRCChannel>(); } /** * Get the set of saved channels for this server * @return Set of saved channels */ public Collection<IRCChannel> getChannels() { return Collections.unmodifiableCollection(channels.values()); } /** * Get the IRCChannel object for the channel with channelNAme * @param channelName Name of channel to get object for * @return IRCChannel object */ public IRCChannel getChannel(String channelName){ return channels.get(channelName); } /** * Get the server address * @return Server address */ public String getServerAddress() { return serverAddress; } /** * Add a channel to the set of saved channels * @param newChannel Channel to save * @return Old channel if one is already saved, null otherwise. */ public IRCChannel addChannel(IRCChannel newChannel){ return channels.put(newChannel.getName(), newChannel); } /** * Remove a channel from the saved set * @param oldChannel Channel to remove * @return IRCChannel that was removed */ public IRCChannel removeChannel(String oldChannel){ return channels.remove(oldChannel); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channels == null) ? 0 : channels.hashCode()); result = prime * result + ((serverAddress == null) ? 0 : serverAddress.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof IRCServer)) return false; IRCServer other = (IRCServer) obj; if (channels == null) { if (other.channels != null) return false; } else if (!channels.equals(other.channels)) return false; if (serverAddress == null) { if (other.serverAddress != null) return false; } else if (!serverAddress.equals(other.serverAddress)) return false; return true; } }
Changed channel list to a tree map that ignores case of channels.
FelisBotus/src/com/wc1/felisBotus/irc/IRCServer.java
Changed channel list to a tree map that ignores case of channels.
Java
apache-2.0
8b73a962190907c561ab9c9895fb0911632daac5
0
robertwb/incubator-beam,chamikaramj/beam,chamikaramj/beam,robertwb/incubator-beam,iemejia/incubator-beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,lukecwik/incubator-beam,apache/beam,apache/beam,robertwb/incubator-beam,markflyhigh/incubator-beam,iemejia/incubator-beam,markflyhigh/incubator-beam,robertwb/incubator-beam,robertwb/incubator-beam,lukecwik/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,chamikaramj/beam,RyanSkraba/beam,lukecwik/incubator-beam,apache/beam,lukecwik/incubator-beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,RyanSkraba/beam,RyanSkraba/beam,robertwb/incubator-beam,markflyhigh/incubator-beam,chamikaramj/beam,chamikaramj/beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,apache/beam,chamikaramj/beam,markflyhigh/incubator-beam,chamikaramj/beam,RyanSkraba/beam,markflyhigh/incubator-beam,apache/beam,RyanSkraba/beam,RyanSkraba/beam,robertwb/incubator-beam,apache/beam,markflyhigh/incubator-beam,RyanSkraba/beam,chamikaramj/beam,apache/beam,robertwb/incubator-beam
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.jdbc; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; import com.google.auto.value.AutoValue; import java.io.IOException; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import javax.annotation.Nullable; import javax.sql.DataSource; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.options.ValueProvider; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.Filter; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Reshuffle; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.transforms.SerializableFunctions; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.transforms.Wait; import org.apache.beam.sdk.transforms.display.DisplayData; import org.apache.beam.sdk.transforms.display.HasDisplayData; import org.apache.beam.sdk.util.BackOff; import org.apache.beam.sdk.util.BackOffUtils; import org.apache.beam.sdk.util.FluentBackoff; import org.apache.beam.sdk.util.Sleeper; import org.apache.beam.sdk.values.PBegin; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; import org.apache.beam.sdk.values.PDone; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbcp2.DataSourceConnectionFactory; import org.apache.commons.dbcp2.PoolableConnectionFactory; import org.apache.commons.dbcp2.PoolingDataSource; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * IO to read and write data on JDBC. * * <h3>Reading from JDBC datasource</h3> * * <p>JdbcIO source returns a bounded collection of {@code T} as a {@code PCollection<T>}. T is the * type returned by the provided {@link RowMapper}. * * <p>To configure the JDBC source, you have to provide a {@link DataSourceConfiguration} using<br> * 1. {@link DataSourceConfiguration#create(DataSource)}(which must be {@link Serializable});<br> * 2. or {@link DataSourceConfiguration#create(String, String)}(driver class name and url). * Optionally, {@link DataSourceConfiguration#withUsername(String)} and {@link * DataSourceConfiguration#withPassword(String)} allows you to define username and password. * * <p>For example: * * <pre>{@code * pipeline.apply(JdbcIO.<KV<Integer, String>>read() * .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb") * .withUsername("username") * .withPassword("password")) * .withQuery("select id,name from Person") * .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of())) * .withRowMapper(new JdbcIO.RowMapper<KV<Integer, String>>() { * public KV<Integer, String> mapRow(ResultSet resultSet) throws Exception { * return KV.of(resultSet.getInt(1), resultSet.getString(2)); * } * }) * ); * }</pre> * * <p>Query parameters can be configured using a user-provided {@link StatementPreparator}. For * example: * * <pre>{@code * pipeline.apply(JdbcIO.<KV<Integer, String>>read() * .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb", * "username", "password")) * .withQuery("select id,name from Person where name = ?") * .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of())) * .withStatementPreparator(new JdbcIO.StatementPreparator() { * public void setParameters(PreparedStatement preparedStatement) throws Exception { * preparedStatement.setString(1, "Darwin"); * } * }) * .withRowMapper(new JdbcIO.RowMapper<KV<Integer, String>>() { * public KV<Integer, String> mapRow(ResultSet resultSet) throws Exception { * return KV.of(resultSet.getInt(1), resultSet.getString(2)); * } * }) * ); * }</pre> * * <p>To customize the building of the {@link DataSource} we can provide a {@link * SerializableFunction}. For example if you need to provide a {@link PoolingDataSource} from an * existing {@link DataSourceConfiguration}: you can use a {@link PoolableDataSourceProvider}: * * <pre>{@code * pipeline.apply(JdbcIO.<KV<Integer, String>>read() * .withDataSourceProviderFn(JdbcIO.PoolableDataSourceProvider.of( * JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb", * "username", "password"))) * // ... * ); * }</pre> * * By default, the provided function instantiates a DataSource per execution thread. In some * circumstances, such as DataSources that have a pool of connections, this can quickly overwhelm * the database by requesting too many connections. In that case you should make the DataSource a * static singleton so it gets instantiated only once per JVM. * * <h3>Writing to JDBC datasource</h3> * * <p>JDBC sink supports writing records into a database. It writes a {@link PCollection} to the * database by converting each T into a {@link PreparedStatement} via a user-provided {@link * PreparedStatementSetter}. * * <p>Like the source, to configure the sink, you have to provide a {@link DataSourceConfiguration}. * * <pre>{@code * pipeline * .apply(...) * .apply(JdbcIO.<KV<Integer, String>>write() * .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb") * .withUsername("username") * .withPassword("password")) * .withStatement("insert into Person values(?, ?)") * .withPreparedStatementSetter(new JdbcIO.PreparedStatementSetter<KV<Integer, String>>() { * public void setParameters(KV<Integer, String> element, PreparedStatement query) * throws SQLException { * query.setInt(1, element.getKey()); * query.setString(2, element.getValue()); * } * }) * ); * }</pre> * * <p>NB: in case of transient failures, Beam runners may execute parts of JdbcIO.Write multiple * times for fault tolerance. Because of that, you should avoid using {@code INSERT} statements, * since that risks duplicating records in the database, or failing due to primary key conflicts. * Consider using <a href="https://en.wikipedia.org/wiki/Merge_(SQL)">MERGE ("upsert") * statements</a> supported by your database instead. */ @Experimental(Experimental.Kind.SOURCE_SINK) public class JdbcIO { private static final Logger LOG = LoggerFactory.getLogger(JdbcIO.class); /** * Read data from a JDBC datasource. * * @param <T> Type of the data to be read. */ public static <T> Read<T> read() { return new AutoValue_JdbcIO_Read.Builder<T>() .setFetchSize(DEFAULT_FETCH_SIZE) .setOutputParallelization(true) .build(); } /** * Like {@link #read}, but executes multiple instances of the query substituting each element of a * {@link PCollection} as query parameters. * * @param <ParameterT> Type of the data representing query parameters. * @param <OutputT> Type of the data to be read. */ public static <ParameterT, OutputT> ReadAll<ParameterT, OutputT> readAll() { return new AutoValue_JdbcIO_ReadAll.Builder<ParameterT, OutputT>() .setFetchSize(DEFAULT_FETCH_SIZE) .setOutputParallelization(true) .build(); } private static final long DEFAULT_BATCH_SIZE = 1000L; private static final int DEFAULT_FETCH_SIZE = 50_000; /** * Write data to a JDBC datasource. * * @param <T> Type of the data to be written. */ public static <T> Write<T> write() { return new Write(); } public static <T> WriteVoid<T> writeVoid() { return new AutoValue_JdbcIO_WriteVoid.Builder<T>() .setBatchSize(DEFAULT_BATCH_SIZE) .setRetryStrategy(new DefaultRetryStrategy()) .build(); } /** * This is the default {@link Predicate} we use to detect DeadLock. It basically test if the * {@link SQLException#getSQLState()} equals 40001. 40001 is the SQL State used by most of * database to identify deadlock. */ public static class DefaultRetryStrategy implements RetryStrategy { @Override public boolean apply(SQLException e) { return "40001".equals(e.getSQLState()); } } private JdbcIO() {} /** * An interface used by {@link JdbcIO.Read} for converting each row of the {@link ResultSet} into * an element of the resulting {@link PCollection}. */ @FunctionalInterface public interface RowMapper<T> extends Serializable { T mapRow(ResultSet resultSet) throws Exception; } /** * A POJO describing a {@link DataSource}, either providing directly a {@link DataSource} or all * properties allowing to create a {@link DataSource}. */ @AutoValue public abstract static class DataSourceConfiguration implements Serializable { @Nullable abstract ValueProvider<String> getDriverClassName(); @Nullable abstract ValueProvider<String> getUrl(); @Nullable abstract ValueProvider<String> getUsername(); @Nullable abstract ValueProvider<String> getPassword(); @Nullable abstract ValueProvider<String> getConnectionProperties(); @Nullable abstract DataSource getDataSource(); abstract Builder builder(); @AutoValue.Builder abstract static class Builder { abstract Builder setDriverClassName(ValueProvider<String> driverClassName); abstract Builder setUrl(ValueProvider<String> url); abstract Builder setUsername(ValueProvider<String> username); abstract Builder setPassword(ValueProvider<String> password); abstract Builder setConnectionProperties(ValueProvider<String> connectionProperties); abstract Builder setDataSource(DataSource dataSource); abstract DataSourceConfiguration build(); } public static DataSourceConfiguration create(DataSource dataSource) { checkArgument(dataSource != null, "dataSource can not be null"); checkArgument(dataSource instanceof Serializable, "dataSource must be Serializable"); return new AutoValue_JdbcIO_DataSourceConfiguration.Builder() .setDataSource(dataSource) .build(); } public static DataSourceConfiguration create(String driverClassName, String url) { checkArgument(driverClassName != null, "driverClassName can not be null"); checkArgument(url != null, "url can not be null"); return create( ValueProvider.StaticValueProvider.of(driverClassName), ValueProvider.StaticValueProvider.of(url)); } public static DataSourceConfiguration create( ValueProvider<String> driverClassName, ValueProvider<String> url) { checkArgument(driverClassName != null, "driverClassName can not be null"); checkArgument(url != null, "url can not be null"); return new AutoValue_JdbcIO_DataSourceConfiguration.Builder() .setDriverClassName(driverClassName) .setUrl(url) .build(); } public DataSourceConfiguration withUsername(String username) { return withUsername(ValueProvider.StaticValueProvider.of(username)); } public DataSourceConfiguration withUsername(ValueProvider<String> username) { return builder().setUsername(username).build(); } public DataSourceConfiguration withPassword(String password) { return withPassword(ValueProvider.StaticValueProvider.of(password)); } public DataSourceConfiguration withPassword(ValueProvider<String> password) { return builder().setPassword(password).build(); } /** * Sets the connection properties passed to driver.connect(...). Format of the string must be * [propertyName=property;]* * * <p>NOTE - The "user" and "password" properties can be add via {@link #withUsername(String)}, * {@link #withPassword(String)}, so they do not need to be included here. */ public DataSourceConfiguration withConnectionProperties(String connectionProperties) { checkArgument(connectionProperties != null, "connectionProperties can not be null"); return withConnectionProperties(ValueProvider.StaticValueProvider.of(connectionProperties)); } /** Same as {@link #withConnectionProperties(String)} but accepting a ValueProvider. */ public DataSourceConfiguration withConnectionProperties( ValueProvider<String> connectionProperties) { checkArgument(connectionProperties != null, "connectionProperties can not be null"); return builder().setConnectionProperties(connectionProperties).build(); } void populateDisplayData(DisplayData.Builder builder) { if (getDataSource() != null) { builder.addIfNotNull(DisplayData.item("dataSource", getDataSource().getClass().getName())); } else { builder.addIfNotNull(DisplayData.item("jdbcDriverClassName", getDriverClassName())); builder.addIfNotNull(DisplayData.item("jdbcUrl", getUrl())); builder.addIfNotNull(DisplayData.item("username", getUsername())); } } DataSource buildDatasource() { if (getDataSource() == null) { BasicDataSource basicDataSource = new BasicDataSource(); if (getDriverClassName() != null) { basicDataSource.setDriverClassName(getDriverClassName().get()); } if (getUrl() != null) { basicDataSource.setUrl(getUrl().get()); } if (getUsername() != null) { basicDataSource.setUsername(getUsername().get()); } if (getPassword() != null) { basicDataSource.setPassword(getPassword().get()); } if (getConnectionProperties() != null && getConnectionProperties().get() != null) { basicDataSource.setConnectionProperties(getConnectionProperties().get()); } return basicDataSource; } return getDataSource(); } } /** * An interface used by the JdbcIO Write to set the parameters of the {@link PreparedStatement} * used to setParameters into the database. */ @FunctionalInterface public interface StatementPreparator extends Serializable { void setParameters(PreparedStatement preparedStatement) throws Exception; } /** Implementation of {@link #read}. */ @AutoValue public abstract static class Read<T> extends PTransform<PBegin, PCollection<T>> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated @Nullable abstract DataSourceConfiguration getDataSourceConfiguration(); @Nullable abstract SerializableFunction<Void, DataSource> getDataSourceProviderFn(); @Nullable abstract ValueProvider<String> getQuery(); @Nullable abstract StatementPreparator getStatementPreparator(); @Nullable abstract RowMapper<T> getRowMapper(); @Nullable abstract Coder<T> getCoder(); abstract int getFetchSize(); abstract boolean getOutputParallelization(); abstract Builder<T> toBuilder(); @AutoValue.Builder abstract static class Builder<T> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated abstract Builder<T> setDataSourceConfiguration(DataSourceConfiguration config); abstract Builder<T> setDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn); abstract Builder<T> setQuery(ValueProvider<String> query); abstract Builder<T> setStatementPreparator(StatementPreparator statementPreparator); abstract Builder<T> setRowMapper(RowMapper<T> rowMapper); abstract Builder<T> setCoder(Coder<T> coder); abstract Builder<T> setFetchSize(int fetchSize); abstract Builder<T> setOutputParallelization(boolean outputParallelization); abstract Read<T> build(); } public Read<T> withDataSourceConfiguration(final DataSourceConfiguration config) { toBuilder().setDataSourceConfiguration(config); return withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config)); } public Read<T> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return toBuilder().setDataSourceProviderFn(dataSourceProviderFn).build(); } public Read<T> withQuery(String query) { checkArgument(query != null, "query can not be null"); return withQuery(ValueProvider.StaticValueProvider.of(query)); } public Read<T> withQuery(ValueProvider<String> query) { checkArgument(query != null, "query can not be null"); return toBuilder().setQuery(query).build(); } public Read<T> withStatementPreparator(StatementPreparator statementPreparator) { checkArgument(statementPreparator != null, "statementPreparator can not be null"); return toBuilder().setStatementPreparator(statementPreparator).build(); } public Read<T> withRowMapper(RowMapper<T> rowMapper) { checkArgument(rowMapper != null, "rowMapper can not be null"); return toBuilder().setRowMapper(rowMapper).build(); } public Read<T> withCoder(Coder<T> coder) { checkArgument(coder != null, "coder can not be null"); return toBuilder().setCoder(coder).build(); } /** * This method is used to set the size of the data that is going to be fetched and loaded in * memory per every database call. Please refer to: {@link java.sql.Statement#setFetchSize(int)} * It should ONLY be used if the default value throws memory errors. */ public Read<T> withFetchSize(int fetchSize) { checkArgument(fetchSize > 0, "fetch size must be > 0"); return toBuilder().setFetchSize(fetchSize).build(); } /** * Whether to reshuffle the resulting PCollection so results are distributed to all workers. The * default is to parallelize and should only be changed if this is known to be unnecessary. */ public Read<T> withOutputParallelization(boolean outputParallelization) { return toBuilder().setOutputParallelization(outputParallelization).build(); } @Override public PCollection<T> expand(PBegin input) { checkArgument(getQuery() != null, "withQuery() is required"); checkArgument(getRowMapper() != null, "withRowMapper() is required"); checkArgument(getCoder() != null, "withCoder() is required"); checkArgument( (getDataSourceProviderFn() != null), "withDataSourceConfiguration() or withDataSourceProviderFn() is required"); return input .apply(Create.of((Void) null)) .apply( JdbcIO.<Void, T>readAll() .withDataSourceConfiguration(getDataSourceConfiguration()) .withDataSourceProviderFn(getDataSourceProviderFn()) .withQuery(getQuery()) .withCoder(getCoder()) .withRowMapper(getRowMapper()) .withFetchSize(getFetchSize()) .withOutputParallelization(getOutputParallelization()) .withParameterSetter( (element, preparedStatement) -> { if (getStatementPreparator() != null) { getStatementPreparator().setParameters(preparedStatement); } })); } @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder.add(DisplayData.item("query", getQuery())); builder.add(DisplayData.item("rowMapper", getRowMapper().getClass().getName())); builder.add(DisplayData.item("coder", getCoder().getClass().getName())); if (getDataSourceProviderFn() instanceof HasDisplayData) { ((HasDisplayData) getDataSourceProviderFn()).populateDisplayData(builder); } } } /** Implementation of {@link #readAll}. */ @AutoValue public abstract static class ReadAll<ParameterT, OutputT> extends PTransform<PCollection<ParameterT>, PCollection<OutputT>> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated @Nullable abstract DataSourceConfiguration getDataSourceConfiguration(); @Nullable abstract SerializableFunction<Void, DataSource> getDataSourceProviderFn(); @Nullable abstract ValueProvider<String> getQuery(); @Nullable abstract PreparedStatementSetter<ParameterT> getParameterSetter(); @Nullable abstract RowMapper<OutputT> getRowMapper(); @Nullable abstract Coder<OutputT> getCoder(); abstract int getFetchSize(); abstract boolean getOutputParallelization(); abstract Builder<ParameterT, OutputT> toBuilder(); @AutoValue.Builder abstract static class Builder<ParameterT, OutputT> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated abstract Builder<ParameterT, OutputT> setDataSourceConfiguration( DataSourceConfiguration config); abstract Builder<ParameterT, OutputT> setDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn); abstract Builder<ParameterT, OutputT> setQuery(ValueProvider<String> query); abstract Builder<ParameterT, OutputT> setParameterSetter( PreparedStatementSetter<ParameterT> parameterSetter); abstract Builder<ParameterT, OutputT> setRowMapper(RowMapper<OutputT> rowMapper); abstract Builder<ParameterT, OutputT> setCoder(Coder<OutputT> coder); abstract Builder<ParameterT, OutputT> setFetchSize(int fetchSize); abstract Builder<ParameterT, OutputT> setOutputParallelization(boolean outputParallelization); abstract ReadAll<ParameterT, OutputT> build(); } public ReadAll<ParameterT, OutputT> withDataSourceConfiguration( DataSourceConfiguration config) { toBuilder().setDataSourceConfiguration(config); return withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config)); } public ReadAll<ParameterT, OutputT> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return toBuilder().setDataSourceProviderFn(dataSourceProviderFn).build(); } public ReadAll<ParameterT, OutputT> withQuery(String query) { checkArgument(query != null, "JdbcIO.readAll().withQuery(query) called with null query"); return withQuery(ValueProvider.StaticValueProvider.of(query)); } public ReadAll<ParameterT, OutputT> withQuery(ValueProvider<String> query) { checkArgument(query != null, "JdbcIO.readAll().withQuery(query) called with null query"); return toBuilder().setQuery(query).build(); } public ReadAll<ParameterT, OutputT> withParameterSetter( PreparedStatementSetter<ParameterT> parameterSetter) { checkArgument( parameterSetter != null, "JdbcIO.readAll().withParameterSetter(parameterSetter) called " + "with null statementPreparator"); return toBuilder().setParameterSetter(parameterSetter).build(); } public ReadAll<ParameterT, OutputT> withRowMapper(RowMapper<OutputT> rowMapper) { checkArgument( rowMapper != null, "JdbcIO.readAll().withRowMapper(rowMapper) called with null rowMapper"); return toBuilder().setRowMapper(rowMapper).build(); } public ReadAll<ParameterT, OutputT> withCoder(Coder<OutputT> coder) { checkArgument(coder != null, "JdbcIO.readAll().withCoder(coder) called with null coder"); return toBuilder().setCoder(coder).build(); } /** * This method is used to set the size of the data that is going to be fetched and loaded in * memory per every database call. Please refer to: {@link java.sql.Statement#setFetchSize(int)} * It should ONLY be used if the default value throws memory errors. */ public ReadAll<ParameterT, OutputT> withFetchSize(int fetchSize) { checkArgument(fetchSize > 0, "fetch size must be >0"); return toBuilder().setFetchSize(fetchSize).build(); } /** * Whether to reshuffle the resulting PCollection so results are distributed to all workers. The * default is to parallelize and should only be changed if this is known to be unnecessary. */ public ReadAll<ParameterT, OutputT> withOutputParallelization(boolean outputParallelization) { return toBuilder().setOutputParallelization(outputParallelization).build(); } @Override public PCollection<OutputT> expand(PCollection<ParameterT> input) { PCollection<OutputT> output = input .apply( ParDo.of( new ReadFn<>( getDataSourceProviderFn(), getQuery(), getParameterSetter(), getRowMapper(), getFetchSize()))) .setCoder(getCoder()); if (getOutputParallelization()) { output = output.apply(new Reparallelize<>()); } return output; } @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder.add(DisplayData.item("query", getQuery())); builder.add(DisplayData.item("rowMapper", getRowMapper().getClass().getName())); builder.add(DisplayData.item("coder", getCoder().getClass().getName())); if (getDataSourceProviderFn() instanceof HasDisplayData) { ((HasDisplayData) getDataSourceProviderFn()).populateDisplayData(builder); } } } /** A {@link DoFn} executing the SQL query to read from the database. */ private static class ReadFn<ParameterT, OutputT> extends DoFn<ParameterT, OutputT> { private final SerializableFunction<Void, DataSource> dataSourceProviderFn; private final ValueProvider<String> query; private final PreparedStatementSetter<ParameterT> parameterSetter; private final RowMapper<OutputT> rowMapper; private final int fetchSize; private DataSource dataSource; private Connection connection; private ReadFn( SerializableFunction<Void, DataSource> dataSourceProviderFn, ValueProvider<String> query, PreparedStatementSetter<ParameterT> parameterSetter, RowMapper<OutputT> rowMapper, int fetchSize) { this.dataSourceProviderFn = dataSourceProviderFn; this.query = query; this.parameterSetter = parameterSetter; this.rowMapper = rowMapper; this.fetchSize = fetchSize; } @Setup public void setup() throws Exception { dataSource = dataSourceProviderFn.apply(null); connection = dataSource.getConnection(); } @ProcessElement public void processElement(ProcessContext context) throws Exception { try (PreparedStatement statement = connection.prepareStatement( query.get(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { statement.setFetchSize(fetchSize); parameterSetter.setParameters(context.element(), statement); try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { context.output(rowMapper.mapRow(resultSet)); } } } } @Teardown public void teardown() throws Exception { connection.close(); } } /** * An interface used by the JdbcIO Write to set the parameters of the {@link PreparedStatement} * used to setParameters into the database. */ @FunctionalInterface public interface PreparedStatementSetter<T> extends Serializable { void setParameters(T element, PreparedStatement preparedStatement) throws Exception; } /** * An interface used to control if we retry the statements when a {@link SQLException} occurs. If * {@link RetryStrategy#apply(SQLException)} returns true, {@link Write} tries to replay the * statements. */ @FunctionalInterface public interface RetryStrategy extends Serializable { boolean apply(SQLException sqlException); } /** * This class is used as the default return value of {@link JdbcIO#write()}. * * <p>All methods in this class delegate to the appropriate method of {@link JdbcIO.WriteVoid}. */ public static class Write<T> extends PTransform<PCollection<T>, PDone> { final WriteVoid<T> inner; Write() { this(JdbcIO.writeVoid()); } Write(WriteVoid<T> inner) { this.inner = inner; } /** See {@link WriteVoid#withDataSourceConfiguration(DataSourceConfiguration)}. */ public Write<T> withDataSourceConfiguration(DataSourceConfiguration config) { return new Write( inner .withDataSourceConfiguration(config) .withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config))); } /** See {@link WriteVoid#withDataSourceProviderFn(SerializableFunction)}. */ public Write<T> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return new Write(inner.withDataSourceProviderFn(dataSourceProviderFn)); } /** See {@link WriteVoid#withStatement(String)}. */ public Write<T> withStatement(String statement) { return new Write(inner.withStatement(statement)); } /** See {@link WriteVoid#withPreparedStatementSetter(PreparedStatementSetter)}. */ public Write<T> withPreparedStatementSetter(PreparedStatementSetter<T> setter) { return new Write(inner.withPreparedStatementSetter(setter)); } /** See {@link WriteVoid#withBatchSize(long)}. */ public Write<T> withBatchSize(long batchSize) { return new Write(inner.withBatchSize(batchSize)); } /** See {@link WriteVoid#withRetryStrategy(RetryStrategy)}. */ public Write<T> withRetryStrategy(RetryStrategy retryStrategy) { return new Write(inner.withRetryStrategy(retryStrategy)); } /** * Returns {@link WriteVoid} transform which can be used in {@link Wait#on(PCollection[])} to * wait until all data is written. * * <p>Example: write a {@link PCollection} to one database and then to another database, making * sure that writing a window of data to the second database starts only after the respective * window has been fully written to the first database. * * <pre>{@code * PCollection<Void> firstWriteResults = data.apply(JdbcIO.write() * .withDataSourceConfiguration(CONF_DB_1).withResults()); * data.apply(Wait.on(firstWriteResults)) * .apply(JdbcIO.write().withDataSourceConfiguration(CONF_DB_2)); * }</pre> */ public WriteVoid<T> withResults() { return inner; } @Override public void populateDisplayData(DisplayData.Builder builder) { inner.populateDisplayData(builder); } @Override public PDone expand(PCollection<T> input) { inner.expand(input); return PDone.in(input.getPipeline()); } } /** A {@link PTransform} to write to a JDBC datasource. */ @AutoValue public abstract static class WriteVoid<T> extends PTransform<PCollection<T>, PCollection<Void>> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated @Nullable abstract DataSourceConfiguration getDataSourceConfiguration(); @Nullable abstract SerializableFunction<Void, DataSource> getDataSourceProviderFn(); @Nullable abstract ValueProvider<String> getStatement(); abstract long getBatchSize(); @Nullable abstract PreparedStatementSetter<T> getPreparedStatementSetter(); @Nullable abstract RetryStrategy getRetryStrategy(); abstract Builder<T> toBuilder(); @AutoValue.Builder abstract static class Builder<T> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated abstract Builder<T> setDataSourceConfiguration(DataSourceConfiguration config); abstract Builder<T> setDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn); abstract Builder<T> setStatement(ValueProvider<String> statement); abstract Builder<T> setBatchSize(long batchSize); abstract Builder<T> setPreparedStatementSetter(PreparedStatementSetter<T> setter); abstract Builder<T> setRetryStrategy(RetryStrategy deadlockPredicate); abstract WriteVoid<T> build(); } public WriteVoid<T> withDataSourceConfiguration(DataSourceConfiguration config) { toBuilder().setDataSourceConfiguration(config); return withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config)); } public WriteVoid<T> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return toBuilder().setDataSourceProviderFn(dataSourceProviderFn).build(); } public WriteVoid<T> withStatement(String statement) { return withStatement(ValueProvider.StaticValueProvider.of(statement)); } public WriteVoid<T> withStatement(ValueProvider<String> statement) { return toBuilder().setStatement(statement).build(); } public WriteVoid<T> withPreparedStatementSetter(PreparedStatementSetter<T> setter) { return toBuilder().setPreparedStatementSetter(setter).build(); } /** * Provide a maximum size in number of SQL statement for the batch. Default is 1000. * * @param batchSize maximum batch size in number of statements */ public WriteVoid<T> withBatchSize(long batchSize) { checkArgument(batchSize > 0, "batchSize must be > 0, but was %s", batchSize); return toBuilder().setBatchSize(batchSize).build(); } /** * When a SQL exception occurs, {@link Write} uses this {@link RetryStrategy} to determine if it * will retry the statements. If {@link RetryStrategy#apply(SQLException)} returns {@code true}, * then {@link Write} retries the statements. */ public WriteVoid<T> withRetryStrategy(RetryStrategy retryStrategy) { checkArgument(retryStrategy != null, "retryStrategy can not be null"); return toBuilder().setRetryStrategy(retryStrategy).build(); } @Override public PCollection<Void> expand(PCollection<T> input) { checkArgument(getStatement() != null, "withStatement() is required"); checkArgument( getPreparedStatementSetter() != null, "withPreparedStatementSetter() is required"); checkArgument( (getDataSourceProviderFn() != null), "withDataSourceConfiguration() or withDataSourceProviderFn() is required"); return input.apply(ParDo.of(new WriteFn<>(this))); } private static class WriteFn<T> extends DoFn<T, Void> { private final WriteVoid<T> spec; private static final int MAX_RETRIES = 5; private static final FluentBackoff BUNDLE_WRITE_BACKOFF = FluentBackoff.DEFAULT .withMaxRetries(MAX_RETRIES) .withInitialBackoff(Duration.standardSeconds(5)); private DataSource dataSource; private Connection connection; private PreparedStatement preparedStatement; private final List<T> records = new ArrayList<>(); public WriteFn(WriteVoid<T> spec) { this.spec = spec; } @Setup public void setup() { dataSource = spec.getDataSourceProviderFn().apply(null); } @StartBundle public void startBundle() throws Exception { connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(spec.getStatement().get()); } @ProcessElement public void processElement(ProcessContext context) throws Exception { T record = context.element(); records.add(record); if (records.size() >= spec.getBatchSize()) { executeBatch(); } } private void processRecord(T record, PreparedStatement preparedStatement) { try { preparedStatement.clearParameters(); spec.getPreparedStatementSetter().setParameters(record, preparedStatement); preparedStatement.addBatch(); } catch (Exception e) { throw new RuntimeException(e); } } @FinishBundle public void finishBundle() throws Exception { executeBatch(); try { if (preparedStatement != null) { preparedStatement.close(); } } finally { if (connection != null) { connection.close(); } } } private void executeBatch() throws SQLException, IOException, InterruptedException { if (records.isEmpty()) { return; } Sleeper sleeper = Sleeper.DEFAULT; BackOff backoff = BUNDLE_WRITE_BACKOFF.backoff(); while (true) { try (PreparedStatement preparedStatement = connection.prepareStatement(spec.getStatement().get())) { try { // add each record in the statement batch for (T record : records) { processRecord(record, preparedStatement); } // execute the batch preparedStatement.executeBatch(); // commit the changes connection.commit(); break; } catch (SQLException exception) { if (!spec.getRetryStrategy().apply(exception)) { throw exception; } LOG.warn("Deadlock detected, retrying", exception); // clean up the statement batch and the connection state preparedStatement.clearBatch(); connection.rollback(); if (!BackOffUtils.next(sleeper, backoff)) { // we tried the max number of times throw exception; } } } } records.clear(); } } } private static class Reparallelize<T> extends PTransform<PCollection<T>, PCollection<T>> { @Override public PCollection<T> expand(PCollection<T> input) { // See https://issues.apache.org/jira/browse/BEAM-2803 // We use a combined approach to "break fusion" here: // (see https://cloud.google.com/dataflow/service/dataflow-service-desc#preventing-fusion) // 1) force the data to be materialized by passing it as a side input to an identity fn, // then 2) reshuffle it with a random key. Initial materialization provides some parallelism // and ensures that data to be shuffled can be generated in parallel, while reshuffling // provides perfect parallelism. // In most cases where a "fusion break" is needed, a simple reshuffle would be sufficient. // The current approach is necessary only to support the particular case of JdbcIO where // a single query may produce many gigabytes of query results. PCollectionView<Iterable<T>> empty = input .apply("Consume", Filter.by(SerializableFunctions.constant(false))) .apply(View.asIterable()); PCollection<T> materialized = input.apply( "Identity", ParDo.of( new DoFn<T, T>() { @ProcessElement public void process(ProcessContext c) { c.output(c.element()); } }) .withSideInputs(empty)); return materialized.apply(Reshuffle.viaRandomKey()); } } /** Wraps a {@link DataSourceConfiguration} to provide a {@link PoolingDataSource}. */ public static class PoolableDataSourceProvider implements SerializableFunction<Void, DataSource>, HasDisplayData { private static PoolableDataSourceProvider instance; private static transient DataSource source; private static SerializableFunction<Void, DataSource> dataSourceProviderFn; private PoolableDataSourceProvider(DataSourceConfiguration config) { dataSourceProviderFn = DataSourceProviderFromDataSourceConfiguration.of(config); } public static synchronized SerializableFunction<Void, DataSource> of( DataSourceConfiguration config) { if (instance == null) { instance = new PoolableDataSourceProvider(config); } return instance; } @Override public DataSource apply(Void input) { return buildDataSource(input); } static synchronized DataSource buildDataSource(Void input) { if (source == null) { DataSource basicSource = dataSourceProviderFn.apply(input); DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(basicSource); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(1); poolConfig.setMinIdle(0); poolConfig.setMinEvictableIdleTimeMillis(10000); poolConfig.setSoftMinEvictableIdleTimeMillis(30000); GenericObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory, poolConfig); poolableConnectionFactory.setPool(connectionPool); poolableConnectionFactory.setDefaultAutoCommit(false); poolableConnectionFactory.setDefaultReadOnly(false); source = new PoolingDataSource(connectionPool); } return source; } @Override public void populateDisplayData(DisplayData.Builder builder) { if (dataSourceProviderFn instanceof HasDisplayData) { ((HasDisplayData) dataSourceProviderFn).populateDisplayData(builder); } } } private static class DataSourceProviderFromDataSourceConfiguration implements SerializableFunction<Void, DataSource>, HasDisplayData { private final DataSourceConfiguration config; private static DataSourceProviderFromDataSourceConfiguration instance; private DataSourceProviderFromDataSourceConfiguration(DataSourceConfiguration config) { this.config = config; } public static SerializableFunction<Void, DataSource> of(DataSourceConfiguration config) { if (instance == null) { instance = new DataSourceProviderFromDataSourceConfiguration(config); } return instance; } @Override public DataSource apply(Void input) { return config.buildDatasource(); } @Override public void populateDisplayData(DisplayData.Builder builder) { config.populateDisplayData(builder); } } }
sdks/java/io/jdbc/src/main/java/org/apache/beam/sdk/io/jdbc/JdbcIO.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.jdbc; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; import com.google.auto.value.AutoValue; import java.io.IOException; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import javax.annotation.Nullable; import javax.sql.DataSource; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.options.ValueProvider; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.Filter; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Reshuffle; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.transforms.SerializableFunctions; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.transforms.Wait; import org.apache.beam.sdk.transforms.display.DisplayData; import org.apache.beam.sdk.transforms.display.HasDisplayData; import org.apache.beam.sdk.util.BackOff; import org.apache.beam.sdk.util.BackOffUtils; import org.apache.beam.sdk.util.FluentBackoff; import org.apache.beam.sdk.util.Sleeper; import org.apache.beam.sdk.values.PBegin; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; import org.apache.beam.sdk.values.PDone; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbcp2.DataSourceConnectionFactory; import org.apache.commons.dbcp2.PoolableConnectionFactory; import org.apache.commons.dbcp2.PoolingDataSource; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * IO to read and write data on JDBC. * * <h3>Reading from JDBC datasource</h3> * * <p>JdbcIO source returns a bounded collection of {@code T} as a {@code PCollection<T>}. T is the * type returned by the provided {@link RowMapper}. * * <p>To configure the JDBC source, you have to provide a {@link DataSourceConfiguration} using<br> * 1. {@link DataSourceConfiguration#create(DataSource)}(which must be {@link Serializable});<br> * 2. or {@link DataSourceConfiguration#create(String, String)}(driver class name and url). * Optionally, {@link DataSourceConfiguration#withUsername(String)} and {@link * DataSourceConfiguration#withPassword(String)} allows you to define username and password. * * <p>For example: * * <pre>{@code * pipeline.apply(JdbcIO.<KV<Integer, String>>read() * .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb") * .withUsername("username") * .withPassword("password")) * .withQuery("select id,name from Person") * .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of())) * .withRowMapper(new JdbcIO.RowMapper<KV<Integer, String>>() { * public KV<Integer, String> mapRow(ResultSet resultSet) throws Exception { * return KV.of(resultSet.getInt(1), resultSet.getString(2)); * } * }) * ); * }</pre> * * <p>Query parameters can be configured using a user-provided {@link StatementPreparator}. For * example: * * <pre>{@code * pipeline.apply(JdbcIO.<KV<Integer, String>>read() * .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb", * "username", "password")) * .withQuery("select id,name from Person where name = ?") * .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of())) * .withStatementPreparator(new JdbcIO.StatementPreparator() { * public void setParameters(PreparedStatement preparedStatement) throws Exception { * preparedStatement.setString(1, "Darwin"); * } * }) * .withRowMapper(new JdbcIO.RowMapper<KV<Integer, String>>() { * public KV<Integer, String> mapRow(ResultSet resultSet) throws Exception { * return KV.of(resultSet.getInt(1), resultSet.getString(2)); * } * }) * ); * }</pre> * * <p>To customize the building of the {@link DataSource} we can provide a {@link * SerializableFunction}. For example if you need to provide a {@link PoolingDataSource} from an * existing {@link DataSourceConfiguration}: you can use a {@link PoolableDataSourceProvider}: * * <pre>{@code * pipeline.apply(JdbcIO.<KV<Integer, String>>read() * .withDataSourceProviderFn(JdbcIO.PoolableDataSourceProvider.of( * JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb", * "username", "password"))) * // ... * ); * }</pre> * * By default, the provided function instantiates a DataSource per execution thread. In some * circumstances, such as DataSources that have a pool of connections, this can quickly overwhelm * the database by requesting too many connections. In that case you should make the DataSource a * static singleton so it gets instantiated only once per JVM. * * <h3>Writing to JDBC datasource</h3> * * <p>JDBC sink supports writing records into a database. It writes a {@link PCollection} to the * database by converting each T into a {@link PreparedStatement} via a user-provided {@link * PreparedStatementSetter}. * * <p>Like the source, to configure the sink, you have to provide a {@link DataSourceConfiguration}. * * <pre>{@code * pipeline * .apply(...) * .apply(JdbcIO.<KV<Integer, String>>write() * .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create( * "com.mysql.jdbc.Driver", "jdbc:mysql://hostname:3306/mydb") * .withUsername("username") * .withPassword("password")) * .withStatement("insert into Person values(?, ?)") * .withPreparedStatementSetter(new JdbcIO.PreparedStatementSetter<KV<Integer, String>>() { * public void setParameters(KV<Integer, String> element, PreparedStatement query) * throws SQLException { * query.setInt(1, element.getKey()); * query.setString(2, element.getValue()); * } * }) * ); * }</pre> * * <p>NB: in case of transient failures, Beam runners may execute parts of JdbcIO.Write multiple * times for fault tolerance. Because of that, you should avoid using {@code INSERT} statements, * since that risks duplicating records in the database, or failing due to primary key conflicts. * Consider using <a href="https://en.wikipedia.org/wiki/Merge_(SQL)">MERGE ("upsert") * statements</a> supported by your database instead. */ @Experimental(Experimental.Kind.SOURCE_SINK) public class JdbcIO { private static final Logger LOG = LoggerFactory.getLogger(JdbcIO.class); /** * Read data from a JDBC datasource. * * @param <T> Type of the data to be read. */ public static <T> Read<T> read() { return new AutoValue_JdbcIO_Read.Builder<T>() .setFetchSize(DEFAULT_FETCH_SIZE) .setOutputParallelization(true) .build(); } /** * Like {@link #read}, but executes multiple instances of the query substituting each element of a * {@link PCollection} as query parameters. * * @param <ParameterT> Type of the data representing query parameters. * @param <OutputT> Type of the data to be read. */ public static <ParameterT, OutputT> ReadAll<ParameterT, OutputT> readAll() { return new AutoValue_JdbcIO_ReadAll.Builder<ParameterT, OutputT>() .setFetchSize(DEFAULT_FETCH_SIZE) .setOutputParallelization(true) .build(); } private static final long DEFAULT_BATCH_SIZE = 1000L; private static final int DEFAULT_FETCH_SIZE = 50_000; /** * Write data to a JDBC datasource. * * @param <T> Type of the data to be written. */ public static <T> Write<T> write() { return new Write(); } public static <T> WriteVoid<T> writeVoid() { return new AutoValue_JdbcIO_WriteVoid.Builder<T>() .setBatchSize(DEFAULT_BATCH_SIZE) .setRetryStrategy(new DefaultRetryStrategy()) .build(); } /** * This is the default {@link Predicate} we use to detect DeadLock. It basically test if the * {@link SQLException#getSQLState()} equals 40001. 40001 is the SQL State used by most of * database to identify deadlock. */ public static class DefaultRetryStrategy implements RetryStrategy { @Override public boolean apply(SQLException e) { return "40001".equals(e.getSQLState()); } } private JdbcIO() {} /** * An interface used by {@link JdbcIO.Read} for converting each row of the {@link ResultSet} into * an element of the resulting {@link PCollection}. */ @FunctionalInterface public interface RowMapper<T> extends Serializable { T mapRow(ResultSet resultSet) throws Exception; } /** * A POJO describing a {@link DataSource}, either providing directly a {@link DataSource} or all * properties allowing to create a {@link DataSource}. */ @AutoValue public abstract static class DataSourceConfiguration implements Serializable { @Nullable abstract ValueProvider<String> getDriverClassName(); @Nullable abstract ValueProvider<String> getUrl(); @Nullable abstract ValueProvider<String> getUsername(); @Nullable abstract ValueProvider<String> getPassword(); @Nullable abstract ValueProvider<String> getConnectionProperties(); @Nullable abstract DataSource getDataSource(); abstract Builder builder(); @AutoValue.Builder abstract static class Builder { abstract Builder setDriverClassName(ValueProvider<String> driverClassName); abstract Builder setUrl(ValueProvider<String> url); abstract Builder setUsername(ValueProvider<String> username); abstract Builder setPassword(ValueProvider<String> password); abstract Builder setConnectionProperties(ValueProvider<String> connectionProperties); abstract Builder setDataSource(DataSource dataSource); abstract DataSourceConfiguration build(); } public static DataSourceConfiguration create(DataSource dataSource) { checkArgument(dataSource != null, "dataSource can not be null"); checkArgument(dataSource instanceof Serializable, "dataSource must be Serializable"); return new AutoValue_JdbcIO_DataSourceConfiguration.Builder() .setDataSource(dataSource) .build(); } public static DataSourceConfiguration create(String driverClassName, String url) { checkArgument(driverClassName != null, "driverClassName can not be null"); checkArgument(url != null, "url can not be null"); return create( ValueProvider.StaticValueProvider.of(driverClassName), ValueProvider.StaticValueProvider.of(url)); } public static DataSourceConfiguration create( ValueProvider<String> driverClassName, ValueProvider<String> url) { checkArgument(driverClassName != null, "driverClassName can not be null"); checkArgument(url != null, "url can not be null"); return new AutoValue_JdbcIO_DataSourceConfiguration.Builder() .setDriverClassName(driverClassName) .setUrl(url) .build(); } public DataSourceConfiguration withUsername(String username) { return withUsername(ValueProvider.StaticValueProvider.of(username)); } public DataSourceConfiguration withUsername(ValueProvider<String> username) { return builder().setUsername(username).build(); } public DataSourceConfiguration withPassword(String password) { return withPassword(ValueProvider.StaticValueProvider.of(password)); } public DataSourceConfiguration withPassword(ValueProvider<String> password) { return builder().setPassword(password).build(); } /** * Sets the connection properties passed to driver.connect(...). Format of the string must be * [propertyName=property;]* * * <p>NOTE - The "user" and "password" properties can be add via {@link #withUsername(String)}, * {@link #withPassword(String)}, so they do not need to be included here. */ public DataSourceConfiguration withConnectionProperties(String connectionProperties) { checkArgument(connectionProperties != null, "connectionProperties can not be null"); return withConnectionProperties(ValueProvider.StaticValueProvider.of(connectionProperties)); } /** Same as {@link #withConnectionProperties(String)} but accepting a ValueProvider. */ public DataSourceConfiguration withConnectionProperties( ValueProvider<String> connectionProperties) { checkArgument(connectionProperties != null, "connectionProperties can not be null"); return builder().setConnectionProperties(connectionProperties).build(); } void populateDisplayData(DisplayData.Builder builder) { if (getDataSource() != null) { builder.addIfNotNull(DisplayData.item("dataSource", getDataSource().getClass().getName())); } else { builder.addIfNotNull(DisplayData.item("jdbcDriverClassName", getDriverClassName())); builder.addIfNotNull(DisplayData.item("jdbcUrl", getUrl())); builder.addIfNotNull(DisplayData.item("username", getUsername())); } } DataSource buildDatasource() { if (getDataSource() == null) { BasicDataSource basicDataSource = new BasicDataSource(); if (getDriverClassName() != null) { basicDataSource.setDriverClassName(getDriverClassName().get()); } if (getUrl() != null) { basicDataSource.setUrl(getUrl().get()); } if (getUsername() != null) { basicDataSource.setUsername(getUsername().get()); } if (getPassword() != null) { basicDataSource.setPassword(getPassword().get()); } if (getConnectionProperties() != null && getConnectionProperties().get() != null) { basicDataSource.setConnectionProperties(getConnectionProperties().get()); } return basicDataSource; } return getDataSource(); } } /** Wraps a {@link DataSourceConfiguration} to provide a {@link PoolingDataSource}. */ public static class PoolableDataSourceProvider extends BaseDataSourceProvider { private static SerializableFunction<Void, DataSource> instance = null; private PoolableDataSourceProvider( SerializableFunction<Void, DataSource> dataSourceProviderFn) { super(dataSourceProviderFn); } public static SerializableFunction<Void, DataSource> of(DataSourceConfiguration config) { if (instance == null) { instance = MemoizedDataSourceProvider.of( new PoolableDataSourceProvider( DataSourceProviderFromDataSourceConfiguration.of(config))); } return instance; } @Override public DataSource apply(Void input) { DataSource current = super.dataSourceProviderFn.apply(input); // wrapping the datasource as a pooling datasource DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(current); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(1); poolConfig.setMinIdle(0); poolConfig.setMinEvictableIdleTimeMillis(10000); poolConfig.setSoftMinEvictableIdleTimeMillis(30000); GenericObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory, poolConfig); poolableConnectionFactory.setPool(connectionPool); poolableConnectionFactory.setDefaultAutoCommit(false); poolableConnectionFactory.setDefaultReadOnly(false); return new PoolingDataSource(connectionPool); } } /** * An interface used by the JdbcIO Write to set the parameters of the {@link PreparedStatement} * used to setParameters into the database. */ @FunctionalInterface public interface StatementPreparator extends Serializable { void setParameters(PreparedStatement preparedStatement) throws Exception; } /** Implementation of {@link #read}. */ @AutoValue public abstract static class Read<T> extends PTransform<PBegin, PCollection<T>> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated @Nullable abstract DataSourceConfiguration getDataSourceConfiguration(); @Nullable abstract SerializableFunction<Void, DataSource> getDataSourceProviderFn(); @Nullable abstract ValueProvider<String> getQuery(); @Nullable abstract StatementPreparator getStatementPreparator(); @Nullable abstract RowMapper<T> getRowMapper(); @Nullable abstract Coder<T> getCoder(); abstract int getFetchSize(); abstract boolean getOutputParallelization(); abstract Builder<T> toBuilder(); @AutoValue.Builder abstract static class Builder<T> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated abstract Builder<T> setDataSourceConfiguration(DataSourceConfiguration config); abstract Builder<T> setDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn); abstract Builder<T> setQuery(ValueProvider<String> query); abstract Builder<T> setStatementPreparator(StatementPreparator statementPreparator); abstract Builder<T> setRowMapper(RowMapper<T> rowMapper); abstract Builder<T> setCoder(Coder<T> coder); abstract Builder<T> setFetchSize(int fetchSize); abstract Builder<T> setOutputParallelization(boolean outputParallelization); abstract Read<T> build(); } public Read<T> withDataSourceConfiguration(final DataSourceConfiguration config) { toBuilder().setDataSourceConfiguration(config); return withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config)); } public Read<T> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return toBuilder().setDataSourceProviderFn(dataSourceProviderFn).build(); } public Read<T> withQuery(String query) { checkArgument(query != null, "query can not be null"); return withQuery(ValueProvider.StaticValueProvider.of(query)); } public Read<T> withQuery(ValueProvider<String> query) { checkArgument(query != null, "query can not be null"); return toBuilder().setQuery(query).build(); } public Read<T> withStatementPreparator(StatementPreparator statementPreparator) { checkArgument(statementPreparator != null, "statementPreparator can not be null"); return toBuilder().setStatementPreparator(statementPreparator).build(); } public Read<T> withRowMapper(RowMapper<T> rowMapper) { checkArgument(rowMapper != null, "rowMapper can not be null"); return toBuilder().setRowMapper(rowMapper).build(); } public Read<T> withCoder(Coder<T> coder) { checkArgument(coder != null, "coder can not be null"); return toBuilder().setCoder(coder).build(); } /** * This method is used to set the size of the data that is going to be fetched and loaded in * memory per every database call. Please refer to: {@link java.sql.Statement#setFetchSize(int)} * It should ONLY be used if the default value throws memory errors. */ public Read<T> withFetchSize(int fetchSize) { checkArgument(fetchSize > 0, "fetch size must be > 0"); return toBuilder().setFetchSize(fetchSize).build(); } /** * Whether to reshuffle the resulting PCollection so results are distributed to all workers. The * default is to parallelize and should only be changed if this is known to be unnecessary. */ public Read<T> withOutputParallelization(boolean outputParallelization) { return toBuilder().setOutputParallelization(outputParallelization).build(); } @Override public PCollection<T> expand(PBegin input) { checkArgument(getQuery() != null, "withQuery() is required"); checkArgument(getRowMapper() != null, "withRowMapper() is required"); checkArgument(getCoder() != null, "withCoder() is required"); checkArgument( (getDataSourceProviderFn() != null), "withDataSourceConfiguration() or withDataSourceProviderFn() is required"); return input .apply(Create.of((Void) null)) .apply( JdbcIO.<Void, T>readAll() .withDataSourceConfiguration(getDataSourceConfiguration()) .withDataSourceProviderFn(getDataSourceProviderFn()) .withQuery(getQuery()) .withCoder(getCoder()) .withRowMapper(getRowMapper()) .withFetchSize(getFetchSize()) .withOutputParallelization(getOutputParallelization()) .withParameterSetter( (element, preparedStatement) -> { if (getStatementPreparator() != null) { getStatementPreparator().setParameters(preparedStatement); } })); } @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder.add(DisplayData.item("query", getQuery())); builder.add(DisplayData.item("rowMapper", getRowMapper().getClass().getName())); builder.add(DisplayData.item("coder", getCoder().getClass().getName())); if (getDataSourceProviderFn() instanceof HasDisplayData) { ((HasDisplayData) getDataSourceProviderFn()).populateDisplayData(builder); } } } /** Implementation of {@link #readAll}. */ @AutoValue public abstract static class ReadAll<ParameterT, OutputT> extends PTransform<PCollection<ParameterT>, PCollection<OutputT>> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated @Nullable abstract DataSourceConfiguration getDataSourceConfiguration(); @Nullable abstract SerializableFunction<Void, DataSource> getDataSourceProviderFn(); @Nullable abstract ValueProvider<String> getQuery(); @Nullable abstract PreparedStatementSetter<ParameterT> getParameterSetter(); @Nullable abstract RowMapper<OutputT> getRowMapper(); @Nullable abstract Coder<OutputT> getCoder(); abstract int getFetchSize(); abstract boolean getOutputParallelization(); abstract Builder<ParameterT, OutputT> toBuilder(); @AutoValue.Builder abstract static class Builder<ParameterT, OutputT> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated abstract Builder<ParameterT, OutputT> setDataSourceConfiguration( DataSourceConfiguration config); abstract Builder<ParameterT, OutputT> setDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn); abstract Builder<ParameterT, OutputT> setQuery(ValueProvider<String> query); abstract Builder<ParameterT, OutputT> setParameterSetter( PreparedStatementSetter<ParameterT> parameterSetter); abstract Builder<ParameterT, OutputT> setRowMapper(RowMapper<OutputT> rowMapper); abstract Builder<ParameterT, OutputT> setCoder(Coder<OutputT> coder); abstract Builder<ParameterT, OutputT> setFetchSize(int fetchSize); abstract Builder<ParameterT, OutputT> setOutputParallelization(boolean outputParallelization); abstract ReadAll<ParameterT, OutputT> build(); } public ReadAll<ParameterT, OutputT> withDataSourceConfiguration( DataSourceConfiguration config) { toBuilder().setDataSourceConfiguration(config); return withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config)); } public ReadAll<ParameterT, OutputT> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return toBuilder().setDataSourceProviderFn(dataSourceProviderFn).build(); } public ReadAll<ParameterT, OutputT> withQuery(String query) { checkArgument(query != null, "JdbcIO.readAll().withQuery(query) called with null query"); return withQuery(ValueProvider.StaticValueProvider.of(query)); } public ReadAll<ParameterT, OutputT> withQuery(ValueProvider<String> query) { checkArgument(query != null, "JdbcIO.readAll().withQuery(query) called with null query"); return toBuilder().setQuery(query).build(); } public ReadAll<ParameterT, OutputT> withParameterSetter( PreparedStatementSetter<ParameterT> parameterSetter) { checkArgument( parameterSetter != null, "JdbcIO.readAll().withParameterSetter(parameterSetter) called " + "with null statementPreparator"); return toBuilder().setParameterSetter(parameterSetter).build(); } public ReadAll<ParameterT, OutputT> withRowMapper(RowMapper<OutputT> rowMapper) { checkArgument( rowMapper != null, "JdbcIO.readAll().withRowMapper(rowMapper) called with null rowMapper"); return toBuilder().setRowMapper(rowMapper).build(); } public ReadAll<ParameterT, OutputT> withCoder(Coder<OutputT> coder) { checkArgument(coder != null, "JdbcIO.readAll().withCoder(coder) called with null coder"); return toBuilder().setCoder(coder).build(); } /** * This method is used to set the size of the data that is going to be fetched and loaded in * memory per every database call. Please refer to: {@link java.sql.Statement#setFetchSize(int)} * It should ONLY be used if the default value throws memory errors. */ public ReadAll<ParameterT, OutputT> withFetchSize(int fetchSize) { checkArgument(fetchSize > 0, "fetch size must be >0"); return toBuilder().setFetchSize(fetchSize).build(); } /** * Whether to reshuffle the resulting PCollection so results are distributed to all workers. The * default is to parallelize and should only be changed if this is known to be unnecessary. */ public ReadAll<ParameterT, OutputT> withOutputParallelization(boolean outputParallelization) { return toBuilder().setOutputParallelization(outputParallelization).build(); } @Override public PCollection<OutputT> expand(PCollection<ParameterT> input) { PCollection<OutputT> output = input .apply( ParDo.of( new ReadFn<>( getDataSourceProviderFn(), getQuery(), getParameterSetter(), getRowMapper(), getFetchSize()))) .setCoder(getCoder()); if (getOutputParallelization()) { output = output.apply(new Reparallelize<>()); } return output; } @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder.add(DisplayData.item("query", getQuery())); builder.add(DisplayData.item("rowMapper", getRowMapper().getClass().getName())); builder.add(DisplayData.item("coder", getCoder().getClass().getName())); if (getDataSourceProviderFn() instanceof HasDisplayData) { ((HasDisplayData) getDataSourceProviderFn()).populateDisplayData(builder); } } } /** A {@link DoFn} executing the SQL query to read from the database. */ private static class ReadFn<ParameterT, OutputT> extends DoFn<ParameterT, OutputT> { private final SerializableFunction<Void, DataSource> dataSourceProviderFn; private final ValueProvider<String> query; private final PreparedStatementSetter<ParameterT> parameterSetter; private final RowMapper<OutputT> rowMapper; private final int fetchSize; private DataSource dataSource; private Connection connection; private ReadFn( SerializableFunction<Void, DataSource> dataSourceProviderFn, ValueProvider<String> query, PreparedStatementSetter<ParameterT> parameterSetter, RowMapper<OutputT> rowMapper, int fetchSize) { this.dataSourceProviderFn = dataSourceProviderFn; this.query = query; this.parameterSetter = parameterSetter; this.rowMapper = rowMapper; this.fetchSize = fetchSize; } @Setup public void setup() throws Exception { dataSource = dataSourceProviderFn.apply(null); connection = dataSource.getConnection(); } @ProcessElement public void processElement(ProcessContext context) throws Exception { try (PreparedStatement statement = connection.prepareStatement( query.get(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { statement.setFetchSize(fetchSize); parameterSetter.setParameters(context.element(), statement); try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { context.output(rowMapper.mapRow(resultSet)); } } } } @Teardown public void teardown() throws Exception { connection.close(); } } /** * An interface used by the JdbcIO Write to set the parameters of the {@link PreparedStatement} * used to setParameters into the database. */ @FunctionalInterface public interface PreparedStatementSetter<T> extends Serializable { void setParameters(T element, PreparedStatement preparedStatement) throws Exception; } /** * An interface used to control if we retry the statements when a {@link SQLException} occurs. If * {@link RetryStrategy#apply(SQLException)} returns true, {@link Write} tries to replay the * statements. */ @FunctionalInterface public interface RetryStrategy extends Serializable { boolean apply(SQLException sqlException); } /** * This class is used as the default return value of {@link JdbcIO#write()}. * * <p>All methods in this class delegate to the appropriate method of {@link JdbcIO.WriteVoid}. */ public static class Write<T> extends PTransform<PCollection<T>, PDone> { final WriteVoid<T> inner; Write() { this(JdbcIO.writeVoid()); } Write(WriteVoid<T> inner) { this.inner = inner; } /** See {@link WriteVoid#withDataSourceConfiguration(DataSourceConfiguration)}. */ public Write<T> withDataSourceConfiguration(DataSourceConfiguration config) { return new Write( inner .withDataSourceConfiguration(config) .withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config))); } /** See {@link WriteVoid#withDataSourceProviderFn(SerializableFunction)}. */ public Write<T> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return new Write(inner.withDataSourceProviderFn(dataSourceProviderFn)); } /** See {@link WriteVoid#withStatement(String)}. */ public Write<T> withStatement(String statement) { return new Write(inner.withStatement(statement)); } /** See {@link WriteVoid#withPreparedStatementSetter(PreparedStatementSetter)}. */ public Write<T> withPreparedStatementSetter(PreparedStatementSetter<T> setter) { return new Write(inner.withPreparedStatementSetter(setter)); } /** See {@link WriteVoid#withBatchSize(long)}. */ public Write<T> withBatchSize(long batchSize) { return new Write(inner.withBatchSize(batchSize)); } /** See {@link WriteVoid#withRetryStrategy(RetryStrategy)}. */ public Write<T> withRetryStrategy(RetryStrategy retryStrategy) { return new Write(inner.withRetryStrategy(retryStrategy)); } /** * Returns {@link WriteVoid} transform which can be used in {@link Wait#on(PCollection[])} to * wait until all data is written. * * <p>Example: write a {@link PCollection} to one database and then to another database, making * sure that writing a window of data to the second database starts only after the respective * window has been fully written to the first database. * * <pre>{@code * PCollection<Void> firstWriteResults = data.apply(JdbcIO.write() * .withDataSourceConfiguration(CONF_DB_1).withResults()); * data.apply(Wait.on(firstWriteResults)) * .apply(JdbcIO.write().withDataSourceConfiguration(CONF_DB_2)); * }</pre> */ public WriteVoid<T> withResults() { return inner; } @Override public void populateDisplayData(DisplayData.Builder builder) { inner.populateDisplayData(builder); } @Override public PDone expand(PCollection<T> input) { inner.expand(input); return PDone.in(input.getPipeline()); } } /** A {@link PTransform} to write to a JDBC datasource. */ @AutoValue public abstract static class WriteVoid<T> extends PTransform<PCollection<T>, PCollection<Void>> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated @Nullable abstract DataSourceConfiguration getDataSourceConfiguration(); @Nullable abstract SerializableFunction<Void, DataSource> getDataSourceProviderFn(); @Nullable abstract ValueProvider<String> getStatement(); abstract long getBatchSize(); @Nullable abstract PreparedStatementSetter<T> getPreparedStatementSetter(); @Nullable abstract RetryStrategy getRetryStrategy(); abstract Builder<T> toBuilder(); @AutoValue.Builder abstract static class Builder<T> { /** @deprecated It is not needed anymore. It will be removed in a future version of Beam. */ @Deprecated abstract Builder<T> setDataSourceConfiguration(DataSourceConfiguration config); abstract Builder<T> setDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn); abstract Builder<T> setStatement(ValueProvider<String> statement); abstract Builder<T> setBatchSize(long batchSize); abstract Builder<T> setPreparedStatementSetter(PreparedStatementSetter<T> setter); abstract Builder<T> setRetryStrategy(RetryStrategy deadlockPredicate); abstract WriteVoid<T> build(); } public WriteVoid<T> withDataSourceConfiguration(DataSourceConfiguration config) { toBuilder().setDataSourceConfiguration(config); return withDataSourceProviderFn(new DataSourceProviderFromDataSourceConfiguration(config)); } public WriteVoid<T> withDataSourceProviderFn( SerializableFunction<Void, DataSource> dataSourceProviderFn) { return toBuilder().setDataSourceProviderFn(dataSourceProviderFn).build(); } public WriteVoid<T> withStatement(String statement) { return withStatement(ValueProvider.StaticValueProvider.of(statement)); } public WriteVoid<T> withStatement(ValueProvider<String> statement) { return toBuilder().setStatement(statement).build(); } public WriteVoid<T> withPreparedStatementSetter(PreparedStatementSetter<T> setter) { return toBuilder().setPreparedStatementSetter(setter).build(); } /** * Provide a maximum size in number of SQL statement for the batch. Default is 1000. * * @param batchSize maximum batch size in number of statements */ public WriteVoid<T> withBatchSize(long batchSize) { checkArgument(batchSize > 0, "batchSize must be > 0, but was %s", batchSize); return toBuilder().setBatchSize(batchSize).build(); } /** * When a SQL exception occurs, {@link Write} uses this {@link RetryStrategy} to determine if it * will retry the statements. If {@link RetryStrategy#apply(SQLException)} returns {@code true}, * then {@link Write} retries the statements. */ public WriteVoid<T> withRetryStrategy(RetryStrategy retryStrategy) { checkArgument(retryStrategy != null, "retryStrategy can not be null"); return toBuilder().setRetryStrategy(retryStrategy).build(); } @Override public PCollection<Void> expand(PCollection<T> input) { checkArgument(getStatement() != null, "withStatement() is required"); checkArgument( getPreparedStatementSetter() != null, "withPreparedStatementSetter() is required"); checkArgument( (getDataSourceProviderFn() != null), "withDataSourceConfiguration() or withDataSourceProviderFn() is required"); return input.apply(ParDo.of(new WriteFn<>(this))); } private static class WriteFn<T> extends DoFn<T, Void> { private final WriteVoid<T> spec; private static final int MAX_RETRIES = 5; private static final FluentBackoff BUNDLE_WRITE_BACKOFF = FluentBackoff.DEFAULT .withMaxRetries(MAX_RETRIES) .withInitialBackoff(Duration.standardSeconds(5)); private DataSource dataSource; private Connection connection; private PreparedStatement preparedStatement; private final List<T> records = new ArrayList<>(); public WriteFn(WriteVoid<T> spec) { this.spec = spec; } @Setup public void setup() { dataSource = spec.getDataSourceProviderFn().apply(null); } @StartBundle public void startBundle() throws Exception { connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(spec.getStatement().get()); } @ProcessElement public void processElement(ProcessContext context) throws Exception { T record = context.element(); records.add(record); if (records.size() >= spec.getBatchSize()) { executeBatch(); } } private void processRecord(T record, PreparedStatement preparedStatement) { try { preparedStatement.clearParameters(); spec.getPreparedStatementSetter().setParameters(record, preparedStatement); preparedStatement.addBatch(); } catch (Exception e) { throw new RuntimeException(e); } } @FinishBundle public void finishBundle() throws Exception { executeBatch(); try { if (preparedStatement != null) { preparedStatement.close(); } } finally { if (connection != null) { connection.close(); } } } private void executeBatch() throws SQLException, IOException, InterruptedException { if (records.isEmpty()) { return; } Sleeper sleeper = Sleeper.DEFAULT; BackOff backoff = BUNDLE_WRITE_BACKOFF.backoff(); while (true) { try (PreparedStatement preparedStatement = connection.prepareStatement(spec.getStatement().get())) { try { // add each record in the statement batch for (T record : records) { processRecord(record, preparedStatement); } // execute the batch preparedStatement.executeBatch(); // commit the changes connection.commit(); break; } catch (SQLException exception) { if (!spec.getRetryStrategy().apply(exception)) { throw exception; } LOG.warn("Deadlock detected, retrying", exception); // clean up the statement batch and the connection state preparedStatement.clearBatch(); connection.rollback(); if (!BackOffUtils.next(sleeper, backoff)) { // we tried the max number of times throw exception; } } } } records.clear(); } } } private static class Reparallelize<T> extends PTransform<PCollection<T>, PCollection<T>> { @Override public PCollection<T> expand(PCollection<T> input) { // See https://issues.apache.org/jira/browse/BEAM-2803 // We use a combined approach to "break fusion" here: // (see https://cloud.google.com/dataflow/service/dataflow-service-desc#preventing-fusion) // 1) force the data to be materialized by passing it as a side input to an identity fn, // then 2) reshuffle it with a random key. Initial materialization provides some parallelism // and ensures that data to be shuffled can be generated in parallel, while reshuffling // provides perfect parallelism. // In most cases where a "fusion break" is needed, a simple reshuffle would be sufficient. // The current approach is necessary only to support the particular case of JdbcIO where // a single query may produce many gigabytes of query results. PCollectionView<Iterable<T>> empty = input .apply("Consume", Filter.by(SerializableFunctions.constant(false))) .apply(View.asIterable()); PCollection<T> materialized = input.apply( "Identity", ParDo.of( new DoFn<T, T>() { @ProcessElement public void process(ProcessContext c) { c.output(c.element()); } }) .withSideInputs(empty)); return materialized.apply(Reshuffle.viaRandomKey()); } } private static class DataSourceProviderFromDataSourceConfiguration implements SerializableFunction<Void, DataSource>, HasDisplayData { private final DataSourceConfiguration config; private static DataSourceProviderFromDataSourceConfiguration instance; private DataSourceProviderFromDataSourceConfiguration(DataSourceConfiguration config) { this.config = config; } public static SerializableFunction<Void, DataSource> of(DataSourceConfiguration config) { if (instance == null) { instance = new DataSourceProviderFromDataSourceConfiguration(config); } return instance; } @Override public DataSource apply(Void input) { return config.buildDatasource(); } @Override public void populateDisplayData(DisplayData.Builder builder) { config.populateDisplayData(builder); } } private abstract static class BaseDataSourceProvider implements SerializableFunction<Void, DataSource>, HasDisplayData { private final SerializableFunction<Void, DataSource> dataSourceProviderFn; BaseDataSourceProvider(SerializableFunction<Void, DataSource> dataSourceProviderFn) { this.dataSourceProviderFn = dataSourceProviderFn; } @Override public void populateDisplayData(DisplayData.Builder builder) { if (dataSourceProviderFn instanceof HasDisplayData) { ((HasDisplayData) dataSourceProviderFn).populateDisplayData(builder); } } } private static class MemoizedDataSourceProvider extends BaseDataSourceProvider { private static MemoizedDataSourceProvider instance = null; @Nullable private static DataSource datasource = null; private MemoizedDataSourceProvider( SerializableFunction<Void, DataSource> dataSourceProviderFn) { super(dataSourceProviderFn); } public static MemoizedDataSourceProvider of( SerializableFunction<Void, DataSource> dataSourceProviderFn) { if (instance == null) { instance = new MemoizedDataSourceProvider(dataSourceProviderFn); } return instance; } @Override public DataSource apply(Void input) { if (datasource == null) { datasource = super.dataSourceProviderFn.apply(null); } return datasource; } } }
[BEAM-7230] Make PoolableDataSourceProvider a static singleton And simplifies all the inner method construction that was error-prone.
sdks/java/io/jdbc/src/main/java/org/apache/beam/sdk/io/jdbc/JdbcIO.java
[BEAM-7230] Make PoolableDataSourceProvider a static singleton And simplifies all the inner method construction that was error-prone.
Java
apache-2.0
1d00931292d336294d02cb739bd7f1838b9c72f3
0
unratito/ceylon.language,ceylon/ceylon.language,jvasileff/ceylon.language,lucaswerkmeister/ceylon.language,lucaswerkmeister/ceylon.language,jvasileff/ceylon.language,ceylon/ceylon.language,unratito/ceylon.language
package ceylon.language; import java.util.ArrayList; import java.util.List; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Class; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes; import com.redhat.ceylon.compiler.java.metadata.Sequenced; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; @Ceylon(major = 1) @Class(extendsType="ceylon.language.Object") @SatisfiedTypes({"ceylon.language.Sequence<Element>", "ceylon.language.Category"}) @TypeParameters(@TypeParameter(value="Element", satisfies={"ceylon.language.Comparable<Element>", "ceylon.language.Ordinal<Element>"})) public class Range<Element extends Comparable<? super Element> & Ordinal<? extends Element>> implements Sequence<Element>, Category { private final Element first; private final Element last; private final long size; public Range(@Name("first") Element first, @Name("last") Element last) { this.first = first; this.last = last; long index = 0; Element x = first; while (!x.equals(last)) { ++index; x = next(x); } this.size = index+1; } @Override public final Element getFirst(){ return first; } @Override public final Element getLast(){ return last; } @Override public final java.lang.String toString(){ return first.toString() + ".." + last.toString(); } public final boolean getDecreasing(){ return last.compare(first).smallerThan(); } private final Element next(Element x){ return getDecreasing() ? x.getPredecessor() : x.getSuccessor(); } @Override @TypeInfo("ceylon.language.Integer") public final long getSize(){ return size; } @Override @TypeInfo("ceylon.language.Integer") public final Integer getLastIndex(){ return Integer.instance(size - 1); } @Override @TypeInfo("ceylon.language.Empty|ceylon.language.Sequence<Element>") public FixedSized<? extends Element> getRest() { if (first.equals(last)) { return (FixedSized)$empty.getEmpty(); } else { return new Range<Element>(next(getFirst()), getLast()); } } @TypeInfo("ceylon.language.Nothing|Element") @Override public Element item(@Name("key") Integer key) { long index = 0; Element x = first; while (index<key.longValue()) { if (x.equals(last)){ return null; } else { ++index; x=next(x); } } return x; } @Override @TypeInfo("ceylon.language.Iterator<Element>") public Iterator<Element> getIterator() { class RangeIterator implements Iterator<Element> { java.lang.Object current; public RangeIterator() { this.current = first; } @TypeInfo("Element|ceylon.language.Finished") public java.lang.Object next() { java.lang.Object result = current; if (!(current instanceof Finished)){ if(current.equals(getLast())) { current = exhausted.getExhausted(); } else { current = Range.this.next((Element) current); } } return result; } @Override public java.lang.String toString() { return "RangeIterator"; } } return new RangeIterator(); } @Override public final boolean contains(@Name("element") java.lang.Object element) { // FIXME try { return element != null /*&& value instanceof Element*/ ? includes((Element) element) : false; } catch (ClassCastException cce) { //ugly hack return false; } } @Override public final long count(@Name("element") java.lang.Object element) { return contains(element) ? 1 : 0; } public final boolean includes(@Name("x") Element x){ if (getDecreasing()){ return x.compare(first).asSmallAs() && x.compare(last).asLargeAs(); } else { return x.compare(first).asLargeAs() && x.compare(last).asSmallAs(); } } @Override @Ignore public final boolean equals(@Name("that") java.lang.Object that){ if (that instanceof Range) { Range<Element> $that = (Range<Element>) that; return $that.getFirst().equals(getFirst()) && $that.getLast().equals(getLast()); } else { return List$impl._equals(this, that); } } @Override @Ignore public int hashCode(){ return List$impl._hashCode(this); } @Override public Range<Element> getClone() { return this; } /*@Override public Ordered<Element> segment(long from, long length) { throw new RuntimeException("Not implemented"); //todo! }*/ @Override @Ignore public Category getKeys() { return Correspondence$impl._getKeys(this); } @Override @Ignore public boolean definesEvery(@Sequenced @Name("keys") @TypeInfo("ceylon.language.Iterable<ceylon.language.Integer>") Iterable<? extends Integer> keys) { return Correspondence$impl._definesEvery(this, keys); } @Override @Ignore public boolean definesEvery() { return Correspondence$impl._definesEvery(this, (Iterable)$empty.getEmpty()); } @Override @Ignore public Iterable<? extends Integer> definesEvery$keys() { return (Iterable)$empty.getEmpty(); } @Override @Ignore public boolean definesAny(@Sequenced @Name("keys") @TypeInfo("ceylon.language.Iterable<ceylon.language.Integer>") Iterable<? extends Integer> keys) { return Correspondence$impl._definesAny(this, keys); } @Override @Ignore public boolean definesAny() { return Correspondence$impl._definesAny(this, (Iterable)$empty.getEmpty()); } @Override @Ignore public Iterable<? extends Integer> definesAny$keys() { return (Iterable)$empty.getEmpty(); } @Override @Ignore public ceylon.language.List<? extends Element> items(@Sequenced @Name("keys") @TypeInfo("ceylon.language.Iterable<ceylon.language.Integer>") Iterable<? extends Integer> keys) { return Correspondence$impl._items(this, keys); } @Override @Ignore public ceylon.language.List<? extends Element> items() { return Correspondence$impl._items(this, (Iterable)$empty.getEmpty()); } @Override @Ignore public Iterable<? extends Integer> items$keys() { return (Iterable)$empty.getEmpty(); } //TODO: @TypeInfo @Override @Ignore public boolean containsEvery(@Sequenced @Name("elements") @TypeInfo("ceylon.language.Iterable<ceylon.language.Object>") Iterable<?> elements) { return Category$impl._containsEvery(this, elements); } @Override @Ignore public boolean containsEvery() { return Category$impl._containsEvery(this, $empty.getEmpty()); } @Override @Ignore public Iterable<?> containsEvery$elements() { return $empty.getEmpty(); } //TODO: @TypeInfo @Override @Ignore public boolean containsAny(@Sequenced @Name("elements") @TypeInfo("ceylon.language.Iterable<ceylon.language.Object>") Iterable<?> elements) { return Category$impl._containsAny(this, elements); } @Override @Ignore public boolean containsAny() { return Category$impl._containsAny(this, $empty.getEmpty()); } @Override @Ignore public Iterable<?> containsAny$elements() { return $empty.getEmpty(); } @Override @Ignore public boolean getEmpty() { return Some$impl._getEmpty(this); } @Override @Ignore public boolean defines(@Name("key") Integer key) { return List$impl._defines(this, key); } @Override @TypeInfo("ceylon.language.Empty|ceylon.language.Sequence<Element>") public ceylon.language.List<? extends Element> segment( @Name("from") final Integer from, @Name("length") final long length) { //only positive length for now if (length<=0) return (ceylon.language.List)$empty.getEmpty(); if (!defines(from)) return (ceylon.language.List)$empty.getEmpty(); Element x = this.first; for (int i=0; i < from.longValue(); i++) { x = this.next(x); } Element y = x; for (int i=1; i < length; i++) { y = this.next(y); } if (!includes(y)) { y = this.last; } return new Range<Element>(x, y); } @Override @TypeInfo("ceylon.language.Empty|ceylon.language.Sequence<Element>") public ceylon.language.List<? extends Element> span( @Name("from") final Integer from, @TypeInfo("ceylon.language.Nothing|ceylon.language.Integer") @Name("to") final Integer to) { Integer fromIndex = largest.largest(Integer.instance(0), from); Integer toIndex = to==null ? getLastIndex() : to; if (!defines(fromIndex)) { //If it's an inverse range, adjust the "from" (upper bound) if (fromIndex.compare(toIndex) == larger.getLarger() && defines(toIndex)) { //Decrease the upper bound while (!defines(fromIndex)) { fromIndex = fromIndex.getPredecessor(); } } else { return (ceylon.language.List)$empty.getEmpty(); } } else while (!defines(toIndex)) { //decrease the upper bound toIndex = toIndex.getPredecessor(); } return new Range<Element>(this.item(fromIndex), this.item(toIndex)); } @Override @TypeInfo("ceylon.language.Iterable<Element>") public Iterable<? extends Element> by( @TypeInfo("ceylon.language.Integer") @Name("stepSize") long stepSize) { if (stepSize==0) { throw new Exception(String.instance("step size must be nonzero"), null); } if (first.equals(last) || stepSize==1) { return this; } boolean decreasing = getDecreasing(); List<Element> list = new ArrayList<Element>(); for (Element elem = first; decreasing ? elem.compare(last).asLargeAs() : elem.compare(last).asSmallAs();) { list.add(elem); for (int i=0; i<stepSize; i++) { elem = next(elem); } } return new ArraySequence<Element>(list); } @Override @Ignore public Iterable<? extends Element> getSequence() { return Iterable$impl._getSequence(this); } @Override @Ignore public Element find(Callable<? extends Boolean> f) { return Iterable$impl._find(this, f); } @Override @Ignore public Iterable<? extends Element> sorted(Callable<? extends Comparison> f) { return Iterable$impl._sorted(this, f); } @Override @Ignore public <Result> Iterable<Result> map(Callable<? extends Result> f) { return new MapIterable<Element, Result>(this, f); } @Override @Ignore public Iterable<? extends Element> filter(Callable<? extends Boolean> f) { return new FilterIterable<Element>(this, f); } @Override @Ignore public <Result> Result fold(Result ini, Callable<? extends Result> f) { return Iterable$impl._fold(this, ini, f); } @Override @Ignore public boolean any(Callable<? extends Boolean> f) { return Iterable$impl._any(this, f); } @Override @Ignore public boolean every(Callable<? extends Boolean> f) { return Iterable$impl._every(this, f); } @Override @Ignore public Iterable<? extends Element> skipping(long skip) { long x=0; Element e=first; while (x<skip) { x++; e=next(e); } return this.includes(e) ? new Range(e, last) : (Iterable)$empty.getEmpty(); } @Override @Ignore public Iterable<? extends Element> taking(long take) { if (take == 0) { return (Iterable)$empty.getEmpty(); } long x=1; Element e=first; while (x<take) { x++; e=next(e); } return this.includes(e) ? new Range(first, e) : this; } }
runtime/ceylon/language/Range.java
package ceylon.language; import java.util.ArrayList; import java.util.List; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Class; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes; import com.redhat.ceylon.compiler.java.metadata.Sequenced; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; @Ceylon(major = 1) @Class(extendsType="ceylon.language.Object") @SatisfiedTypes({"ceylon.language.Sequence<Element>", "ceylon.language.Category"}) @TypeParameters(@TypeParameter(value="Element", satisfies={"ceylon.language.Comparable<Element>", "ceylon.language.Ordinal<Element>"})) public class Range<Element extends Comparable<? super Element> & Ordinal<? extends Element>> implements Sequence<Element>, Category { private final Element first; private final Element last; private final long size; public Range(@Name("first") Element first, @Name("last") Element last) { this.first = first; this.last = last; long index = 0; Element x = first; while (!x.equals(last)) { ++index; x = next(x); } this.size = index+1; } @Override public final Element getFirst(){ return first; } @Override public final Element getLast(){ return last; } @Override public final java.lang.String toString(){ return first.toString() + ".." + last.toString(); } public final boolean getDecreasing(){ return last.compare(first).smallerThan(); } private final Element next(Element x){ return getDecreasing() ? x.getPredecessor() : x.getSuccessor(); } @Override @TypeInfo("ceylon.language.Integer") public final long getSize(){ return size; } @Override @TypeInfo("ceylon.language.Integer") public final Integer getLastIndex(){ return Integer.instance(size - 1); } @Override @TypeInfo("ceylon.language.Empty|ceylon.language.Sequence<Element>") public FixedSized<? extends Element> getRest() { if (first.equals(last)) { return (FixedSized)$empty.getEmpty(); } else { return new Range<Element>(next(getFirst()), getLast()); } } @TypeInfo("ceylon.language.Nothing|Element") @Override public Element item(@Name("key") Integer key) { long index = 0; Element x = first; while (index<key.longValue()) { if (x.equals(last)){ return null; } else { ++index; x=next(x); } } return x; } @Override @TypeInfo("ceylon.language.Iterator<Element>") public Iterator<Element> getIterator() { class RangeIterator implements Iterator<Element> { java.lang.Object current; public RangeIterator() { this.current = first; } @TypeInfo("Element|ceylon.language.Finished") public java.lang.Object next() { java.lang.Object result = current; if (!(current instanceof Finished)){ if(current.equals(getLast())) { current = exhausted.getExhausted(); } else { current = Range.this.next((Element) current); } } return result; } @Override public java.lang.String toString() { return "RangeIterator"; } } return new RangeIterator(); } @Override public final boolean contains(@Name("element") java.lang.Object element) { // FIXME try { return element != null /*&& value instanceof Element*/ ? includes((Element) element) : false; } catch (ClassCastException cce) { //ugly hack return false; } } @Override public final long count(@Name("element") java.lang.Object element) { return contains(element) ? 1 : 0; } public final boolean includes(@Name("x") Element x){ if (getDecreasing()){ return x.compare(first).asSmallAs() && x.compare(last).asLargeAs(); } else { return x.compare(first).asLargeAs() && x.compare(last).asSmallAs(); } } @Override @Ignore public final boolean equals(@Name("that") java.lang.Object that){ if (that instanceof Range) { Range<Element> $that = (Range<Element>) that; return $that.getFirst().equals(getFirst()) && $that.getLast().equals(getLast()); } else { return List$impl._equals(this, that); } } @Override @Ignore public int hashCode(){ return List$impl._hashCode(this); } @Override public Range<Element> getClone() { return this; } /*@Override public Ordered<Element> segment(long from, long length) { throw new RuntimeException("Not implemented"); //todo! }*/ @Override @Ignore public Category getKeys() { return Correspondence$impl._getKeys(this); } @Override @Ignore public boolean definesEvery(@Sequenced @Name("keys") @TypeInfo("ceylon.language.Iterable<ceylon.language.Integer>") Iterable<? extends Integer> keys) { return Correspondence$impl._definesEvery(this, keys); } @Override @Ignore public boolean definesEvery() { return Correspondence$impl._definesEvery(this, (Iterable)$empty.getEmpty()); } @Override @Ignore public Iterable<? extends Integer> definesEvery$keys() { return (Iterable)$empty.getEmpty(); } @Override @Ignore public boolean definesAny(@Sequenced @Name("keys") @TypeInfo("ceylon.language.Iterable<ceylon.language.Integer>") Iterable<? extends Integer> keys) { return Correspondence$impl._definesAny(this, keys); } @Override @Ignore public boolean definesAny() { return Correspondence$impl._definesAny(this, (Iterable)$empty.getEmpty()); } @Override @Ignore public Iterable<? extends Integer> definesAny$keys() { return (Iterable)$empty.getEmpty(); } @Override @Ignore public ceylon.language.List<? extends Element> items(@Sequenced @Name("keys") @TypeInfo("ceylon.language.Iterable<ceylon.language.Integer>") Iterable<? extends Integer> keys) { return Correspondence$impl._items(this, keys); } @Override @Ignore public ceylon.language.List<? extends Element> items() { return Correspondence$impl._items(this, (Iterable)$empty.getEmpty()); } @Override @Ignore public Iterable<? extends Integer> items$keys() { return (Iterable)$empty.getEmpty(); } //TODO: @TypeInfo @Override @Ignore public boolean containsEvery(@Sequenced @Name("elements") @TypeInfo("ceylon.language.Iterable<ceylon.language.Object>") Iterable<?> elements) { return Category$impl._containsEvery(this, elements); } @Override @Ignore public boolean containsEvery() { return Category$impl._containsEvery(this, $empty.getEmpty()); } @Override @Ignore public Iterable<?> containsEvery$elements() { return $empty.getEmpty(); } //TODO: @TypeInfo @Override @Ignore public boolean containsAny(@Sequenced @Name("elements") @TypeInfo("ceylon.language.Iterable<ceylon.language.Object>") Iterable<?> elements) { return Category$impl._containsAny(this, elements); } @Override @Ignore public boolean containsAny() { return Category$impl._containsAny(this, $empty.getEmpty()); } @Override @Ignore public Iterable<?> containsAny$elements() { return $empty.getEmpty(); } @Override @Ignore public boolean getEmpty() { return Some$impl._getEmpty(this); } @Override @Ignore public boolean defines(@Name("key") Integer key) { return List$impl._defines(this, key); } @Override @TypeInfo("ceylon.language.Empty|ceylon.language.Sequence<Element>") public ceylon.language.List<? extends Element> segment( @Name("from") final Integer from, @Name("length") final long length) { //only positive length for now if (length<=0) return (ceylon.language.List)$empty.getEmpty(); if (!defines(from)) return (ceylon.language.List)$empty.getEmpty(); Element x = this.first; for (int i=0; i < from.longValue(); i++) { x = this.next(x); } Element y = x; for (int i=1; i < length; i++) { y = this.next(y); } if (!includes(y)) { y = this.last; } return new Range<Element>(x, y); } @Override @TypeInfo("ceylon.language.Empty|ceylon.language.Sequence<Element>") public ceylon.language.List<? extends Element> span( @Name("from") final Integer from, @TypeInfo("ceylon.language.Nothing|ceylon.language.Integer") @Name("to") final Integer to) { Integer fromIndex = largest.largest(Integer.instance(0), from); Integer toIndex = to==null ? getLastIndex() : to; if (!defines(fromIndex)) { //If it's an inverse range, adjust the "from" (upper bound) if (fromIndex.compare(toIndex) == larger.getLarger() && defines(toIndex)) { //Decrease the upper bound while (!defines(fromIndex)) { fromIndex = fromIndex.getPredecessor(); } } else { return (ceylon.language.List)$empty.getEmpty(); } } else while (!defines(toIndex)) { //decrease the upper bound toIndex = toIndex.getPredecessor(); } return new Range<Element>(this.item(fromIndex), this.item(toIndex)); } @Override @TypeInfo("ceylon.language.Iterable<Element>") public Iterable<? extends Element> by( @TypeInfo("ceylon.language.Integer") @Name("stepSize") long stepSize) { if (stepSize==0) { throw new Exception(String.instance("step size must be nonzero"), null); } if (first.equals(last) || stepSize==1) { return this; } boolean decreasing = getDecreasing(); List<Element> list = new ArrayList<Element>(); for (Element elem = first; decreasing ? elem.compare(last).asLargeAs() : elem.compare(last).asSmallAs();) { list.add(elem); for (int i=0; i<stepSize; i++) { elem = next(elem); } } return new ArraySequence<Element>(list); } @Override @Ignore public Iterable<? extends Element> getSequence() { return Iterable$impl._getSequence(this); } @Override @Ignore public Element find(Callable<? extends Boolean> f) { return Iterable$impl._find(this, f); } @Override @Ignore public Iterable<? extends Element> sorted(Callable<? extends Comparison> f) { return Iterable$impl._sorted(this, f); } @Override @Ignore public <Result> Iterable<Result> map(Callable<? extends Result> f) { return new MapIterable<Element, Result>(this, f); } @Override @Ignore public Iterable<? extends Element> filter(Callable<? extends Boolean> f) { return new FilterIterable<Element>(this, f); } @Override @Ignore public <Result> Result fold(Result ini, Callable<? extends Result> f) { return Iterable$impl._fold(this, ini, f); } @Override @Ignore public boolean any(Callable<? extends Boolean> f) { return Iterable$impl._any(this, f); } @Override @Ignore public boolean every(Callable<? extends Boolean> f) { return Iterable$impl._every(this, f); } @Override @Ignore public Iterable<? extends Element> skipping(long skip) { long x=0; Element e=first; while (x<skip) { x++; e=next(e); } return this.includes(e) ? new Range(e, last) : (Iterable)$empty.getEmpty(); } @Override @Ignore public Iterable<? extends Element> taking(long take) { long x=0; Element e=first; while (x<take) { x++; e=next(e); } return this.includes(e) ? new Range(first, e) : (Iterable)$empty.getEmpty(); } }
Fix Range.taking
runtime/ceylon/language/Range.java
Fix Range.taking