answer
stringlengths
17
10.2M
package org.gestern.gringotts.data; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.gestern.gringotts.AccountChest; import org.gestern.gringotts.Gringotts; import org.gestern.gringotts.GringottsAccount; import org.gestern.gringotts.Util; import org.gestern.gringotts.accountholder.AccountHolder; import com.avaje.ebean.EbeanServer; import com.avaje.ebean.SqlQuery; import com.avaje.ebean.SqlRow; import com.avaje.ebean.SqlUpdate; import com.avaje.ebean.validation.NotNull; public class EBeanDAO implements DAO { private final EbeanServer db = Gringotts.G.getDatabase(); private final Logger log = Gringotts.G.getLogger(); @Override public boolean storeAccountChest(AccountChest chest) { SqlUpdate storeChest = db.createSqlUpdate( "insert into gringotts_accountchest (world,x,y,z,account) values (:world, :x, :y, :z, (select id from gringotts_account where owner=:owner and type=:type))"); Sign mark = chest.sign; storeChest.setParameter("world", mark.getWorld()); storeChest.setParameter("x", mark.getX()); storeChest.setParameter("y", mark.getY()); storeChest.setParameter("z", mark.getZ()); storeChest.setParameter("owner", chest.account.owner.getId()); storeChest.setParameter("type", chest.account.owner.getType()); return storeChest.execute() > 0; } @Override public boolean destroyAccountChest(AccountChest chest) { Sign mark = chest.sign; return deleteAccountChest(mark.getWorld().getName(), mark.getX(), mark.getY(), mark.getZ()); } @Override public boolean storeAccount(GringottsAccount account) { EBeanAccount acc = new EBeanAccount(account.owner.getType(), account.owner.getId(), 0); db.save(acc); return true; } @Override public boolean hasAccount(AccountHolder accountHolder) { int accCount = db.find(EBeanAccount.class) .where().ieq("type", accountHolder.getType()).ieq("name", accountHolder.getName()).findRowCount(); return accCount == 1; } @Override public Set<AccountChest> getChests() { List<SqlRow> result = db.createSqlQuery("SELECT ac.world, ac.x, ac.y, ac.z, a.type, a.owner " + "FROM gringotts_accountchest ac JOIN gringotts_account a ON ac.account = a.id ").findList(); Set<AccountChest> chests = new HashSet<AccountChest>(); for (SqlRow c : result) { String worldName = c.getString("world"); int x = c.getInteger("x"); int y = c.getInteger("y"); int z = c.getInteger("z"); String type = c.getString("type"); String ownerId = c.getString("owner"); World world = Bukkit.getWorld(worldName); Location loc = new Location(world, x, y, z); Block signBlock = loc.getBlock(); if (Util.isSignBlock(signBlock)) { AccountHolder owner = Gringotts.G.accountHolderFactory.get(type, ownerId); if (owner == null) { log.info("AccountHolder "+type+":"+ownerId+" is not valid. Deleting associated account chest at " + signBlock.getLocation()); deleteAccountChest(signBlock.getWorld().getName(), signBlock.getX(), signBlock.getY(), signBlock.getZ()); } else { GringottsAccount ownerAccount = new GringottsAccount(owner); Sign sign = (Sign) signBlock.getState(); chests.add(new AccountChest(sign, ownerAccount)); } } else { // remove accountchest from storage if it is not a valid chest deleteAccountChest(worldName, x, y, z); } } return chests; } private boolean deleteAccountChest(String world, int x, int y, int z) { SqlUpdate deleteChest = db.createSqlUpdate( "delete from accountchest where world = :world and x = :x and y = :y and z = :z"); deleteChest.setParameter("world", world); deleteChest.setParameter("x", x); deleteChest.setParameter("y", y); deleteChest.setParameter("z", z); return deleteChest.execute() > 0; } @Override public Set<AccountChest> getChests(GringottsAccount account) { SqlQuery getChests = db.createSqlQuery("SELECT ac.world, ac.x, ac.y, ac.z " + "FROM accountchest ac JOIN account a ON ac.account = a.id " + "WHERE a.owner = :owner and a.type = :type"); getChests.setParameter("owner", account.owner.getId()); getChests.setParameter("type", account.owner.getType()); Set<AccountChest> chests = new HashSet<AccountChest>(); for (SqlRow result : getChests.findSet()) { String worldName = result.getString("world"); int x = result.getInteger("x"); int y = result.getInteger("y"); int z = result.getInteger("z"); World world = Bukkit.getWorld(worldName); Location loc = new Location(world, x, y, z); Block signBlock = loc.getBlock(); if (Util.isSignBlock(signBlock)) { Sign sign = (Sign) loc.getBlock().getState(); chests.add(new AccountChest(sign, account)); } else { // remove accountchest from storage if it is not a valid chest deleteAccountChest(worldName, x, y, z); } } return chests; } @Override public boolean storeCents(GringottsAccount account, long amount) { EBeanAccount acc = new EBeanAccount(account.owner.getType(), account.owner.getId(), amount); db.save(acc); // TODO does this do a proper update? or just a new insert? return true; } @Override public long getCents(GringottsAccount account) { // TODO can this NPE? return db.find(EBeanAccount.class) .where().ieq("type", account.owner.getType()).ieq("name", account.owner.getName()) .findUnique().cents; } @Override public void deleteAccount(GringottsAccount acc) { throw new RuntimeException("delete account not supported yet in EBeanDAO"); // TODO Auto-generated method stub } @Entity @Table(name="gringotts_account") @UniqueConstraint(columnNames={"type","owner"}) private static class EBeanAccount { @Id int id; /** Type string. */ @NotNull String type; /** Owner id. */ @NotNull String owner; /** Virtual balance. */ @NotNull long cents; public EBeanAccount(String type, String owner, long balance) { this.owner = owner; this.type = type; this.cents = balance; } } @Entity @Table(name="gringotts_accountchest") @UniqueConstraint(columnNames={"world","x","y","z"}) private static class EBeanAccountChest { @Id int id; @NotNull String world; @NotNull int x; @NotNull int y; @NotNull int z; @NotNull int account; public EBeanAccountChest(String world, int x, int y, int z, int account) { this.world = world; this.x = x; this.y = y; this.z = z; this.account = account; } } }
package de.kleppmann.maniation.dynamics; import de.kleppmann.maniation.maths.Vector; class StateVectorScaled extends StateVector { private StateVector origin; private double factor; public StateVectorScaled(StateVector origin, double factor) { super(origin.getScene()); setDerivative(origin.isDerivative()); this.origin = origin; this.factor = factor; } public double getComponent(int index) { return factor*origin.getComponent(index); } public Vector mult(double scalar) { return new StateVectorScaled(origin, factor*scalar); } }
package thredds.server.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.context.ServletContextAware; import org.springframework.web.util.Log4jWebConfigurer; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import thredds.featurecollection.InvDatasetFeatureCollection; import thredds.servlet.ServletUtil; import thredds.util.filesource.*; import ucar.httpservices.HTTPFactory; import ucar.httpservices.HTTPMethod; import ucar.httpservices.HTTPSession; import ucar.nc2.util.IO; import ucar.unidata.util.StringUtil2; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.*; /** * TDScontext implements ServletContextAware so it gets a ServletContext and performs most initial THREDDS set up: * - checks version * - check for latest stable and development release versions * - sets the content directory * - reads persistent user defined params and runs ThreddsConfig.init * - creates, if don't exist, log and public dirs in content directory * - Get default and jsp dispatchers from servletContext * - Creates and initializes the TdsConfigMapper * * LOOK would be nice to make Immutable * @author edavis * @since 4.0 */ @Component("TdsContext") public final class TdsContext implements ServletContextAware, InitializingBean, DisposableBean { private final Logger logServerStartup = LoggerFactory.getLogger("serverStartup"); private final Logger logCatalogInit = LoggerFactory.getLogger(TdsContext.class.getName() + ".catalogInit"); // Properties from tds.properties // The values for these properties all come from tds/src/main/template/thredds/server/tds.properties except for // "tds.content.root.path", which must be defined on the command line. @Value("${tds.version}") private String tdsVersion; @Value("${tds.version.builddate}") private String tdsVersionBuildDate; @Value("${tds.content.root.path}") private String contentRootPathProperty; // wants a trailing slash @Value("${tds.content.path}") private String contentPathProperty; @Value("${tds.config.file}") private String configFileProperty; @Value("${tds.content.startup.path}") private String contentStartupPathProperty; // set by spring @Autowired private HtmlConfig htmlConfig; @Autowired private TdsServerInfo serverInfo; @Autowired private WmsConfig wmsConfig; @Autowired private CorsConfig corsConfig; @Autowired private TdsUpdateConfig tdsUpdateConfig; private ServletContext servletContext; private String contextPath; private String webappDisplayName; private File rootDirectory; private File contentDirectory; private File publicContentDirectory; private File startupContentDirectory; private File tomcatLogDir; private FileSource publicContentDirSource; private FileSource catalogRootDirSource; // look for catalog files at this(ese) root(s) private RequestDispatcher defaultRequestDispatcher; //////////// called by Spring lifecycle management @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void destroy() { logServerStartup.info("TdsContext: shutdownLogging()"); Log4jWebConfigurer.shutdownLogging(servletContext); // probably not needed anymore with log4j-web in classpath } @Override public void afterPropertiesSet() { if (servletContext == null) throw new IllegalArgumentException("ServletContext must not be null."); // Set the webapp name. display-name from web.xml this.webappDisplayName = servletContext.getServletContextName(); // Set the context path, eg "thredds" contextPath = servletContext.getContextPath(); ServletUtil.setContextPath(contextPath); InvDatasetFeatureCollection.setContextName(contextPath); // Set the root directory and source. String rootPath = servletContext.getRealPath("/"); if (rootPath == null) { String msg = "Webapp [" + this.webappDisplayName + "] must run with exploded deployment directory (not from .war)."; logServerStartup.error("TdsContext.init(): " + msg); throw new IllegalStateException(msg); } this.rootDirectory = new File(rootPath); BasicDescendantFileSource rootDirSource = new BasicDescendantFileSource(this.rootDirectory); this.rootDirectory = rootDirSource.getRootDirectory(); ServletUtil.setRootPath(rootDirSource.getRootDirectoryPath()); // Set the startup (initial install) content directory and source. this.startupContentDirectory = new File(this.rootDirectory, this.contentStartupPathProperty); DescendantFileSource startupContentDirSource = new BasicDescendantFileSource(this.startupContentDirectory); this.startupContentDirectory = startupContentDirSource.getRootDirectory(); // set the tomcat logging directory try { String base = System.getProperty("catalina.base"); if (base != null) { this.tomcatLogDir = new File(base, "logs").getCanonicalFile(); if (!this.tomcatLogDir.exists()) { String msg = "'catalina.base' directory not found: " + this.tomcatLogDir; logServerStartup.error("TdsContext.init(): " + msg); } } else { String msg = "'catalina.base' property not found - probably not a tomcat server"; logServerStartup.warn("TdsContext.init(): " + msg); } } catch (IOException e) { String msg = "tomcatLogDir could not be created"; logServerStartup.error("TdsContext.init(): " + msg); } String contentRootPathKey = "tds.content.root.path"; // In applicationContext-tdsConfig.xml, we have ignoreUnresolvablePlaceholders set to "true". // As a result, when properties aren't defined, they will keep their placeholder String. // In this case, that's "${tds.content.root.path}". if (this.contentRootPathProperty.equals("${tds.content.root.path}")) { String message = String.format("\"%s\" property isn't defined.", contentRootPathKey); logServerStartup.error(message); throw new IllegalStateException(message); } contentRootPathProperty = StringUtil2.replace(contentRootPathProperty, "\\", "/"); if (!contentRootPathProperty.endsWith("/")) contentRootPathProperty += "/"; // Set the content directory and source. File contentRootDir = new File(this.contentRootPathProperty); if (!contentRootDir.isAbsolute()) this.contentDirectory = new File(new File(this.rootDirectory, this.contentRootPathProperty), this.contentPathProperty); else { if (contentRootDir.isDirectory()) this.contentDirectory = new File(contentRootDir, this.contentPathProperty); else { String msg = "Content root directory [" + this.contentRootPathProperty + "] not a directory."; logServerStartup.error("TdsContext.init(): " + msg); throw new IllegalStateException(msg); } } // If content directory exists, make sure it is a directory. DescendantFileSource contentDirSource; if (this.contentDirectory.isDirectory()) { contentDirSource = new BasicDescendantFileSource(StringUtils.cleanPath(this.contentDirectory.getAbsolutePath())); this.contentDirectory = contentDirSource.getRootDirectory(); } else { String message = String.format( "TdsContext.init(): Content directory is not a directory: %s", this.contentDirectory.getAbsolutePath()); logServerStartup.error(message); throw new IllegalStateException(message); } ServletUtil.setContentPath(contentDirSource.getRootDirectoryPath()); // public content this.publicContentDirectory = new File(this.contentDirectory, "public"); if (!publicContentDirectory.exists()) { if (!publicContentDirectory.mkdirs()) { String msg = "Couldn't create TDS public directory [" + publicContentDirectory.getPath() + "]."; logServerStartup.error("TdsContext.init(): " + msg); throw new IllegalStateException(msg); } } this.publicContentDirSource = new BasicDescendantFileSource(this.publicContentDirectory); // places to look for catalogs ?? List<DescendantFileSource> chain = new ArrayList<>(); DescendantFileSource contentMinusPublicSource = new BasicWithExclusionsDescendantFileSource(this.contentDirectory, Collections.singletonList("public")); chain.add(contentMinusPublicSource); this.catalogRootDirSource = new ChainedFileSource(chain); //jspRequestDispatcher = servletContext.getNamedDispatcher("jsp"); defaultRequestDispatcher = servletContext.getNamedDispatcher("default"); //////////////////////////////////// Copy default startup files, if necessary //////////////////////////////////// try { File catalogFile = new File(contentDirectory, "catalog.xml"); if (!catalogFile.exists()) { File defaultCatalogFile = new File(startupContentDirectory, "catalog.xml"); logServerStartup.info("TdsContext.init(): Copying default catalog file from {}.", defaultCatalogFile); IO.copyFile(defaultCatalogFile, catalogFile); File enhancedCatalogFile = new File(contentDirectory, "enhancedCatalog.xml"); File defaultEnhancedCatalogFile = new File(startupContentDirectory, "enhancedCatalog.xml"); logServerStartup.info("TdsContext.init(): Copying default enhanced catalog file from {}.", defaultEnhancedCatalogFile); IO.copyFile(defaultEnhancedCatalogFile, enhancedCatalogFile); File dataDir = new File(new File(contentDirectory, "public"), "testdata"); File defaultDataDir = new File(new File(startupContentDirectory, "public"), "testdata"); logServerStartup.info("TdsContext.init(): Copying default testdata directory from {}.", defaultDataDir); IO.copyDirTree(defaultDataDir.getCanonicalPath(), dataDir.getCanonicalPath()); } File threddsConfigFile = new File(contentDirectory, "threddsConfig.xml"); if (!threddsConfigFile.exists()) { File defaultThreddsConfigFile = new File(startupContentDirectory, "threddsConfig.xml"); logServerStartup.info("TdsContext.init(): Copying default THREDDS config file from {}.", defaultThreddsConfigFile); IO.copyFile(defaultThreddsConfigFile, threddsConfigFile); } File wmsConfigXmlFile = new File(contentDirectory, "wmsConfig.xml"); if (!wmsConfigXmlFile.exists()) { File defaultWmsConfigXmlFile = new File(startupContentDirectory, "wmsConfig.xml"); logServerStartup.info("TdsContext.init(): Copying default WMS config file from {}.", defaultWmsConfigXmlFile); IO.copyFile(defaultWmsConfigXmlFile, wmsConfigXmlFile); File wmsConfigDtdFile = new File(contentDirectory, "wmsConfig.dtd"); File defaultWmsConfigDtdFile = new File(startupContentDirectory, "wmsConfig.dtd"); logServerStartup.info("TdsContext.init(): Copying default WMS config DTD from {}.", defaultWmsConfigDtdFile); IO.copyFile(defaultWmsConfigDtdFile, wmsConfigDtdFile); } } catch (IOException e) { String message = String.format("Could not copy default startup files to %s.", contentDirectory); logServerStartup.error("TdsContext.init(): " + message); throw new IllegalStateException(message, e); } // logging File logDir = new File(this.contentDirectory, "logs"); if (!logDir.exists()) { if (!logDir.mkdirs()) { String msg = "Couldn't create TDS log directory [" + logDir.getPath() + "]."; logServerStartup.error("TdsContext.init(): " + msg); throw new IllegalStateException(msg); } } String loggingDirectory = StringUtil2.substitute(logDir.getPath(), "\\", "/"); System.setProperty("tds.log.dir", loggingDirectory); // variable substitution // LOOK Remove log4j init JC 6/13/2012 // which is used in log4j.xml file loaded here. // LOOK Remove Log4jWebConfigurer,initLogging - depends on log4g v1, we are using v2 JC 9/2/2013 // Log4jWebConfigurer.initLogging( servletContext ); logServerStartup.info("TdsContext version= " + getVersionInfo()); logServerStartup.info("TdsContext intialized logging in " + logDir.getPath()); // read in persistent user-defined params from threddsConfig.xml File tdsConfigFile = contentDirSource.getFile(this.getConfigFileProperty()); if (tdsConfigFile == null) { tdsConfigFile = new File(contentDirSource.getRootDirectory(), this.getConfigFileProperty()); String msg = "TDS configuration file doesn't exist: " + tdsConfigFile; logServerStartup.error("TdsContext.init(): " + msg); throw new IllegalStateException(msg); } ThreddsConfig.init(tdsConfigFile.getPath()); // initialize/populate all of the various config objects TdsConfigMapper tdsConfigMapper = new TdsConfigMapper(); tdsConfigMapper.setTdsServerInfo(this.serverInfo); tdsConfigMapper.setHtmlConfig(this.htmlConfig); tdsConfigMapper.setWmsConfig(this.wmsConfig); tdsConfigMapper.setCorsConfig(this.corsConfig); tdsConfigMapper.setTdsUpdateConfig(this.tdsUpdateConfig); tdsConfigMapper.init(this); // log current server version in catalogInit, where it is // most likely to be seen by the user String message = "You are currently running TDS version " + this.getVersionInfo(); logCatalogInit.info(message); // check and log the latest stable and development version information // only if it is OK according to the threddsConfig file. if (this.tdsUpdateConfig.isLogVersionInfo()) { Map<String, String> latestVersionInfo = getLatestVersionInfo(); if (!latestVersionInfo.isEmpty()) { logCatalogInit.info("Latest Available TDS Version Info:"); for (Map.Entry entry : latestVersionInfo.entrySet()) { message = "latest " + entry.getKey() + " version = " + entry.getValue(); logServerStartup.info("TdsContext: " + message); logCatalogInit.info(" " + message); } logCatalogInit.info(""); } } } public Map<String, String> getLatestVersionInfo() { int socTimeout = 1; // http socket timeout in seconds int connectionTimeout = 3; // http connection timeout in seconds Map<String, String> latestVersionInfo = new HashMap<>(); String versionUrl = "http: try { try (HTTPMethod method = HTTPFactory.Get(versionUrl)) { HTTPSession httpClient = method.getSession(); httpClient.setSoTimeout(socTimeout * 1000); httpClient.setConnectionTimeout(connectionTimeout * 1000); httpClient.setUserAgent("TDS_" + getVersionInfo().replace(" ", "")); method.execute(); InputStream responseIs = method.getResponseBodyAsStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(responseIs); Element docEle = dom.getDocumentElement(); NodeList versionElements = docEle.getElementsByTagName("version"); if(versionElements != null && versionElements.getLength() > 0) { for(int i = 0;i < versionElements.getLength();i++) { //get the version element Element versionElement = (Element) versionElements.item(i); String verType = versionElement.getAttribute("name"); String verStr = versionElement.getAttribute("value"); latestVersionInfo.put(verType, verStr); } } } } catch (IOException e) { logServerStartup.warn("TdsContext - Could not get latest version information from Unidata."); } catch (ParserConfigurationException e) { logServerStartup.error("TdsContext - Error configuring latest version xml parser" + e.getMessage() + "."); } catch (SAXException e) { logServerStartup.error("TdsContext - Could not parse latest version information."); } return latestVersionInfo; } @Override public String toString() { final StringBuilder sb = new StringBuilder("TdsContext{"); sb.append("\n contextPath='").append(contextPath).append('\''); sb.append("\n webappName='").append(webappDisplayName).append('\''); sb.append("\n webappVersion='").append(tdsVersion).append('\''); sb.append("\n webappVersionBuildDate='").append(tdsVersionBuildDate).append('\''); sb.append("\n"); sb.append("\n contentPath= '").append(contentPathProperty).append('\''); sb.append("\n contentRootPath= '").append(contentRootPathProperty).append('\''); sb.append("\n contentStartupPath= '").append(contentStartupPathProperty).append('\''); sb.append("\n configFile= '").append(configFileProperty).append('\''); sb.append("\n"); sb.append("\n rootDirectory= ").append(rootDirectory); sb.append("\n contentDirectory=").append(contentDirectory); sb.append("\n publicContentDir=").append(publicContentDirectory); sb.append("\n startupContentDirectory=").append(startupContentDirectory); sb.append("\n tomcatLogDir=").append(tomcatLogDir); sb.append("\n"); sb.append("\n publicContentDirSource= ").append(publicContentDirSource); sb.append("\n catalogRootDirSource=").append(catalogRootDirSource); sb.append('}'); return sb.toString(); } // public getters /** * Return the context path under which this web app is running (e.g., "/thredds"). * * @return the context path. */ public String getContextPath() { return contextPath; } /** * Return the full version string (<major>.<minor>.<bug>.<build>)* * @return the full version string. */ public String getWebappVersion() { return this.tdsVersion; } public String getTdsVersionBuildDate() { return this.tdsVersionBuildDate; } public String getVersionInfo() { Formatter f = new Formatter(); f.format("%s", getWebappVersion()); if (getTdsVersionBuildDate() != null) { f.format(" - %s", getTdsVersionBuildDate()); } return f.toString(); } /** * @return the name of the webapp as given by the display-name element in web.xml. */ public String getWebappDisplayName() { return this.webappDisplayName; } /** * Return the web apps root directory (i.e., getRealPath( "/")). * Typically {tomcat}/webapps/thredds * @return the root directory for the web app. */ public File getRootDirectory() { return rootDirectory; } public File getTomcatLogDirectory() { return tomcatLogDir; } /** * Return File for content directory (exists() may be false). * * @return a File to the content directory. */ public File getContentDirectory() { return contentDirectory; } public FileSource getCatalogRootDirSource() { return this.catalogRootDirSource; } // {tomcat}/content/thredds/public public FileSource getPublicContentDirSource() { return this.publicContentDirSource; } public RequestDispatcher getDefaultRequestDispatcher() { return this.defaultRequestDispatcher; } public String getContentRootPathProperty() { return this.contentRootPathProperty; } public String getConfigFileProperty() { return this.configFileProperty; } public TdsServerInfo getServerInfo() { return serverInfo; } public HtmlConfig getHtmlConfig() { return this.htmlConfig; } public WmsConfig getWmsConfig() { return wmsConfig; } // used by MockTdsContextLoader public void setContentRootPathProperty(String contentRootPathProperty) { this.contentRootPathProperty = contentRootPathProperty; } }
package org.lantern.http; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.lantern.Censored; import org.lantern.ConnectivityChangedEvent; import org.lantern.JsonUtils; import org.lantern.LanternClientConstants; import org.lantern.LanternFeedback; import org.lantern.LanternUtils; import org.lantern.XmppHandler; import org.lantern.event.Events; import org.lantern.event.InvitesChangedEvent; import org.lantern.event.ResetEvent; import org.lantern.state.Connectivity; import org.lantern.state.InternalState; import org.lantern.state.InviteQueue; import org.lantern.state.JsonModelModifier; import org.lantern.state.LocationChangedEvent; import org.lantern.state.Modal; import org.lantern.state.Mode; import org.lantern.state.Model; import org.lantern.state.ModelIo; import org.lantern.state.ModelService; import org.lantern.state.Notification.MessageType; import org.lantern.state.Settings; import org.lantern.state.SyncPath; import org.lantern.util.Desktop; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class InteractionServlet extends HttpServlet { private final InternalState internalState; // XXX DRY: these are also defined in lantern-ui/app/js/constants.js private enum Interaction { GET, GIVE, INVITE, CONTINUE, SETTINGS, CLOSE, RESET, SET, PROXIEDSITES, CANCEL, LANTERNFRIENDS, RETRY, REQUESTINVITE, CONTACT, ABOUT, ACCEPT, DECLINE, UNEXPECTEDSTATERESET, UNEXPECTEDSTATEREFRESH, URL, EXCEPTION } // modals the user can switch to from other modals private static final Set<Modal> switchModals = new HashSet<Modal>(); static { switchModals.add(Modal.about); switchModals.add(Modal.contact); switchModals.add(Modal.settings); switchModals.add(Modal.proxiedSites); switchModals.add(Modal.lanternFriends); } private final Logger log = LoggerFactory.getLogger(getClass()); /** * Generated serialization ID. */ private static final long serialVersionUID = -8820179746803371322L; private final ModelService modelService; private final Model model; private final ModelIo modelIo; private final XmppHandler xmppHandler; private final Censored censored; private final LanternFeedback lanternFeedback; private final InviteQueue inviteQueue; /* only open external urls to these hosts: */ private static final Set<String> allowedDomains = new HashSet<String>( Arrays.asList("google.com", "github.com", "getlantern.org")); @Inject public InteractionServlet(final Model model, final ModelService modelService, final InternalState internalState, final ModelIo modelIo, final XmppHandler xmppHandler, final Censored censored, final LanternFeedback lanternFeedback, final InviteQueue inviteQueue) { this.model = model; this.modelService = modelService; this.internalState = internalState; this.modelIo = modelIo; this.xmppHandler = xmppHandler; this.censored = censored; this.lanternFeedback = lanternFeedback; this.inviteQueue = inviteQueue; Events.register(this); } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } protected void processRequest(final HttpServletRequest req, final HttpServletResponse resp) { LanternUtils.addCSPHeader(resp); final String uri = req.getRequestURI(); log.debug("Received URI: {}", uri); final String interactionStr = StringUtils.substringAfterLast(uri, "/"); if (StringUtils.isBlank(interactionStr)) { log.debug("blank interaction"); HttpUtils.sendClientError(resp, "blank interaction"); return; } log.debug("Headers: "+HttpUtils.getRequestHeaders(req)); if (!"XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) { log.debug("invalid X-Requested-With"); HttpUtils.sendClientError(resp, "invalid X-Requested-With"); return; } if (!model.getXsrfToken().equals(req.getHeader("X-XSRF-TOKEN"))) { log.debug("X-XSRF-TOKEN wrong: got {} expected {}", req.getHeader("X-XSRF-TOKEN"), model.getXsrfToken()); HttpUtils.sendClientError(resp, "invalid X-XSRF-TOKEN"); return; } final int cl = req.getContentLength(); String json = ""; if (cl > 0) { try { json = IOUtils.toString(req.getInputStream()); } catch (final IOException e) { log.error("Could not parse json?"); } } log.debug("Body: '"+json+"'"); final Interaction inter = Interaction.valueOf(interactionStr.toUpperCase()); if (inter == Interaction.CLOSE) { if (handleClose(json)) { return; } } if (inter == Interaction.URL) { final String url = JsonUtils.getValueFromJson("url", json); final URL url_; if (!StringUtils.startsWith(url, "http: !StringUtils.startsWith(url, "https: log.error("http(s) url expected, got {}", url); HttpUtils.sendClientError(resp, "http(s) urls only"); return; } try { url_ = new URL(url); } catch (MalformedURLException e) { log.error("invalid url: {}", url); HttpUtils.sendClientError(resp, "invalid url"); return; } final String host = url_.getHost(); final String[] hostParts = StringUtils.split(host, "."); if (hostParts.length < 2) { log.error("host not allowed: {}", host); HttpUtils.sendClientError(resp, "host not allowed"); return; } final String domain = hostParts[hostParts.length-2] + "." + hostParts[hostParts.length-1]; if (!allowedDomains.contains(domain)) { log.error("domain not allowed: {}", domain); HttpUtils.sendClientError(resp, "domain not allowed"); return; } final String cmd; if (SystemUtils.IS_OS_MAC_OSX) { cmd = "open"; } else if (SystemUtils.IS_OS_LINUX) { cmd = "gnome-open"; } else if (SystemUtils.IS_OS_WINDOWS) { cmd = "start"; } else { log.error("unsupported OS"); HttpUtils.sendClientError(resp, "unsupported OS"); return; } try { if (SystemUtils.IS_OS_WINDOWS) { // On Windows, we have to quote the url to allow for // e.g. ? and & characters in query string params. // To quote the url, we supply a dummy first argument, // since otherwise start treats the first argument as a // title for the new console window when it's quoted. LanternUtils.runCommand(cmd, "\"\"", "\""+url+"\""); } else { // on OS X and Linux, special characters in the url make // it through this call without our having to quote them. LanternUtils.runCommand(cmd, url); } } catch (IOException e) { log.error("open url failed"); HttpUtils.sendClientError(resp, "open url failed"); return; } return; } final Modal modal = this.model.getModal(); log.debug("processRequest: modal = {}, inter = {}, mode = {}", modal, inter, this.model.getSettings().getMode()); if (handleExceptionalInteractions(modal, inter, json)) { return; } Modal switchTo = null; try { // XXX a map would make this more robust switchTo = Modal.valueOf(interactionStr); } catch (IllegalArgumentException e) { } if (switchTo != null && switchModals.contains(switchTo)) { if (!switchTo.equals(modal)) { if (!switchModals.contains(modal)) { this.internalState.setLastModal(modal); } Events.syncModal(model, switchTo); } return; } switch (modal) { case welcome: this.model.getSettings().setMode(Mode.unknown); switch (inter) { case GET: log.debug("Setting get mode"); handleSetModeWelcome(Mode.get); break; case GIVE: log.debug("Setting give mode"); handleSetModeWelcome(Mode.give); break; } break; case authorize: log.debug("Processing authorize modal..."); this.internalState.setModalCompleted(Modal.authorize); this.internalState.advanceModal(null); break; case finished: this.internalState.setCompletedTo(Modal.finished); switch (inter) { case CONTINUE: log.debug("Processing continue"); this.model.setShowVis(true); Events.sync(SyncPath.SHOWVIS, true); this.internalState.setModalCompleted(Modal.finished); this.internalState.advanceModal(null); break; case SET: log.debug("Processing set in finished modal...applying JSON\n{}", json); applyJson(json); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); break; } break; case firstInviteReceived: log.error("Processing invite received..."); break; case lanternFriends: this.internalState.setCompletedTo(Modal.lanternFriends); switch (inter) { case INVITE: invite(json); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); break; case CONTINUE: // This dialog always passes continue as of this writing and // not close. case CLOSE: log.debug("Processing continue/close for friends dialog"); if (this.model.isSetupComplete()) { Events.syncModal(model, Modal.none); } else { this.internalState.setModalCompleted(Modal.lanternFriends); this.internalState.advanceModal(null); } break; case ACCEPT: acceptInvite(json); Events.syncModal(model, Modal.lanternFriends); break; case DECLINE: declineInvite(json); Events.syncModal(model, Modal.lanternFriends); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); break; } break; case none: break; case notInvited: switch (inter) { case RETRY: Events.syncModal(model, Modal.authorize); break; case REQUESTINVITE: Events.syncModal(model, Modal.requestInvite); break; default: log.error("Unexpected interaction: " + inter); break; } break; case proxiedSites: this.internalState.setCompletedTo(Modal.proxiedSites); switch (inter) { case CONTINUE: if (this.model.isSetupComplete()) { Events.syncModal(model, Modal.none); } else { this.internalState.setModalCompleted(Modal.proxiedSites); this.internalState.advanceModal(null); } break; case LANTERNFRIENDS: log.debug("Processing lanternFriends from proxiedSites"); Events.syncModal(model, Modal.lanternFriends); break; case SET: if (!model.getSettings().isSystemProxy()) { String msg = "Because you are using manual proxy " + "configuration, you may have to restart your " + "browser for your updated proxied sites list " + "to take effect."; model.addNotification(msg, MessageType.info, 30); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); } applyJson(json); break; case SETTINGS: log.debug("Processing settings from proxiedSites"); Events.syncModal(model, Modal.settings); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "unexpected interaction for proxied sites"); break; } break; case requestInvite: log.info("Processing request invite"); switch (inter) { case CANCEL: this.internalState.setModalCompleted(Modal.requestInvite); this.internalState.advanceModal(Modal.notInvited); break; case CONTINUE: applyJson(json); this.internalState.setModalCompleted(Modal.proxiedSites); //TODO: need to do something here this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "unexpected interaction for request invite"); break; } break; case requestSent: log.debug("Process request sent"); break; case settings: switch (inter) { case GET: log.debug("Setting get mode"); // Only deal with a mode change if the mode has changed! if (modelService.getMode() == Mode.give) { // Break this out because it's set in the subsequent // setMode call final boolean everGet = model.isEverGetMode(); this.modelService.setMode(Mode.get); if (!everGet) { // need to do more setup to switch to get mode from // give mode model.setSetupComplete(false); model.setModal(Modal.proxiedSites); Events.syncModel(model); } else { // This primarily just triggers a setup complete event, // which triggers connecting to proxies, setting up // the local system proxy, etc. model.setSetupComplete(true); } } break; case GIVE: log.debug("Setting give mode"); this.modelService.setMode(Mode.give); break; case CLOSE: log.debug("Processing settings close"); Events.syncModal(model, Modal.none); break; case SET: log.debug("Processing set in setting...applying JSON\n{}", json); applyJson(json); break; case RESET: log.debug("Processing reset"); Events.syncModal(model, Modal.confirmReset); break; case PROXIEDSITES: log.debug("Processing proxied sites in settings"); Events.syncModal(model, Modal.proxiedSites); break; case LANTERNFRIENDS: log.debug("Processing friends in settings"); Events.syncModal(model, Modal.lanternFriends); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); break; } break; case settingsLoadFailure: switch (inter) { case RETRY: modelIo.reload(); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); Events.syncModal(model, model.getModal()); break; case RESET: backupSettings(); Events.syncModal(model, Modal.welcome); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); break; } break; case systemProxy: this.internalState.setCompletedTo(Modal.systemProxy); switch (inter) { case CONTINUE: log.debug("Processing continue in systemProxy", json); applyJson(json); Events.sync(SyncPath.SYSTEMPROXY, model.getSettings().isSystemProxy()); this.internalState.setModalCompleted(Modal.systemProxy); this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "error setting system proxy pref"); break; } break; case updateAvailable: switch (inter) { case CLOSE: this.internalState.setModalCompleted(Modal.updateAvailable); this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); break; } break; case authorizeLater: log.error("Did not handle interaction {} for modal {}", inter, modal); break; case confirmReset: log.debug("Handling confirm reset interaction"); switch (inter) { case CANCEL: log.debug("Processing cancel"); Events.syncModal(model, Modal.settings); break; case RESET: handleReset(); Events.syncModel(this.model); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); } break; case about: switch (inter) { case CLOSE: Events.syncModal(model, this.internalState.getLastModal()); break; default: HttpUtils.sendClientError(resp, "invalid interaction "+inter); } break; case contact: switch(inter) { case CONTINUE: String msg; MessageType messageType; try { lanternFeedback.submit(json, this.model.getProfile().getEmail()); msg = "Thank you for contacting Lantern."; messageType = MessageType.info; } catch(Exception e) { log.error("Error submitting contact form: {}", e); msg = "Error sending message. Please check your "+ "connection and try again."; messageType = MessageType.error; } model.addNotification(msg, messageType, 30); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); // fall through because this should be done in both cases: case CANCEL: Events.syncModal(model, this.internalState.getLastModal()); break; default: HttpUtils.sendClientError(resp, "invalid interaction "+inter); } break; case giveModeForbidden: if (inter == Interaction.CONTINUE) { // need to do more setup to switch to get mode from give mode model.getSettings().setMode(Mode.get); model.setSetupComplete(false); this.internalState.advanceModal(null); Events.syncModal(model, Modal.proxiedSites); Events.sync(SyncPath.SETUPCOMPLETE, false); } break; default: log.error("No matching modal for {}", modal); } this.modelIo.write(); } private void backupSettings() { try { File backup = new File(Desktop.getDesktopPath(), "lantern-model-backup"); FileUtils.copyFile(LanternClientConstants.DEFAULT_MODEL_FILE, backup); } catch (final IOException e) { log.warn("Could not backup model file."); } } private boolean handleExceptionalInteractions( final Modal modal, final Interaction inter, final String json) { boolean handled = false; Map<String, Object> map; Boolean notify; switch(inter) { case EXCEPTION: handleException(json); handled = true; break; case UNEXPECTEDSTATERESET: log.debug("Handling unexpected state reset."); backupSettings(); handleReset(); Events.syncModel(this.model); // fall through because this should be done in both cases: case UNEXPECTEDSTATEREFRESH: try { map = jsonToMap(json); } catch(Exception e) { log.error("Bad json payload in inter '{}': {}", inter, json); return true; } notify = (Boolean)map.get("notify"); if(notify) { try { lanternFeedback.submit((String)map.get("report"), this.model.getProfile().getEmail()); } catch(Exception e) { log.error("Could not submit unexpected state report: {}\n {}", e.getMessage(), (String)map.get("report")); } } handled = true; break; } return handled; } private void handleException(final String json) { StringBuilder logMessage = new StringBuilder(); Map<String, Object> map; try { map = jsonToMap(json); } catch(Exception e) { log.error("UI Exception (unable to parse json)"); return; } for(Map.Entry<String, Object> entry : map.entrySet()) { logMessage.append( String.format("\t%s: %s\n", entry.getKey(), entry.getValue() ) ); } log.error("UI Exception:\n {}", logMessage.toString()); } private Map<String, Object> jsonToMap(final String json) throws JsonParseException, JsonMappingException, IOException { final ObjectMapper om = new ObjectMapper(); Map<String, Object> map; map = om.readValue(json, Map.class); return map; } private boolean handleClose(String json) { if (StringUtils.isBlank(json)) { return false; } final ObjectMapper om = new ObjectMapper(); Map<String, Object> map; try { map = om.readValue(json, Map.class); final String notification = (String) map.get("notification"); model.closeNotification(Integer.parseInt(notification)); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); return true; } catch (JsonParseException e) { log.warn("Exception closing notifications {}", e); } catch (JsonMappingException e) { log.warn("Exception closing notifications {}", e); } catch (IOException e) { log.warn("Exception closing notifications {}", e); } return false; } private void declineInvite(final String json) { final String email = JsonUtils.getValueFromJson("email", json); this.xmppHandler.unsubscribed(email); } private void acceptInvite(final String json) { final String email = JsonUtils.getValueFromJson("email", json); this.xmppHandler.subscribed(email); // We also automatically subscribe to them in turn so we know about // their presence. this.xmppHandler.subscribe(email); } static class Invite { List<String> invite; public Invite() {} public List<String> getInvite() { return invite; } public void setInvite(List<String> invite) { this.invite = invite; } } private void invite(String json) { ObjectMapper om = new ObjectMapper(); try { if (json.length() == 0) { return;//nobody to invite } ArrayList<String> invites = om.readValue(json, ArrayList.class); inviteQueue.invite(invites); } catch (IOException e) { throw new RuntimeException(e); } } private void handleSetModeWelcome(final Mode mode) { this.model.setModal(Modal.authorize); this.internalState.setModalCompleted(Modal.welcome); this.modelService.setMode(mode); Events.syncModal(model); } private void applyJson(final String json) { final JsonModelModifier mod = new JsonModelModifier(modelService); mod.applyJson(json); } private void handleReset() { // This posts the reset event to any classes that need to take action, // avoiding coupling this class to those classes. Events.eventBus().post(new ResetEvent()); if (LanternClientConstants.DEFAULT_MODEL_FILE.isFile()) { try { FileUtils.forceDelete(LanternClientConstants.DEFAULT_MODEL_FILE); } catch (final IOException e) { log.warn("Could not delete model file?"); } } final Model base = new Model(model.getCountryService()); model.setLaunchd(base.isLaunchd()); model.setModal(base.getModal()); model.setNinvites(base.getNinvites()); model.setNodeId(base.getNodeId()); model.setProfile(base.getProfile()); model.setNproxiedSitesMax(base.getNproxiedSitesMax()); //we need to keep clientID and clientSecret, because they are application-level settings String clientID = model.getSettings().getClientID(); String clientSecret = model.getSettings().getClientSecret(); model.setSettings(base.getSettings()); model.getSettings().setClientID(clientID); model.getSettings().setClientSecret(clientSecret); model.setSetupComplete(base.isSetupComplete()); model.setShowVis(base.isShowVis()); model.clearNotifications(); modelIo.write(); } @Subscribe public void onLocationChanged(final LocationChangedEvent e) { Events.sync(SyncPath.LOCATION, e.getNewLocation()); if (censored.isCountryCodeCensored(e.getNewCountry())) { if (!censored.isCountryCodeCensored(e.getOldCountry())) { //moving from uncensored to censored if (model.getSettings().getMode() == Mode.give) { Events.syncModal(model, Modal.giveModeForbidden); } } } } @Subscribe public void onInvitesChanged(final InvitesChangedEvent e) { int newInvites = e.getNewInvites(); if (e.getOldInvites() == 0) { String invitation = newInvites == 1 ? "invitation" : "invitations"; String text = "You now have " + newInvites + " " + invitation; model.addNotification(text, MessageType.info); } else if (newInvites == 0 && e.getOldInvites() > 0) { model.addNotification("You have no more invitations. You will be notified when you receive more.", MessageType.important); } Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); } @Subscribe public void onConnectivityChanged(final ConnectivityChangedEvent e) { Connectivity connectivity = model.getConnectivity(); if (!e.isConnected()) { connectivity.setInternet(false); Events.sync(SyncPath.CONNECTIVITY_INTERNET, false); return; } InetAddress ip = e.getNewIp(); connectivity.setIp(ip.getHostAddress()); connectivity.setInternet(true); Events.sync(SyncPath.CONNECTIVITY, model.getConnectivity()); Settings set = model.getSettings(); if (set.getMode() == null || set.getMode() == Mode.unknown) { if (censored.isCensored()) { set.setMode(Mode.get); } else { set.setMode(Mode.give); } } else if (set.getMode() == Mode.give && censored.isCensored()) { // want to set the mode to get now so that we don't mistakenly // proxy any more than necessary set.setMode(Mode.get); log.info("Disconnected; setting giveModeForbidden"); Events.syncModal(model, Modal.giveModeForbidden); } } }
package org.lightmare.cache; import java.lang.reflect.Method; /** * Container class to cache {@link javax.interceptor.Interceptors} annotation * defined data * * @author Levan * @since 0.0.57-SNAPSHOT */ public class InterceptorData { private Class<?> BeanClass; private Method beanMethod; private Class<?> interceptorClass; private Method interceptorMethod; public Class<?> getBeanClass() { return BeanClass; } public void setBeanClass(Class<?> beanClass) { BeanClass = beanClass; } public Method getBeanMethod() { return beanMethod; } public void setBeanMethod(Method beanMethod) { this.beanMethod = beanMethod; } public Class<?> getInterceptorClass() { return interceptorClass; } public void setInterceptorClass(Class<?> interceptorCLass) { this.interceptorClass = interceptorCLass; } public Method getInterceptorMethod() { return interceptorMethod; } public void setInterceptorMethod(Method interceptorMethod) { this.interceptorMethod = interceptorMethod; } }
package org.mitre.synthea.helpers; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.fasterxml.jackson.dataformat.csv.CsvSchema.ColumnType; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Helper class to translate CSV data back and forth between raw string data and a simple data * structure. */ public class SimpleCSV { /** * Parse the data from the given CSV file into a List of Maps, where the key is the * column name. Uses a LinkedHashMap specifically to ensure the order of columns is preserved in * the resulting maps. * * @param csvData * Raw CSV data * @return parsed data * @throws IOException * if any exception occurs while parsing the data */ public static List<LinkedHashMap<String, String>> parse(String csvData) throws IOException { // Read schema from the first line; start with bootstrap instance // to enable reading of schema from the first line // NOTE: reads schema and uses it for binding CsvMapper mapper = new CsvMapper(); // use first row as header; otherwise defaults are fine CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<LinkedHashMap<String, String>> it = mapper.readerFor(LinkedHashMap.class) .with(schema).readValues(csvData); return it.readAll(); } /** * Parse the data from the given CSV file into an Iterator of Maps, where the key is the * column name. Uses a LinkedHashMap specifically to ensure the order of columns is preserved in * the resulting maps. Uses an Iterator, as opposed to a list, in order to parse line by line and * avoid memory overload. * * @param csvData * Raw CSV data * @return parsed data * @throws IOException * if any exception occurs while parsing the data */ public static Iterator<LinkedHashMap<String, String>> parseLineByLine(String csvData) throws IOException { CsvMapper mapper = new CsvMapper(); // use first row as header; otherwise defaults are fine CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<LinkedHashMap<String, String>> it = mapper.readerFor(LinkedHashMap.class) .with(schema).readValues(csvData); return it; } /** * Convert the data in the given List of Maps to a String of CSV data. * Each Map in the List represents one line of the resulting CSV. Uses the keySet from the * first Map to populate the set of columns. This means that the first Map must contain all * the columns desired in the final CSV. The order of the columns is specified by the order * provided by the first Map's keySet, so using an ordered Map implementation * (such as LinkedHashMap) is recommended. * * @param data List of Map data. CSV data read/modified from SimpleCSV.parse(...) * @return data formatted as a String containing raw CSV data * @throws IOException on file IO write errors. */ public static String unparse(List<? extends Map<String, String>> data) throws IOException { CsvMapper mapper = new CsvMapper(); CsvSchema.Builder schemaBuilder = CsvSchema.builder(); schemaBuilder.setUseHeader(true); Collection<String> columns = data.get(0).keySet(); schemaBuilder.addColumns(columns, ColumnType.STRING); return mapper.writer(schemaBuilder.build()).writeValueAsString(data); } }
package org.semtix.shared.print; import org.semtix.shared.daten.ArrayHelper; import java.io.IOException; import static org.semtix.config.SettingsExternal.PDF_PATH; public class OdtRenderer { /* * Renders one file as pdf * * @param path file location * @throws IOException Dateizugrifffehler */ public static void print(String path) throws IOException { printFiles(new String[]{path}); } /** * Renders file with soffic bin. Ignores lock and does not display splash screen * Default output path is CWD if OUT_PATH=null * * @param pathnames space separated list of absolute filepaths that are to be rendered * @throws IOException Dateizugrifffehler */ public static void printFiles(String[] pathnames) throws IOException { String[] wholeCommand = ArrayHelper.concatenate(new String[]{"soffice", "--headless", "--nolockcheck", "--convert-to", "pdf", "--outdir", PDF_PATH}, pathnames); wholeCommand = ArrayHelper.concatenate(wholeCommand, new String[]{" &"}); Runtime.getRuntime().exec(wholeCommand); } }
package org.sonar.plugins.stash; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.stream.Collectors; import org.sonar.api.Plugin; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.api.PropertyType; import org.sonar.api.batch.rule.Severity; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import java.util.List; import org.sonar.plugins.stash.issue.StashDiffReport; @Properties({ @Property(key = StashPlugin.STASH_NOTIFICATION, name = "Stash Notification", defaultValue = "false", description = "Analysis result will be issued in Stash pull request", global = false), @Property(key = StashPlugin.STASH_PROJECT, name = "Stash Project", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_REPOSITORY, name = "Stash Repository", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_PULL_REQUEST_ID, name = "Stash Pull-request Id", description = "Stash pull-request Id", global = false)}) public class StashPlugin implements Plugin { private static final String DEFAULT_STASH_TIMEOUT_VALUE = "10000"; private static final String DEFAULT_STASH_THRESHOLD_VALUE = "100"; private static final boolean DEFAULT_STASH_ANALYSIS_OVERVIEW = true; private static final boolean DEFAULT_STASH_INCLUDE_EXISTING_ISSUES = false; private static final int DEFAULT_STASH_INCLUDE_VICINITY_RANGE = StashDiffReport.VICINITY_RANGE_NONE; private static final String DEFAULT_STASH_EXCLUDE_RULES = ""; private static final String CONFIG_PAGE_SUB_CATEGORY_STASH = "Stash"; public static final String SEVERITY_NONE = "NONE"; private static final List<String> SEVERITY_LIST = Arrays.stream(Severity.values()) .map(Severity::name).collect(Collectors.toList()); private static final List<String> SEVERITY_LIST_WITH_NONE = Lists .asList(SEVERITY_NONE, SEVERITY_LIST.toArray(new String[]{})); public enum IssueType { CONTEXT, REMOVED, ADDED, } public static final String STASH_NOTIFICATION = "sonar.stash.notification"; public static final String STASH_PROJECT = "sonar.stash.project"; public static final String STASH_REPOSITORY = "sonar.stash.repository"; public static final String STASH_PULL_REQUEST_ID = "sonar.stash.pullrequest.id"; public static final String STASH_RESET_COMMENTS = "sonar.stash.comments.reset"; public static final String STASH_URL = "sonar.stash.url"; public static final String STASH_LOGIN = "sonar.stash.login"; public static final String STASH_USER_SLUG = "sonar.stash.user.slug"; public static final String STASH_PASSWORD = "sonar.stash.password"; public static final String STASH_PASSWORD_ENVIRONMENT_VARIABLE = "sonar.stash.password.variable"; public static final String STASH_REVIEWER_APPROVAL = "sonar.stash.reviewer.approval"; public static final String STASH_REVIEWER_APPROVAL_SEVERITY_THRESHOLD = "sonar.stash.reviewer.approval.severity.threshold"; public static final String STASH_ISSUE_THRESHOLD = "sonar.stash.issue.threshold"; public static final String STASH_ISSUE_SEVERITY_THRESHOLD = "sonar.stash.issue.severity.threshold"; public static final String STASH_TIMEOUT = "sonar.stash.timeout"; public static final String STASH_TASK_SEVERITY_THRESHOLD = "sonar.stash.task.issue.severity.threshold"; public static final String STASH_INCLUDE_ANALYSIS_OVERVIEW = "sonar.stash.include.overview"; public static final String STASH_REPOSITORY_ROOT = "sonar.stash.repository.root"; public static final String STASH_INCLUDE_EXISTING_ISSUES = "sonar.stash.include.existing.issues"; public static final String STASH_INCLUDE_VICINITY_RANGE = "sonar.stash.include.vicinity.issues.range"; public static final String STASH_EXCLUDE_RULES = "sonar.stash.exclude.rules"; @Override public void define(Context context) { context.addExtensions( StashIssueReportingPostJob.class, StashPluginConfiguration.class, StashRequestFacade.class, StashProjectBuilder.class, PropertyDefinition.builder(STASH_URL) .name("Stash base URL") .description("HTTP URL of Stash instance, such as http://yourhost.yourdomain/stash") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT).build(), PropertyDefinition.builder(STASH_LOGIN) .name("Stash base User") .description("User to push data on Stash instance") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT).build(), PropertyDefinition.builder(STASH_USER_SLUG) .name("Stash base user slug") .description("If the username has special characters this setting has also to be specified") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onlyOnQualifiers(Qualifiers.PROJECT).build(), PropertyDefinition.builder(STASH_PASSWORD) .name("Stash base Password") .description("Password for Stash base User (Do NOT use in production, passwords are public" + " for everyone with UNAUTHENTICATED HTTP access to SonarQube") .type(PropertyType.PASSWORD) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT).build(), PropertyDefinition.builder(STASH_TIMEOUT) .name("Stash issue Timeout") .description("Timeout when pushing a new issue to Stash (in ms)") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(DEFAULT_STASH_TIMEOUT_VALUE).build(), PropertyDefinition.builder(STASH_REVIEWER_APPROVAL) .name("Stash reviewer approval") .description("Does SonarQube approve the pull-request if there is no new issues?") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .type(PropertyType.BOOLEAN) .defaultValue("false").build(), PropertyDefinition.builder(STASH_ISSUE_THRESHOLD) .name("Stash issue Threshold") .description("Threshold to limit the number of issues pushed to Stash server") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(DEFAULT_STASH_THRESHOLD_VALUE).build(), PropertyDefinition.builder(STASH_ISSUE_SEVERITY_THRESHOLD) .name("Stash issue severity Threshold") .description("Defines minimum issue severity to create diff-view comments for." + " Overview comment will still contain all severities." + " By default, all issues are pushed to Stash.") .type(PropertyType.SINGLE_SELECT_LIST) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(SEVERITY_LIST.get(0)) .options(SEVERITY_LIST).build(), PropertyDefinition.builder(STASH_REVIEWER_APPROVAL_SEVERITY_THRESHOLD) .name("Threshold tie the approval to the severity of the found issues") .description("Maximum severity of an issue for approval to complete") .type(PropertyType.SINGLE_SELECT_LIST) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(SEVERITY_NONE) .options(SEVERITY_LIST_WITH_NONE).build(), PropertyDefinition.builder(STASH_TASK_SEVERITY_THRESHOLD) .name("Stash tasks severity threshold") .description("Only create tasks for issues with the same or higher severity") .type(PropertyType.SINGLE_SELECT_LIST) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(SEVERITY_NONE) .options(SEVERITY_LIST_WITH_NONE).build(), PropertyDefinition.builder(STASH_INCLUDE_ANALYSIS_OVERVIEW) .name("Include Analysis Overview Comment") .description("Create a comment to the Pull Request providing a overview of the results") .type(PropertyType.BOOLEAN) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(Boolean.toString(DEFAULT_STASH_ANALYSIS_OVERVIEW)).build(), PropertyDefinition.builder(STASH_INCLUDE_EXISTING_ISSUES) .name("Include Existing Issues") .description("Set to true to include already existing issues on modified lines.") .type(PropertyType.BOOLEAN) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(Boolean.toString(DEFAULT_STASH_INCLUDE_EXISTING_ISSUES)).build(), PropertyDefinition.builder(STASH_INCLUDE_VICINITY_RANGE) .name("Include Vicinity Issues Range") .description("Specifies the range around the actual changes for which issues are reported. (In lines)") .type(PropertyType.INTEGER) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(String.valueOf(DEFAULT_STASH_INCLUDE_VICINITY_RANGE)).build(), PropertyDefinition.builder(STASH_EXCLUDE_RULES) .name("Excluded Rules") .description("Comma separated list of rules for which no comments should be created.") .type(PropertyType.STRING) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(DEFAULT_STASH_EXCLUDE_RULES).build() ); } }
package org.spout.downpour; import java.io.IOException; /** * An exception that is thrown when the cache file was not found */ public class NoCacheException extends IOException { private static final long serialVersionUID = 1L; }
package org.trancecode.function; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.MapMaker; import java.util.Map; import org.trancecode.core.AbstractImmutableObject; /** * Utility methods related to {@link Function}. * * @author Herve Quiroz */ public final class TcFunctions { private TcFunctions() { // No instantiation } public static <E, P> E apply(final E initialElement, final Iterable<P> parameters, final Function<Pair<E, P>, E> function) { E currentElement = initialElement; for (final P parameter : parameters) { currentElement = function.apply(Pairs.newImmutablePair(currentElement, parameter)); } return currentElement; } public static <F, T> Function<Function<F, T>, T> applyTo(final F argument) { return new ApplyToFunction<F, T>(argument); } private static class ApplyToFunction<F, T> extends AbstractImmutableObject implements Function<Function<F, T>, T> { private final F argument; public ApplyToFunction(final F argument) { super(argument); this.argument = argument; } @Override public T apply(final Function<F, T> function) { return function.apply(argument); } } public static <F, T> Function<F, T> memoize(final Function<F, T> function) { return new MemoizeFunction<F, T>(function); } private static class MemoizeFunction<F, T> extends AbstractImmutableObject implements Function<F, T> { private final Map<F, T> cache; private MemoizeFunction(final Function<F, T> function) { super(function); cache = new MapMaker().softValues().makeComputingMap(function); } @Override public T apply(final F from) { return cache.get(from); } } public static <F, T> Function<F, T> conditional(final Predicate<F> predicate, final Function<? super F, T> ifTrue, final Function<? super F, T> ifFalse) { return new ConditionalFunction<F, T>(predicate, ifTrue, ifFalse); } private static class ConditionalFunction<F, T> implements Function<F, T> { private final Predicate<F> predicate; private final Function<? super F, T> ifTrue; private final Function<? super F, T> ifFalse; public ConditionalFunction(final Predicate<F> predicate, final Function<? super F, T> ifTrue, final Function<? super F, T> ifFalse) { super(); this.predicate = Preconditions.checkNotNull(predicate); this.ifTrue = Preconditions.checkNotNull(ifTrue); this.ifFalse = Preconditions.checkNotNull(ifFalse); } @Override public T apply(final F from) { if (predicate.apply(from)) { return ifTrue.apply(from); } return ifFalse.apply(from); } } public static <T> Function<T, Iterable<T>> toIterable(final Class<T> elementClass) { return new ToIterableFunction<T>(); } private static class ToIterableFunction<T> implements Function<T, Iterable<T>> { @Override public Iterable<T> apply(final T element) { return ImmutableList.of(element); } } public static <T> Function<T, Boolean> asFunction(final Predicate<T> predicate) { return new PredicateAsFunction<T>(predicate); } private static class PredicateAsFunction<T> implements Function<T, Boolean> { private final Predicate<T> predicate; public PredicateAsFunction(final Predicate<T> predicate) { super(); this.predicate = Preconditions.checkNotNull(predicate); } @Override public Boolean apply(final T from) { return predicate.apply(from); } } }
package be.ibridge.kettle.trans.step.textfileoutput; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Converts input rows to text and then writes this text to one or more files. * * @author Matt * @since 4-apr-2003 */ public class TextFileOutput extends BaseStep implements StepInterface { private TextFileOutputMeta meta; private TextFileOutputData data; public TextFileOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(TextFileOutputMeta)smi; data=(TextFileOutputData)sdi; Row r; boolean result=true; r=getRow(); // This also waits for a row to be finished. if ( ( r==null && data.headerrow!=null && meta.isFooterEnabled() ) || ( r!=null && linesOutput>0 && meta.getSplitEvery()>0 && (linesOutput%meta.getSplitEvery())==0) ) { if (writeHeader()) linesOutput++; // Done with this part or with everything. closeFile(); // Not finished: open another file... if (r!=null) { if (!openNewFile()) { logError("Unable to open new file (split #"+data.splitnr+"..."); setErrors(1); return false; } if (meta.isHeaderEnabled() && data.headerrow!=null) if (writeHeader()) linesOutput++; } } if (r==null) // no more input to be expected... { setOutputDone(); return false; } result=writeRowToFile(r); if (!result) { setErrors(1); stopAll(); return false; } putRow(r); // in case we want it to go further... if ((linesOutput>0) && (linesOutput%Const.ROWS_UPDATE)==0)logBasic("linenr "+linesOutput); return result; } private boolean writeRowToFile(Row r) { Value v; try { if (first) { first=false; if (!meta.isFileAppended() && ( meta.isHeaderEnabled() || meta.isFooterEnabled())) // See if we have to write a header-line) { data.headerrow=new Row(r); // copy the row for the footer! if (meta.isHeaderEnabled()) { if (writeHeader()) return false; } } data.fieldnrs=new int[meta.getOutputFields().length]; for (int i=0;i<meta.getOutputFields().length;i++) { data.fieldnrs[i]=r.searchValueIndex(meta.getOutputFields()[i].getName()); if (data.fieldnrs[i]<0) { logError("Field ["+meta.getOutputFields()[i].getName()+"] couldn't be found in the input stream!"); setErrors(1); stopAll(); return false; } } } if (meta.getOutputFields()==null || meta.getOutputFields().length==0) { /* * Write all values in stream to text file. */ for (int i=0;i<r.size();i++) { if (i>0) data.writer.write(meta.getSeparator().toCharArray()); v=r.getValue(i); if(!writeField(v, -1)) return false; } data.writer.write(meta.getNewline().toCharArray()); } else { /* * Only write the fields specified! */ for (int i=0;i<meta.getOutputFields().length;i++) { if (i>0) data.writer.write(meta.getSeparator().toCharArray()); v=r.getValue(data.fieldnrs[i]); v.setLength(meta.getOutputFields()[i].getLength(), meta.getOutputFields()[i].getPrecision()); if(!writeField(v, i)) return false; } data.writer.write(meta.getNewline().toCharArray()); } } catch(Exception e) { logError("Error writing line :"+e.toString()); return false; } linesOutput++; return true; } private String formatField(Value v, int idx) { String retval=""; TextFileField field = null; if (idx>=0) field = meta.getOutputFields()[idx]; if (v.isBigNumber()) { retval+=v.getString(); // Sorry, no formatting yet, just dump it... } else if (v.isNumeric()) { if (idx>=0 && field!=null && field.getFormat()!=null) { if (v.isNull()) { if (field.getNullString()!=null) retval=field.getNullString(); } else { data.df.applyPattern(field.getFormat()); if (field.getDecimalSymbol()!=null && field.getDecimalSymbol().length()>0) data.dfs.setDecimalSeparator( field.getDecimalSymbol().charAt(0) ); if (field.getGroupingSymbol()!=null && field.getGroupingSymbol().length()>0) data.dfs.setGroupingSeparator( field.getGroupingSymbol().charAt(0) ); if (field.getCurrencySymbol()!=null) data.dfs.setCurrencySymbol( field.getCurrencySymbol() ); data.df.setDecimalFormatSymbols(data.dfs); retval=data.df.format(v.getNumber()); } } else { if (v.isNull()) { if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString(); } else { retval=v.toString(); } } } else if (v.isDate()) { if (idx>=0 && field!=null && field.getFormat()!=null && v.getDate()!=null) { data.daf.applyPattern( field.getFormat() ); data.daf.setDateFormatSymbols(data.dafs); retval= data.daf.format(v.getDate()); } else { if (v.isNull() || v.getDate()==null) { if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString(); } else { retval=v.toString(); } } } else if (v.isString()) { if (v.isNull() || v.getString()==null) { if (idx>=0 && field!=null && field.getNullString()!=null) { if (meta.isEnclosureForced() && meta.getEnclosure()!=null) { retval=meta.getEnclosure()+field.getNullString()+meta.getEnclosure(); } else { retval=field.getNullString(); } } } else { // Any separators in string? // example: 123.4;"a;b;c";Some name if (meta.isEnclosureForced() && meta.getEnclosure()!=null) // Force enclosure? { retval=meta.getEnclosure()+v.toString()+meta.getEnclosure(); } else // See if there is a separator in the String... { int seppos = v.toString().indexOf(meta.getSeparator()); if (seppos<0) retval=v.toString(); else retval=meta.getEnclosure()+v.toString()+meta.getEnclosure(); } } } else // Boolean { if (v.isNull()) { if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString(); } else { retval=v.toString(); } } if (meta.isPadded()) // maybe we need to rightpad to field length? { // What's the field length? int length, precision; if (idx<0 || field==null) // Nothing specified: get it from the values themselves. { length =v.getLength()<0?0:v.getLength(); precision=v.getPrecision()<0?0:v.getPrecision(); } else // Get the info from the specified lengths & precision... { length =field.getLength() <0?0:field.getLength(); precision=field.getPrecision()<0?0:field.getPrecision(); } if (v.isNumber()) { length++; // for the sign... if (precision>0) length++; // for the decimal point... } if (v.isDate()) { length=23; precision=0; } if (v.isBoolean()) { length=5; precision=0; } retval=Const.rightPad(new StringBuffer(retval), length+precision); } return retval; } private boolean writeField(Value v, int idx) { try { String str = formatField(v, idx); if (str!=null) data.writer.write(str.toCharArray()); } catch(Exception e) { logError("Error writing line :"+e.toString()); return false; } return true; } private boolean writeHeader() { boolean retval=false; Row r=data.headerrow; try { // If we have fields specified: list them in this order! if (meta.getOutputFields()!=null && meta.getOutputFields().length>0) { String header = ""; for (int i=0;i<meta.getOutputFields().length;i++) { String fieldName = meta.getOutputFields()[i].getName(); Value v = r.searchValue(fieldName); if (i>0 && meta.getSeparator()!=null && meta.getSeparator().length()>0) { header+=meta.getSeparator(); } if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v!=null && v.isString()) { header+=meta.getEnclosure(); } header+=fieldName; if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v!=null && v.isString()) { header+=meta.getEnclosure(); } } header+=meta.getNewline(); data.writer.write(header.toCharArray()); } else if (r!=null) // Just put all field names in the header/footer { for (int i=0;i<r.size();i++) { if (i>0) data.writer.write(meta.getSeparator().toCharArray()); Value v = r.getValue(i); // Header-value contains the name of the value Value header_value = new Value(v.getName(), Value.VALUE_TYPE_STRING); header_value.setValue(v.getName()); if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v.isString()) { data.writer.write(meta.getEnclosure().toCharArray()); } data.writer.write(header_value.toString().toCharArray()); if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v.isString()) { data.writer.write(meta.getEnclosure().toCharArray()); } } data.writer.write(meta.getNewline().toCharArray()); } else { data.writer.write(("no rows selected"+Const.CR).toCharArray()); } } catch(Exception e) { logError("Error writing header line: "+e.toString()); e.printStackTrace(); retval=true; } linesOutput++; return retval; } public String buildFilename(boolean ziparchive) { return meta.buildFilename(getCopy(), data.splitnr, ziparchive); } public boolean openNewFile() { boolean retval=false; data.writer=null; try { File file = new File(buildFilename(true)); // Add this to the result file names... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname()); resultFile.setComment("This file was created with a text file output step"); addResultFile(resultFile); OutputStream outputStream; if (meta.isZipped()) { FileOutputStream fos = new FileOutputStream(file, meta.isFileAppended()); data.zip = new ZipOutputStream(fos); File entry = new File(buildFilename(false)); ZipEntry zipentry = new ZipEntry(entry.getName()); zipentry.setComment("Compressed by Kettle"); data.zip.putNextEntry(zipentry); outputStream=data.zip; } else { FileOutputStream fos=new FileOutputStream(file, meta.isFileAppended()); outputStream=fos; } if (meta.getEncoding()!=null && meta.getEncoding().length()>0) { log.logBasic(toString(), "Opening output stream in encoding: "+meta.getEncoding()); data.writer = new OutputStreamWriter(outputStream, meta.getEncoding()); } else { log.logBasic(toString(), "Opening output stream in default encoding"); data.writer = new OutputStreamWriter(outputStream); } retval=true; } catch(Exception e) { logError("Error opening new file : "+e.toString()); } // System.out.println("end of newFile(), splitnr="+splitnr); data.splitnr++; return retval; } private boolean closeFile() { boolean retval=false; try { if (meta.isZipped()) { //System.out.println("close zip entry "); data.zip.closeEntry(); //System.out.println("finish file..."); data.zip.finish(); data.zip.close(); } else { data.writer.close(); } //System.out.println("Closed file..."); retval=true; } catch(Exception e) { } return retval; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(TextFileOutputMeta)smi; data=(TextFileOutputData)sdi; if (super.init(smi, sdi)) { data.splitnr=0; if (openNewFile()) { return true; } else { logError("Couldn't open file "+meta.getFileName()); setErrors(1L); stopAll(); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta=(TextFileOutputMeta)smi; data=(TextFileOutputData)sdi; super.dispose(smi, sdi); closeFile(); } // Run is were the action happens! public void run() { try { logBasic("Starting to run..."); while (processRow(meta, data) && !isStopped()); } catch(Exception e) { logError("Unexpected error : "+e.toString()); logError(Const.getStackTracker(e)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package org.usfirst.frc.team4828; import com.ctre.CANTalon; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.Timer; import org.usfirst.frc.team4828.Vision.PixyThread; public class DriveTrain { private CANTalon frontLeft; private CANTalon frontRight; private CANTalon backLeft; private CANTalon backRight; private AHRS navx; private static final double TWIST_THRESHOLD = 0.15; private static final double DIST_TO_ENC = 1.0; //todo: determine conversion factor private static final double AUTON_SPEED = 0.3; //todo: calibrate speed private static final double TURN_DEADZONE = 1; private static final double TURN_SPEED = .25; private static final double VISION_DEADZONE = 0.5; private static final double PLACING_DIST = -3; //todo: determine distance from the wall to stop when placing gear /** * Create drive train object containing mecanum motor functionality. * * @param frontLeftPort port of the front left motor * @param backLeftPort port of the back left motor * @param frontRightPort port of the front right motor * @param backRightPort port of the back right motor */ public DriveTrain(int frontLeftPort, int backLeftPort, int frontRightPort, int backRightPort) { frontLeft = new CANTalon(frontLeftPort); frontRight = new CANTalon(frontRightPort); backLeft = new CANTalon(backLeftPort); backRight = new CANTalon(backRightPort); navx = new AHRS(SPI.Port.kMXP); } /** * Test drive train object. */ public DriveTrain(boolean gyro) { if (gyro) { navx = new AHRS(SPI.Port.kMXP); } System.out.println("Created dummy drivetrain"); } /** * Ensure that wheel speeds are valid numbers. * * @param wheelSpeeds wheel speeds */ public static void normalize(double[] wheelSpeeds) { double maxMagnitude = Math.abs(wheelSpeeds[0]); for (int i = 1; i < 4; i++) { double temp = Math.abs(wheelSpeeds[i]); if (maxMagnitude < temp) { maxMagnitude = temp; } } if (maxMagnitude > 1.0) { for (int i = 0; i < 4; i++) { wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude; } } } /** * Rotate a vector in Cartesian space. * * @param xcomponent X component of the vector * @param ycomponent Y component of the vector * @return the resultant vector as a double[2] */ public double[] rotateVector(double xcomponent, double ycomponent) { double angle = navx.getAngle(); double cosA = Math.cos(angle * (3.14159 / 180.0)); double sinA = Math.sin(angle * (3.14159 / 180.0)); double[] out = new double[2]; out[0] = xcomponent * cosA - ycomponent * sinA; out[1] = xcomponent * sinA + ycomponent * cosA; return out; } /** * Adjust motor speeds according to joystick input. * * @param xcomponent x component of the joystick * @param ycomponent y component of the joystick * @param rotation rotation of the joystick */ public void mecanumDriveAbsolute(double xcomponent, double ycomponent, double rotation) { if (Math.abs(rotation) <= TWIST_THRESHOLD) { rotation = 0.0; } // Negate y for the joystick. ycomponent = -ycomponent; double[] wheelSpeeds = new double[4]; wheelSpeeds[0] = xcomponent + ycomponent + rotation; wheelSpeeds[1] = -xcomponent + ycomponent - rotation; wheelSpeeds[2] = -xcomponent + ycomponent + rotation; wheelSpeeds[3] = xcomponent + ycomponent - rotation; normalize(wheelSpeeds); frontLeft.set(wheelSpeeds[0]); frontRight.set(wheelSpeeds[1]); backLeft.set(wheelSpeeds[2]); backRight.set(wheelSpeeds[3]); } /** * Adjust motor speeds according to heading and joystick input. * Uses input from the gyroscope to determine field orientation. * * @param xcomponent x component of the joystick * @param ycomponent y component of the joystick * @param rotation rotation of the joystick */ public void mecanumDrive(double xcomponent, double ycomponent, double rotation) { // Ignore tiny inadvertent joystick rotations if (Math.abs(rotation) <= TWIST_THRESHOLD) { rotation = 0.0; } // Negate y for the joystick. ycomponent = -ycomponent; // Compensate for gyro angle. double[] rotated = rotateVector(xcomponent, ycomponent); xcomponent = rotated[0]; ycomponent = rotated[1]; double[] wheelSpeeds = new double[4]; wheelSpeeds[0] = xcomponent + ycomponent + rotation; wheelSpeeds[1] = -xcomponent + ycomponent - rotation; wheelSpeeds[2] = -xcomponent + ycomponent + rotation; wheelSpeeds[3] = xcomponent + ycomponent - rotation; normalize(wheelSpeeds); frontLeft.set(wheelSpeeds[0]); frontRight.set(wheelSpeeds[1]); backLeft.set(wheelSpeeds[2]); backRight.set(wheelSpeeds[3]); } /** * Move motors a certain distance. * * @param dist distance */ public void moveDistance(double dist) { double encoderChange = Math.abs(dist * DIST_TO_ENC); int dir = 1; frontLeft.setEncPosition(0); if (dist < 0) { dir = -1; } while (frontLeft.getEncPosition() < encoderChange) { mecanumDrive(0, AUTON_SPEED * dir, 0); } brake(); } /** * @param pos 1 = Right, 2 = Middle, 3 = Right * @param pixy */ public void placeGear(int pos, PixyThread pixy, GearGobbler gobbler) { //todo: confirm angles for each side if(pixy.isBlocksDetected()) { if (pos == 1) { turnDegrees(-30); } else if (pos == 2) { turnDegrees(-90); } else if (pos == 3) { turnDegrees(-150); } else { turnDegrees(0); } int dir; while (Math.abs(pixy.horizontalOffset()) > VISION_DEADZONE) { dir = 1; if (pixy.horizontalOffset() < 0) { dir = -1; } // center relative to the target mecanumDrive(0, AUTON_SPEED * dir, 0); } while (pixy.distanceFromLift() >= PLACING_DIST) { // approach the target dir = 1; if (pixy.horizontalOffset() < 0) { dir = -1; } mecanumDrive(AUTON_SPEED, AUTON_SPEED * dir, 0); } brake(); gobbler.open(); Timer.delay(.5); gobbler.close(); } } /** * Teleop version finds nearest angle before starting. * * @param pixy */ public void placeGear(PixyThread pixy, GearGobbler gobbler) { //todo: round to nearest angle double angle = navx.getAngle(); if (angle > 0 && angle < 60) { placeGear(1, pixy, gobbler); } } /** * Turn all wheels slowly for testing purposes. */ public void testMotors() { frontLeft.set(.2); frontRight.set(.2); backLeft.set(.2); backRight.set(.2); } /** * Turns at a certain speed * * @param speed double -1-1 */ public void turn(double speed) { frontLeft.set(-speed); backLeft.set(-speed); frontRight.set(speed); backRight.set(speed); } /** * Turn a certain amount of degrees * * @param degrees target degrees */ public void turnDegrees(double degrees) { int dir = getOptimalDirection(getTrueAngle(), degrees); while (getTrueAngle() - TURN_DEADZONE > degrees || getTrueAngle() + TURN_DEADZONE < degrees) { turn(TURN_SPEED * dir); } brake(); } /** * Get the true navx angle * * @return 0 <= angle < 360 */ public double getTrueAngle() { double angle = navx.getAngle() % 360; if (angle < 0) { return 360 + angle; } return angle; } /** * Get the best direction to turn * * @param current current angle * @param target target angle * @return -1 = left, 1 = right */ public int getOptimalDirection(double current, double target) { if (Math.abs(current - target) <= 180) { if (current > target) { return -1; } return 1; } if (current > target) { return 1; } return -1; } /** * Turn all wheels at set speeds. * * @param fl speed for front left wheel * @param fr speed for front right wheel * @param bl speed for back left wheel * @param br speed for back right wheel */ public void testMotors(int fl, int fr, int bl, int br) { frontLeft.set(fl); frontRight.set(fr); backLeft.set(bl); backRight.set(br); } /** * Stop all motors. */ public void brake() { frontLeft.set(0); frontRight.set(0); backRight.set(0); backLeft.set(0); } /** * @return the current gyro heading */ public String toString() { return Double.toString(navx.getAngle()); } /** * Prints current average encoder values. */ public void debugEncoders() { System.out.print((backLeft.getPosition() + backRight.getPosition() + frontLeft.getPosition() + frontRight.getPosition()) / 4); } /** * Zero the gyro. */ public void reset() { navx.reset(); } }
import java.io.*; import java.util.*; import irgeneration.*; import semanticanalysis.*; import symboltable.*; import syntaxtree.*; import visitor.*; public class MiniJavaCompiler { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("usage: java NameAnalysisTest <input-file>"); System.exit(1); } MiniJavaParser parser = new MiniJavaParser(new MiniJavaLexer(new FileReader(args[0]))); Program program = (Program)parser.parse().value; BuildSymbolTableVisitor symbolTableBuilder = new BuildSymbolTableVisitor(); symbolTableBuilder.visit(program); ISymbolTable symbolTable = symbolTableBuilder.getSymbolTable(); for (String error : symbolTableBuilder.getErrors()) System.out.println(error); NameAnalysisVisitor nameAnalysis = new NameAnalysisVisitor(symbolTable); nameAnalysis.visit(program); for (String error : nameAnalysis.getErrors()) System.out.println(error); TypeCheckVisitor typeChecker = new TypeCheckVisitor(symbolTable); typeChecker.visit(program); for (String error : typeChecker.getErrors()) System.out.println(error); if(!(typeChecker.getErrors().isEmpty() && nameAnalysis.getErrors().isEmpty() && symbolTableBuilder.getErrors().isEmpty())) { System.out.println("Errors encountered, cannot generate IR."); return; } IRGenVisitor irGenerator = new IRGenVisitor((SymbolTable)symbolTable); irGenerator.visit(program); irGenerator.printIRList(); } }
package seedu.address.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_INVALID_PERSON_DISPLAYED_INDEX = "The person index provided is invalid"; public static final String MESSAGE_TODOS_LISTED_OVERVIEW = "%1$d persons listed!"; }
package com.atsebak.embeddedlinuxjvm.commandline; import com.atsebak.embeddedlinuxjvm.runner.conf.EmbeddedLinuxJVMRunConfiguration; import com.intellij.execution.configurations.JavaParameters; import lombok.Builder; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import java.util.Map; @Builder public class CommandLineTarget { private final JavaParameters parameters; private final EmbeddedLinuxJVMRunConfiguration embeddedLinuxJVMRunConfiguration; private final boolean isDebugging; /** * Builds the command line command to invoke the java from the target machine * * @return */ @Override public String toString() { StringBuilder cmdBuf = new StringBuilder(); addRunAsRootOption(cmdBuf); addEnvironmentVariables(cmdBuf); cmdBuf.append(" java "); addVMArguments(cmdBuf); addClasspath(cmdBuf); addMainType(cmdBuf); addArguments(cmdBuf); return cmdBuf.toString().replaceAll("\\s{2,}", " ").trim(); } /** * Adds Main class * * @param cmdBuf */ private void addMainType(@NotNull StringBuilder cmdBuf) { cmdBuf.append(" ").append(parameters.getMainClass()).append(" "); } /** * Adds the classpath to java app * * @param cmdBuf */ private void addClasspath(@NotNull StringBuilder cmdBuf) { cmdBuf.append(" -cp classes:lib/'*' "); } /** * Adds Virtual Machine Arguments * @param cmdBuf */ private void addVMArguments(@NotNull StringBuilder cmdBuf) { if (isDebugging) { //debugging with the port this is added on the remote device command line cmdBuf.append("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=" + embeddedLinuxJVMRunConfiguration.getRunnerParameters().getPort()); } for (String arg : parameters.getVMParametersList().getParameters()) { //todo see if devs need the java agent support because for now this is a quick fix that might not be the proper way if (!arg.contains("transport=dt_socket") && !arg.contains("javaagent") && StringUtils.isNotBlank(arg) && !parameters.getProgramParametersList().getParameters().equals(parameters.getVMParametersList().getParameters())) { cmdBuf.append(' ').append(arg.trim()); } } } /** * Adds debug options * @param cmdBuf */ private void addArguments(@NotNull StringBuilder cmdBuf) { if (!parameters.getProgramParametersList().getParameters().isEmpty()) { for (String arg : parameters.getProgramParametersList().getParameters()) { cmdBuf.append(' ').append(arg.trim()); } } } /** * Adds Environment Variables * * @param cmdBuf */ private void addEnvironmentVariables(@NotNull StringBuilder cmdBuf) { cmdBuf.append(" "); for (Map.Entry<String, String> entry : parameters.getEnv().entrySet()) { String value = entry.getValue().replaceAll("\"", "\\\""); cmdBuf.append(entry.getKey()).append("=\"").append(value).append("\" "); } cmdBuf.append(" "); } /** * Adds the sudo user to command * @param cmdBuf */ private void addRunAsRootOption(@NotNull StringBuilder cmdBuf) { if (embeddedLinuxJVMRunConfiguration.getRunnerParameters().isRunAsRoot()) { cmdBuf.append(" sudo "); } } }
package seedu.tache.logic.parser; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import seedu.tache.commons.exceptions.IllegalValueException; import seedu.tache.commons.util.StringUtil; import seedu.tache.model.tag.Tag; import seedu.tache.model.tag.UniqueTagList; import seedu.tache.model.task.DateTime; import seedu.tache.model.task.Name; /** * Contains utility methods used for parsing strings in the various *Parser classes */ public class ParserUtil { //@@author A0139925U private static final Pattern INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern NAME_FORMAT = Pattern.compile("^\".+\""); private static final Pattern DATE_FORMAT = Pattern.compile("^[0-3]?[0-9]/[0-1]?[0-9]/(?:[0-9]{2})?[0-9]{2}$" + "|^[0-3]?[0-9]-[0-1]?[0-9]-(?:[0-9]{2})?[0-9]{2}$" + "|^[0-3]{1}[0-9]{1}[0-1]{1}[0-9]{1}" + "(?:[0-9]{2})?[0-9]{2}$"); private static final Pattern TIME_FORMAT = Pattern.compile("^[0-2][0-9][0-5][0-9]|^([0-1][0-2]|[0-9])" + "([.][0-5][0-9])?\\s?(am|pm){1}"); private static final Pattern DURATION_FORMAT = Pattern.compile("^\\d+\\s?((h|hr|hrs)|(m|min|mins))"); public static final int TYPE_TASK = 0; public static final int TYPE_DETAILED_TASK = 1; //@@author //@@author A0150120H static enum DateTimeType { START, END, UNKNOWN }; public static final String[] START_DATE_IDENTIFIER = {"from"}; public static final String[] END_DATE_IDENTIFIER = {"to", "on", "by", "before"}; //@@author /** * Returns the specified index in the {@code command} if it is a positive unsigned integer * Returns an {@code Optional.empty()} otherwise. */ public static Optional<Integer> parseIndex(String command) { final Matcher matcher = INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Returns a new Set populated by all elements in the given list of strings * Returns an empty set if the given {@code Optional} is empty, * or if the list contained in the {@code Optional} is empty */ public static Set<String> toSet(Optional<List<String>> list) { List<String> elements = list.orElse(Collections.emptyList()); return new HashSet<>(elements); } /** * Splits a preamble string into ordered fields. * @return A list of size {@code numFields} where the ith element is the ith field value if specified in * the input, {@code Optional.empty()} otherwise. */ public static List<Optional<String>> splitPreamble(String preamble, int numFields) { return Arrays.stream(Arrays.copyOf(preamble.split("\\s+", numFields), numFields)) .map(Optional::ofNullable) .collect(Collectors.toList()); } /** * Parses a {@code Optional<String> name} into an {@code Optional<Name>} if {@code name} is present. */ public static Optional<Name> parseName(Optional<String> name) throws IllegalValueException { assert name != null; return name.isPresent() ? Optional.of(new Name(name.get())) : Optional.empty(); } /** * Parses {@code Collection<String> tags} into an {@code UniqueTagList}. */ public static UniqueTagList parseTags(Collection<String> tags) throws IllegalValueException { assert tags != null; final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } return new UniqueTagList(tagSet); } //@@author A0139925U /** * Returns True if input is a valid date * Returns False otherwise. */ public static boolean isValidDate(String input) { final Matcher matcher = DATE_FORMAT.matcher(input.trim()); return matcher.matches(); } /** * Returns True if input is a valid time * Returns False otherwise. */ public static boolean isValidTime(String input) { final Matcher matcher = TIME_FORMAT.matcher(input.trim()); return matcher.matches(); } /** * Returns True if input is a valid duration * Returns False otherwise. */ public static boolean isValidDuration(String input) { final Matcher matcher = DURATION_FORMAT.matcher(input.trim()); return matcher.matches(); } /** * Returns True if input is a valid name * Returns False otherwise. */ public static boolean isValidName(String input) { final Matcher matcher = NAME_FORMAT.matcher(input.trim()); return matcher.matches(); } //@@author /** * Returns number of date parameters in input. */ public static boolean hasDate(String input) { try { parseDate(input); return true; } catch (IllegalValueException ex) { return false; } } /** * Returns number of time parameters in input. */ public static boolean hasTime(String input) { try { parseTime(input); return true; } catch (IllegalValueException ex) { return false; } } //@@author A0150120H /** * Returns the first time String encountered */ public static String parseTime(String input) throws IllegalValueException { String[] inputs = input.split(" "); for (String candidate : inputs) { Matcher matcher = TIME_FORMAT.matcher(candidate.trim()); if (matcher.lookingAt()) { return matcher.group(); } } throw new IllegalValueException("Invalid Input"); } /** * Returns the first date String encountered */ public static String parseDate(String input) throws IllegalValueException { String[] inputs = input.split(" "); for (String candidate : inputs) { Matcher matcher = DATE_FORMAT.matcher(candidate.trim()); if (matcher.lookingAt()) { return matcher.group(); } } throw new IllegalValueException("Invalid Input"); } /** * Checks if the given String is a start date identifier * @param s String to check * @return true if it's a start date identifier, false otherwise */ public static boolean isStartDateIdentifier(String s) { for (String identifier: START_DATE_IDENTIFIER) { if (s.equalsIgnoreCase(identifier)) { return true; } } return false; } /** * Checks if the given String is an end date identifier * @param s String to check * @return true if it's a start date identifier, false otherwise */ public static boolean isEndDateIdentifier(String s) { for (String identifier: END_DATE_IDENTIFIER) { if (s.equalsIgnoreCase(identifier)) { return true; } } return false; } /** * Looks for all possible date/time strings based on identifiers * @param input String to parse * @return Deque of PossibleDateTime objects, each representing a possible date/time string */ public static Deque<PossibleDateTime> parseDateTimeIdentifiers(String input) { String[] inputs = input.split(" "); Deque<PossibleDateTime> result = new LinkedList<PossibleDateTime>(); PossibleDateTime current = new PossibleDateTime(PossibleDateTime.INVALID_INDEX, DateTimeType.UNKNOWN); for (int i = 0; i < inputs.length; i++) { String word = inputs[i]; if (isStartDateIdentifier(word)) { result.push(current); current = new PossibleDateTime(i, DateTimeType.START); } else if (isEndDateIdentifier(word)) { result.push(current); current = new PossibleDateTime(i, DateTimeType.END); } else { current.appendDateTime(i, word); } } result.push(current); return result; } /** * Class to describe a date/time String that was found * */ static class PossibleDateTime { int startIndex; int endIndex; String data; DateTimeType type; static final int INVALID_INDEX = -1; PossibleDateTime(int index, DateTimeType type) { this.startIndex = index; this.endIndex = index; this.type = type; this.data = new String(); } void appendDateTime(int index, String data) { this.data += " " + data; this.endIndex = index; } } public static boolean canParse(String s) { return DateTime.canParse(s); } public static boolean isTime(String s) { return DateTime.isTime(s); } public static boolean isDate(String s) { return DateTime.isDate(s); } }
package com.fjx.wechat.base.admin.service; import com.fjx.common.framework.base.service.impl.BaseAbstractService; import com.fjx.common.framework.system.exception.MyRuntimeException; import com.fjx.common.framework.system.pagination.Pagination; import com.fjx.common.utils.CommonUtils; import com.fjx.wechat.base.admin.entity.*; import com.fjx.wechat.mysdk.constants.WechatMenuConstants; import com.fjx.wechat.mysdk.constants.WechatRespMsgtypeConstants; import com.fjx.wechat.mysdk.tools.MaterialUtil; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import java.util.*; /** * service * * @author fengjx xd-fjx@qq.com * @date 201499 */ @Service public class RespMsgActionServiceImpl extends BaseAbstractService<RespMsgActionEntity> implements RespMsgActionService { private Logger logger = Logger.getLogger(this.getClass()); /* * (non-Javadoc) * @see * com.fjx.wechat.base.admin.service.RespMsgActionService#saveAction(com * .fjx.wechat.base.admin.entity.RespMsgActionEntity, * com.fjx.wechat.base.admin.entity.WechatMenuEntity, * com.fjx.wechat.base.admin.entity.MaterialEntity) */ @Override public void saveAction(RespMsgActionEntity actionEntity, WechatMenuEntity menuEntity, MaterialEntity materialEntity) { if (null != menuEntity) { saveMenuAction(actionEntity, menuEntity, materialEntity); } else { saveMsgAction(actionEntity, materialEntity); } } /* * (non-Javadoc) * @see * com.fjx.wechat.base.admin.service.RespMsgActionService#updateAction(com * .fjx.wechat.base.admin.entity.RespMsgActionEntity, * com.fjx.wechat.base.admin.entity.WechatMenuEntity, * com.fjx.wechat.base.admin.entity.MaterialEntity) */ @Override public void updateAction(RespMsgActionEntity actionEntity, WechatMenuEntity menuEntity, MaterialEntity materialEntity) { String action_id = actionEntity.getId(); if (StringUtils.isNotBlank(action_id)) { deleteMsgActionById(action_id); } saveAction(actionEntity, menuEntity, materialEntity); } /* * (non-Javadoc) * @see * com.fjx.wechat.base.admin.service.RespMsgActionService#loadMsgAction( * java.lang.String, java.lang.String, java.lang.String) */ @Override public RespMsgActionEntity loadMsgAction(String ext_type, String req_type, String event_type, String key_word, SysUserEntity sysUser) { RespMsgActionEntity actionEntity = null; List<String> parameters = new ArrayList<String>(); StringBuffer hql = new StringBuffer("from RespMsgActionEntity a "); hql.append("where a.sysUser.id = ? "); parameters.add(sysUser.getId()); if (StringUtils.isNotBlank(ext_type)) { hql.append(" and a.ext_type = ?"); parameters.add(ext_type); } if (StringUtils.isNotBlank(req_type)) { hql.append(" and a.req_type = ?"); parameters.add(req_type); } if (StringUtils.isNotBlank(event_type)) { hql.append(" and a.event_type = ?"); parameters.add(event_type); } if (StringUtils.isNotBlank(key_word)) { hql.append(" and a.key_word = ?"); parameters.add(key_word); } actionEntity = findOneByHql(hql.toString(), parameters); return actionEntity; } /* * (non-Javadoc) * @see * com.fjx.wechat.base.admin.service.RespMsgActionService#deleteMsgActionById * (java.lang.String) */ @Override public void deleteMsgActionById(String ids) { if (StringUtils.isBlank(ids)) { throw new MyRuntimeException("ID"); } String _ids[] = ids.split(","); if (null != _ids && _ids.length > 1) { for (String id : _ids) { deleteAction(ids); } } else { deleteAction(ids); } } private void deleteAction(String id){ bulkUpdate("delete from RespMsgActionEntity a where a.id = ?",true,id); } /* * (non-Javadoc) * @see * com.fjx.wechat.base.admin.service.RespMsgActionService#deleteMsgActionByKey * (java.lang.String) */ @Override public void deleteMsgActionByKey(String key_word) { String hql = "delete RespMsgActionEntity a where a.key_word = ?"; bulkUpdate(hql, true, key_word); } @Override public Pagination<KeyWordActionView> pageMsgAction(Map<String, String> param, SysUserEntity sysUser) { List<Object> parameters = new ArrayList<Object>(); // StringBuffer sql = new // StringBuffer("select a.id as id, a.req_type as req_type, a.action_type as action_type, a.key_word as key_word, a.material_id as material_id, a.app_id as app_id, a.in_time as in_time,"); // sql.append(" b.bean_name as bean_name, b.method_name as method_name, b.name as app_name,"); // sql.append(" c.xml_data as xml_data, c.msg_type as msg_type,"); // sql.append(" d.dict_name as dict_name"); // sql.append(" from wechat_resp_msg_action a"); // sql.append(" left join wechat_ext_app b "); // sql.append(" on a.app_id = b.id"); // sql.append(" left join wechat_material c"); // sql.append(" on a.material_id = c.id"); // sql.append(" left join wechat_data_dict d"); // sql.append(" on c.msg_type = d.dict_value"); // sql.append(" where d.group_code = 'resp_type' "); // sql.append(" and a.user_id = ? "); StringBuffer hql = new StringBuffer( "select new com.fjx.wechat.base.admin.entity.KeyWordActionView( "); hql.append(" a.id as id, a.req_type as req_type, a.action_type as action_type, a.key_word as key_word, a.in_time as in_time,"); hql.append(" b.id as app_id, b.bean_name as method_name, b.method_name as method_name, b.name as app_name,"); hql.append(" c.id as material_id, c.xml_data as xml_data, c.msg_type as msg_type,"); hql.append(" d.dict_name as dict_name )"); hql.append(" from RespMsgActionEntity as a, DataDictEntity d"); hql.append(" left join a.extApp as b "); hql.append(" left join a.material as c"); hql.append(" where a.action_type=d.dict_value"); hql.append(" and d.group_code = 'action_type' "); hql.append(" and a.sysUser.id = ? "); // StringBuffer sql = new // StringBuffer("select a.id id, a.req_type req_type, a.action_type action_type, a.key_word key_word, a.material_id material_id, a.app_id app_id, a.in_time in_time, a.user_id user_id, a.beanName beanName, a.methodName methodName, a.app_name app_name, a.xml_data xml_data, a.msg_type msg_type, a.dict_name dict_name "); // StringBuffer hql = new // StringBuffer("select a.id as id, a.req_type as req_type, a.action_type as action_type, a.key_word as key_word, a.material_id as material_id, a.app_id as app_id, a.in_time as in_time, a.user_id as user_id, a.beanName as beanName, a.methodName as methodName, a.app_name as app_name, a.xml_data as xml_data, a.msg_type as msg_type, a.dict_name as dict_name "); // StringBuffer hql = new StringBuffer(); // hql.append("from KeyWordActionView a"); // hql.append(" where a.user_id = ? "); parameters.add(sysUser.getId()); if (StringUtils.isNotBlank(param.get("req_type"))) { hql.append(" and a.req_type = ?"); parameters.add(param.get("req_type")); } if (StringUtils.isNotBlank(param.get("event_type"))) { hql.append(" and a.event_type = ?"); parameters.add(param.get("event_type")); } if (StringUtils.isNotBlank(param.get("action_type"))) { hql.append(" and a.action_type = ?"); parameters.add(param.get("action_type")); } if (StringUtils.isNotBlank(param.get("key_word"))) { hql.append(" and a.key_word like ?"); parameters.add("%" + param.get("key_word") + "%"); } if (StringUtils.isNotBlank(param.get("start_time"))) { hql.append(" and a.in_time >= ?"); parameters.add(CommonUtils.string2Date(param.get("start_time").trim() + " 00:00:00")); } if (StringUtils.isNotBlank(param.get("end_time"))) { hql.append(" and a.in_time < ?"); parameters.add(CommonUtils.string2Date(param.get("end_time").trim() + " 23:59:59")); } hql.append(" order by a.in_time desc"); return pageByHql(hql.toString(), parameters); } /** * * * @param actionEntity * @param menuEntity * @param materialEntity */ private void saveMenuAction(RespMsgActionEntity actionEntity, WechatMenuEntity menuEntity, MaterialEntity materialEntity) { Date now = new Date(); String menu_id = menuEntity.getId(); menuEntity.setUpdate_time(now); actionEntity.setIn_time(now); String menuType = menuEntity.getType(); // click if (menuType.equals(WechatMenuConstants.TYPE_CLICK)) { menuEntity.setMenu_key("key_" + menu_id); menuEntity.setUrl(null); actionEntity.setKey_word("key_" + menu_id); // or key String action_type = actionEntity.getAction_type(); if (RespMsgActionEntity.ACTION_TYPE_MATERIAL.equals(action_type)) { String resp_type = actionEntity.getMaterial().getMsg_type(); if (resp_type.equals(WechatRespMsgtypeConstants.RESP_MESSAGE_TYPE_TEXT)) { materialEntity.setIn_time(now); materialEntity.setMsg_type(WechatRespMsgtypeConstants.RESP_MESSAGE_TYPE_TEXT); List<Map<String, String>> materialList = new ArrayList<Map<String, String>>(); Map<String, String> materiaParam = new HashMap<String, String>(); materiaParam.put("msg_type", materialEntity.getMsg_type()); materiaParam.put("txt_content", materialEntity.getContent()); materialList.add(materiaParam); String materialXml = MaterialUtil.data2Xml(materialList); materialEntity.setXml_data(materialXml); logger.debug("materiaXmlParam json data: {} " + materialXml); actionEntity.setMaterial(materialEntity); save(materialEntity); } } save(actionEntity); } else if (menuType.equals(WechatMenuConstants.TYPE_VIEW)) { menuEntity.setMenu_key(null); } update(menuEntity); } /** * * * @param actionEntity * @param materialEntity */ private void saveMsgAction(RespMsgActionEntity actionEntity, MaterialEntity materialEntity) { Date now = new Date(); actionEntity.setIn_time(now); String action_type = actionEntity.getAction_type(); if (RespMsgActionEntity.ACTION_TYPE_MATERIAL.equals(action_type)) { String resp_type = actionEntity.getMaterial().getMsg_type(); if (resp_type.equals(WechatRespMsgtypeConstants.RESP_MESSAGE_TYPE_TEXT)) { materialEntity.setIn_time(now); materialEntity.setMsg_type(WechatRespMsgtypeConstants.RESP_MESSAGE_TYPE_TEXT); List<Map<String, String>> materialList = new ArrayList<Map<String, String>>(); Map<String, String> materiaParam = new HashMap<String, String>(); materiaParam.put("msg_type", materialEntity.getMsg_type()); materiaParam.put("txt_content", materialEntity.getContent()); materialList.add(materiaParam); String materialXml = MaterialUtil.data2Xml(materialList); materialEntity.setXml_data(materialXml); logger.debug("materiaXmlParam json data: {} " + materialXml); actionEntity.setMaterial(materialEntity); save(materialEntity); } } RespMsgActionEntity actionEntity2 = loadMsgAction(actionEntity.getExt_type(), actionEntity.getReq_type(), actionEntity.getEvent_type(), actionEntity.getKey_word(), actionEntity.getSysUser()); if (null != actionEntity2) { throw new MyRuntimeException(""); } save(actionEntity); } }
package space.npstr.wolfia.listing; import net.dv8tion.jda.core.JDA; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import space.npstr.wolfia.Config; import space.npstr.wolfia.Wolfia; import java.io.IOException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class Listings { private static final Logger log = LoggerFactory.getLogger(Listings.class); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static volatile String lastBotsDiscordPwPayload = ""; private static volatile Future botsDiscordPwTask; public static synchronized void postToBotsDiscordPw(final JDA jda) { if (botsDiscordPwTask != null && !botsDiscordPwTask.isCancelled() && !botsDiscordPwTask.isDone()) { log.info("Skipping posting stats to bots.discord.pw since there is a task to do that running already."); return; } postToBotsDiscordPw(jda, 0); } //according to their discord: post these on guild join, guild leave, and ready events //which is bonkers given guild joins and leaves are wonky when discord is having issues private static void postToBotsDiscordPw(final JDA jda, final int attempt) { if (Config.C.isDebug) { log.info("Skipping posting stats to bots.discord.pw due to running in debug mode"); return; } final String payload = new JSONObject().put("server_count", jda.getGuilds().size()).toString(); if (payload.equals(lastBotsDiscordPwPayload)) { log.info("Skipping sending stats to bots.discord.pw since the payload has not changed"); return; } final int att = attempt + 1; final RequestBody body = RequestBody.create(JSON, payload); final Request req = new Request.Builder() .url(String.format("https://bots.discord.pw/api/bots/%s/stats", jda.getSelfUser().getIdLong())) .addHeader("Authorization", Config.C.botsDiscordPwToken) .post(body) .build(); try { final Response response = Wolfia.httpClient.newCall(req).execute(); if (response.isSuccessful()) { log.info("Attempt {} successfully posted bot stats to bots.discord.pw, code {}", att, response.code()); lastBotsDiscordPwPayload = payload; } else { log.warn("Attempt {} failed to post stats to bots.discord.pw: code {}, body:\n{}", att, response.code(), response.body() != null ? response.body().string() : "null"); botsDiscordPwTask = reschedule(() -> postToBotsDiscordPw(jda, att), att); } } catch (final IOException e) { log.warn("Attempt {} failed to post stats to bots.discord.pw", att, e); botsDiscordPwTask = reschedule(() -> postToBotsDiscordPw(jda, att), att); } } //increase delay with growing attempts to avoid overloading the listing servers private static Future reschedule(final Runnable task, final int attempt) { return Wolfia.schedule(task, 10 * attempt, TimeUnit.SECONDS); } private static volatile String lastDiscordbotsOrgPayload = ""; private static volatile Future discordbotsOrgTask; public static synchronized void postToDiscordbotsOrg(final JDA jda) { if (discordbotsOrgTask != null && !discordbotsOrgTask.isCancelled() && !discordbotsOrgTask.isDone()) { log.info("Skipping posting stats to discordbots.org since there is a task to do that running already."); return; } postToDiscordbotsOrg(jda, 0); } private static void postToDiscordbotsOrg(final JDA jda, final int attempt) { if (Config.C.isDebug) { log.info("Skipping posting stats to discordbots.org due to running in debug mode"); return; } final String payload = new JSONObject().put("server_count", jda.getGuilds().size()).toString(); if (payload.equals(lastDiscordbotsOrgPayload)) { log.info("Skipping sending stats to discordbots.org since the payload has not changed"); return; } final int att = attempt + 1; final RequestBody body = RequestBody.create(JSON, payload); final Request req = new Request.Builder() .url(String.format("https://discordbots.org/api/bots/%s/stats", jda.getSelfUser().getIdLong())) .addHeader("Authorization", Config.C.discordbotsOrgToken) .post(body) .build(); try { final Response response = Wolfia.httpClient.newCall(req).execute(); if (response.isSuccessful()) { log.info("Attempt {} successfully posted bot stats to discordbots.org, code {}", att, response.code()); lastDiscordbotsOrgPayload = payload; } else { log.warn("Attempt {} failed to post stats to discordbots.org: code {}, body:\n{}", att, response.code(), response.body() != null ? response.body().string() : "null"); discordbotsOrgTask = reschedule(() -> postToDiscordbotsOrg(jda, att), att); } } catch (final IOException e) { log.warn("Attempt {} failed to post stats to discordbots.org", attempt, e); discordbotsOrgTask = reschedule(() -> postToDiscordbotsOrg(jda, att), att); } } }
package example; import com.artifex.mupdf.fitz.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.File; import java.io.FilenameFilter; import java.lang.reflect.Field; import java.util.Vector; import java.util.Date; public class Viewer extends Frame implements WindowListener, ActionListener, ItemListener, TextListener { protected Document doc; protected ScrollPane pageScroll; protected Panel pageHolder; protected ImageCanvas pageCanvas; protected Matrix pageCTM; protected Button firstButton, prevButton, nextButton, lastButton; protected TextField pageField; protected Label pageLabel; protected Button zoomInButton, zoomOutButton; protected Choice zoomChoice; protected Button fontIncButton, fontDecButton; protected Label fontSizeLabel; protected TextField searchField; protected Button searchPrevButton, searchNextButton; protected int searchHitPage = -1; protected Quad searchHits[]; protected List outlineList; protected Vector<Outline> flatOutline; protected int pageCount; protected int pageNumber = 0; protected int zoomLevel = 5; protected int layoutWidth = 450; protected int layoutHeight = 600; protected int layoutEm = 12; protected float pixelScale; protected static final int zoomList[] = { 18, 24, 36, 54, 72, 96, 120, 144, 180, 216, 288 }; protected static BufferedImage imageFromPixmap(Pixmap pixmap) { int w = pixmap.getWidth(); int h = pixmap.getHeight(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR); image.setRGB(0, 0, w, h, pixmap.getPixels(), 0, w); return image; } protected static BufferedImage imageFromPage(Page page, Matrix ctm) { Rect bbox = page.getBounds().transform(ctm); Pixmap pixmap = new Pixmap(ColorSpace.DeviceBGR, bbox, true); pixmap.clear(255); DrawDevice dev = new DrawDevice(pixmap); page.run(dev, ctm, null); dev.close(); dev.destroy(); BufferedImage image = imageFromPixmap(pixmap); pixmap.destroy(); return image; } protected static void messageBox(Frame owner, String title, String message) { final Dialog box = new Dialog(owner, title, true); box.add(new Label(message), BorderLayout.CENTER); Panel buttonPane = new Panel(new FlowLayout()); Button okayButton = new Button("Okay"); okayButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { box.setVisible(false); } }); buttonPane.add(okayButton); box.add(buttonPane, BorderLayout.SOUTH); box.pack(); box.setVisible(true); box.dispose(); } protected static String passwordDialog(Frame owner) { final Dialog box = new Dialog(owner, "Password", true); final TextField textField = new TextField(20); textField.setEchoChar('*'); Panel buttonPane = new Panel(new FlowLayout()); Button cancelButton = new Button("Cancel"); Button okayButton = new Button("Okay"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText(""); box.setVisible(false); } }); okayButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { box.setVisible(false); } }); box.add(new Label("Password:"), BorderLayout.NORTH); box.add(textField, BorderLayout.CENTER); buttonPane.add(cancelButton); buttonPane.add(okayButton); box.add(buttonPane, BorderLayout.SOUTH); box.pack(); box.setVisible(true); box.dispose(); String pwd = textField.getText(); if (pwd.length() == 0) return null; return pwd; } protected class ImageCanvas extends Canvas { protected BufferedImage image; public void setImage(BufferedImage image_) { image = image_; repaint(); } public Dimension getPreferredSize() { return new Dimension(image.getWidth(), image.getHeight()); } public void paint(Graphics g) { float imageScale = 1 / pixelScale; final Graphics2D g2d = (Graphics2D)g.create(0, 0, image.getWidth(), image.getHeight()); g2d.scale(imageScale, imageScale); g2d.drawImage(image, 0, 0, null); if (searchHitPage == pageNumber && searchHits != null && searchHits.length > 0) { g2d.setColor(new Color(1, 0, 0, 0.4f)); for (int i = 0; i < searchHits.length; ++i) { Rect hit = new Rect(searchHits[i]).transform(pageCTM); g2d.fillRect((int)hit.x0, (int)hit.y0, (int)(hit.x1-hit.x0), (int)(hit.y1-hit.y0)); } } g2d.dispose(); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } public void update(Graphics g) { paint(g); } } public Viewer(Document doc_) { this.doc = doc_; pixelScale = getRetinaScale(); setTitle("MuPDF: " + doc.getMetaData(Document.META_INFO_TITLE)); doc.layout(layoutWidth, layoutHeight, layoutEm); pageCount = doc.countPages(); Panel rightPanel = new Panel(new BorderLayout()); { Panel toolpane = new Panel(new GridBagLayout()); { GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.WEST; Panel toolbar = new Panel(new FlowLayout(FlowLayout.LEFT)); { firstButton = new Button("|<"); firstButton.addActionListener(this); prevButton = new Button("<"); prevButton.addActionListener(this); nextButton = new Button(">"); nextButton.addActionListener(this); lastButton = new Button(">|"); lastButton.addActionListener(this); pageField = new TextField(4); pageField.addActionListener(this); pageLabel = new Label("/ " + pageCount); toolbar.add(firstButton); toolbar.add(prevButton); toolbar.add(pageField); toolbar.add(pageLabel); toolbar.add(nextButton); toolbar.add(lastButton); } c.gridy = 0; toolpane.add(toolbar, c); toolbar = new Panel(new FlowLayout(FlowLayout.LEFT)); { zoomOutButton = new Button("Zoom-"); zoomOutButton.addActionListener(this); zoomInButton = new Button("Zoom+"); zoomInButton.addActionListener(this); zoomChoice = new Choice(); for (int i = 0; i < zoomList.length; ++i) zoomChoice.add(String.valueOf(zoomList[i])); zoomChoice.select(zoomLevel); zoomChoice.addItemListener(this); toolbar.add(zoomOutButton); toolbar.add(zoomChoice); toolbar.add(zoomInButton); } c.gridy += 1; toolpane.add(toolbar, c); if (doc.isReflowable()) { toolbar = new Panel(new FlowLayout(FlowLayout.LEFT)); { fontDecButton = new Button("Font-"); fontDecButton.addActionListener(this); fontIncButton = new Button("Font+"); fontIncButton.addActionListener(this); fontSizeLabel = new Label(String.valueOf(layoutEm)); toolbar.add(fontDecButton); toolbar.add(fontSizeLabel); toolbar.add(fontIncButton); } c.gridy += 1; toolpane.add(toolbar, c); } toolbar = new Panel(new FlowLayout(FlowLayout.LEFT)); { searchField = new TextField(20); searchField.addActionListener(this); searchField.addTextListener(this); searchPrevButton = new Button("<"); searchPrevButton.addActionListener(this); searchNextButton = new Button(">"); searchNextButton.addActionListener(this); toolbar.add(searchField); toolbar.add(searchPrevButton); toolbar.add(searchNextButton); } c.gridy += 1; toolpane.add(toolbar, c); } rightPanel.add(toolpane, BorderLayout.NORTH); outlineList = new List(); outlineList.addItemListener(this); rightPanel.add(outlineList, BorderLayout.CENTER); } this.add(rightPanel, BorderLayout.EAST); pageScroll = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); { pageHolder = new Panel(new GridBagLayout()); { pageHolder.setBackground(Color.gray); pageCanvas = new ImageCanvas(); pageHolder.add(pageCanvas); } pageScroll.add(pageHolder); } this.add(pageScroll, BorderLayout.CENTER); addWindowListener(this); updateOutline(); updatePageCanvas(); pack(); } protected void addOutline(Outline[] outline, String indent) { for (int i = 0; i < outline.length; ++i) { Outline node = outline[i]; if (node.title != null) { flatOutline.add(node); outlineList.add(indent + node.title); } if (node.down != null) addOutline(node.down, indent + " "); } } protected void updateOutline() { Outline[] outline; try { outline = doc.loadOutline(); } catch (Exception ex) { outline = null; } outlineList.removeAll(); if (outline != null) { flatOutline = new Vector<Outline>(); addOutline(outline, ""); outlineList.setVisible(true); } else { outlineList.setVisible(false); } } protected void updatePageCanvas() { pageField.setText(String.valueOf(pageNumber + 1)); pageCTM = new Matrix().scale(zoomList[zoomLevel] / 72.0f * pixelScale); BufferedImage image = imageFromPage(doc.loadPage(pageNumber), pageCTM); pageCanvas.setImage(image); Dimension size = pageHolder.getPreferredSize(); size.width += 40; size.height += 40; pageScroll.setPreferredSize(size); pageCanvas.invalidate(); validate(); } protected void doSearch(int direction) { int searchPage; if (searchHitPage == -1) searchPage = pageNumber; else searchPage = pageNumber + direction; searchHitPage = -1; String needle = searchField.getText(); while (searchPage >= 0 && searchPage < pageCount) { Page page = doc.loadPage(searchPage); searchHits = page.search(needle); page.destroy(); if (searchHits != null && searchHits.length > 0) { searchHitPage = searchPage; pageNumber = searchPage; break; } searchPage += direction; } } public void textValueChanged(TextEvent event) { Object source = event.getSource(); if (source == searchField) { searchHitPage = -1; } } public void actionPerformed(ActionEvent event) { Object source = event.getSource(); int oldPageNumber = pageNumber; int oldLayoutEm = layoutEm; int oldZoomLevel = zoomLevel; Quad[] oldSearchHits = searchHits; if (source == firstButton) pageNumber = 0; if (source == lastButton) pageNumber = pageCount - 1; if (source == prevButton) { pageNumber = pageNumber - 1; if (pageNumber < 0) pageNumber = 0; } if (source == nextButton) { pageNumber = pageNumber + 1; if (pageNumber >= pageCount) pageNumber = pageCount - 1; } if (source == pageField) { pageNumber = Integer.parseInt(pageField.getText()) - 1; if (pageNumber < 0) pageNumber = 0; if (pageNumber >= pageCount) pageNumber = pageCount - 1; pageField.setText(String.valueOf(pageNumber)); } if (source == searchField) doSearch(1); if (source == searchNextButton) doSearch(1); if (source == searchPrevButton) doSearch(-1); if (source == fontIncButton && doc.isReflowable()) { layoutEm += 1; if (layoutEm > 36) layoutEm = 36; fontSizeLabel.setText(String.valueOf(layoutEm)); } if (source == fontDecButton && doc.isReflowable()) { layoutEm -= 1; if (layoutEm < 6) layoutEm = 6; fontSizeLabel.setText(String.valueOf(layoutEm)); } if (source == zoomOutButton) { zoomLevel -= 1; if (zoomLevel < 0) zoomLevel = 0; zoomChoice.select(zoomLevel); } if (source == zoomInButton) { zoomLevel += 1; if (zoomLevel >= zoomList.length) zoomLevel = zoomList.length - 1; zoomChoice.select(zoomLevel); } if (layoutEm != oldLayoutEm) { long mark = doc.makeBookmark(pageNumber); doc.layout(layoutWidth, layoutHeight, layoutEm); updateOutline(); pageCount = doc.countPages(); pageLabel.setText("/ " + pageCount); pageNumber = doc.findBookmark(mark); } if (zoomLevel != oldZoomLevel || pageNumber != oldPageNumber || layoutEm != oldLayoutEm || searchHits != oldSearchHits) updatePageCanvas(); } public void itemStateChanged(ItemEvent event) { Object source = event.getSource(); if (source == zoomChoice) { int oldZoomLevel = zoomLevel; zoomLevel = zoomChoice.getSelectedIndex(); if (zoomLevel != oldZoomLevel) updatePageCanvas(); } if (source == outlineList) { int i = outlineList.getSelectedIndex(); Outline node = (Outline)flatOutline.elementAt(i); if (node.page >= 0) { if (node.page != pageNumber) { pageNumber = node.page; updatePageCanvas(); } } } } public void windowClosing(WindowEvent event) { dispose(); } public void windowActivated(WindowEvent event) { } public void windowDeactivated(WindowEvent event) { } public void windowIconified(WindowEvent event) { } public void windowDeiconified(WindowEvent event) { } public void windowOpened(WindowEvent event) { } public void windowClosed(WindowEvent event) { } public static void main(String[] args) { File selectedFile; if (args.length <= 0) { FileDialog fileDialog = new FileDialog((Frame)null, "MuPDF Open File", FileDialog.LOAD); fileDialog.setDirectory(System.getProperty("user.dir")); fileDialog.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return Document.recognize(name); } }); fileDialog.setVisible(true); if (fileDialog.getFile() == null) System.exit(0); selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile()); fileDialog.dispose(); } else { selectedFile = new File(args[0]); } try { Document doc = Document.openDocument(selectedFile.getAbsolutePath()); if (doc.needsPassword()) { String pwd; do { pwd = passwordDialog(null); if (pwd == null) System.exit(1); } while (!doc.authenticatePassword(pwd)); } Viewer app = new Viewer(doc); app.setVisible(true); return; } catch (Exception e) { messageBox(null, "MuPDF Error", "Cannot open \"" + selectedFile + "\": " + e.getMessage() + "."); System.exit(1); } } public float getRetinaScale() { // first try Oracle's VM (we should also test for 1.7.0_40 or higher) final String vendor = System.getProperty("java.vm.vendor"); boolean isOracle = vendor != null && vendor.toLowerCase().contains("Oracle".toLowerCase()); if (isOracle) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice device = env.getDefaultScreenDevice(); try { Field field = device.getClass().getDeclaredField("scale"); if (field != null) { field.setAccessible(true); Object scale = field.get(device); if (scale instanceof Integer && ((Integer)scale).intValue() == 2) { return 2.0f; } } } catch (Exception ignore) { } return 1.0f; } // try Apple VM final Float scaleFactor = (Float)Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor"); if (scaleFactor != null && scaleFactor.intValue() == 2) { return 2.0f; } return 1.0f; } }
package water.fvec; import jsr166y.CountedCompleter; import water.*; import water.nbhm.NonBlockingHashMapLong; import water.util.Utils; import java.util.Arrays; import java.util.UUID; import static water.util.Utils.seq; /** * A single distributed vector column. * <p> * A distributed vector has a count of elements, an element-to-chunk mapping, a * Java type (mostly determines rounding on store and display), and functions * to directly load elements without further indirections. The data is * compressed, or backed by disk or both. *Writing* to elements may throw if the * backing data is read-only (file backed). * <p> * <pre> * Vec Key format is: Key. VEC - byte, 0 - byte, 0 - int, normal Key bytes. * DVec Key format is: Key.DVEC - byte, 0 - byte, chunk# - int, normal Key bytes. * </pre> * * The main API is at, set, and isNA:<br> *<pre> * double at ( long row ); // Returns the value expressed as a double. NaN if missing. * long at8 ( long row ); // Returns the value expressed as a long. Throws if missing. * boolean isNA( long row ); // True if the value is missing. * set( long row, double d ); // Stores a double; NaN will be treated as missing. * set( long row, long l ); // Stores a long; throws if l exceeds what fits in a double and any floats are ever set. * setNA( long row ); // Sets the value as missing. * </pre> * * Note this dangerous scenario: loading a missing value as a double, and * setting it as a long: <pre> * set(row,(long)at(row)); // Danger! *</pre> * The cast from a Double.NaN to a long produces a zero! This code will * replace a missing value with a zero. * * @author Cliff Click */ public class Vec extends Iced { /** Log-2 of Chunk size. */ public static final int LOG_CHK = ValueArray.LOG_CHK; // Same as VA to help conversions /** Chunk size. Bigger increases batch sizes, lowers overhead costs, lower * increases fine-grained parallelism. */ static final int CHUNK_SZ = 1 << LOG_CHK; /** Key mapping a Value which holds this Vec. */ final public Key _key; // Top-level key /** Element-start per chunk. Always zero for chunk 0. One more entry than * chunks, so the last entry is the total number of rows. This field is * dead/ignored in subclasses that are guaranteed to have fixed-sized chunks * such as file-backed Vecs. */ final public long _espc[]; /** Enum/factor/categorical names. */ public String [] _domain; /** Time parse, index into Utils.TIME_PARSE, or -1 for not-a-time */ public byte _time; /** RollupStats: min/max/mean of this Vec lazily computed. */ private double _min, _max, _mean, _sigma; long _size; boolean _isInt; /** The count of missing elements.... or -2 if we have active writers and no * rollup info can be computed (because the vector is being rapidly * modified!), or -1 if rollups have not been computed since the last * modification. */ volatile long _naCnt=-1; /** Maximal size of enum domain */ public static final int MAX_ENUM_SIZE = 10000; /** Main default constructor; requires the caller understand Chunk layout * already, along with count of missing elements. */ public Vec( Key key, long espc[]) { this(key, espc, null); } public Vec( Key key, long espc[], String[] domain) { assert key._kb[0]==Key.VEC; _key = key; _espc = espc; _time = -1; // not-a-time _domain = domain; } protected Vec( Key key, Vec v ) { this(key, v._espc); assert group()==v.group(); } public Vec [] makeZeros(int n){return makeZeros(n,null);} public Vec [] makeZeros(int n, String [][] domain){ return makeCons(n, 0, domain);} public Vec [] makeCons(int n, final long l, String [][] domain){ if( _espc == null ) throw H2O.unimpl(); // need to make espc for e.g. NFSFileVecs! final int nchunks = nChunks(); Key [] keys = group().addVecs(n); final Vec [] vs = new Vec[keys.length]; for(int i = 0; i < vs.length; ++i) vs[i] = new Vec(keys[i],_espc,domain == null?null:domain[i]); new DRemoteTask(){ @Override public void lcompute(){ addToPendingCount(vs.length); for(int i = 0; i < vs.length; ++i){ final int fi = i; new H2O.H2OCountedCompleter(this){ @Override public void compute2(){ long row=0; // Start row Key k; for( int i=0; i<nchunks; i++ ) { long nrow = chunk2StartElem(i+1); // Next row if((k = vs[fi].chunkKey(i)).home()) DKV.put(k,new C0LChunk(l,(int)(nrow-row)),_fs); row = nrow; } tryComplete(); } }.fork(); } tryComplete(); } @Override public final void lonCompletion( CountedCompleter caller ) { Futures fs = new Futures(); for(Vec v:vs) if(v._key.home()) DKV.put(v._key,v,fs); fs.blockForPending(); } @Override public void reduce(DRemoteTask drt){} }.invokeOnAllNodes(); return vs; } /** * Create an array of Vecs from scratch * @param rows Length of each vec * @param cols Number of vecs * @param val Constant value (long) * @param domain Factor levels (for factor columns) * @return Array of Vecs */ static public Vec [] makeNewCons(final long rows, final int cols, final long val, final String [][] domain){ int chunks = Math.min((int)rows, 4*H2O.NUMCPUS*H2O.CLOUD.size()); long[] espc = new long[chunks+1]; for (int i = 0; i<=chunks; ++i) espc[i] = i * rows / chunks; Vec v = new Vec(Vec.newKey(), espc); Vec[] vecs = v.makeCons(cols, val, domain); return vecs; } /** Make a new vector with the same size and data layout as the old one, and * initialized to zero. */ public Vec makeZero() { return makeCon(0); } public Vec makeZero(String[] domain) { return makeCon(0, domain); } /** Make a new vector with the same size and data layout as the old one, and * initialized to a constant. */ public Vec makeCon( final long l ) { return makeCon(l, null); } public Vec makeCon( final long l, String[] domain ) { Futures fs = new Futures(); if( _espc == null ) throw H2O.unimpl(); // need to make espc for e.g. NFSFileVecs! final int nchunks = nChunks(); final Vec v0 = new Vec(group().addVecs(1)[0],_espc, domain); new DRemoteTask(){ @Override public void lcompute(){ long row=0; // Start row Key k; for( int i=0; i<nchunks; i++ ) { long nrow = chunk2StartElem(i+1); // Next row if((k = v0.chunkKey(i)).home()) DKV.put(k,new C0LChunk(l,(int)(nrow-row)),_fs); row = nrow; } tryComplete(); } @Override public void reduce(DRemoteTask drt){} }.invokeOnAllNodes(); DKV.put(v0._key,v0,fs); fs.blockForPending(); return v0; } public Vec makeCon( final double d ) { Futures fs = new Futures(); if( _espc == null ) throw H2O.unimpl(); // need to make espc for e.g. NFSFileVecs! if( (long)d==d ) return makeCon((long)d); final int nchunks = nChunks(); final Vec v0 = new Vec(group().addVecs(1)[0],_espc); new DRemoteTask(){ @Override public void lcompute(){ long row=0; // Start row Key k; for( int i=0; i<nchunks; i++ ) { long nrow = chunk2StartElem(i+1); // Next row if((k = v0.chunkKey(i)).home()) DKV.put(k,new C0DChunk(d,(int)(nrow-row)),_fs); row = nrow; } tryComplete(); } @Override public void reduce(DRemoteTask drt){} }.invokeOnAllNodes(); DKV.put(v0._key,v0,fs); fs.blockForPending(); return v0; } public static Vec makeSeq( int len ) { Futures fs = new Futures(); AppendableVec av = new AppendableVec(VectorGroup.VG_LEN1.addVec()); NewChunk nc = new NewChunk(av,0); for (int r = 0; r < len; r++) nc.addNum(r+1); nc.close(0,fs); Vec v = av.close(fs); fs.blockForPending(); return v; } public static Vec makeConSeq(double x, int len) { Futures fs = new Futures(); AppendableVec av = new AppendableVec(VectorGroup.VG_LEN1.addVec()); NewChunk nc = new NewChunk(av,0); for (int r = 0; r < len; r++) nc.addNum(x); nc.close(0,fs); Vec v = av.close(fs); fs.blockForPending(); return v; } /** Create a new 1-element vector in the shared vector group for 1-element vectors. */ public static Vec make1Elem(double d) { return make1Elem(Vec.VectorGroup.VG_LEN1.addVec(), d); } /** Create a new 1-element vector representing a scalar value. */ public static Vec make1Elem(Key key, double d) { assert key.isVec(); Vec v = new Vec(key,new long[]{0,1}); Futures fs = new Futures(); DKV.put(v.chunkKey(0),new C0DChunk(d,1),fs); DKV.put(key,v,fs); fs.blockForPending(); return v; } /** Create a vector transforming values according given domain map. * @see Vec#makeTransf(int[], int[], String[]) */ public Vec makeTransf(final int[][] map, String[] finalDomain) { return makeTransf(map[0], map[1], finalDomain); } /** * Creates a new transformation from given values to given indexes of * given domain. * @param values values being mapped from * @param indexes values being mapped to * @param domain domain of new vector * @return always return a new vector which maps given values into a new domain */ Vec makeTransf(final int[] values, final int[] indexes, final String[] domain) { if( _espc == null ) throw H2O.unimpl(); Vec v0 = new TransfVec(values, indexes, domain, this._key, group().addVecs(1)[0],_espc); UKV.put(v0._key,v0); return v0; } /** * Makes a new transformation vector with identity mapping. * * @return a new transformation vector * @see Vec#makeTransf(int[], int[], String[]) */ Vec makeIdentityTransf() { assert _domain != null : "Cannot make an identity transformation of non-enum vector!"; return makeTransf(seq(0, _domain.length), null, _domain); } /** * Makes a new transformation vector from given values to * values 0..domain size * @param values values which are mapped from * @param domain target domain which is mapped to * @return a new transformation vector providing mapping between given values and target domain. * @see Vec#makeTransf(int[], int[], String[]) */ Vec makeSimpleTransf(long[] values, String[] domain) { int is[] = new int[values.length]; for( int i=0; i<values.length; i++ ) is[i] = (int)values[i]; return makeTransf(is, null, domain); } /** This Vec does not have dependent hidden Vec it uses. * * @return dependent hidden vector or <code>null</code> */ public Vec masterVec() { return null; } /** * Adapt given vector <code>v</code> to this vector. * I.e., unify domains, compute transformation, and call makeTransf(). * * This vector is a leader - it determines a domain (i.e., {@link #domain()}) and mapping between values stored in vector * and domain values. * The vector <code>v</code> can contain different domain (subset, superset), hence the values stored in the vector * has to be transformed to the values determined by this vector. The resulting vector domain is the * same as this vector domain. * * Always returns a new vector and user's responsibility is delete the vector. * * @param v vector which should be adapter in according this vector. * @param exact should vector match exactly (recommended value is true). * @return a new vector which implements transformation of original values. */ /*// Not used any more in code ?? public Vec adaptTo(Vec v, boolean exact) { assert isInt() : "This vector has to be int/enum vector!"; int[] domain = null; // Compute domain of this vector // - if vector is enum, use domain directly // - if vector is int, then vector numeric domain is collected and transformed to string domain // and then adapted String[] sdomain = (_domain == null) ? Utils.toStringMap(domain = new CollectDomain(this).doAll(this).domain()) // it is number-column : domain(); // it is enum // Compute transformation - domain map - each value in an array is one value from vector domain, its index // represents an index into string domain representation. int[] domMap = Model.getDomainMapping(v._domain, sdomain, exact); if (domain!=null) { // do a mapping from INT -> ENUM -> this vector ENUM domMap = Utils.compose(Utils.mapping(domain), domMap); } return this.makeTransf(domMap, sdomain); }*/ /** Number of elements in the vector. Overridden by subclasses that compute * length in an alternative way, such as file-backed Vecs. */ public long length() { return _espc[_espc.length-1]; } /** Number of chunks. Overridden by subclasses that compute chunks in an * alternative way, such as file-backed Vecs. */ public int nChunks() { return _espc.length-1; } /** Whether or not this column parsed as a time, and if so what pattern was used. */ public final boolean isTime(){ return _time>=0; } public final int timeMode(){ return _time; } public final String timeParse(){ return ParseTime.TIME_PARSE[_time]; } /** Map the integer value for a enum/factor/categorical to it's String. * Error if it is not an ENUM. */ public String domain(long i) { return _domain[(int)i]; } /** Return an array of domains. This is eagerly manifested for enum or * categorical columns. Returns null for non-Enum/factor columns. */ public String[] domain() { return _domain; } /** Returns cardinality for enum domain or -1 for other types. */ public int cardinality() { return isEnum() ? _domain.length : -1; } /** Transform this vector to enum. * If the vector is integer vector then its domain is collected and transformed to * corresponding strings. * If the vector is enum an identity transformation vector is returned. * Transformation is done by a {@link TransfVec} which provides a mapping between values. * * @return always returns a new vector and the caller is responsible for vector deletion! */ public Vec toEnum() { if( isEnum() ) return this.makeIdentityTransf(); // Make an identity transformation of this vector if( !isInt() ) throw new IllegalArgumentException("Enum conversion only works on integer columns"); long[] domain; String[] sdomain = Utils.toString(domain = new CollectDomain(this).doAll(this).domain()); if( domain.length > MAX_ENUM_SIZE ) throw new IllegalArgumentException("Column domain is too large to be represented as an enum: " + domain.length + " > " + MAX_ENUM_SIZE); return this.makeSimpleTransf(domain, sdomain); } /** Default read/write behavior for Vecs. File-backed Vecs are read-only. */ protected boolean readable() { return true ; } /** Default read/write behavior for Vecs. AppendableVecs are write-only. */ protected boolean writable() { return true; } /** Return column min - lazily computed as needed. */ public double min() { return rollupStats()._min; } /** Return column max - lazily computed as needed. */ public double max() { return rollupStats()._max; } /** Return column mean - lazily computed as needed. */ public double mean() { return rollupStats()._mean; } /** Return column standard deviation - lazily computed as needed. */ public double sigma(){ return rollupStats()._sigma; } /** Return column missing-element-count - lazily computed as needed. */ public long naCnt() { return rollupStats()._naCnt; } /** Is all integers? */ public boolean isInt(){return rollupStats()._isInt; } /** Size of compressed vector data. */ public long byteSize(){return rollupStats()._size; } public byte[] hash() { final Vec rst = rollupStats(); final int hi = new Double(rst._mean).hashCode(); final int lo = new Double(rst._sigma).hashCode(); return new byte[]{(byte)(hi >> 3), (byte)(hi >> 2), (byte)(hi >> 1), (byte)(hi >> 0), (byte)(lo >> 3),(byte)(lo >> 2),(byte)(lo >> 1), (byte)(lo >> 0)}; } /** Is the column a factor/categorical/enum? Note: all "isEnum()" columns * are are also "isInt()" but not vice-versa. */ public final boolean isEnum(){return _domain != null;} /** Is the column constant. * <p>Returns true if the column contains only constant values and it is not full of NAs.</p> */ public final boolean isConst() { return min() == max(); } /** Is the column bad. * <p>Returns true if the column is full of NAs.</p> */ public final boolean isBad() { return naCnt() == length(); } /** Is the column contains float values. */ public final boolean isFloat() { return !isEnum() && !isInt(); } public final boolean isByteVec() { return (this instanceof ByteVec); } Vec setRollupStats( RollupStats rs ) { _min = rs._min; _max = rs._max; _mean = rs._mean; _sigma = Math.sqrt(rs._sigma / (rs._rows - 1)); _size =rs._size; _isInt= rs._isInt; if( rs._rows == 0 ) // All rows missing? Then no rollups _min = _max = _mean = _sigma = Double.NaN; _naCnt= rs._naCnt; // Volatile write last to announce all stats ready return this; } Vec setRollupStats( Vec v ) { _min = v._min; _max = v._max; _mean = v._mean; _sigma = v._sigma; _size = v._size; _isInt = v._isInt; _naCnt= v._naCnt; // Volatile write last to announce all stats ready return this; } /** Compute the roll-up stats as-needed, and copy into the Vec object */ public Vec rollupStats() { return rollupStats(null); } // Allow a bunch of rollups to run in parallel. If Futures is passed in, run // the rollup in the background. *Always* returns "this". public Vec rollupStats(Futures fs) { Vec vthis = DKV.get(_key).get(); if( vthis._naCnt==-2 ) throw new IllegalArgumentException("Cannot ask for roll-up stats while the vector is being actively written."); if( vthis._naCnt>= 0 ) // KV store has a better answer return vthis == this ? this : setRollupStats(vthis); // KV store reports we need to recompute RollupStats rs = new RollupStats().dfork(this); if(fs != null) fs.add(rs); else setRollupStats(rs.getResult()); return this; } /** A private class to compute the rollup stats */ private static class RollupStats extends MRTask2<RollupStats> { double _min=Double.MAX_VALUE, _max=-Double.MAX_VALUE, _mean, _sigma; long _rows, _naCnt, _size; boolean _isInt=true; @Override public void postGlobal(){ final RollupStats rs = this; _fr.vecs()[0].setRollupStats(rs); // Now do this remotely also new TAtomic<Vec>() { @Override public Vec atomic(Vec v) { if( v!=null && v._naCnt == -1 ) v.setRollupStats(rs); return v; } }.fork(_fr._keys[0]); } @Override public void map( Chunk c ) { _size = c.byteSize(); for( int i=0; i<c._len; i++ ) { double d = c.at0(i); long v = Double.doubleToRawLongBits(d); if( Double.isNaN(d) ) _naCnt++; else { if( d < _min ) _min = d; if( d > _max ) _max = d; _mean += d; _rows++; if( _isInt && ((long)d) != d ) _isInt = false; } } _mean = _mean / _rows; for( int i=0; i<c._len; i++ ) { if( !c.isNA0(i) ) { double d = c.at0(i); _sigma += (d - _mean) * (d - _mean); } } } @Override public void reduce( RollupStats rs ) { _min = Math.min(_min,rs._min); _max = Math.max(_max,rs._max); _naCnt += rs._naCnt; double delta = _mean - rs._mean; if (_rows == 0) { _mean = rs._mean; _sigma = rs._sigma; } else if (rs._rows > 0) { _mean = (_mean*_rows + rs._mean*rs._rows)/(_rows + rs._rows); _sigma = _sigma + rs._sigma + delta*delta * _rows*rs._rows / (_rows+rs._rows); } _rows += rs._rows; _size += rs._size; _isInt &= rs._isInt; } // Just toooo common to report always. Drowning in multi-megabyte log file writes. @Override public boolean logVerbose() { return false; } } /** Writing into this Vector from *some* chunk. Immediately clear all caches * (_min, _max, _mean, etc). Can be called repeatedly from one or all * chunks. Per-chunk row-counts will not be changing, just row contents and * caches of row contents. */ void preWriting( ) { if( _naCnt == -2 ) return; // Already set _naCnt = -2; if( !writable() ) throw new IllegalArgumentException("Vector not writable"); // Set remotely lazily. This will trigger a cloud-wide invalidate of the // existing Vec, and eventually we'll have to load a fresh copy of the Vec // with active writing turned on, and caching disabled. new TAtomic<Vec>() { @Override public Vec atomic(Vec v) { if( v!=null ) v._naCnt=-2; return v; } }.invoke(_key); } /** Stop writing into this Vec. Rollup stats will again (lazily) be computed. */ public void postWrite() { Vec vthis = DKV.get(_key).get(); if( vthis._naCnt==-2 ) { _naCnt = vthis._naCnt=-1; new TAtomic<Vec>() { @Override public Vec atomic(Vec v) { if( v!=null && v._naCnt==-2 ) v._naCnt=-1; return v; } }.invoke(_key); } } /** Convert a row# to a chunk#. For constant-sized chunks this is a little * shift-and-add math. For variable-sized chunks this is a binary search, * with a sane API (JDK has an insane API). Overridden by subclasses that * compute chunks in an alternative way, such as file-backed Vecs. */ int elem2ChunkIdx( long i ) { assert 0 <= i && i < length() : "0 <= "+i+" < "+length(); int lo=0, hi = nChunks(); while( lo < hi-1 ) { int mid = (hi+lo)>>>1; if( i < _espc[mid] ) hi = mid; else lo = mid; } while( _espc[lo+1] == i ) lo++; return lo; } /** Convert a chunk-index into a starting row #. For constant-sized chunks * this is a little shift-and-add math. For variable-sized chunks this is a * table lookup. */ public long chunk2StartElem( int cidx ) { return _espc[cidx]; } /** Number of rows in chunk. Does not fetch chunk content. */ public int chunkLen( int cidx ) { return (int) (_espc[cidx + 1] - _espc[cidx]); } /** Get a Vec Key from Chunk Key, without loading the Chunk */ static public Key getVecKey( Key key ) { assert key._kb[0]==Key.DVEC; byte [] bits = key._kb.clone(); bits[0] = Key.VEC; UDP.set4(bits,6,-1); // chunk return Key.make(bits); } /** Get a Chunk Key from a chunk-index. Basically the index-to-key map. */ public Key chunkKey(int cidx ) { byte [] bits = _key._kb.clone(); bits[0] = Key.DVEC; UDP.set4(bits,6,cidx); // chunk return Key.make(bits); } /** Get a Chunk's Value by index. Basically the index-to-key map, * plus the {@code DKV.get()}. Warning: this pulls the data locally; * using this call on every Chunk index on the same node will * probably trigger an OOM! */ public Value chunkIdx( int cidx ) { Value val = DKV.get(chunkKey(cidx)); assert checkMissing(cidx,val); return val; } protected boolean checkMissing(int cidx, Value val) { if( val != null ) return true; System.out.println("Error: Missing chunk "+cidx+" for "+_key); return false; } /** Make a new random Key that fits the requirements for a Vec key. */ static public Key newKey(){return newKey(Key.make());} public static final int KEY_PREFIX_LEN = 4+4+1+1; /** Make a new Key that fits the requirements for a Vec key, based on the * passed-in key. Used to make Vecs that back over e.g. disk files. */ static Key newKey(Key k) { byte [] kb = k._kb; byte [] bits = MemoryManager.malloc1(kb.length+KEY_PREFIX_LEN); bits[0] = Key.VEC; bits[1] = -1; // Not homed UDP.set4(bits,2,0); // new group, so we're the first vector UDP.set4(bits,6,-1); // 0xFFFFFFFF in the chunk# area System.arraycopy(kb, 0, bits, 4+4+1+1, kb.length); return Key.make(bits); } /** Make a Vector-group key. */ public Key groupKey(){ byte [] bits = _key._kb.clone(); bits[0] = Key.VGROUP; UDP.set4(bits, 2, -1); UDP.set4(bits, 6, -1); return Key.make(bits); } /** * Get the group this vector belongs to. * In case of a group with only one vector, the object actually does not exist in KV store. * * @return VectorGroup this vector belongs to. */ public final VectorGroup group() { Key gKey = groupKey(); Value v = DKV.get(gKey); if(v != null)return v.get(VectorGroup.class); // no group exists so we have to create one return new VectorGroup(gKey,1); } /** The Chunk for a chunk#. Warning: this loads the data locally! */ public Chunk chunkForChunkIdx(int cidx) { long start = chunk2StartElem(cidx); // Chunk# to chunk starting element# Value dvec = chunkIdx(cidx); // Chunk# to chunk data Chunk c = dvec.get(); // Chunk data to compression wrapper long cstart = c._start; // Read once, since racily filled in Vec v = c._vec; if( cstart == start && v != null) return c; // Already filled-in assert cstart == -1 || v == null; // Was not filled in (everybody racily writes the same start value) c._vec = this; // Fields not filled in by unpacking from Value c._start = start; // Fields not filled in by unpacking from Value return c; } /** The Chunk for a row#. Warning: this loads the data locally! */ private Chunk chunkForRow_impl(long i) { return chunkForChunkIdx(elem2ChunkIdx(i)); } // Cache of last Chunk accessed via at/set api transient Chunk _cache; /** The Chunk for a row#. Warning: this loads the data locally! */ public final Chunk chunkForRow(long i) { Chunk c = _cache; return (c != null && c._chk2==null && c._start <= i && i < c._start+c._len) ? c : (_cache = chunkForRow_impl(i)); } /** Fetch element the slow way, as a long. Floating point values are * silently rounded to an integer. Throws if the value is missing. */ public final long at8( long i ) { return chunkForRow(i).at8(i); } /** Fetch element the slow way, as a double. Missing values are * returned as Double.NaN instead of throwing. */ public final double at( long i ) { return chunkForRow(i).at(i); } /** Fetch the missing-status the slow way. */ public final boolean isNA(long row){ return chunkForRow(row).isNA(row); } /** Write element the VERY slow way, as a long. There is no way to write a * missing value with this call. Under rare circumstances this can throw: * if the long does not fit in a double (value is larger magnitude than * 2^52), AND float values are stored in Vector. In this case, there is no * common compatible data representation. * * NOTE: For a faster way, but still slow, use the Vec.Writer below. * */ public final long set( long i, long l) { Chunk ck = chunkForRow(i); long ret = ck.set(i,l); ck.close(ck.cidx(), null); //slow to do this for every set -> use Writer if writing many values return ret; } /** Write element the VERY slow way, as a double. Double.NaN will be treated as * a set of a missing element. * */ public final double set( long i, double d) { Chunk ck = chunkForRow(i); double ret = ck.set(i,d); ck.close(ck.cidx(), null); //slow to do this for every set -> use Writer if writing many values return ret; } /** Write element the VERY slow way, as a float. Float.NaN will be treated as * a set of a missing element. * */ public final float set( long i, float f) { Chunk ck = chunkForRow(i); float ret = ck.set(i, f); ck.close(ck.cidx(), null); //slow to do this for every set -> use Writer if writing many values return ret; } /** Set the element as missing the VERY slow way. */ public final boolean setNA( long i ) { Chunk ck = chunkForRow(i); boolean ret = ck.setNA(i); ck.close(ck.cidx(), null); //slow to do this for every set -> use Writer if writing many values return ret; } /** * More efficient way to write randomly to a Vec - still slow, but much faster than Vec.set() * * Usage: * Vec.Writer vw = vec.open(); * vw.set(0, 3.32); * vw.set(1, 4.32); * vw.set(2, 5.32); * vw.close(); */ public final static class Writer { Vec _vec; private Writer(Vec v){ _vec=v; _vec.preWriting(); } public final long set( long i, long l) { return _vec.chunkForRow(i).set(i,l); } public final double set( long i, double d) { return _vec.chunkForRow(i).set(i,d); } public final float set( long i, float f) { return _vec.chunkForRow(i).set(i,f); } public final boolean setNA( long i ) { return _vec.chunkForRow(i).setNA(i); } public void close() { _vec.close(); _vec.postWrite(); } } public final Writer open() { return new Writer(this); } /** Close all chunks that are local (not just the ones that are homed) * This should only be called from a Writer object * */ private final void close() { int nc = nChunks(); for( int i=0; i<nc; i++ ) { if (H2O.get(chunkKey(i)) != null) { chunkForChunkIdx(i).close(i, null); } } } /** Pretty print the Vec: [#elems, min/mean/max]{chunks,...} */ @Override public String toString() { String s = "["+length()+(_naCnt<0 ? ", {" : ","+_min+"/"+_mean+"/"+_max+", "+PrettyPrint.bytes(_size)+", {"); int nc = nChunks(); for( int i=0; i<nc; i++ ) { s += chunkKey(i).home_node()+":"+chunk2StartElem(i)+":"; // CNC: Bad plan to load remote data during a toString... messes up debug printing // Stupidly chunkForChunkIdx loads all data locally // s += chunkForChunkIdx(i).getClass().getSimpleName().replaceAll("Chunk","")+", "; } return s+"}]"; } public void remove( Futures fs ) { for( int i=0; i<nChunks(); i++ ) UKV.remove(chunkKey(i),fs); } @Override public boolean equals( Object o ) { return o instanceof Vec && ((Vec)o)._key.equals(_key); } @Override public int hashCode() { return _key.hashCode(); } /** Always makes a copy of the given vector which shares the same * group. * * The user is responsible for deleting the returned vector. * * This can be expensive operation since it can force copy of data * among nodes. * * @param vec vector which is intended to be copied * @return a copy of vec which shared the same {@link VectorGroup} with this vector */ public Vec align(final Vec vec) { assert ! this.group().equals(vec.group()) : "Vector align expects a vector from different vector group"; assert this._size == vec._size : "Trying to align vectors with different length!"; Vec avec = makeZero(); // aligned vector new MRTask2() { @Override public void map(Chunk c0) { long srow = c0._start; for (int r = 0; r < c0._len; r++) c0.set0(r, vec.at(srow + r)); } }.doAll(avec); avec._domain = _domain; return avec; } /** * Class representing the group of vectors. * * Vectors from the same group have same distribution of chunks among nodes. * Each vector is member of exactly one group. Default group of one vector * is created for each vector. Group of each vector can be retrieved by * calling group() method; * * The expected mode of operation is that user wants to add new vectors * matching the source. E.g. parse creates several vectors (one for each * column) which are all colocated and are colocated with the original * bytevector. * * To do this, user should first ask for the set of keys for the new vectors * by calling addVecs method on the target group. * * Vectors in the group will have the same keys except for the prefix which * specifies index of the vector inside the group. The only information the * group object carries is it's own key and the number of vectors it * contains(deleted vectors still count). * * Because vectors(and chunks) share the same key-pattern with the group, * default group with only one vector does not have to be actually created, * it is implicit. * * @author tomasnykodym * */ public static class VectorGroup extends Iced { // The common shared vector group for length==1 vectors public static VectorGroup VG_LEN1 = new VectorGroup(); final int _len; final Key _key; private VectorGroup(Key key, int len){_key = key;_len = len;} public VectorGroup() { byte[] bits = new byte[26]; bits[0] = Key.VGROUP; bits[1] = -1; UDP.set4(bits, 2, -1); UDP.set4(bits, 6, -1); UUID uu = UUID.randomUUID(); UDP.set8(bits,10,uu.getLeastSignificantBits()); UDP.set8(bits,18,uu. getMostSignificantBits()); _key = Key.make(bits); _len = 0; } public Key vecKey(int vecId){ byte [] bits = _key._kb.clone(); bits[0] = Key.VEC; UDP.set4(bits,2,vecId); return Key.make(bits); } /** * Task to atomically add vectors into existing group. * @author tomasnykodym */ private static class AddVecs2GroupTsk extends TAtomic<VectorGroup>{ final Key _key; int _n; // INPUT: Keys to allocate; OUTPUT: start of run of keys private AddVecs2GroupTsk(Key key, int n){_key = key; _n = n;} @Override public VectorGroup atomic(VectorGroup old) { int n = _n; // how many // If the old group is missing, assume it is the default group-of-self // (having 1 ID already allocated for self), not a new group with // zero prior vectors. _n = old==null ? 1 : old._len; // start of allocated key run return new VectorGroup(_key, n+_n); } } // reserve range of keys and return index of first new available key public int reserveKeys(final int n){ AddVecs2GroupTsk tsk = new AddVecs2GroupTsk(_key, n); tsk.invoke(_key); return tsk._n; } /** * Gets the next n keys of this group. * Performs atomic update of the group object to assure we get unique keys. * The group size will be updated by adding n. * * @param n number of keys to make * @return arrays of unique keys belonging to this group. */ public Key [] addVecs(final int n){ AddVecs2GroupTsk tsk = new AddVecs2GroupTsk(_key, n); tsk.invoke(_key); Key [] res = new Key[n]; for(int i = 0; i < n; ++i) res[i] = vecKey(i + tsk._n); return res; } /** * Shortcut for addVecs(1). * @see #addVecs(int) */ public Key addVec() { return addVecs(1)[0]; } @Override public String toString() { return "VecGrp "+_key.toString()+", next free="+_len; } @Override public boolean equals( Object o ) { return o instanceof VectorGroup && ((VectorGroup)o)._key.equals(_key); } @Override public int hashCode() { return _key.hashCode(); } } /** Collect numeric domain of given vector */ public static class CollectDomain extends MRTask2<CollectDomain> { transient NonBlockingHashMapLong<Object> _uniques; @Override protected void setupLocal() { _uniques = new NonBlockingHashMapLong(); } public CollectDomain(Vec v) { } @Override public void map(Chunk ys) { for( int row=0; row<ys._len; row++ ) if( !ys.isNA0(row) ) _uniques.put(ys.at80(row),""); } @Override public void reduce(CollectDomain mrt) { if( _uniques == mrt._uniques ) return; _uniques.putAll(mrt._uniques); } @Override public AutoBuffer write( AutoBuffer ab ) { super.write(ab); return ab.putA8(_uniques==null ? null : _uniques.keySetLong()); } @Override public Freezable read( AutoBuffer ab ) { super.read(ab); assert _uniques == null || _uniques.size()==0; long ls[] = ab.getA8(); _uniques = new NonBlockingHashMapLong(); if( ls != null ) for( long l : ls ) _uniques.put(l,""); return this; } @Override public void copyOver(Freezable that) { super.copyOver(that); _uniques = ((CollectDomain)that)._uniques; } /** Returns exact numeric domain of given vector computed by this task. * The domain is always sorted. Hence: * domain()[0] - minimal domain value * domain()[domain().length-1] - maximal domain value */ public long[] domain() { long[] dom = _uniques.keySetLong(); Arrays.sort(dom); return dom; } } }
package com.miviclin.droidengine2d.graphics.textures; /** * TextureRegion representa una region dentro de una textura. * * @author Miguel Vicente Linares * */ public class TextureRegion { // TODO: revisar el calculo de U y V (restar medio texel?) private final GLTexture texture; private float u1; private float v1; private float u2; private float v2; private float x; private float y; private float width; private float height; /** * Crea un nuevo TextureRegion * * @param texture Textura a la que pertenece la region * @param x Posicion de la region en el eje X, relativo a la esquina superior izquierda de la textura (en pixeles) * @param y Posicion de la region en el eje Y, relativo a la esquina superior izquierda de la textura (en pixeles) * @param width Ancho de la region * @param height Alto de la region */ public TextureRegion(GLTexture texture, float x, float y, float width, float height) { if (texture == null) { throw new IllegalArgumentException("texture can not be null"); } this.texture = texture; setWidth(width); setHeight(height); setX(x); setY(y); } /** * Invierte la coordenada U de la region * * @return Devuelve este TextureRegion para poder encadenar llamadas a metodos */ public TextureRegion flipX() { float u = u1; u1 = u2; u2 = u; return this; } /** * Invierte la coordenada V de la region * * @return Devuelve este TextureRegion para poder encadenar llamadas a metodos */ public TextureRegion flipY() { float v = v1; v1 = v2; v2 = v; return this; } /** * Devuelve la textura a la que pertenece esta region * * @return GLTexture */ public final GLTexture getTexture() { return texture; } /** * Devuelve la coordenada U1 de la region. [0..1] * * @return U1 */ public float getU1() { return u1; } /** * Devuelve la coordenada V1 de la region. [0..1] * * @return V1 */ public float getV1() { return v1; } /** * Devuelve la coordenada U2 de la region. [0..1] * * @return U2 */ public float getU2() { return u2; } /** * Devuelve la coordenada V2 de la region. [0..1] * * @return V2 */ public float getV2() { return v2; } /** * Devuelve la posicion en el eje X de la region con respecto a la esquina superior izquierda de la textura, en pixeles * * @return posicion en el eje X */ public final float getX() { return x; } /** * Asigna la posicion en el eje X de la region con respecto a la esquina superior izquierda de la textura, en pixeles * * @param x Nueva posicion en el eje X */ public final void setX(float x) { if (x < 0) { throw new IllegalArgumentException("x must be equal or greater than 0"); } if ((x + width) > texture.getWidth()) { throw new IllegalArgumentException("The TextureRegion must be fully contained inside the texture"); } this.u1 = x / texture.getWidth(); this.u2 = (x + width) / texture.getWidth(); this.x = x; } /** * Devuelve la posicion en el eje Y de la region con respecto a la esquina superior izquierda de la textura, en pixeles * * @return posicion en el eje Y */ public final float getY() { return y; } /** * Asigna la posicion en el eje Y de la region con respecto a la esquina superior izquierda de la textura, en pixeles * * @param y Nueva posicion en el eje Y */ public final void setY(float y) { if (y < 0) { throw new IllegalArgumentException("y must be equal or greater than 0"); } if ((y + height) > texture.getHeight()) { throw new IllegalArgumentException("The TextureRegion must be fully contained inside the texture"); } this.v1 = y / texture.getHeight(); this.v2 = (y + height) / texture.getHeight(); this.y = y; } /** * Devuelve el ancho de la region, en pixeles * * @return ancho de la region */ public final float getWidth() { return width; } /** * Asigna el ancho de la region, en pixeles * * @param width Nuevo ancho */ public final void setWidth(float width) { if (width <= 0) { throw new IllegalArgumentException("width must be greater than 0"); } this.width = width; } /** * Devuelve el alto de la region, en pixeles * * @return alto de la region */ public final float getHeight() { return height; } /** * Asigna el alto de la region, en pixeles * * @param height Nuevo alto */ public final void setHeight(float height) { if (height <= 0) { throw new IllegalArgumentException("height must be greater than 0"); } this.height = height; } }
package com.nietky.librarythingbrowser; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import android.content.Context; import android.widget.ArrayAdapter; import android.widget.SectionIndexer; class SectionIndexingArrayAdapter<T> extends ArrayAdapter<T> implements SectionIndexer { HashMap<String, Integer> sectionsMap = new HashMap<String, Integer>(); ArrayList<String> sectionsList = new ArrayList<String>(); ArrayList<Integer> sectionForPosition = new ArrayList<Integer>(); ArrayList<Integer> positionForSection = new ArrayList<Integer>(); public SectionIndexingArrayAdapter(Context context, int textViewResourceId, List<T> objects) { super(context, textViewResourceId, objects); // Note that List<T> objects has already been sorted alphabetically // e.g. with Collections.sort(objects) **before** being passed to // this constructor. // Figure out what the sections should be (one section per unique // initial letter, to accommodate letters that might be missing, // or characters like ,) for (int i = 0; i < objects.size(); i++) { String objectString = objects.get(i).toString(); if (objectString.length() > 0) { String firstLetter = objectString.substring(0, 1).toUpperCase(); if (!sectionsMap.containsKey(firstLetter)) { sectionsMap.put(firstLetter, sectionsMap.size()); sectionsList.add(firstLetter); } } } // Calculate the section for each position in the list. for (int i = 0; i < objects.size(); i++) { String objectString = objects.get(i).toString(); if (objectString.length() > 0) { String firstLetter = objectString.substring(0, 1).toUpperCase(); if (sectionsMap.containsKey(firstLetter)) { sectionForPosition.add(sectionsMap.get(firstLetter)); } else sectionForPosition.add(0); } else sectionForPosition.add(0); } // Calculate the first position where each section begins. for (int i = 0; i < sectionsMap.size(); i++) positionForSection.add(0); for (int i = 0; i < sectionsMap.size(); i++) { for (int j = 0; j < objects.size(); j++) { Integer section = sectionForPosition.get(j); if (section == i) { positionForSection.set(i, j); break; } } } } // The interface methods. public int getPositionForSection(int section) { return positionForSection.get(section); } public int getSectionForPosition(int position) { return sectionForPosition.get(position); } public Object[] getSections() { return sectionsList.toArray(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.slidellrobotics.reboundrumble.subsystems; import com.slidellrobotics.reboundrumble.RobotMap; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * * @author gixxy */ public class BalancingGyro extends Subsystem { private Gyro balanceGyro; // Put methods for controlling this subsystem // here. Call these from Commands. public BalancingGyro() { System.out.println("[BalancingGyro] Starting"); balanceGyro = new Gyro(RobotMap.balanceGyro); System.out.println("[BalancingGyro] balanceGyro initialized"); balanceGyro.reset(); System.out.println("[BalancingGyro] balanceGyro reset"); System.out.println("[BalancingGyro] Started"); } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void setZero() { balanceGyro.reset(); //System.out.println("[BalancingGyro] balanceGyro reset"); //uncomment for debugging } public double getAngle() { SmartDashboard.putDouble("Balancing Gyro", balanceGyro.getAngle()); //System.out.println("[BalancingGyro] balanceGyro angle" + balanceGyro.getAngle()); //uncomment for debugging return balanceGyro.getAngle(); } }
package squeek.quakemovement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.math.MathHelper; import api.player.client.ClientPlayerAPI; import api.player.client.ClientPlayerBase; import net.minecraftforge.fml.common.Loader; public class QuakeClientPlayer extends ClientPlayerBase { public boolean didJumpThisTick = false; List<float[]> baseVelocities = new ArrayList<float[]>(); private static Class<?> hudSpeedometer = null; private static Method setDidJumpThisTick = null; private static Method setIsJumping = null; static { try { if (Loader.isModLoaded("Squeedometer")) { hudSpeedometer = Class.forName("squeek.speedometer.HudSpeedometer"); setDidJumpThisTick = hudSpeedometer.getDeclaredMethod("setDidJumpThisTick", new Class<?>[]{boolean.class}); setIsJumping = hudSpeedometer.getDeclaredMethod("setIsJumping", new Class<?>[]{boolean.class}); } } catch (Exception e) { e.printStackTrace(); } } public QuakeClientPlayer(ClientPlayerAPI playerapi) { super(playerapi); } @Override public void moveEntityWithHeading(float sidemove, float forwardmove) { double d0 = this.player.posX; double d1 = this.player.posY; double d2 = this.player.posZ; if ((this.player.capabilities.isFlying || this.player.isElytraFlying()) && this.player.getRidingEntity() == null) super.moveEntityWithHeading(sidemove, forwardmove); else this.quake_moveEntityWithHeading(sidemove, forwardmove); this.player.addMovementStat(this.player.posX - d0, this.player.posY - d1, this.player.posZ - d2); } @Override public void beforeOnLivingUpdate() { this.didJumpThisTick = false; if (setDidJumpThisTick != null) { try { setDidJumpThisTick.invoke(null, false); } catch (Exception e) { } } if (!baseVelocities.isEmpty()) { baseVelocities.clear(); } super.beforeOnLivingUpdate(); } @Override public void onLivingUpdate() { if (setIsJumping != null) { try { setIsJumping.invoke(null, this.playerAPI.getIsJumpingField()); } catch (Exception e) { } } super.onLivingUpdate(); } @Override public void moveFlying(float sidemove, float forwardmove, float wishspeed) { if ((this.player.capabilities.isFlying && this.player.getRidingEntity() == null) || this.player.isInWater()) { super.moveFlying(sidemove, forwardmove, wishspeed); return; } wishspeed *= 2.15f; float[] wishdir = getMovementDirection(sidemove, forwardmove); float[] wishvel = new float[]{wishdir[0] * wishspeed, wishdir[1] * wishspeed}; baseVelocities.add(wishvel); } @Override public void jump() { super.jump(); // undo this dumb thing if (this.player.isSprinting()) { float f = this.player.rotationYaw * 0.017453292F; this.player.motionX += MathHelper.sin(f) * 0.2F; this.player.motionZ -= MathHelper.cos(f) * 0.2F; } quake_Jump(); this.didJumpThisTick = true; if (setDidJumpThisTick != null) { try { setDidJumpThisTick.invoke(null, true); } catch (Exception e) { } } } public double getSpeed() { return MathHelper.sqrt_double(this.player.motionX * this.player.motionX + this.player.motionZ * this.player.motionZ); } public float getSurfaceFriction() { float f2 = 1.0F; if (this.player.onGround) { BlockPos groundPos = new BlockPos(MathHelper.floor_double(this.player.posX), MathHelper.floor_double(this.player.getEntityBoundingBox().minY) - 1, MathHelper.floor_double(this.player.posZ)); Block ground = this.player.worldObj.getBlockState(groundPos).getBlock(); f2 = 1.0F - ground.slipperiness; } return f2; } public float getSlipperiness() { float f2 = 0.91F; if (this.player.onGround) { f2 = 0.54600006F; BlockPos groundPos = new BlockPos(MathHelper.floor_double(this.player.posX), MathHelper.floor_double(this.player.getEntityBoundingBox().minY) - 1, MathHelper.floor_double(this.player.posZ)); Block ground = this.player.worldObj.getBlockState(groundPos).getBlock(); if (ground != null) f2 = ground.slipperiness * 0.91F; } return f2; } public float minecraft_getMoveSpeed() { float f2 = this.getSlipperiness(); float f3 = 0.16277136F / (f2 * f2 * f2); return this.player.getAIMoveSpeed() * f3; } public float[] getMovementDirection(float sidemove, float forwardmove) { float f3 = sidemove * sidemove + forwardmove * forwardmove; float[] dir = {0.0F, 0.0F}; if (f3 >= 1.0E-4F) { f3 = MathHelper.sqrt_float(f3); if (f3 < 1.0F) { f3 = 1.0F; } f3 = 1.0F / f3; sidemove *= f3; forwardmove *= f3; float f4 = MathHelper.sin(this.player.rotationYaw * (float) Math.PI / 180.0F); float f5 = MathHelper.cos(this.player.rotationYaw * (float) Math.PI / 180.0F); dir[0] = (sidemove * f5 - forwardmove * f4); dir[1] = (forwardmove * f5 + sidemove * f4); } return dir; } public float quake_getMoveSpeed() { float baseSpeed = this.player.getAIMoveSpeed(); return !this.player.isSneaking() ? baseSpeed * 2.15F : baseSpeed * 1.11F; } public float quake_getMaxMoveSpeed() { float baseSpeed = this.player.getAIMoveSpeed(); return baseSpeed * 2.15F; } private void spawnBunnyhopParticles(int numParticles) { // taken from sprint int j = MathHelper.floor_double(this.player.posX); int i = MathHelper.floor_double(this.player.posY - 0.20000000298023224D - this.player.getYOffset()); int k = MathHelper.floor_double(this.player.posZ); IBlockState blockState = this.player.worldObj.getBlockState(new BlockPos(j, i, k)); if (blockState.getRenderType() != EnumBlockRenderType.INVISIBLE) { for (int iParticle = 0; iParticle < numParticles; iParticle++) { this.player.worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, this.player.posX + (this.playerAPI.getRandField().nextFloat() - 0.5D) * this.player.width, this.player.getEntityBoundingBox().minY + 0.1D, this.player.posZ + (this.playerAPI.getRandField().nextFloat() - 0.5D) * this.player.width, -this.player.motionX * 4.0D, 1.5D, -this.player.motionZ * 4.0D, new int[] {Block.getStateId(blockState)}); } } } public boolean isJumping() { return this.playerAPI.getIsJumpingField(); } private void minecraft_ApplyGravity() { if (this.player.worldObj.isRemote && (!this.player.worldObj.isBlockLoaded(new BlockPos((int)this.player.posX, 0, (int)this.player.posZ)) || !this.player.worldObj.getChunkFromBlockCoords(new BlockPos((int) this.player.posX, (int) this.player.posY, (int) this.player.posZ)).isLoaded())) { if (this.player.posY > 0.0D) { this.player.motionY = -0.1D; } else { this.player.motionY = 0.0D; } } else { // gravity this.player.motionY -= 0.08D; } // air resistance this.player.motionY *= 0.9800000190734863D; } private void minecraft_ApplyFriction(float momentumRetention) { this.player.motionX *= momentumRetention; this.player.motionZ *= momentumRetention; } private void minecraft_ApplyLadderPhysics() { if (this.player.isOnLadder()) { float f5 = 0.15F; if (this.player.motionX < (-f5)) { this.player.motionX = (-f5); } if (this.player.motionX > f5) { this.player.motionX = f5; } if (this.player.motionZ < (-f5)) { this.player.motionZ = (-f5); } if (this.player.motionZ > f5) { this.player.motionZ = f5; } this.player.fallDistance = 0.0F; if (this.player.motionY < -0.15D) { this.player.motionY = -0.15D; } boolean flag = this.player.isSneaking(); if (flag && this.player.motionY < 0.0D) { this.player.motionY = 0.0D; } } } private void minecraft_ClimbLadder() { if (this.player.isCollidedHorizontally && this.player.isOnLadder()) { this.player.motionY = 0.2D; } } private void minecraft_SwingLimbsBasedOnMovement() { this.player.prevLimbSwingAmount = this.player.limbSwingAmount; double d0 = this.player.posX - this.player.prevPosX; double d1 = this.player.posZ - this.player.prevPosZ; float f6 = MathHelper.sqrt_double(d0 * d0 + d1 * d1) * 4.0F; if (f6 > 1.0F) { f6 = 1.0F; } this.player.limbSwingAmount += (f6 - this.player.limbSwingAmount) * 0.4F; this.player.limbSwing += this.player.limbSwingAmount; } private void minecraft_WaterMove(float sidemove, float forwardmove) { double d0 = this.player.posY; this.player.moveRelative(sidemove, forwardmove, 0.04F); this.player.moveEntity(this.player.motionX, this.player.motionY, this.player.motionZ); this.player.motionX *= 0.800000011920929D; this.player.motionY *= 0.800000011920929D; this.player.motionZ *= 0.800000011920929D; this.player.motionY -= 0.02D; if (this.player.isCollidedHorizontally && this.player.isOffsetPositionInLiquid(this.player.motionX, this.player.motionY + 0.6000000238418579D - this.player.posY + d0, this.player.motionZ)) { this.player.motionY = 0.30000001192092896D; } } public void minecraft_moveEntityWithHeading(float sidemove, float forwardmove) { // take care of water and lava movement using default code if ((this.player.isInWater() && !this.player.capabilities.isFlying) || (this.player.isInLava() && !this.player.capabilities.isFlying)) { super.moveEntityWithHeading(sidemove, forwardmove); } else { // get friction float momentumRetention = this.getSlipperiness(); // alter motionX/motionZ based on desired movement this.player.moveRelative(sidemove, forwardmove, this.minecraft_getMoveSpeed()); // make adjustments for ladder interaction minecraft_ApplyLadderPhysics(); // do the movement this.player.moveEntity(this.player.motionX, this.player.motionY, this.player.motionZ); // climb ladder here for some reason minecraft_ClimbLadder(); // gravity + friction minecraft_ApplyGravity(); minecraft_ApplyFriction(momentumRetention); // swing them arms minecraft_SwingLimbsBasedOnMovement(); } } /** * Moves the entity based on the specified heading. Args: strafe, forward */ public void quake_moveEntityWithHeading(float sidemove, float forwardmove) { // take care of lava movement using default code if ((this.player.isInLava() && !this.player.capabilities.isFlying)) { super.moveEntityWithHeading(sidemove, forwardmove); return; } else if (this.player.isInWater() && !this.player.capabilities.isFlying) { if (ModConfig.SHARKING_ENABLED) quake_WaterMove(sidemove, forwardmove); else { super.moveEntityWithHeading(sidemove, forwardmove); return; } } else { // get all relevant movement values float wishspeed = (sidemove != 0.0F || forwardmove != 0.0F) ? this.quake_getMoveSpeed() : 0.0F; float[] wishdir = this.getMovementDirection(sidemove, forwardmove); boolean onGroundForReal = this.player.onGround && !this.isJumping(); float momentumRetention = this.getSlipperiness(); // ground movement if (onGroundForReal) { // apply friction before acceleration so we can accelerate back up to maxspeed afterwards //quake_Friction(); // buggy because material-based friction uses a totally different format minecraft_ApplyFriction(momentumRetention); double sv_accelerate = ModConfig.ACCELERATE; if (wishspeed != 0.0F) { // alter based on the surface friction sv_accelerate *= this.minecraft_getMoveSpeed() * 2.15F / wishspeed; quake_Accelerate(wishspeed, wishdir[0], wishdir[1], sv_accelerate); } if (!baseVelocities.isEmpty()) { float speedMod = wishspeed / quake_getMaxMoveSpeed(); // add in base velocities for (float[] baseVel : baseVelocities) { this.player.motionX += baseVel[0] * speedMod; this.player.motionZ += baseVel[1] * speedMod; } } } // air movement else { double sv_airaccelerate = ModConfig.AIR_ACCELERATE; quake_AirAccelerate(wishspeed, wishdir[0], wishdir[1], sv_airaccelerate); if (ModConfig.SHARKING_ENABLED && ModConfig.SHARKING_SURFACE_TENSION > 0.0D && this.playerAPI.getIsJumpingField() && this.player.motionY < 0.0F) { AxisAlignedBB axisalignedbb = this.player.getEntityBoundingBox().offset(this.player.motionX, this.player.motionY, this.player.motionZ); boolean isFallingIntoWater = this.player.worldObj.containsAnyLiquid(axisalignedbb); if (isFallingIntoWater) this.player.motionY *= ModConfig.SHARKING_SURFACE_TENSION; } } // make adjustments for ladder interaction minecraft_ApplyLadderPhysics(); // apply velocity this.player.moveEntity(this.player.motionX, this.player.motionY, this.player.motionZ); // climb ladder here for some reason minecraft_ClimbLadder(); // HL2 code applies half gravity before acceleration and half after acceleration, but this seems to work fine minecraft_ApplyGravity(); } // swing them arms minecraft_SwingLimbsBasedOnMovement(); } private void quake_Jump() { quake_ApplySoftCap(this.quake_getMaxMoveSpeed()); boolean didTrimp = quake_DoTrimp(); if (!didTrimp) { quake_ApplyHardCap(this.quake_getMaxMoveSpeed()); } } private boolean quake_DoTrimp() { if (ModConfig.TRIMPING_ENABLED && this.player.isSneaking()) { double curspeed = this.getSpeed(); float movespeed = this.quake_getMaxMoveSpeed(); if (curspeed > movespeed) { double speedbonus = curspeed / movespeed * 0.5F; if (speedbonus > 1.0F) speedbonus = 1.0F; this.player.motionY += speedbonus * curspeed * ModConfig.TRIMP_MULTIPLIER; if (ModConfig.TRIMP_MULTIPLIER > 0) { float mult = 1.0f / ModConfig.TRIMP_MULTIPLIER; this.player.motionX *= mult; this.player.motionZ *= mult; } spawnBunnyhopParticles(30); return true; } } return false; } private void quake_ApplyWaterFriction(double friction) { this.player.motionX *= friction; this.player.motionY *= friction; this.player.motionZ *= friction; newspeed = speed - 0.05F * speed * friction; //* player->m_surfaceFriction; float mult = newspeed/speed; this.player.motionX *= mult; this.player.motionY *= mult; this.player.motionZ *= mult; } return newspeed; */ /* // slow in water this.player.motionX *= 0.800000011920929D; this.player.motionY *= 0.800000011920929D; this.player.motionZ *= 0.800000011920929D; */ } @SuppressWarnings("unused") private void quake_WaterAccelerate(float wishspeed, float speed, double wishX, double wishZ, double accel) { float addspeed = wishspeed - speed; if (addspeed > 0) { float accelspeed = (float) (accel * wishspeed * 0.05F); if (accelspeed > addspeed) { accelspeed = addspeed; } this.player.motionX += accelspeed * wishX; this.player.motionZ += accelspeed * wishZ; } } private void quake_WaterMove(float sidemove, float forwardmove) { double lastPosY = this.player.posY; // get all relevant movement values float wishspeed = (sidemove != 0.0F || forwardmove != 0.0F) ? this.quake_getMaxMoveSpeed() : 0.0F; float[] wishdir = this.getMovementDirection(sidemove, forwardmove); boolean isSharking = this.isJumping() && this.player.isOffsetPositionInLiquid(0.0D, 1.0D, 0.0D); double curspeed = this.getSpeed(); if (!isSharking || curspeed < 0.078F) { minecraft_WaterMove(sidemove, forwardmove); } else { if (curspeed > 0.09) quake_ApplyWaterFriction(ModConfig.SHARKING_WATER_FRICTION); if (curspeed > 0.098) quake_AirAccelerate(wishspeed, wishdir[0], wishdir[1], ModConfig.ACCELERATE); else quake_Accelerate(.0980F, wishdir[0], wishdir[1], ModConfig.ACCELERATE); this.player.moveEntity(this.player.motionX, this.player.motionY, this.player.motionZ); this.player.motionY = 0.0D; } // water jump if (this.player.isCollidedHorizontally && this.player.isOffsetPositionInLiquid(this.player.motionX, this.player.motionY + 0.6000000238418579D - this.player.posY + lastPosY, this.player.motionZ)) { this.player.motionY = 0.30000001192092896D; } if (!baseVelocities.isEmpty()) { float speedMod = wishspeed / quake_getMaxMoveSpeed(); // add in base velocities for (float[] baseVel : baseVelocities) { this.player.motionX += baseVel[0] * speedMod; this.player.motionZ += baseVel[1] * speedMod; } } } private void quake_Accelerate(float wishspeed, double wishX, double wishZ, double accel) { double addspeed, accelspeed, currentspeed; // Determine veer amount // this is a dot product currentspeed = this.player.motionX * wishX + this.player.motionZ * wishZ; // See how much to add addspeed = wishspeed - currentspeed; // If not adding any, done. if (addspeed <= 0) return; // Determine acceleration speed after acceleration accelspeed = accel * wishspeed / getSlipperiness() * 0.05F; // Cap it if (accelspeed > addspeed) accelspeed = addspeed; // Adjust pmove vel. this.player.motionX += accelspeed * wishX; this.player.motionZ += accelspeed * wishZ; } private void quake_AirAccelerate(float wishspeed, double wishX, double wishZ, double accel) { double addspeed, accelspeed, currentspeed; float wishspd = wishspeed; float maxAirAcceleration = (float) ModConfig.MAX_AIR_ACCEL_PER_TICK; if (wishspd > maxAirAcceleration) wishspd = maxAirAcceleration; // Determine veer amount // this is a dot product currentspeed = this.player.motionX * wishX + this.player.motionZ * wishZ; // See how much to add addspeed = wishspd - currentspeed; // If not adding any, done. if (addspeed <= 0) return; // Determine acceleration speed after acceleration accelspeed = accel * wishspeed * 0.05F; // Cap it if (accelspeed > addspeed) accelspeed = addspeed; // Adjust pmove vel. this.player.motionX += accelspeed * wishX; this.player.motionZ += accelspeed * wishZ; } @SuppressWarnings("unused") private void quake_Friction() { double speed, newspeed, control; float friction; float drop; // Calculate speed speed = this.getSpeed(); // If too slow, return if (speed <= 0.0F) { return; } drop = 0.0F; // convars float sv_friction = 1.0F; float sv_stopspeed = 0.005F; float surfaceFriction = this.getSurfaceFriction(); friction = sv_friction * surfaceFriction; // Bleed off some speed, but if we have less than the bleed // threshold, bleed the threshold amount. control = (speed < sv_stopspeed) ? sv_stopspeed : speed; // Add the amount to the drop amount. drop += control * friction * 0.05F; // scale the velocity newspeed = speed - drop; if (newspeed < 0.0F) newspeed = 0.0F; if (newspeed != speed) { // Determine proportion of old speed we are using. newspeed /= speed; // Adjust velocity according to proportion. this.player.motionX *= newspeed; this.player.motionZ *= newspeed; } } private void quake_ApplySoftCap(float movespeed) { float softCapPercent = ModConfig.SOFT_CAP; float softCapDegen = ModConfig.SOFT_CAP_DEGEN; if (ModConfig.UNCAPPED_BUNNYHOP_ENABLED) { softCapPercent = 1.0F; softCapDegen = 1.0F; } float speed = (float) (this.getSpeed()); float softCap = movespeed * softCapPercent; // apply soft cap first; if soft -> hard is not done, then you can continually trigger only the hard cap and stay at the hard cap if (speed > softCap) { if (softCapDegen != 1.0F) { float applied_cap = (speed - softCap) * softCapDegen + softCap; float multi = applied_cap / speed; this.player.motionX *= multi; this.player.motionZ *= multi; } spawnBunnyhopParticles(10); } } private void quake_ApplyHardCap(float movespeed) { if (ModConfig.UNCAPPED_BUNNYHOP_ENABLED) return; float hardCapPercent = ModConfig.HARD_CAP; float speed = (float) (this.getSpeed()); float hardCap = movespeed * hardCapPercent; if (speed > hardCap && hardCap != 0.0F) { float multi = hardCap / speed; this.player.motionX *= multi; this.player.motionZ *= multi; spawnBunnyhopParticles(30); } } @SuppressWarnings("unused") private void quake_OnLivingUpdate() { this.didJumpThisTick = false; } }
package de.markusfisch.android.shadereditor; import android.content.SharedPreferences; import android.database.Cursor; import android.preference.PreferenceManager; import android.service.wallpaper.WallpaperService; import android.view.MotionEvent; import android.view.SurfaceHolder; public class ShaderWallpaperService extends WallpaperService { @Override public final Engine onCreateEngine() { return new ShaderWallpaperEngine(); } private class ShaderWallpaperEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener { private ShaderWallpaperView view = null; private String fragmentShader = null; public ShaderWallpaperEngine() { super(); PreferenceManager.setDefaultValues( ShaderWallpaperService.this, R.xml.preferences, false ); SharedPreferences p = ShaderWallpaperService.this.getSharedPreferences( ShaderPreferenceActivity.SHARED_PREFERENCES_NAME, 0 ); p.registerOnSharedPreferenceChangeListener( this ); onSharedPreferenceChanged( p, null ); setTouchEventsEnabled( true ); } @Override public void onSharedPreferenceChanged( SharedPreferences p, String key ) { ShaderDataSource dataSource = new ShaderDataSource( ShaderWallpaperService.this ); dataSource.open(); final long id = Long.parseLong( p.getString( ShaderPreferenceActivity.SHADER, "1" ) ); if( (fragmentShader = dataSource.getShader( id )) == null ) { Cursor c = dataSource.getRandomShader(); if( c != null ) { fragmentShader = c.getString( c.getColumnIndex( ShaderDataSource.COLUMN_SHADER ) ); ShaderListPreference.saveShader( p, c.getLong( c.getColumnIndex( ShaderDataSource.COLUMN_ID ) ) ); } } if( view != null ) view.renderer.fragmentShader = fragmentShader; dataSource.close(); } @Override public void onCreate( SurfaceHolder holder ) { super.onCreate( holder ); view = new ShaderWallpaperView(); view.renderer.fragmentShader = fragmentShader; } @Override public void onDestroy() { super.onDestroy(); view.destroy(); view = null; } @Override public void onVisibilityChanged( boolean visible ) { super.onVisibilityChanged( visible ); if( visible ) { view.onResume(); view.requestRender(); } else view.onPause(); } @Override public void onTouchEvent( MotionEvent e ) { super.onTouchEvent( e ); view.renderer.onTouch( e.getX(), e.getY() ); } @Override public void onOffsetsChanged( float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels ) { view.renderer.offset[0] = xOffset; view.renderer.offset[1] = yOffset; } private class ShaderWallpaperView extends ShaderView { public ShaderWallpaperView() { super( ShaderWallpaperService.this ); } @Override public final SurfaceHolder getHolder() { return ShaderWallpaperEngine.this.getSurfaceHolder(); } public void destroy() { super.onDetachedFromWindow(); } } } }
package net.psexton.missinghttp; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * MatlabShim - MATLAB shim for missing-http. * Because #twatlab, it is problematic for long-lived java objects to * stick around that MATLAB allocated. So instead we provide object-free static * functionality. * * Each MATLAB function has a corresponding static method in this class. * All arguments are passed in as Strings. varargs is used for additional headers. * Because we really don't want to return "custom" objects (see previous paragraph) * all return values are strings. Integer response codes are returned as Strings. * Response code / response body pairs are returned as a String[]. * * @author PSexton */ public class MatlabShim { // Private constructor to prevent instantiation private MatlabShim() {}; public static String fileGet(String url, String filePath, String... headers) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet(url); // Set request headers request.addHeader("Accept", ContentType.APPLICATION_OCTET_STREAM.toString()); if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response. // Get the respone status code first. If it's not 200, don't bother // with the response body. int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { HttpEntity responseEntity = response.getEntity(); try (FileOutputStream destStream = new FileOutputStream(new File(filePath))) { responseEntity.writeTo(destStream); } } else { EntityUtils.consume(response.getEntity()); // Consume the response so we can reuse the connection } // Package it up for MATLAB. String returnVal = Integer.toString(statusCode); return returnVal; } } } public static String[] filePut(String url, File source, String... headers) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPut request = new HttpPut(url); // Set request body FileEntity requestEntity = new FileEntity(source, ContentType.APPLICATION_OCTET_STREAM); request.setEntity(requestEntity); // Set request headers request.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); // Package it up for MATLAB. String[] returnVal = {Integer.toString(statusCode), responseBody}; return returnVal; } } } public static String head(String url, String... headers) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpHead request = new HttpHead(url); // Set request headers if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response int statusCode = response.getStatusLine().getStatusCode(); // Package it up for MATLAB. String returnVal = Integer.toString(statusCode); return returnVal; } } } public static String[] jsonGet(String url, String... headers) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet(url); // Set request headers request.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); // Package it up for MATLAB. String[] returnVal = {Integer.toString(statusCode), responseBody}; return returnVal; } } } public static String[] jsonPost(String url, String requestBody, String... headers) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost request = new HttpPost(url); // Set request body StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); request.setEntity(requestEntity); // Set request headers request.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); // Package it up for MATLAB. String[] returnVal = {Integer.toString(statusCode), responseBody}; return returnVal; } } } public static String[] jsonPut(String url, String requestBody, String... headers) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPut request = new HttpPut(url); // Set request body StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); request.setEntity(requestEntity); // Set request headers request.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); // Package it up for MATLAB. String[] returnVal = {Integer.toString(statusCode), responseBody}; return returnVal; } } } /** * * @param url * @param requestParts Each request part is a string, with newlines separating the type, name, and body * @param headers * @return * @throws java.io.IOException */ public static String[] multipartPost(String url, String[] requestParts, String... headers) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost request = new HttpPost(url); // Set request headers request.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Set request body // The most difficult part here is undoing the string mangling // that #twatlab forced us to do. // Actually doing a multi-part post isn't that much more difficult // than a single-part request. HttpComponents is awesome. MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for(String part : requestParts) { String[] partParts = part.split("\n", 3); // If there are newlines in partBody, leave them alone if(partParts.length != 3) { throw new IllegalArgumentException("RequestPart " + prettifyRequestPart(part) + " has " + partParts.length + " lines (expected 3)."); } String partType = partParts[0]; String partName = partParts[1]; String partBody = partParts[2]; switch(partType) { case "file": FileBody fileBody = new FileBody(new File(partBody)); builder.addPart(partName, fileBody); break; case "json": StringBody jsonBody = new StringBody(partBody, ContentType.APPLICATION_JSON); builder.addPart(partName, jsonBody); break; case "string": StringBody stringBody = new StringBody(partBody, ContentType.DEFAULT_TEXT); builder.addPart(partName, (ContentBody) stringBody); break; default: throw new IllegalArgumentException("RequestPart " + prettifyRequestPart(part) + " has an unsupported type (expected \"file\", \"json\", or \"string\")."); } } request.setEntity(builder.build()); // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); // Package it up for MATLAB. String[] returnVal = {Integer.toString(statusCode), responseBody}; return returnVal; } } } /** * Utility for printing error messages from multipartPost * @param part * @return */ private static String prettifyRequestPart(String part) { part = part.replace("\n", "\",\""); part = "{\"" + part + "\"}"; return part; } }
package dr.inference.distribution; import dr.inference.model.AbstractModel; import dr.inference.model.Model; import dr.inference.model.Parameter; import dr.inference.model.Variable; import dr.math.UnivariateFunction; import dr.math.distributions.InverseGaussianDistribution; import dr.xml.*; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * @author Wai Lok Sibon Li * @version $Id: InverseGaussianDistributionModel.java,v 1.8 2009/03/30 20:25:59 rambaut Exp $ */ public class InverseGaussianDistributionModel extends AbstractModel implements ParametricDistributionModel { public static final String INVERSEGAUSSIAN_DISTRIBUTION_MODEL = "inverseGaussianDistributionModel"; public static final String MEAN = "mean"; public static final String STDEV = "stdev"; public static final String SHAPE = "shape"; public static final String OFFSET = "offset"; /** * @param meanParameter the mean, mu * @param igParameter either the standard deviation parameter, sigma or the shape parameter, lamba * @param offset offset of the distribution * @param useShape whether shape or stdev is used */ public InverseGaussianDistributionModel(Parameter meanParameter, Parameter igParameter, double offset, boolean useShape) { super(INVERSEGAUSSIAN_DISTRIBUTION_MODEL); if(useShape) { this.shapeParameter = igParameter; this.stdevParameter = null; addVariable(shapeParameter); this.shapeParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); } else { this.stdevParameter = igParameter; this.shapeParameter = null; addVariable(stdevParameter); this.stdevParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); } this.meanParameter = meanParameter; addVariable(meanParameter); this.offset = offset; this.meanParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); } public final double getS() { if(stdevParameter==null) { return Math.sqrt(InverseGaussianDistribution.variance(getM(), getShape())); } return stdevParameter.getParameterValue(0); } public final void setS(double S) { if(stdevParameter==null) { throw new RuntimeException("Standard deviation parameter is not being used"); } else { stdevParameter.setParameterValue(0, S); } } public final Parameter getSParameter() { if(stdevParameter==null) { throw new RuntimeException("Standard deviation parameter is not being used"); } return stdevParameter; } public final double getShape() { if(shapeParameter == null) { double shape = (getM() * getM() * getM()) / (getS() * getS()); return shape; } return shapeParameter.getParameterValue(0); } public final void setShape(double shape) { if(shapeParameter==null) { throw new RuntimeException("Shape parameter is not being used"); } else { shapeParameter.setParameterValue(0, shape); } } public final Parameter getShapeParameter() { if(shapeParameter==null) { throw new RuntimeException("Shape parameter is not being used"); } return shapeParameter; } /* Unused method */ //private double getStDev() { //return Math.sqrt(InverseGaussianDistribution.variance(getM(), getShape()));//Math.sqrt((getM()*getM()*getM())/getShape()); /** * @return the mean */ public final double getM() { return meanParameter.getParameterValue(0); } public final void setM(double M) { meanParameter.setParameterValue(0, M); //double shape = (getM() * getM() * getM()) / (getS() * getS()); //setShape(shape); } public final Parameter getMParameter() { return meanParameter; } // Interface Distribution public double pdf(double x) { if (x - offset <= 0.0) return 0.0; return InverseGaussianDistribution.pdf(x - offset, getM(), getShape()); } public double logPdf(double x) { if (x - offset <= 0.0) return Double.NEGATIVE_INFINITY; return InverseGaussianDistribution.logPdf(x - offset, getM(), getShape()); } public double cdf(double x) { if (x - offset <= 0.0) return 0.0; return InverseGaussianDistribution.cdf(x - offset, getM(), getShape()); } public double quantile(double y) { return InverseGaussianDistribution.quantile(y, getM(), getShape()) + offset; } /** * @return the mean of the distribution */ public double mean() { //return InverseGaussianDistribution.mean(getM(), getShape()) + offset; return getM() + offset; } /** * @return the variance of the distribution. */ public double variance() { //return InverseGaussianDistribution.variance(getM(), getShape()); return getS() * getS(); } public final UnivariateFunction getProbabilityDensityFunction() { return pdfFunction; } private final UnivariateFunction pdfFunction = new UnivariateFunction() { public final double evaluate(double x) { System.out.println("just checking if this ever gets used anyways... probably have to change the getLowerBound in LogNormalDistributionModel if it does"); return pdf(x); } public final double getLowerBound() { return 0.0; //return Double.NEGATIVE_INFINITY; } public final double getUpperBound() { return Double.POSITIVE_INFINITY; } }; // Interface Model public void handleModelChangedEvent(Model model, Object object, int index) { // no intermediates need to be recalculated... } public void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { // no intermediates need to be recalculated... } protected void storeState() { } // no additional state needs storing protected void restoreState() { } // no additional state needs restoring protected void acceptState() { } // no additional state needs accepting // XMLElement IMPLEMENTATION public Element createElement(Document document) { throw new RuntimeException("Not implemented!"); } /** * Reads an inverse gaussian distribution model from a DOM Document element. */ public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return INVERSEGAUSSIAN_DISTRIBUTION_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { Parameter meanParam; double offset = xo.getAttribute(OFFSET, 0.0); XMLObject cxo = (XMLObject) xo.getChild(MEAN); if (cxo.getChild(0) instanceof Parameter) { meanParam = (Parameter) cxo.getChild(Parameter.class); } else { meanParam = new Parameter.Default(cxo.getDoubleChild(0)); } if(xo.hasChildNamed(STDEV) && xo.hasChildNamed(SHAPE)) { throw new RuntimeException("XML has both standard deviation and shape for Inverse Gaussian distribution"); } else if(xo.hasChildNamed(STDEV)) { Parameter stdevParam; cxo = (XMLObject) xo.getChild(STDEV); if (cxo.getChild(0) instanceof Parameter) { stdevParam = (Parameter) cxo.getChild(Parameter.class); } else { stdevParam = new Parameter.Default(cxo.getDoubleChild(0)); } return new InverseGaussianDistributionModel(meanParam, stdevParam, offset, false); } else if(xo.hasChildNamed(SHAPE)) { Parameter shapeParam; cxo = (XMLObject) xo.getChild(SHAPE); if (cxo.getChild(0) instanceof Parameter) { shapeParam = (Parameter) cxo.getChild(Parameter.class); } else { shapeParam = new Parameter.Default(cxo.getDoubleChild(0)); } return new InverseGaussianDistributionModel(meanParam, shapeParam, offset, true); } else { throw new RuntimeException("XML has neither standard deviation nor shape for Inverse Gaussian distribution"); } }
package com.smartnsoft.droid4me.cache; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.smartnsoft.droid4me.bo.Business; import com.smartnsoft.droid4me.bo.Business.IOStreamer; import com.smartnsoft.droid4me.bo.Business.UriStreamParser; import com.smartnsoft.droid4me.log.Logger; import com.smartnsoft.droid4me.log.LoggerFactory; public final class Values { private final static Logger log = LoggerFactory.getInstance(Values.class); /** * Gathers a business object and its time stamp. */ public static class Info<BusinessObjectType> { public final BusinessObjectType value; public final Date timestamp; private Business.Source source; public Info(BusinessObjectType value, Date timestamp, Business.Source source) { this.value = value; this.timestamp = timestamp; this.source = source; } public Business.Source getSource() { return source; } } /** * Used when requesting a {@link Values.CacheableValue} or a {@link CachedMap} for retrieving a business object, depending on the current workflow. * * @since 2010.09.09 */ public static interface CachingEvent { /** * Is invoked when the wrapped business object is bound to be retrieved from an {@link IOStreamer}, i.e. from the persistence layer. */ void onIOStreamer(Cacher.Status status); /** * Is invoked when the wrapped business object is bound to be retrieved from an {@link UriStreamParser}, i.e. not locally. */ void onUriStreamParser(Cacher.Status status); } /** * Used and required when the business object is not available in memory. */ public static interface Instructions<BusinessObjectType, ExceptionType extends Exception, ProblemExceptionType extends Exception> { /** * States the result of an assessment. * * @see Values.Instructions#assess(Values.Info) */ public static enum Result { Rejected, Accepted } /** * Is invoked every time the business object is tested in order to determine whether it is valid in its current state, or should be reloaded. * * @param info * the proposed business object, its associated timestamp, and source * @return the status which indicates whether the provided business object state has been validated */ Values.Instructions.Result assess(Values.Info<BusinessObjectType> info); /** * Is invoked after each {@link #assess(Values.Info) assessment} and enables to store its result. * * @param source * where the business object comes from * @param result * the result of the assessment */ void remember(Business.Source source, Values.Instructions.Result result); /** * Is invoked when the underlying business object will not be taken from the memory cache, or when the cached value has been rejected. * * @param cachingEvent * the interface that will be used to notify the caller about the loading workflow ; may be {@code null} * @return the wrapped business object that should be attempted to be requested from another place than the cache */ Values.Info<BusinessObjectType> onNotFromLoaded(Values.CachingEvent cachingEvent) throws ExceptionType, ProblemExceptionType; /** * Will be invoked when the business object cannot be eventually retrieved. * * @param causeException * the reason which states why the business object cannot be retrieved * @return an exception to be thrown to the caller */ ProblemExceptionType onUnaccessible(Exception causeException); } public final static class InstructionsException extends Exception { private static final long serialVersionUID = 1724469505270150039L; private InstructionsException(String message) { super(message); } } /** * Defines a basic contract which enables to cache a business object in memory, know when it has been cached, and have a dynamic strategy for * refreshing the object. * * @since 2009.06.18 */ public static interface CacheableValue<BusinessObjectType, ExceptionType extends Exception, ProblemExceptionType extends Exception> { // TODO: document this boolean isEmpty(); BusinessObjectType getLoadedValue(); void setLoadedInfoValue(Values.Info<BusinessObjectType> info); BusinessObjectType getValue(Values.Instructions<BusinessObjectType, ExceptionType, ProblemExceptionType> instructions, Values.CachingEvent cachingEvent) throws ExceptionType, ProblemExceptionType; } /** * Defines a common class for all "cacheables", i.e. {@link CacheableValue} and {@link BackedCachedMap}, so that we can register them. * * @since 2010.06.25 */ public static abstract class Caching { private final static List<Values.Caching> instances = new ArrayList<Values.Caching>(); protected Caching() { Caching.instances.add(this); } /** * Is supposed to empty the underlying cached value(s). Invoking {@link #isEmpty()} afterwards will return <code>true</code. */ public abstract void empty(); /** * Empties all {@link Values.Caching} instances. */ public static synchronized void emptyAll() { for (Values.Caching caching : instances) { caching.empty(); } } } /** * Enables to cache a business object in memory only. * * @since 2009.06.18 */ public static class CachedValue<BusinessObjectType, ExceptionType extends Exception> extends Values.Caching implements Values.CacheableValue<BusinessObjectType, ExceptionType, ExceptionType> { private Values.Info<BusinessObjectType> info; public final boolean isEmpty() { return info == null; } public final Values.Info<BusinessObjectType> getLoadedInfoValue() { return info; } public final BusinessObjectType getLoadedValue() { if (info == null) { return null; } return info.value; } public final void setLoadedInfoValue(Values.Info<BusinessObjectType> info) { this.info = info; } public final Values.Info<BusinessObjectType> getInfoValue(Values.Instructions<BusinessObjectType, ExceptionType, ExceptionType> instructions, Values.CachingEvent cachingEvent) throws ExceptionType { // The business object is first attempted to be retrieved from memory if (isEmpty() == false) { info.source = Business.Source.Memory; final Values.Instructions.Result result = instructions.assess(info); instructions.remember(info.source, result); if (result == Values.Instructions.Result.Accepted) { return getLoadedInfoValue(); } } final Values.Info<BusinessObjectType> newInfo = instructions.onNotFromLoaded(cachingEvent); if (newInfo != null) { // We check whether the newly retrieved info is accepted final Values.Instructions.Result result = instructions.assess(newInfo); instructions.remember(newInfo.source, result); if (result == Values.Instructions.Result.Accepted) { setLoadedInfoValue(newInfo); return newInfo; } else { final Values.Info<BusinessObjectType> reloadedInfo = instructions.onNotFromLoaded(cachingEvent); if (reloadedInfo != null) { setLoadedInfoValue(reloadedInfo); return reloadedInfo; } } } throw instructions.onUnaccessible(new Values.InstructionsException("Cannot access to the live business object when the data should not be taken from the cache!")); } public final BusinessObjectType getValue(Values.Instructions<BusinessObjectType, ExceptionType, ExceptionType> instructions, Values.CachingEvent cachingEvent) throws ExceptionType { final Info<BusinessObjectType> infoValue = getInfoValue(instructions, cachingEvent); return infoValue == null ? null : infoValue.value; } @Override public final void empty() { info = null; } } public final static class CacheException extends Business.BusinessException { private static final long serialVersionUID = -2742319642305884562L; private CacheException(String message, Throwable cause) { super(message, cause); } private CacheException(Throwable cause) { super(cause); } } public abstract static class WithParameterInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> implements Values.Instructions<BusinessObjectType, Values.CacheException, Values.CacheException> { protected final Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher; protected final ParameterType parameter; protected WithParameterInstructions( Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher, ParameterType parameter) { this.cacher = cacher; this.parameter = parameter; } public void remember(Business.Source source, Values.Instructions.Result result) { } public final Values.CacheException onUnaccessible(Exception exception) { return new Values.CacheException("Could not access to the business object neither through the cache nor through the IO streamer", exception); } }; public static class OnlyFromCacheInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> extends WithParameterInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> { private final boolean fromMemory; public OnlyFromCacheInstructions(Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher, ParameterType parameter, boolean fromMemory) { super(cacher, parameter); this.fromMemory = fromMemory; } public Values.Instructions.Result assess(Values.Info<BusinessObjectType> info) { return fromMemory == false ? (info.source == Business.Source.IOStreamer ? Values.Instructions.Result.Accepted : Values.Instructions.Result.Rejected) : Values.Instructions.Result.Accepted; } public Values.Info<BusinessObjectType> onNotFromLoaded(Values.CachingEvent cachingEvent) throws Values.CacheException { try { return cacher.getCachedValue(parameter); } catch (Throwable throwable) { throw new Values.CacheException("Could not read from the cache the business object corresponding to the URI '" + parameter + "'", throwable); } } }; public static class MemoryInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> extends WithParameterInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> { protected final boolean fromCache; protected final Map<Business.Source, Values.Instructions.Result> assessments = new LinkedHashMap<Business.Source, Values.Instructions.Result>(); public MemoryInstructions(Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher, ParameterType parameter, boolean fromCache) { super(cacher, parameter); this.fromCache = fromCache; } @Override public void remember(Business.Source source, Values.Instructions.Result result) { assessments.put(source, result); } public Values.Info<BusinessObjectType> onNotFromLoaded(final Values.CachingEvent cachingEvent) throws Values.CacheException { try { return cacher.getValue(new Cacher.Instructions() { public boolean queryTimestamp() { return assessFromCacher(true, null); } public boolean takeFromCache(Date lastUpdate) { return assessFromCacher(false, lastUpdate); } public void onIOStreamer(Cacher.Status status) { if (cachingEvent != null) { cachingEvent.onIOStreamer(status); } } public void onUriStreamParser(Cacher.Status status) { if (cachingEvent != null) { cachingEvent.onUriStreamParser(status); } } }, parameter); } catch (Throwable throwable) { // TODO: add a flag which controls whether a last attempts should be run // A last attempt is done to retrieve the data from the cache try { return cacher.getValue(new Cacher.Instructions() { public boolean queryTimestamp() { return false; } public boolean takeFromCache(Date lastUpdate) { return true; } public void onIOStreamer(Cacher.Status status) { if (cachingEvent != null) { cachingEvent.onIOStreamer(status); } } public void onUriStreamParser(Cacher.Status status) { if (cachingEvent != null) { cachingEvent.onUriStreamParser(status); } } }, parameter); } catch (Throwable innerThrowable) { throw new Values.CacheException("Could not read the business object corresponding to the URI '" + parameter + "'", innerThrowable); } } } public Values.Instructions.Result assess(Values.Info<BusinessObjectType> info) { return (fromCache == true || (info.source == Business.Source.UriStreamer || assessments.size() >= 1)) ? Values.Instructions.Result.Accepted : Values.Instructions.Result.Rejected; } protected boolean assessFromCacher(boolean queryTimestamp, Date lastUpdate) { if (fromCache == true) { return queryTimestamp == false; } else { if (assessments.containsKey(Business.Source.UriStreamer) == true) { if (assessments.size() == 1) { return false; } else { return queryTimestamp == false; } } else { return false; } } } }; public static class MemoryAndCacheInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> extends MemoryInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> { private final boolean fromMemory; public MemoryAndCacheInstructions(Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher, ParameterType parameter, boolean fromMemory, boolean fromCache) { super(cacher, parameter, fromCache); this.fromMemory = fromMemory; } @Override public Values.Instructions.Result assess(Values.Info<BusinessObjectType> info) { if (fromMemory == true) { return Values.Instructions.Result.Accepted; } else if (fromCache == true) { return info.source != Business.Source.Memory ? Values.Instructions.Result.Accepted : Values.Instructions.Result.Rejected; } else { return (info.source == Business.Source.UriStreamer || assessments.size() >= 1) ? Values.Instructions.Result.Accepted : Values.Instructions.Result.Rejected; } } }; public static class RetentionInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> extends MemoryInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> { private final long cachingPeriodInMilliseconds; public RetentionInstructions(Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher, ParameterType parameter, boolean fromCache, long cachingPeriodInMilliseconds) { super(cacher, parameter, fromCache); this.cachingPeriodInMilliseconds = cachingPeriodInMilliseconds; } @Override public Values.Instructions.Result assess(Values.Info<BusinessObjectType> info) { if (fromCache == false) { return (info.source == Business.Source.UriStreamer || assessments.size() >= 1) ? Values.Instructions.Result.Accepted : Values.Instructions.Result.Rejected; } else { if (cachingPeriodInMilliseconds == -1 || ((System.currentTimeMillis() - info.timestamp.getTime()) <= cachingPeriodInMilliseconds)) { return Values.Instructions.Result.Accepted; } else { return (info.source == Business.Source.UriStreamer || assessments.size() >= 1) ? Values.Instructions.Result.Accepted : Values.Instructions.Result.Rejected; } } } @Override protected boolean assessFromCacher(boolean queryTimestamp, Date lastUpdate) { if (fromCache == true) { if (cachingPeriodInMilliseconds == -1) { return queryTimestamp == false; } else { return queryTimestamp == true ? true : (((System.currentTimeMillis() - lastUpdate.getTime()) <= cachingPeriodInMilliseconds) ? true : false); } } else { if (assessments.containsKey(Business.Source.UriStreamer) == true) { if (assessments.size() == 1) { return false; } else { return queryTimestamp == false; } } else { return false; } } } }; public static class SessionInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> extends WithParameterInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> { public SessionInstructions(Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher, ParameterType parameter) { super(cacher, parameter); } public Values.Instructions.Result assess(Values.Info<BusinessObjectType> info) { return info.source == Business.Source.UriStreamer ? Values.Instructions.Result.Accepted : Values.Instructions.Result.Rejected; } public Values.Info<BusinessObjectType> onNotFromLoaded(Values.CachingEvent cachingEvent) throws Values.CacheException { try { final Values.Info<BusinessObjectType> info = cacher.getValue(parameter); return info; } catch (Throwable throwable) { throw new Values.CacheException("Could not read the business object corresponding to the URI '" + parameter + "'", throwable); } } }; /** * @since 2009.08.31 */ public static class BackedCachedValue<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> extends Values.CachedValue<BusinessObjectType, Values.CacheException> { public final Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher; public BackedCachedValue(Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher) { this.cacher = cacher; } public void setValue(ParameterType parameter, BusinessObjectType businessObject) throws Values.CacheException { final Values.Info<BusinessObjectType> info = new Values.Info<BusinessObjectType>(businessObject, new Date(), Business.Source.Memory); // Even if cacher fails to persist the business object, the memory is up-to-date super.setLoadedInfoValue(info); try { cacher.setValue(parameter, info); } catch (Throwable throwable) { throw new Values.CacheException("Could not save the business object corresponding to the parameter '" + parameter + "'", throwable); } } public final BusinessObjectType safeGet(ParameterType parameter) { return safeGet(true, true, null, parameter); } public final BusinessObjectType safeGet(boolean fromCache, ParameterType parameter) { return safeGet(fromCache, true, null, parameter); } public final BusinessObjectType safeGet(boolean fromMemory, boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) { try { return getMemoryValue(fromMemory, fromCache, cachingEvent, parameter); } catch (Values.CacheException exception) { if (log.isWarnEnabled()) { log.warn("Ignoring the failed reading of the business object with parameter '" + parameter + "': returning the cached value if any", exception); } return getLoadedValue(); } } public final void safeSet(ParameterType parameter, BusinessObjectType businessObject) { try { setValue(parameter, businessObject); } catch (Values.CacheException exception) { if (log.isWarnEnabled()) { log.warn("Ignoring the failed saving of the business object with URI '" + parameter + "'", exception); } } } public final void remove(ParameterType parameter) throws Values.CacheException { try { cacher.remove(parameter); } catch (Throwable throwable) { if (log.isWarnEnabled()) { log.warn("Could not remove from the persistent cache te business object with parameter '" + parameter + "'", throwable); throw new Values.CacheException(throwable); } } setLoadedInfoValue(null); } public final void safeRemove(ParameterType parameter) { try { remove(parameter); } catch (Values.CacheException exception) { if (log.isWarnEnabled()) { log.warn("Ignoring the failed removing of the business object with URI '" + parameter + "'", exception); } } } public final Values.Info<BusinessObjectType> getOnlyFromCacheInfoValue(boolean fromMemory, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.OnlyFromCacheInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromMemory), null); } public final BusinessObjectType getOnlyFromCacheValue(boolean fromMemory, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getOnlyFromCacheInfoValue(fromMemory, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getSessionInfoValue(Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.SessionInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter), cachingEvent); } public final BusinessObjectType getSessionValue(Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getSessionInfoValue(cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getMemoryInfoValue(boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.MemoryInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromCache), cachingEvent); } public final BusinessObjectType getMemoryValue(boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getMemoryInfoValue(fromCache, cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getMemoryInfoValue(boolean fromMemory, boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.MemoryAndCacheInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromMemory, fromCache), cachingEvent); } public final BusinessObjectType getMemoryValue(boolean fromMemory, boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getMemoryInfoValue(fromMemory, fromCache, cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getRetentionInfoValue(boolean fromCache, long cachingPeriodInMilliseconds, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.RetentionInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromCache, cachingPeriodInMilliseconds), cachingEvent); } public final BusinessObjectType getRetentionValue(boolean fromCache, long cachingPeriodInMilliseconds, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getRetentionInfoValue(fromCache, cachingPeriodInMilliseconds, cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } } /** * Enables to cache in memory a map of business objects. * * @since 2009.06.18 */ public static class CachedMap<BusinessObjectType, KeyType, ExceptionType extends Exception> extends Values.Caching { protected final Map<KeyType, Values.CachedValue<BusinessObjectType, ExceptionType>> map = new ConcurrentHashMap<KeyType, Values.CachedValue<BusinessObjectType, ExceptionType>>(); public Values.Info<BusinessObjectType> getInfoValue(Values.Instructions<BusinessObjectType, ExceptionType, ExceptionType> ifValueNotCached, Values.CachingEvent cachingEvent, KeyType key) throws ExceptionType { final Values.CachedValue<BusinessObjectType, ExceptionType> cached; if (map.containsKey(key) == false) { cached = new Values.CachedValue<BusinessObjectType, ExceptionType>(); map.put(key, cached); } else { cached = map.get(key); } return cached.getInfoValue(ifValueNotCached, cachingEvent); } public BusinessObjectType getValue(Values.Instructions<BusinessObjectType, ExceptionType, ExceptionType> ifValueNotCached, Values.CachingEvent cachingEvent, KeyType key) throws ExceptionType { final Values.Info<BusinessObjectType> infoValue = getInfoValue(ifValueNotCached, cachingEvent, key); return infoValue == null ? null : infoValue.value; } /** * This implementation does not empty the {@link Values.CacheableValue} values. * * @see Values.Caching#empty() */ @Override public final void empty() { map.clear(); } } /** * Enables to cache in memory and on persistent cache a map of business objects. * * @since 2009.09.09 */ public static final class BackedCachedMap<BusinessObjectType, UriType, ParameterType, ParseExceptionType extends Exception, StreamerExceptionType extends Throwable, InputExceptionType extends Exception> extends Values.CachedMap<BusinessObjectType, ParameterType, Values.CacheException> { public final Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher; public BackedCachedMap(Cacher<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType> cacher) { this.cacher = cacher; } /** * If two setting and getting methods are called concurrently, the consistency of the results are not granted! */ // TODO: why is this method overloaded? @Override public final BusinessObjectType getValue(Values.Instructions<BusinessObjectType, Values.CacheException, Values.CacheException> instructions, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final boolean toAdd; Values.CachedValue<BusinessObjectType, Values.CacheException> cachedValue = map.get(parameter); if (cachedValue == null) { toAdd = true; cachedValue = new Values.CachedValue<BusinessObjectType, Values.CacheException>(); } else { toAdd = false; } final BusinessObjectType businessObject = cachedValue.getValue(instructions, cachingEvent); if (businessObject != null && toAdd == true) { map.put(parameter, cachedValue); } return businessObject; } public final BusinessObjectType getValue(boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getValue(true, fromCache, cachingEvent, parameter); } public final BusinessObjectType getValue(boolean fromMemory, final boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getValue( new Values.MemoryAndCacheInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromMemory, fromCache), cachingEvent, parameter); } public final BusinessObjectType safeGet(Values.CachingEvent cachingEvent, ParameterType parameter) { return safeGet(true, true, cachingEvent, parameter); } public final BusinessObjectType safeGet(boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) { return safeGet(fromCache, true, cachingEvent, parameter); } public final BusinessObjectType safeGet(boolean fromMemory, boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) { try { return getValue(fromMemory, fromCache, cachingEvent, parameter); } catch (Values.CacheException exception) { if (log.isWarnEnabled()) { log.warn("Ignoring the failed reading of the business object with parameter '" + parameter + "': returning the cached value if any", exception); } return getLoadedValue(parameter); } } public final BusinessObjectType getLoadedValue(ParameterType parameter) { final Values.CachedValue<BusinessObjectType, Values.CacheException> cachedValue; cachedValue = map.get(parameter); if (cachedValue != null) { return cachedValue.getLoadedValue(); } return null; } public final void remove(ParameterType parameter) throws Values.CacheException { try { cacher.remove(parameter); } catch (Throwable throwable) { if (log.isWarnEnabled()) { log.warn("Could not remove from the persistent cache te business object with parameter '" + parameter + "'", throwable); throw new Values.CacheException(throwable); } } // We clean-up the memory cache, only provided the IO streamer has been cleaned-up map.remove(parameter); } public final void safeRemove(ParameterType parameter) { try { remove(parameter); } catch (Values.CacheException exception) { if (log.isWarnEnabled()) { log.warn("Ignoring the failed removing of the business object with URI '" + parameter + "'", exception); } } } public final void setValue(ParameterType parameter, BusinessObjectType businessObject) throws Values.CacheException { final Values.Info<BusinessObjectType> info = new Values.Info<BusinessObjectType>(businessObject, new Date(), Business.Source.Memory); // We modify the memory first, so as to make sure that it is actually modified setLoadedValue(parameter, info); try { cacher.setValue(parameter, info); } catch (Throwable throwable) { throw new Values.CacheException(throwable); } } public final void safeSet(ParameterType parameter, BusinessObjectType businessObject) { try { setValue(parameter, businessObject); } catch (Values.CacheException exception) { if (log.isWarnEnabled()) { log.warn("Failed to save to the cache the business object with parameter '" + parameter + "': only taken into account in memory!", exception); } } } private void setLoadedValue(ParameterType parameter, Values.Info<BusinessObjectType> info) { Values.CachedValue<BusinessObjectType, Values.CacheException> cachedValue = map.get(parameter); if (cachedValue == null) { cachedValue = new Values.CachedValue<BusinessObjectType, Values.CacheException>(); map.put(parameter, cachedValue); } cachedValue.setLoadedInfoValue(info); } public final Values.Info<BusinessObjectType> getOnlyFromCacheInfoValue(boolean fromMemory, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.OnlyFromCacheInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromMemory), cachingEvent, parameter); } public final BusinessObjectType getOnlyFromCacheValue(boolean fromMemory, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getOnlyFromCacheInfoValue(fromMemory, cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getSessionInfoValue(Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.SessionInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter), cachingEvent, parameter); } public final BusinessObjectType getSessionValue(Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getSessionInfoValue(cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getMemoryInfoValue(boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.MemoryInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromCache), cachingEvent, parameter); } public final BusinessObjectType getMemoryValue(boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getMemoryInfoValue(fromCache, cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getMemoryInfoValue(boolean fromMemory, boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.MemoryAndCacheInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromMemory, fromCache), cachingEvent, parameter); } public final BusinessObjectType getMemoryValue(boolean fromMemory, boolean fromCache, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getMemoryInfoValue(fromMemory, fromCache, cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } public final Values.Info<BusinessObjectType> getRetentionInfoValue(boolean fromCache, long cachingPeriodInMilliseconds, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { return getInfoValue( new Values.RetentionInstructions<BusinessObjectType, UriType, ParameterType, ParseExceptionType, StreamerExceptionType, InputExceptionType>(cacher, parameter, fromCache, cachingPeriodInMilliseconds), cachingEvent, parameter); } public final BusinessObjectType getRetentionValue(boolean fromCache, long cachingPeriodInMilliseconds, Values.CachingEvent cachingEvent, ParameterType parameter) throws Values.CacheException { final Values.Info<BusinessObjectType> infoValue = getRetentionInfoValue(fromCache, cachingPeriodInMilliseconds, cachingEvent, parameter); return infoValue == null ? null : infoValue.value; } } }
package edu.clemson.resolve.jetbrains.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Iconable; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.impl.ElementBase; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.RowIcon; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PlatformIcons; import edu.clemson.resolve.jetbrains.RESOLVEIcons; import edu.clemson.resolve.jetbrains.psi.*; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public abstract class ResNamedElementImpl extends ResCompositeElementImpl implements ResCompositeElement, ResNamedElement { public ResNamedElementImpl(@NotNull ASTNode node) { super(node); } @Nullable @Override public PsiElement getNameIdentifier() { return getIdentifier(); } public boolean isPublic() { return true; } @Nullable @Override public String getName() { PsiElement identifier = getIdentifier(); return identifier != null ? identifier.getText() : null; } @NotNull @Override public PsiElement setName( @NonNls @NotNull String newName) throws IncorrectOperationException { PsiElement identifier = getIdentifier(); if (identifier != null) { identifier.replace(ResElementFactory .createIdentifierFromText(getProject(), newName)); } return this; } @Override public int getTextOffset() { PsiElement identifier = getIdentifier(); return identifier != null ? identifier.getTextOffset() : super.getTextOffset(); } @Override public boolean processDeclarations( @NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { return ResCompositeElementImpl.processDeclarationsDefault( this, processor, state, lastParent, place); } @Nullable @Override public ResType getResType( @Nullable ResolveState context) { if (context != null) return getResTypeInner(context); return CachedValuesManager.getCachedValue(this, new CachedValueProvider<ResType>() { @Nullable @Override public Result<ResType> compute() { return Result.create(getResTypeInner(null), PsiModificationTracker.MODIFICATION_COUNT); } }); } @Nullable @Override public ResMathExp getResMathMetaTypeExp( @Nullable ResolveState context) { if (context != null) return getResMathMetaTypeExpInner(context); return CachedValuesManager.getCachedValue(this, new CachedValueProvider<ResMathExp>() { @Nullable @Override public Result<ResMathExp> compute() { return Result.create(getResMathMetaTypeExpInner(null), PsiModificationTracker.MODIFICATION_COUNT); } }); } @Nullable protected ResType getResTypeInner( @Nullable ResolveState context) { return findSiblingType(); } @Nullable @Override public ResType findSiblingType() { return PsiTreeUtil.getNextSiblingOfType(this, ResType.class); } @Nullable protected ResMathExp getResMathMetaTypeExpInner( @Nullable ResolveState context) { ResMathExp nextExp = findSiblingMathMetaType(); return nextExp; } /** Ok, here's the deal: this will basically look to our right hand side * siblings of {@code this} AST (Jetbrains speak: PSI) node for a math exp * and return the first one it finds. * <p> * Here's the thing though, this is * not good/flexible enough since we also want to return a ResType, think * in the case of a parameter decl: there we'll want a ResType, resolve * that, * and get back to the math expr.</p> */ @Nullable @Override public ResMathExp findSiblingMathMetaType() { ResMathExp purelyMathTypeExp = PsiTreeUtil.getNextSiblingOfType(this, ResMathExp.class); if (purelyMathTypeExp != null) return purelyMathTypeExp; //ok, maybe we're dealing with a programmatic type or something... ResType progType = findSiblingType(); if (progType != null && progType.getTypeReferenceExp() != null) { PsiElement resolvedProgramType = progType.getTypeReferenceExp() .getReference().resolve(); if (resolvedProgramType instanceof ResTypeLikeNodeDecl) { return ((ResTypeLikeNodeDecl) resolvedProgramType) .getMathMetaTypeExp(); } } return null; } @Nullable @Override public Icon getIcon(int flags) { Icon icon = null; if (this instanceof ResPrecisModuleDecl) icon = RESOLVEIcons.PRECIS; else if (this instanceof ResPrecisExtensionModuleDecl) icon = RESOLVEIcons.PRECIS_EXT; else if (this instanceof ResConceptModuleDecl) icon = RESOLVEIcons.CONCEPT; else if (this instanceof ResConceptExtensionModuleDecl) icon = RESOLVEIcons.CONCEPT_EXT; else if (this instanceof ResImplModuleDecl) icon = RESOLVEIcons.IMPL; else if (this instanceof ResFacilityModuleDecl) icon = RESOLVEIcons.FACILITY; else if (this instanceof ResTypeModelDecl) icon = RESOLVEIcons.TYPE_MODEL; else if (this instanceof ResTypeReprDecl) icon = RESOLVEIcons.TYPE_REPR; else if (this instanceof ResFacilityDecl) icon = RESOLVEIcons.FACILITY; else if (this instanceof ResTypeParamDecl) icon = RESOLVEIcons.GENERIC_TYPE; else if (this instanceof ResMathVarDef) icon = RESOLVEIcons.VARIABLE; else if (this instanceof ResOperationDecl) icon = RESOLVEIcons.FUNCTION_DECL; else if (this instanceof ResParamDef) icon = RESOLVEIcons.PARAMETER; //TODO: complete the icon list here as you go along if (icon != null) { if ((flags & Iconable.ICON_FLAG_VISIBILITY) != 0) { RowIcon rowIcon = ElementBase.createLayeredIcon(this, icon, flags); rowIcon.setIcon(isPublic() ? PlatformIcons.PUBLIC_ICON : PlatformIcons.PRIVATE_ICON, 1); return rowIcon; } return icon; } return super.getIcon(flags); } }
package gov.nih.nci.calab.service.submit; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.HibernateDataAccess; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.InstrumentConfiguration; import gov.nih.nci.calab.domain.Keyword; import gov.nih.nci.calab.domain.LabFile; import gov.nih.nci.calab.domain.LookupType; import gov.nih.nci.calab.domain.MeasureType; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.OutputFile; import gov.nih.nci.calab.domain.ProtocolFile; import gov.nih.nci.calab.domain.nano.characterization.Characterization; import gov.nih.nci.calab.domain.nano.characterization.CharacterizationFileType; import gov.nih.nci.calab.domain.nano.characterization.DatumName; import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData; import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayDataCategory; import gov.nih.nci.calab.domain.nano.characterization.invitro.CFU_GM; import gov.nih.nci.calab.domain.nano.characterization.invitro.Caspase3Activation; import gov.nih.nci.calab.domain.nano.characterization.invitro.CellLineType; import gov.nih.nci.calab.domain.nano.characterization.invitro.CellViability; import gov.nih.nci.calab.domain.nano.characterization.invitro.Chemotaxis; import gov.nih.nci.calab.domain.nano.characterization.invitro.Coagulation; import gov.nih.nci.calab.domain.nano.characterization.invitro.ComplementActivation; import gov.nih.nci.calab.domain.nano.characterization.invitro.CytokineInduction; import gov.nih.nci.calab.domain.nano.characterization.invitro.EnzymeInduction; import gov.nih.nci.calab.domain.nano.characterization.invitro.Hemolysis; import gov.nih.nci.calab.domain.nano.characterization.invitro.LeukocyteProliferation; import gov.nih.nci.calab.domain.nano.characterization.invitro.NKCellCytotoxicActivity; import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeBurst; import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeStress; import gov.nih.nci.calab.domain.nano.characterization.invitro.Phagocytosis; import gov.nih.nci.calab.domain.nano.characterization.invitro.PlasmaProteinBinding; import gov.nih.nci.calab.domain.nano.characterization.invitro.PlateletAggregation; import gov.nih.nci.calab.domain.nano.characterization.physical.MolecularWeight; import gov.nih.nci.calab.domain.nano.characterization.physical.Morphology; import gov.nih.nci.calab.domain.nano.characterization.physical.MorphologyType; import gov.nih.nci.calab.domain.nano.characterization.physical.Purity; import gov.nih.nci.calab.domain.nano.characterization.physical.Shape; import gov.nih.nci.calab.domain.nano.characterization.physical.ShapeType; import gov.nih.nci.calab.domain.nano.characterization.physical.Size; import gov.nih.nci.calab.domain.nano.characterization.physical.Solubility; import gov.nih.nci.calab.domain.nano.characterization.physical.SolventType; import gov.nih.nci.calab.domain.nano.characterization.physical.Surface; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ParticleComposition; import gov.nih.nci.calab.domain.nano.characterization.toxicity.Cytotoxicity; import gov.nih.nci.calab.domain.nano.function.Agent; import gov.nih.nci.calab.domain.nano.function.Attachment; import gov.nih.nci.calab.domain.nano.function.BondType; import gov.nih.nci.calab.domain.nano.function.Function; import gov.nih.nci.calab.domain.nano.function.ImageContrastAgent; import gov.nih.nci.calab.domain.nano.function.ImageContrastAgentType; import gov.nih.nci.calab.domain.nano.function.Linkage; import gov.nih.nci.calab.domain.nano.particle.Nanoparticle; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.composition.CompositionBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.InstrumentBean; import gov.nih.nci.calab.dto.common.InstrumentConfigBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.function.FunctionBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** * This class includes service calls involved in creating nanoparticle general * info and adding functions and characterizations for nanoparticles, as well as * creating reports. * * @author pansu * */ public class SubmitNanoparticleService { private static Logger logger = Logger .getLogger(SubmitNanoparticleService.class); // remove existing visibilities for the data private UserService userService; public SubmitNanoparticleService() throws Exception { userService = new UserService(CaNanoLabConstants.CSM_APP_NAME); } /** * Update keywords and visibilities for the particle with the given name and * type * * @param particleType * @param particleName * @param keywords * @param visibilities * @throws Exception */ public void addParticleGeneralInfo(String particleType, String particleName, String[] keywords, String[] visibilities) throws Exception { // save nanoparticle to the database IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // get the existing particle from database created during sample // creation List results = ida.search("from Nanoparticle where name='" + particleName + "' and type='" + particleType + "'"); Nanoparticle particle = null; for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle == null) { throw new CalabException("No such particle in the database"); } particle.getKeywordCollection().clear(); if (keywords != null) { for (String keyword : keywords) { Keyword keywordObj = new Keyword(); if (keyword.length() > 0) { keywordObj.setName(keyword); particle.getKeywordCollection().add(keywordObj); } } } } catch (Exception e) { ida.rollback(); logger .error("Problem updating particle with name: " + particleName); throw e; } finally { ida.close(); } userService.setVisiblity(particleName, visibilities); } /** * Save characterization to the database. * * @param particleType * @param particleName * @param achar * @throws Exception */ private void addParticleCharacterization(String particleType, String particleName, Characterization achar, CharacterizationBean charBean) throws Exception { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; try { ida.open(); // check if viewTitle is already used the same type of // characterization for the same particle boolean viewTitleUsed = isCharacterizationViewTitleUsed(ida, particleType, particleName, achar, charBean); if (viewTitleUsed) { throw new RuntimeException( "The view title is already in use. Please enter a different one."); } else { // if ID exists, load from database if (charBean.getId() != null) { // check if ID is still valid achar = (Characterization) ida.get(Characterization.class, new Long(charBean.getId())); if (achar == null) throw new Exception( "This characterization is no longer in the database. Please log in again to refresh."); } // updated domain object if (achar instanceof Shape) { ((ShapeBean) charBean).updateDomainObj(achar); } else if (achar instanceof Morphology) { ((MorphologyBean) charBean).updateDomainObj(achar); } else if (achar instanceof Solubility) { ((SolubilityBean) charBean).updateDomainObj(achar); } else if (achar instanceof Surface) { ((SurfaceBean) charBean).updateDomainObj(achar); } else if (achar instanceof Cytotoxicity) { ((CytotoxicityBean) charBean).updateDomainObj(achar); } else charBean.updateDomainObj(achar); addProtocolFile(charBean.getProtocolFileBean(), achar, ida); // store instrumentConfig and instrument addInstrumentConfig(charBean.getInstrumentConfigBean(), achar, ida); if (charBean.getId() == null) { List results = ida .search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getCharacterizationCollection().add(achar); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization. "); throw e; } finally { ida.close(); } // save file to the file system // if this block of code is inside the db try catch block, hibernate // doesn't persist derivedBioAssayData if (!achar.getDerivedBioAssayDataCollection().isEmpty()) { int count = 0; for (DerivedBioAssayData derivedBioAssayData : achar .getDerivedBioAssayDataCollection()) { DerivedBioAssayDataBean derivedBioAssayDataBean = new DerivedBioAssayDataBean( derivedBioAssayData); // assign visibility DerivedBioAssayDataBean unsaved = charBean .getDerivedBioAssayDataList().get(count); derivedBioAssayDataBean.setVisibilityGroups(unsaved .getVisibilityGroups()); saveCharacterizationFile(derivedBioAssayDataBean); count++; } } } public void addNewCharacterizationDataDropdowns( CharacterizationBean charBean, String characterizationName) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); if (!charBean.getDerivedBioAssayDataList().isEmpty()) { for (DerivedBioAssayDataBean derivedBioAssayDataBean : charBean .getDerivedBioAssayDataList()) { // add new characterization file type if necessary if (derivedBioAssayDataBean.getType().length() > 0) { CharacterizationFileType fileType = new CharacterizationFileType(); addLookupType(ida, fileType, derivedBioAssayDataBean .getType()); } // add new derived data cateory for (String category : derivedBioAssayDataBean .getCategories()) { addDerivedDataCategory(ida, category, characterizationName); } // add new datum name, measure type, and unit for (DatumBean datumBean : derivedBioAssayDataBean .getDatumList()) { addDatumName(ida, datumBean.getName(), characterizationName); MeasureType measureType = new MeasureType(); addLookupType(ida, measureType, datumBean .getStatisticsType()); addMeasureUnit(ida, datumBean.getUnit(), characterizationName); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization data drop downs. "); throw e; } finally { ida.close(); } } /* * check if viewTitle is already used the same type of characterization for * the same particle */ private boolean isCharacterizationViewTitleUsed(IDataAccess ida, String particleType, String particleName, Characterization achar, CharacterizationBean charBean) throws Exception { String viewTitleQuery = ""; if (charBean.getId() == null) { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + charBean.getViewTitle() + "' and achar.name='" + achar.getName() + "'"; } else { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + charBean.getViewTitle() + "' and achar.name='" + achar.getName() + "' and achar.id!=" + charBean.getId(); } List viewTitleResult = ida.search(viewTitleQuery); int existingViewTitleCount = -1; for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount > 0) { return true; } else { return false; } } /** * Save the file to the file system * * @param fileBean */ public void saveCharacterizationFile(DerivedBioAssayDataBean fileBean) throws Exception { byte[] fileContent = fileBean.getFileContent(); String rootPath = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); if (fileContent != null) { FileService fileService = new FileService(); fileService.writeFile(fileContent, rootPath + File.separator + fileBean.getUri()); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } private void addInstrumentConfig(InstrumentConfigBean instrumentConfigBean, Characterization doChar, IDataAccess ida) throws Exception { InstrumentBean instrumentBean = instrumentConfigBean .getInstrumentBean(); if (instrumentBean.getType() == null && instrumentBean.getManufacturer() == null && instrumentConfigBean.getDescription() == null) { return; } if (instrumentBean.getType() != null && instrumentBean.getType().length() == 0 && instrumentBean.getManufacturer().length() == 0) { doChar.setInstrumentConfiguration(null); return; } // check if instrument is already in database based on type and // manufacturer Instrument instrument = null; List instrumentResults = ida .search("select instrument from Instrument instrument where instrument.type='" + instrumentBean.getType() + "' and instrument.manufacturer='" + instrumentBean.getManufacturer() + "'"); for (Object obj : instrumentResults) { instrument = (Instrument) obj; } // if not in the database, create one if (instrument == null) { instrument = new Instrument(); instrument.setType(instrumentBean.getType()); instrument.setManufacturer(instrumentBean.getManufacturer()); ida.store(instrument); } InstrumentConfiguration instrumentConfig = null; // new instrumentConfig if (instrumentConfigBean.getId() == null) { instrumentConfig = new InstrumentConfiguration(); doChar.setInstrumentConfiguration(instrumentConfig); } else { instrumentConfig = doChar.getInstrumentConfiguration(); } instrumentConfig.setDescription(instrumentConfigBean.getDescription()); instrumentConfig.setInstrument(instrument); ida.store(instrumentConfig); } private void addProtocolFile(ProtocolFileBean protocolFileBean, Characterization doChar, IDataAccess ida) throws Exception { if (protocolFileBean.getId() != null && protocolFileBean.getId().length() > 0) { ProtocolFile protocolFile = (ProtocolFile) ida.get( ProtocolFile.class, new Long(protocolFileBean.getId())); doChar.setProtocolFile(protocolFile); } } /** * Saves the particle composition to the database * * @param particleType * @param particleName * @param composition * @throws Exception */ public void addParticleComposition(String particleType, String particleName, CompositionBean composition) throws Exception { ParticleComposition doComp = composition.getDomainObj(); addParticleCharacterization(particleType, particleName, doComp, composition); } /** * O Saves the size characterization to the database * * @param particleType * @param particleName * @param size * @throws Exception */ public void addParticleSize(String particleType, String particleName, CharacterizationBean size) throws Exception { Size doSize = new Size(); addParticleCharacterization(particleType, particleName, doSize, size); } /** * Saves the size characterization to the database * * @param particleType * @param particleName * @param surface * @throws Exception */ public void addParticleSurface(String particleType, String particleName, CharacterizationBean surface) throws Exception { Surface doSurface = new Surface(); addParticleCharacterization(particleType, particleName, doSurface, surface); // addMeasureUnit(doSurface.getCharge().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_CHARGE); // addMeasureUnit(doSurface.getSurfaceArea().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_AREA); // addMeasureUnit(doSurface.getZetaPotential().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_ZETA_POTENTIAL); } private void addLookupType(IDataAccess ida, LookupType lookupType, String type) throws Exception { String className = lookupType.getClass().getSimpleName(); if (type != null && type.length() > 0) { List results = ida.search("select count(distinct name) from " + className + " type where name='" + type + "'"); lookupType.setName(type); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(lookupType); } } } private void addDatumName(IDataAccess ida, String name, String characterizationName) throws Exception { List results = ida.search("select count(distinct name) from DatumName" + " where characterizationName='" + characterizationName + "'" + " and name='" + name + "'"); DatumName datumName = new DatumName(); datumName.setName(name); datumName.setCharacterizationName(characterizationName); datumName.setDatumParsed(false); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(datumName); } } private void addDerivedDataCategory(IDataAccess ida, String name, String characterizationName) throws Exception { List results = ida .search("select count(distinct name) from DerivedBioAssayDataCategory" + " where characterizationName='" + characterizationName + "'" + " and name='" + name + "'"); DerivedBioAssayDataCategory category = new DerivedBioAssayDataCategory(); category.setName(name); category.setCharacterizationName(characterizationName); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(category); } } private void addLookupType(LookupType lookupType, String type) throws Exception { if (type != null && type.length() > 0) { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); String className = lookupType.getClass().getSimpleName(); try { ida.open(); List results = ida.search("select count(distinct name) from " + className + " type where name='" + type + "'"); lookupType.setName(type); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(lookupType); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving look up type: " + type); throw e; } finally { ida.close(); } } } // private void addMeasureUnit(String unit, String type) throws Exception { // if (unit == null || unit.length() == 0) { // return; // // if ID is not set save to the database otherwise update // IDataAccess ida = (new DataAccessProxy()) // .getInstance(IDataAccess.HIBERNATE); // MeasureUnit measureUnit = new MeasureUnit(); // try { // ida.open(); // List results = ida // .search("select count(distinct measureUnit.name) from " // + "MeasureUnit measureUnit where measureUnit.name='" // + unit + "' and measureUnit.type='" + type + "'"); // int count = -1; // for (Object obj : results) { // count = ((Integer) (obj)).intValue(); // if (count == 0) { // measureUnit.setName(unit); // measureUnit.setType(type); // ida.createObject(measureUnit); // } catch (Exception e) { // e.printStackTrace(); // ida.rollback(); // logger.error("Problem saving look up type: " + type); // throw e; // } finally { // ida.close(); private void addMeasureUnit(IDataAccess ida, String unit, String type) throws Exception { if (unit == null || unit.length() == 0) { return; } List results = ida.search("select count(distinct name) from " + " MeasureUnit where name='" + unit + "' and type='" + type + "'"); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } MeasureUnit measureUnit = new MeasureUnit(); if (count == 0) { measureUnit.setName(unit); measureUnit.setType(type); ida.createObject(measureUnit); } } /** * Saves the molecular weight characterization to the database * * @param particleType * @param particleName * @param molecularWeight * @throws Exception */ public void addParticleMolecularWeight(String particleType, String particleName, CharacterizationBean molecularWeight) throws Exception { MolecularWeight doMolecularWeight = new MolecularWeight(); addParticleCharacterization(particleType, particleName, doMolecularWeight, molecularWeight); } /** * Saves the morphology characterization to the database * * @param particleType * @param particleName * @param morphology * @throws Exception */ public void addParticleMorphology(String particleType, String particleName, MorphologyBean morphology) throws Exception { Morphology doMorphology = new Morphology(); addParticleCharacterization(particleType, particleName, doMorphology, morphology); MorphologyType morphologyType = new MorphologyType(); addLookupType(morphologyType, morphology.getType()); } /** * Saves the shape characterization to the database * * @param particleType * @param particleName * @param shape * @throws Exception */ public void addParticleShape(String particleType, String particleName, ShapeBean shape) throws Exception { Shape doShape = new Shape(); addParticleCharacterization(particleType, particleName, doShape, shape); ShapeType shapeType = new ShapeType(); addLookupType(shapeType, shape.getType()); } /** * Saves the purity characterization to the database * * @param particleType * @param particleName * @param purity * @throws Exception */ public void addParticlePurity(String particleType, String particleName, CharacterizationBean purity) throws Exception { Purity doPurity = new Purity(); addParticleCharacterization(particleType, particleName, doPurity, purity); } /** * Saves the solubility characterization to the database * * @param particleType * @param particleName * @param solubility * @throws Exception */ public void addParticleSolubility(String particleType, String particleName, SolubilityBean solubility) throws Exception { Solubility doSolubility = new Solubility(); addParticleCharacterization(particleType, particleName, doSolubility, solubility); SolventType solventType = new SolventType(); addLookupType(solventType, solubility.getSolvent()); // addMeasureUnit(solubility.getCriticalConcentration() // .getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_CONCENTRATION); } /** * Saves the invitro hemolysis characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addHemolysis(String particleType, String particleName, CharacterizationBean hemolysis) throws Exception { Hemolysis doHemolysis = new Hemolysis(); addParticleCharacterization(particleType, particleName, doHemolysis, hemolysis); } /** * Saves the invitro coagulation characterization to the database * * @param particleType * @param particleName * @param coagulation * @throws Exception */ public void addCoagulation(String particleType, String particleName, CharacterizationBean coagulation) throws Exception { Coagulation doCoagulation = new Coagulation(); addParticleCharacterization(particleType, particleName, doCoagulation, coagulation); } /** * Saves the invitro plate aggregation characterization to the database * * @param particleType * @param particleName * @param plateletAggregation * @throws Exception */ public void addPlateletAggregation(String particleType, String particleName, CharacterizationBean plateletAggregation) throws Exception { PlateletAggregation doPlateletAggregation = new PlateletAggregation(); addParticleCharacterization(particleType, particleName, doPlateletAggregation, plateletAggregation); } /** * Saves the invitro chemotaxis characterization to the database * * @param particleType * @param particleName * @param chemotaxis * @throws Exception */ public void addChemotaxis(String particleType, String particleName, CharacterizationBean chemotaxis) throws Exception { Chemotaxis doChemotaxis = new Chemotaxis(); addParticleCharacterization(particleType, particleName, doChemotaxis, chemotaxis); } /** * Saves the invitro NKCellCytotoxicActivity characterization to the * database * * @param particleType * @param particleName * @param nkCellCytotoxicActivity * @throws Exception */ public void addNKCellCytotoxicActivity(String particleType, String particleName, CharacterizationBean nkCellCytotoxicActivity) throws Exception { NKCellCytotoxicActivity doNKCellCytotoxicActivity = new NKCellCytotoxicActivity(); addParticleCharacterization(particleType, particleName, doNKCellCytotoxicActivity, nkCellCytotoxicActivity); } /** * Saves the invitro LeukocyteProliferation characterization to the database * * @param particleType * @param particleName * @param leukocyteProliferation * @throws Exception */ public void addLeukocyteProliferation(String particleType, String particleName, CharacterizationBean leukocyteProliferation) throws Exception { LeukocyteProliferation doLeukocyteProliferation = new LeukocyteProliferation(); addParticleCharacterization(particleType, particleName, doLeukocyteProliferation, leukocyteProliferation); } /** * Saves the invitro CFU_GM characterization to the database * * @param particleType * @param particleName * @param cfu_gm * @throws Exception */ public void addCFU_GM(String particleType, String particleName, CharacterizationBean cfu_gm) throws Exception { CFU_GM doCFU_GM = new CFU_GM(); addParticleCharacterization(particleType, particleName, doCFU_GM, cfu_gm); } /** * Saves the invitro Complement Activation characterization to the database * * @param particleType * @param particleName * @param complementActivation * @throws Exception */ public void addComplementActivation(String particleType, String particleName, CharacterizationBean complementActivation) throws Exception { ComplementActivation doComplementActivation = new ComplementActivation(); addParticleCharacterization(particleType, particleName, doComplementActivation, complementActivation); } /** * Saves the invitro OxidativeBurst characterization to the database * * @param particleType * @param particleName * @param oxidativeBurst * @throws Exception */ public void addOxidativeBurst(String particleType, String particleName, CharacterizationBean oxidativeBurst) throws Exception { OxidativeBurst doOxidativeBurst = new OxidativeBurst(); addParticleCharacterization(particleType, particleName, doOxidativeBurst, oxidativeBurst); } /** * Saves the invitro Phagocytosis characterization to the database * * @param particleType * @param particleName * @param phagocytosis * @throws Exception */ public void addPhagocytosis(String particleType, String particleName, CharacterizationBean phagocytosis) throws Exception { Phagocytosis doPhagocytosis = new Phagocytosis(); addParticleCharacterization(particleType, particleName, doPhagocytosis, phagocytosis); } /** * Saves the invitro CytokineInduction characterization to the database * * @param particleType * @param particleName * @param cytokineInduction * @throws Exception */ public void addCytokineInduction(String particleType, String particleName, CharacterizationBean cytokineInduction) throws Exception { CytokineInduction doCytokineInduction = new CytokineInduction(); addParticleCharacterization(particleType, particleName, doCytokineInduction, cytokineInduction); } /** * Saves the invitro plasma protein binding characterization to the database * * @param particleType * @param particleName * @param plasmaProteinBinding * @throws Exception */ public void addProteinBinding(String particleType, String particleName, CharacterizationBean plasmaProteinBinding) throws Exception { PlasmaProteinBinding doProteinBinding = new PlasmaProteinBinding(); addParticleCharacterization(particleType, particleName, doProteinBinding, plasmaProteinBinding); } /** * Saves the invitro binding characterization to the database * * @param particleType * @param particleName * @param cellViability * @throws Exception */ public void addCellViability(String particleType, String particleName, CytotoxicityBean cellViability) throws Exception { CellViability doCellViability = new CellViability(); addParticleCharacterization(particleType, particleName, doCellViability, cellViability); CellLineType cellLineType = new CellLineType(); addLookupType(cellLineType, cellViability.getCellLine()); } /** * Saves the invitro EnzymeInduction binding characterization to the * database * * @param particleType * @param particleName * @param enzymeInduction * @throws Exception */ public void addEnzymeInduction(String particleType, String particleName, CharacterizationBean enzymeInduction) throws Exception { EnzymeInduction doEnzymeInduction = new EnzymeInduction(); addParticleCharacterization(particleType, particleName, doEnzymeInduction, enzymeInduction); } /** * Saves the invitro OxidativeStress characterization to the database * * @param particleType * @param particleName * @param oxidativeStress * @throws Exception */ public void addOxidativeStress(String particleType, String particleName, CharacterizationBean oxidativeStress) throws Exception { OxidativeStress doOxidativeStress = new OxidativeStress(); addParticleCharacterization(particleType, particleName, doOxidativeStress, oxidativeStress); } /** * Saves the invitro Caspase3Activation characterization to the database * * @param particleType * @param particleName * @param caspase3Activation * @throws Exception */ public void addCaspase3Activation(String particleType, String particleName, CytotoxicityBean caspase3Activation) throws Exception { Caspase3Activation doCaspase3Activation = new Caspase3Activation(); addParticleCharacterization(particleType, particleName, doCaspase3Activation, caspase3Activation); CellLineType cellLineType = new CellLineType(); addLookupType(cellLineType, caspase3Activation.getCellLine()); } public void addParticleFunction(String particleType, String particleName, FunctionBean function) throws Exception { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; Function doFunction = new Function(); try { ida.open(); boolean viewTitleUsed = isFunctionViewTitleUsed(ida, particleType, particleName, doFunction); if (viewTitleUsed) { throw new RuntimeException( "The view title is already in use. Please enter a different one."); } else { // if function already exists in the database, load it first if (function.getId() != null) { doFunction = (Function) ida.get(Function.class, new Long( function.getId())); function.updateDomainObj(doFunction); } else { function.updateDomainObj(doFunction); List results = ida .search("select particle from Nanoparticle particle left join fetch particle.functionCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getFunctionCollection().add(doFunction); } } } // persist bondType and image contrast agent type drop-down for (Linkage linkage : doFunction.getLinkageCollection()) { if (linkage instanceof Attachment) { String bondType = ((Attachment) linkage).getBondType(); BondType lookup = new BondType(); addLookupType(ida, lookup, bondType); } Agent agent = linkage.getAgent(); if (agent instanceof ImageContrastAgent) { String agentType = ((ImageContrastAgent) agent).getType(); ImageContrastAgentType lookup = new ImageContrastAgentType(); addLookupType(ida, lookup, agentType); } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving function: "); throw e; } finally { ida.close(); } } /* * check if viewTitle is already used the same type of function for the same * particle */ private boolean isFunctionViewTitleUsed(IDataAccess ida, String particleType, String particleName, Function function) throws Exception { // check if viewTitle is already used the same type of // function for the same particle String viewTitleQuery = ""; if (function.getId() == null) { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + function.getIdentificationName() + "' and function.type='" + function.getType() + "'"; } else { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + function.getIdentificationName() + "' and function.id!=" + function.getId() + " and function.type='" + function.getType() + "'"; } List viewTitleResult = ida.search(viewTitleQuery); int existingViewTitleCount = -1; for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount > 0) { return true; } else { return false; } } /** * Load the file for the given fileId from the database * * @param fileId * @return */ public LabFileBean getFile(String fileId) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); LabFileBean fileBean = null; try { ida.open(); LabFile file = (LabFile) ida.load(LabFile.class, StringUtils .convertToLong(fileId)); fileBean = new LabFileBean(file); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting file with file ID: " + fileId); throw e; } finally { ida.close(); } // get visibilities UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = userService.getAccessibleGroups( fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups.toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); return fileBean; } /** * Load the derived data file for the given fileId from the database * * @param fileId * @return */ public DerivedBioAssayDataBean getDerivedBioAssayData(String fileId) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); DerivedBioAssayDataBean fileBean = null; try { ida.open(); DerivedBioAssayData file = (DerivedBioAssayData) ida.load( DerivedBioAssayData.class, StringUtils .convertToLong(fileId)); // load keywords file.getKeywordCollection(); fileBean = new DerivedBioAssayDataBean(file, CaNanoLabConstants.OUTPUT); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting file with file ID: " + fileId); throw e; } finally { ida.close(); } // get visibilities UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = userService.getAccessibleGroups( fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups.toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); return fileBean; } /** * Get the list of all run output files associated with a particle * * @param particleName * @return * @throws Exception */ public List<LabFileBean> getAllRunFiles(String particleName) throws Exception { List<LabFileBean> runFiles = new ArrayList<LabFileBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String query = "select distinct outFile from Run run join run.outputFileCollection outFile join run.runSampleContainerCollection runContainer where runContainer.sampleContainer.sample.name='" + particleName + "'"; List results = ida.search(query); for (Object obj : results) { OutputFile file = (OutputFile) obj; // active status only if (file.getDataStatus() == null) { LabFileBean fileBean = new LabFileBean(); fileBean.setId(file.getId().toString()); fileBean.setName(file.getFilename()); fileBean.setUri(file.getUri()); runFiles.add(fileBean); } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting run files for particle: " + particleName); throw e; } finally { ida.close(); } return runFiles; } /** * Update the meta data associated with a file stored in the database * * @param fileBean * @throws Exception */ public void updateFileMetaData(LabFileBean fileBean) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); LabFile file = (LabFile) ida.load(LabFile.class, StringUtils .convertToLong(fileBean.getId())); file.setTitle(fileBean.getTitle().toUpperCase()); file.setDescription(fileBean.getDescription()); file.setComments(fileBean.getComments()); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem updating file meta data: "); throw e; } finally { ida.close(); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } /** * Delete the characterizations */ public void deleteCharacterizations(String particleName, String particleType, String[] charIds) throws Exception { // if ID is not set save to the database otherwise update HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // Get ID for (String strCharId : charIds) { Long charId = Long.parseLong(strCharId); Object charObj = ida.load(Characterization.class, charId); // deassociate first String hqlString = "from Nanoparticle particle where particle.characterizationCollection.id = '" + strCharId + "'"; List results = ida.search(hqlString); for (Object obj : results) { Nanoparticle particle = (Nanoparticle) obj; particle.getCharacterizationCollection().remove(charObj); } // then delete ida.delete(charObj); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem deleting characterization: "); throw new Exception( "The characterization is no longer exist in the database, please login again to refresh the view."); } finally { ida.close(); } } }
package net.fortuna.ical4j.model.component; import java.io.FileInputStream; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Calendar; import java.util.Iterator; import junit.framework.TestSuite; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentTest; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.Recur; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.WeekDay; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.util.Calendars; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.UidGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A test case for VEvents. * @author Ben Fortuna */ public class VEventTest extends ComponentTest { private static Log log = LogFactory.getLog(VEventTest.class); private VEvent event; private Period period; private Date date; private TzId tzParam; /** * @param testMethod */ public VEventTest(String testMethod) { super(testMethod, null); } /** * @param testMethod * @param component */ public VEventTest(String testMethod, VEvent event) { super(testMethod, event); this.event = event; } /** * @param testMethod * @param component * @param period */ public VEventTest(String testMethod, VEvent component, Period period) { this(testMethod, component); this.period = period; } /** * @param testMethod * @param component * @param date */ public VEventTest(String testMethod, VEvent component, Date date) { this(testMethod, component); this.date = date; } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ public void setUp() throws Exception { super.setUp(); // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); // create timezone property.. VTimeZone tz = registry.getTimeZone("Australia/Melbourne").getVTimeZone(); // create tzid parameter.. tzParam = new TzId(tz.getProperty(Property.TZID).getValue()); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_VALIDATION, false); super.tearDown(); } /** * @return */ private static Calendar getCalendarInstance() { return Calendar.getInstance(); //java.util.TimeZone.getTimeZone(TimeZones.GMT_ID)); } /** * @param filename * @return */ private net.fortuna.ical4j.model.Calendar loadCalendar(String filename) throws IOException, ParserException, ValidationException { net.fortuna.ical4j.model.Calendar calendar = Calendars.load( filename); calendar.validate(); log.info("File: " + filename); if (log.isDebugEnabled()) { log.debug("Calendar:\n=========\n" + calendar.toString()); } return calendar; } public final void testChristmas() { // create event start date.. java.util.Calendar calendar = getCalendarInstance(); calendar.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); calendar.set(java.util.Calendar.DAY_OF_MONTH, 25); DtStart start = new DtStart(new Date(calendar.getTime())); start.getParameters().add(tzParam); start.getParameters().add(Value.DATE); Summary summary = new Summary("Christmas Day; \n this is a, test\\"); VEvent christmas = new VEvent(); christmas.getProperties().add(start); christmas.getProperties().add(summary); log.info(christmas); } /** * Test creating an event with an associated timezone. */ public final void testMelbourneCup() { TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); TimeZone timezone = registry.getTimeZone("Australia/Melbourne"); java.util.Calendar cal = java.util.Calendar.getInstance(timezone); cal.set(java.util.Calendar.YEAR, 2005); cal.set(java.util.Calendar.MONTH, java.util.Calendar.NOVEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 15); cal.clear(java.util.Calendar.MINUTE); cal.clear(java.util.Calendar.SECOND); DateTime dt = new DateTime(cal.getTime()); dt.setTimeZone(timezone); VEvent melbourneCup = new VEvent(dt, "Melbourne Cup"); log.info(melbourneCup); } public final void test2() { java.util.Calendar cal = getCalendarInstance(); cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 25); VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day"); // initialise as an all-day event.. christmas.getProperty(Property.DTSTART).getParameters().add(Value.DATE); // add timezone information.. christmas.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(christmas); } public final void test3() { java.util.Calendar cal = getCalendarInstance(); // tomorrow.. cal.add(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 9); cal.set(java.util.Calendar.MINUTE, 30); VEvent meeting = new VEvent(new DateTime(cal.getTime().getTime()), new Dur(0, 1, 0, 0), "Progress Meeting"); // add timezone information.. meeting.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(meeting); } /** * Test Null Dates * Test Start today, End One month from now. * * @throws Exception */ public final void testGetConsumedTime() throws Exception { // Test Null Dates try { event.getConsumedTime(null, null); fail("Should've thrown an exception."); } catch (RuntimeException re) { log.info("Expecting an exception here."); } // Test Start 04/01/2005, End One month later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0); queryStartDate.set(Calendar.MILLISECOND, 0); DateTime queryStart = new DateTime(queryStartDate.getTime().getTime()); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.MAY, 1, 07, 15, 0); queryEndDate.set(Calendar.MILLISECOND, 0); DateTime queryEnd = new DateTime(queryEndDate.getTime().getTime()); Calendar week1EndDate = getCalendarInstance(); week1EndDate.set(2005, Calendar.APRIL, 8, 11, 15, 0); week1EndDate.set(Calendar.MILLISECOND, 0); Calendar week4StartDate = getCalendarInstance(); week4StartDate.set(2005, Calendar.APRIL, 24, 14, 47, 0); week4StartDate.set(Calendar.MILLISECOND, 0); // DateTime week4Start = new DateTime(week4StartDate.getTime().getTime()); // This range is monday to friday every three weeks, starting from // March 7th 2005, which means for our query dates we need // April 18th through to the 22nd. PeriodList weeklyPeriods = event.getConsumedTime(queryStart, queryEnd); // PeriodList dailyPeriods = dailyWeekdayEvents.getConsumedTime(queryStart, queryEnd); // week1EndDate.getTime()); // dailyPeriods.addAll(dailyWeekdayEvents.getConsumedTime(week4Start, queryEnd)); Calendar expectedCal = Calendar.getInstance(); //TimeZone.getTimeZone(TimeZones.GMT_ID)); expectedCal.set(2005, Calendar.APRIL, 1, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime().getTime()); expectedCal.set(2005, Calendar.APRIL, 1, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime().getTime()); assertNotNull(weeklyPeriods); assertTrue(weeklyPeriods.size() > 0); Period firstPeriod = (Period) weeklyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(dailyPeriods, weeklyPeriods); } public final void testGetConsumedTimeDaily() throws Exception { // Test Starts 04/03/2005, Ends One week later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 10, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every day (which has a filtering // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 10th. // PeriodList weeklyPeriods = // event.getConsumedTime(new DateTime(queryStartDate.getTime()), // new DateTime(queryEndDate.getTime())); PeriodList dailyPeriods = event.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(dailyPeriods); assertTrue(dailyPeriods.size() > 0); Period firstPeriod = (Period) dailyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(weeklyPeriods, dailyPeriods); } /** * Test whether you can select weekdays using a monthly frequency. * <p> * This test really belongs in RecurTest, but the weekly range test * in this VEventTest matches so perfectly with the daily range test * that should produce the same results for some weeks that it was * felt leveraging the existing test code was more important. * <p> * Section 4.3.10 of the iCalendar specification RFC 2445 reads: * <pre> * If an integer modifier is not present, it means all days of * this type within the specified frequency. * </pre> * This test ensures compliance. */ public final void testGetConsumedTimeMonthly() throws Exception { // Test Starts 04/03/2005, Ends two weeks later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 17, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every month (which has a multiplying // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 17th. PeriodList monthlyPeriods = event.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); // PeriodList dailyPeriods = // dailyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()), // new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(monthlyPeriods); assertTrue(monthlyPeriods.size() > 0); Period firstPeriod = (Period) monthlyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(dailyPeriods, monthlyPeriods); } public final void testGetConsumedTime2() throws Exception { String filename = "etc/samples/valid/derryn.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); Date start = new Date(); Calendar endCal = getCalendarInstance(); endCal.setTime(start); endCal.add(Calendar.WEEK_OF_YEAR, 4); // Date end = new Date(start.getTime() + (1000 * 60 * 60 * 24 * 7 * 4)); for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) { Component c = (Component) i.next(); if (c instanceof VEvent) { PeriodList consumed = ((VEvent) c).getConsumedTime(start, new Date(endCal.getTime().getTime())); log.debug("Event [" + c + "]"); log.debug("Consumed time [" + consumed + "]"); } } } public final void testGetConsumedTime3() throws Exception { String filename = "etc/samples/valid/calconnect10.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); VEvent vev = (VEvent) calendar.getComponent(Component.VEVENT); Date start = vev.getStartDate().getDate(); Calendar cal = getCalendarInstance(); cal.add(Calendar.YEAR, 1); Date latest = new Date(cal.getTime()); PeriodList pl = vev.getConsumedTime(start, latest); assertTrue(!pl.isEmpty()); } /** * Test COUNT rules. */ public void testGetConsumedTimeByCount() { Recur recur = new Recur(Recur.WEEKLY, 3); recur.setInterval(1); recur.getDayList().add(WeekDay.SU); log.info(recur); Calendar cal = getCalendarInstance(); cal.set(Calendar.DAY_OF_MONTH, 8); Date start = new DateTime(cal.getTime()); // cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 10); cal.add(Calendar.HOUR_OF_DAY, 1); Date end = new DateTime(cal.getTime()); // log.info(recur.getDates(start, end, Value.DATE_TIME)); RRule rrule = new RRule(recur); VEvent event = new VEvent(start, end, "Test recurrence COUNT"); event.getProperties().add(rrule); log.info(event); Calendar rangeCal = getCalendarInstance(); Date rangeStart = new DateTime(rangeCal.getTime()); rangeCal.add(Calendar.WEEK_OF_YEAR, 4); Date rangeEnd = new DateTime(rangeCal.getTime()); log.info(event.getConsumedTime(rangeStart, rangeEnd)); } /** * A test to confirm that the end date is calculated correctly * from a given start date and duration. */ public final void testEventEndDate() { Calendar cal = getCalendarInstance(); Date startDate = new Date(cal.getTime()); log.info("Start date: " + startDate); VEvent event = new VEvent(startDate, new Dur(3, 0, 0, 0), "3 day event"); Date endDate = event.getEndDate().getDate(); log.info("End date: " + endDate); cal.add(Calendar.DAY_OF_YEAR, 3); assertEquals(new Date(cal.getTime()), endDate); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate() throws ParseException { VEvent event1 = new VEvent(new DateTime("20050103T080000"), new Dur(0, 0, 15, 0), "Event 1"); Recur rRuleRecur = new Recur("FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR"); RRule rRule = new RRule(rRuleRecur); event1.getProperties().add(rRule); ParameterList parameterList = new ParameterList(); parameterList.add(Value.DATE); ExDate exDate = new ExDate(parameterList, "20050106"); event1.getProperties().add(exDate); Date start = new Date("20050106"); Date end = new Date("20050107"); PeriodList list = event1.getConsumedTime(start, end); assertTrue(list.isEmpty()); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate2() throws IOException, ParserException { FileInputStream fin = new FileInputStream("etc/samples/valid/friday13.ics"); net.fortuna.ical4j.model.Calendar calendar = new CalendarBuilder().build(fin); VEvent event = (VEvent) calendar.getComponent(Component.VEVENT); Calendar cal = Calendar.getInstance(); cal.set(1997, 8, 2); Date start = new Date(cal.getTime()); cal.set(1997, 8, 4); Date end = new Date(cal.getTime()); PeriodList periods = event.getConsumedTime(start, end); assertTrue(periods.isEmpty()); } /** * Test equality of events with different alarm sub-components. */ public void testEquals() { Date date = new Date(); String summary = "test event"; PropertyList props = new PropertyList(); props.add(new DtStart(date)); props.add(new Summary(summary)); VEvent e1 = new VEvent(props); VEvent e2 = new VEvent(props); assertTrue(e1.equals(e2)); e2.getAlarms().add(new VAlarm()); assertFalse(e1.equals(e2)); } public void testCalculateRecurrenceSetNotEmpty() { PeriodList recurrenceSet = event.calculateRecurrenceSet(period); assertTrue(!recurrenceSet.isEmpty()); } /** * Unit tests for {@link VEvent#getOccurrence(Date)}. */ public void testGetOccurrence() throws IOException, ParseException, URISyntaxException { VEvent occurrence = event.getOccurrence(date); assertNotNull(occurrence); assertEquals(event.getUid(), occurrence.getUid()); } /** * @return * @throws ValidationException * @throws ParseException * @throws URISyntaxException * @throws IOException */ public static TestSuite suite() throws ValidationException, ParseException, IOException, URISyntaxException { UidGenerator uidGenerator = new UidGenerator("1"); Calendar weekday9AM = getCalendarInstance(); weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0); weekday9AM.set(Calendar.MILLISECOND, 0); Calendar weekday5PM = getCalendarInstance(); weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0); weekday5PM.set(Calendar.MILLISECOND, 0); // Do the recurrence until December 31st. Calendar untilCal = getCalendarInstance(); untilCal.set(2005, Calendar.DECEMBER, 31); untilCal.set(Calendar.MILLISECOND, 0); Date until = new Date(untilCal.getTime().getTime()); // 9:00AM to 5:00PM Rule using weekly Recur recurWeekly = new Recur(Recur.WEEKLY, until); recurWeekly.getDayList().add(WeekDay.MO); recurWeekly.getDayList().add(WeekDay.TU); recurWeekly.getDayList().add(WeekDay.WE); recurWeekly.getDayList().add(WeekDay.TH); recurWeekly.getDayList().add(WeekDay.FR); recurWeekly.setInterval(1); recurWeekly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleWeekly = new RRule(recurWeekly); // 9:00AM to 5:00PM Rule using daily frequency Recur recurDaily = new Recur(Recur.DAILY, until); recurDaily.getDayList().add(WeekDay.MO); recurDaily.getDayList().add(WeekDay.TU); recurDaily.getDayList().add(WeekDay.WE); recurDaily.getDayList().add(WeekDay.TH); recurDaily.getDayList().add(WeekDay.FR); recurDaily.setInterval(1); recurDaily.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleDaily = new RRule(recurDaily); // 9:00AM to 5:00PM Rule using monthly frequency Recur recurMonthly = new Recur(Recur.MONTHLY, until); recurMonthly.getDayList().add(WeekDay.MO); recurMonthly.getDayList().add(WeekDay.TU); recurMonthly.getDayList().add(WeekDay.WE); recurMonthly.getDayList().add(WeekDay.TH); recurMonthly.getDayList().add(WeekDay.FR); recurMonthly.setInterval(1); recurMonthly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleMonthly = new RRule(recurMonthly); Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED WEEKLY"); VEvent weekdayNineToFiveEvents = new VEvent(); weekdayNineToFiveEvents.getProperties().add(rruleWeekly); weekdayNineToFiveEvents.getProperties().add(summary); DtStart dtStart = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtStart); DtEnd dtEnd = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtEnd); weekdayNineToFiveEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. weekdayNineToFiveEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED DAILY"); VEvent dailyWeekdayEvents = new VEvent(); dailyWeekdayEvents.getProperties().add(rruleDaily); dailyWeekdayEvents.getProperties().add(summary); DtStart dtStart2 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtStart2); DtEnd dtEnd2 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtEnd2); dailyWeekdayEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. dailyWeekdayEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED MONTHLY"); VEvent monthlyWeekdayEvents = new VEvent(); monthlyWeekdayEvents.getProperties().add(rruleMonthly); monthlyWeekdayEvents.getProperties().add(summary); DtStart dtStart3 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtStart3); DtEnd dtEnd3 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtEnd3); monthlyWeekdayEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. monthlyWeekdayEvents.validate(); TestSuite suite = new TestSuite(); //testCalculateRecurrenceSet.. DateTime periodStart = new DateTime("20050101T000000"); DateTime periodEnd = new DateTime("20051231T235959"); Period period = new Period(periodStart, periodEnd); suite.addTest(new VEventTest("testCalculateRecurrenceSetNotEmpty", weekdayNineToFiveEvents, period)); //testGetOccurrence.. suite.addTest(new VEventTest("testGetOccurrence", weekdayNineToFiveEvents, weekdayNineToFiveEvents.getStartDate().getDate())); //testGetConsumedTime.. suite.addTest(new VEventTest("testGetConsumedTime", weekdayNineToFiveEvents)); suite.addTest(new VEventTest("testGetConsumedTimeDaily", dailyWeekdayEvents)); suite.addTest(new VEventTest("testGetConsumedTimeMonthly", monthlyWeekdayEvents)); //test event validation.. UidGenerator ug = new UidGenerator("1"); Uid uid = ug.generateUid(); DtStart start = new DtStart(new Date()); DtEnd end = new DtEnd(new Date()); VEvent event = new VEvent(); event.getProperties().add(uid); event.getProperties().add(start); event.getProperties().add(end); suite.addTest(new VEventTest("testValidation", event)); event = (VEvent) event.copy(); // start = (DtStart) event.getProperty(Property.DTSTART); start = new DtStart(new DateTime()); start.getParameters().replace(Value.DATE_TIME); event.getProperties().remove(event.getProperty(Property.DTSTART)); event.getProperties().add(start); suite.addTest(new VEventTest("testValidationException", event)); // test 1.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().replace(Value.DATE); suite.addTest(new VEventTest("testValidationException", event)); // event = (VEvent) event.copy(); // start = (DtStart) event.getProperty(Property.DTSTART); // start.getParameters().remove(Value.DATE_TIME); // end = (DtEnd) event.getProperty(Property.DTEND); // end.getParameters().replace(Value.DATE_TIME); // suite.addTest(new VEventTest("testValidation", event)); // test 2.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().replace(Value.DATE_TIME); end = (DtEnd) event.getProperty(Property.DTEND); end.getParameters().replace(Value.DATE); suite.addTest(new VEventTest("testValidationException", event)); // test 3.. // event = (VEvent) event.copy(); // start = (DtStart) event.getProperty(Property.DTSTART); // start.getParameters().remove(Value.DATE); // end = (DtEnd) event.getProperty(Property.DTEND); // end.getParameters().replace(Value.DATE); // suite.addTest(new VEventTest("testValidationException", event)); suite.addTest(new VEventTest("testChristmas")); suite.addTest(new VEventTest("testMelbourneCup")); suite.addTest(new VEventTest("testGetConsumedTime2")); suite.addTest(new VEventTest("testGetConsumedTime3")); suite.addTest(new VEventTest("testGetConsumedTimeByCount")); suite.addTest(new VEventTest("testEventEndDate")); suite.addTest(new VEventTest("testGetConsumedTimeWithExDate")); suite.addTest(new VEventTest("testGetConsumedTimeWithExDate2")); suite.addTest(new VEventTest("testIsCalendarComponent", event)); suite.addTest(new VEventTest("testEquals")); // suite.addTest(new VEventTest("testValidation")); return suite; } }
package gov.nih.nci.calab.service.submit; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.DerivedDataFile; import gov.nih.nci.calab.domain.InstrumentType; import gov.nih.nci.calab.domain.Keyword; import gov.nih.nci.calab.domain.LabFile; import gov.nih.nci.calab.domain.Manufacturer; import gov.nih.nci.calab.domain.OutputFile; import gov.nih.nci.calab.domain.nano.characterization.Characterization; import gov.nih.nci.calab.domain.nano.function.Agent; import gov.nih.nci.calab.domain.nano.function.AgentTarget; import gov.nih.nci.calab.domain.nano.function.Function; import gov.nih.nci.calab.domain.nano.function.Linkage; import gov.nih.nci.calab.domain.nano.particle.Nanoparticle; import gov.nih.nci.calab.dto.characterization.CharacterizationFileBean; import gov.nih.nci.calab.dto.characterization.composition.CompositionBean; import gov.nih.nci.calab.dto.characterization.invitro.CFU_GMBean; import gov.nih.nci.calab.dto.characterization.invitro.CYP450Bean; import gov.nih.nci.calab.dto.characterization.invitro.Caspase3ActivationBean; import gov.nih.nci.calab.dto.characterization.invitro.CellViabilityBean; import gov.nih.nci.calab.dto.characterization.invitro.ChemotaxisBean; import gov.nih.nci.calab.dto.characterization.invitro.CoagulationBean; import gov.nih.nci.calab.dto.characterization.invitro.ComplementActivationBean; import gov.nih.nci.calab.dto.characterization.invitro.CytokineInductionBean; import gov.nih.nci.calab.dto.characterization.invitro.EnzymeInductionBean; import gov.nih.nci.calab.dto.characterization.invitro.GlucuronidationSulphationBean; import gov.nih.nci.calab.dto.characterization.invitro.HemolysisBean; import gov.nih.nci.calab.dto.characterization.invitro.LeukocyteProliferationBean; import gov.nih.nci.calab.dto.characterization.invitro.NKCellCytotoxicActivityBean; import gov.nih.nci.calab.dto.characterization.invitro.OxidativeBurstBean; import gov.nih.nci.calab.dto.characterization.invitro.OxidativeStressBean; import gov.nih.nci.calab.dto.characterization.invitro.PhagocytosisBean; import gov.nih.nci.calab.dto.characterization.invitro.PlasmaProteinBindingBean; import gov.nih.nci.calab.dto.characterization.invitro.PlateAggregationBean; import gov.nih.nci.calab.dto.characterization.invitro.ROSBean; import gov.nih.nci.calab.dto.characterization.physical.MolecularWeightBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.PurityBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SizeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.StabilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.function.FunctionBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.service.util.file.HttpFileUploadSessionData; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.log4j.Logger; import org.apache.struts.upload.FormFile; /** * This class includes service calls involved in creating nanoparticles and * adding functions and characterizations for nanoparticles. * * @author pansu * */ public class SubmitNanoparticleService { private static Logger logger = Logger .getLogger(SubmitNanoparticleService.class); /** * Update keywords and visibilities for the particle with the given name and * type * * @param particleType * @param particleName * @param keywords * @param visibilities * @throws Exception */ public void createNanoparticle(String particleType, String particleName, String[] keywords, String[] visibilities) throws Exception { // save nanoparticle to the database IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // get the existing particle from database created during sample // creation List results = ida.search("from Nanoparticle where name='" + particleName + "' and type='" + particleType + "'"); Nanoparticle particle = null; for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle == null) { throw new CalabException("No such particle in the database"); } particle.getKeywordCollection().clear(); if (keywords != null) { for (String keyword : keywords) { Keyword keywordObj = new Keyword(); keywordObj.setName(keyword); particle.getKeywordCollection().add(keywordObj); } } } catch (Exception e) { ida.rollback(); logger .error("Problem updating particle with name: " + particleName); throw e; } finally { ida.close(); } // remove existing visiblities for the nanoparticle UserService userService = new UserService(CalabConstants.CSM_APP_NAME); List<String> currentVisibilities = userService.getAccessibleGroups( particleName, "R"); for (String visiblity : currentVisibilities) { userService.removeAccessibleGroup(particleName, visiblity, "R"); } // set new visibilities for the nanoparticle // by default, always set visibility to NCL_PI and NCL_Researcher to // be true userService.secureObject(particleName, "NCL_PI", "R"); userService.secureObject(particleName, "NCL_Researcher", "R"); if (visibilities != null) { for (String visibility : visibilities) { userService.secureObject(particleName, visibility, "R"); } } } /** * Save characterization to the database. * * @param particleType * @param particleName * @param achar * @throws Exception */ private void addParticleCharacterization(String particleType, String particleName, Characterization achar) throws Exception { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; int existingViewTitleCount = -1; try { ida.open(); /* * if (achar.getInstrument() != null) * ida.store(achar.getInstrument()); */ if (achar.getInstrument() != null) { Manufacturer manuf = achar.getInstrument().getManufacturer(); String manufacturerQuery = " from Manufacturer manufacturer where manufacturer.name = '" + manuf.getName() + "'"; List result = ida.search(manufacturerQuery); Manufacturer manufacturer = null; boolean newManufacturer = false; for (Object obj : result) { manufacturer = (Manufacturer) obj; } if (manufacturer == null) { newManufacturer = true; manufacturer = manuf; ida.store(manufacturer); } InstrumentType iType = achar.getInstrument() .getInstrumentType(); String instrumentTypeQuery = " from InstrumentType instrumentType left join fetch instrumentType.manufacturerCollection where instrumentType.name = '" + iType.getName() + "'"; result = ida.search(instrumentTypeQuery); InstrumentType instrumentType = null; for (Object obj : result) { instrumentType = (InstrumentType) obj; } if (instrumentType == null) { instrumentType = iType; ida.createObject(instrumentType); HashSet<Manufacturer> manufacturers = new HashSet<Manufacturer>(); manufacturers.add(manufacturer); instrumentType.setManufacturerCollection(manufacturers); } else { if (newManufacturer) { instrumentType.getManufacturerCollection().add( manufacturer); } } ida.store(instrumentType); achar.getInstrument().setInstrumentType(instrumentType); achar.getInstrument().setManufacturer(manufacturer); ida.store(achar.getInstrument()); } if (achar.getCharacterizationProtocol() != null) { ida.store(achar.getCharacterizationProtocol()); } // check if viewTitle is already used the same type of // characterization for the same particle String viewTitleQuery = ""; if (achar.getId() == null) { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + achar.getIdentificationName() + "' and achar.name='" + achar.getName() + "'"; } else { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + achar.getIdentificationName() + "' and achar.name='" + achar.getName() + "' and achar.id!=" + achar.getId(); } List viewTitleResult = ida.search(viewTitleQuery); for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount == 0) { // if ID exists, do update if (achar.getId() != null) { ida.store(achar); } else {// get the existing particle and compositions // from database // created // during sample // creation List results = ida .search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getCharacterizationCollection().add(achar); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization: "); throw e; } finally { ida.close(); } if (existingViewTitleCount > 0) { throw new CalabException( "The view title is already in use. Please enter a different one."); } } /** * Save Instrument to the database. * * @param particleType * @param particleName * @param achar * @throws Exception */ /* * private Instrument addInstrument(Instrument instrument) throws Exception { * Instrument rInstrument = null; // if ID is not set save to the database * otherwise update IDataAccess ida = (new DataAccessProxy()) * .getInstance(IDataAccess.HIBERNATE); * * //int existingInstrumentCount = -1; Instrument existingInstrument = null; * try { ida.open(); // check if instrument is already existed String * viewQuery = ""; if (instrument.getId() == null) { viewQuery = "select * instrument from Instrument instrument where instrument.type='" + * instrument.getType() + "' and instrument.manufacturer='" + * instrument.getManufacturer() + "'"; } else { viewQuery = "select * instrument from Instrument instrument where instrument.type='" + * instrument.getType() + "' and instrument.manufacturer='" + * instrument.getManufacturer() + "' and instrument.id!=" + * instrument.getId(); } List viewTitleResult = ida.search(viewQuery); * * for (Object obj : viewTitleResult) { existingInstrument = (Instrument) * obj; } if (existingInstrument == null) { ida.store(instrument); * rInstrument = instrument; } else { rInstrument = existingInstrument; } } * catch (Exception e) { e.printStackTrace(); ida.rollback(); * logger.error("Problem saving characterization: "); throw e; } finally { * ida.close(); } return rInstrument; } */ /** * Saves the particle composition to the database * * @param particleType * @param particleName * @param composition * @throws Exception */ public void addParticleComposition(String particleType, String particleName, CompositionBean composition) throws Exception { Characterization doComp = composition.getDomainObj(); addParticleCharacterization(particleType, particleName, doComp); } /** * Saves the size characterization to the database * * @param particleType * @param particleName * @param size * @throws Exception */ public void addParticleSize(String particleType, String particleName, SizeBean size) throws Exception { Characterization doSize = size.getDomainObj(); // TODO think about how to deal with characterization file. /* * if (doSize.getInstrument() != null) { Instrument instrument = * addInstrument(doSize.getInstrument()); * doSize.setInstrument(instrument); } */ addParticleCharacterization(particleType, particleName, doSize); } /** * Saves the size characterization to the database * * @param particleType * @param particleName * @param size * @throws Exception */ public void addParticleSurface(String particleType, String particleName, SurfaceBean surface) throws Exception { Characterization doSurface = surface.getDomainObj(); // TODO think about how to deal with characterization file. /* * if (doSize.getInstrument() != null) { Instrument instrument = * addInstrument(doSize.getInstrument()); * doSize.setInstrument(instrument); } */ addParticleCharacterization(particleType, particleName, doSurface); } /** * Saves the molecular weight characterization to the database * * @param particleType * @param particleName * @param molecularWeight * @throws Exception */ public void addParticleMolecularWeight(String particleType, String particleName, MolecularWeightBean molecularWeight) throws Exception { Characterization doMolecularWeight = molecularWeight.getDomainObj(); // TODO think about how to deal with characterization file. /* * if (doSize.getInstrument() != null) { Instrument instrument = * addInstrument(doSize.getInstrument()); * doSize.setInstrument(instrument); } */ addParticleCharacterization(particleType, particleName, doMolecularWeight); } /** * Saves the morphology characterization to the database * * @param particleType * @param particleName * @param morphology * @throws Exception */ public void addParticleMorphology(String particleType, String particleName, MorphologyBean morphology) throws Exception { Characterization doMorphology = morphology.getDomainObj(); // TODO think about how to deal with characterization file. /* * if (doSize.getInstrument() != null) { Instrument instrument = * addInstrument(doSize.getInstrument()); * doSize.setInstrument(instrument); } */ addParticleCharacterization(particleType, particleName, doMorphology); } /** * Saves the shape characterization to the database * * @param particleType * @param particleName * @param shape * @throws Exception */ public void addParticleShape(String particleType, String particleName, ShapeBean shape) throws Exception { Characterization doShape = shape.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doShape); } /** * Saves the stability characterization to the database * * @param particleType * @param particleName * @param stability * @throws Exception */ public void addParticleStability(String particleType, String particleName, StabilityBean stability) throws Exception { Characterization doStability = stability.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doStability); } /** * Saves the purity characterization to the database * * @param particleType * @param particleName * @param purity * @throws Exception */ public void addParticlePurity(String particleType, String particleName, PurityBean purity) throws Exception { Characterization doPurity = purity.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doPurity); } /** * Saves the solubility characterization to the database * * @param particleType * @param particleName * @param solubility * @throws Exception */ public void addParticleSolubility(String particleType, String particleName, SolubilityBean solubility) throws Exception { Characterization doSolubility = solubility.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doSolubility); } /** * Saves the invitro hemolysis characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addHemolysis(String particleType, String particleName, HemolysisBean hemolysis) throws Exception { Characterization doHemolysis = hemolysis.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doHemolysis); } /** * Saves the invitro coagulation characterization to the database * * @param particleType * @param particleName * @param coagulation * @throws Exception */ public void addCoagulation(String particleType, String particleName, CoagulationBean coagulation) throws Exception { Characterization doCoagulation = coagulation.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doCoagulation); } /** * Saves the invitro plate aggregation characterization to the database * * @param particleType * @param particleName * @param plateAggregation * @throws Exception */ public void addPlateAggregation(String particleType, String particleName, PlateAggregationBean plateAggregation) throws Exception { Characterization doPlateAggregation = plateAggregation.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doPlateAggregation); } /** * Saves the invitro Complement Activation characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addComplementActivation(String particleType, String particleName, ComplementActivationBean complementActivation) throws Exception { Characterization doComplementActivation = complementActivation .getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doComplementActivation); } /** * Saves the invitro chemotaxis characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addChemotaxis(String particleType, String particleName, ChemotaxisBean chemotaxis) throws Exception { Characterization doChemotaxis = chemotaxis.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doChemotaxis); } /** * Saves the invitro NKCellCytotoxicActivity characterization to the * database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addNKCellCytotoxicActivity(String particleType, String particleName, NKCellCytotoxicActivityBean nkCellCytotoxicActivity) throws Exception { Characterization doNKCellCytotoxicActivity = nkCellCytotoxicActivity .getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doNKCellCytotoxicActivity); } /** * Saves the invitro LeukocyteProliferation characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addLeukocyteProliferation(String particleType, String particleName, LeukocyteProliferationBean leukocyteProliferation) throws Exception { Characterization doLeukocyteProliferation = leukocyteProliferation .getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doLeukocyteProliferation); } /** * Saves the invitro CFU_GM characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addCFU_GM(String particleType, String particleName, CFU_GMBean cfu_gm) throws Exception { Characterization doCFU_GM = cfu_gm.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doCFU_GM); } /** * Saves the invitro OxidativeBurst characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addOxidativeBurst(String particleType, String particleName, OxidativeBurstBean oxidativeBurst) throws Exception { Characterization doOxidativeBurst = oxidativeBurst.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doOxidativeBurst); } /** * Saves the invitro Phagocytosis characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addPhagocytosis(String particleType, String particleName, PhagocytosisBean phagocytosis) throws Exception { Characterization doPhagocytosis = phagocytosis.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doPhagocytosis); } /** * Saves the invitro CytokineInduction characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addCytokineInduction(String particleType, String particleName, CytokineInductionBean cytokineInduction) throws Exception { Characterization doCytokineInduction = cytokineInduction.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doCytokineInduction); } /** * Saves the invitro plasma protein binding characterization to the database * * @param particleType * @param particleName * @param plasmaProteinBinding * @throws Exception */ public void addProteinBinding(String particleType, String particleName, PlasmaProteinBindingBean plasmaProteinBinding) throws Exception { Characterization doProteinBinding = plasmaProteinBinding.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doProteinBinding); } /** * Saves the invitro CellViability binding characterization to the database * * @param particleType * @param particleName * @param plasmaProteinBinding * @throws Exception */ public void addCellViability(String particleType, String particleName, CellViabilityBean cellViability) throws Exception { Characterization doCellViability = cellViability.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doCellViability); } /** * Saves the invitro EnzymeInduction binding characterization to the * database * * @param particleType * @param particleName * @param plasmaProteinBinding * @throws Exception */ public void addEnzymeInduction(String particleType, String particleName, EnzymeInductionBean enzymeInduction) throws Exception { Characterization EnzymeInduction = enzymeInduction.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, EnzymeInduction); } /** * Saves the invitro OxidativeStress characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addOxidativeStress(String particleType, String particleName, OxidativeStressBean oxidativeStress) throws Exception { Characterization doOxidativeStress = oxidativeStress.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doOxidativeStress); } /** * Saves the invitro Caspase3Activation characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addCaspase3Activation(String particleType, String particleName, Caspase3ActivationBean caspase3Activation) throws Exception { Characterization doCaspase3Activation = caspase3Activation .getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doCaspase3Activation); } /** * Saves the invitro GlucuronidationSulphation characterization to the * database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addGlucuronidationSulphation(String particleType, String particleName, GlucuronidationSulphationBean glucuronidationSulphation) throws Exception { Characterization doGlucuronidationSulphation = glucuronidationSulphation .getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doGlucuronidationSulphation); } /** * Saves the invitro CYP450 characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addCYP450(String particleType, String particleName, CYP450Bean cyp450) throws Exception { Characterization doCYP450 = cyp450.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doCYP450); } /** * Saves the invitro ROS characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addROS(String particleType, String particleName, ROSBean ros) throws Exception { Characterization doROS = ros.getDomainObj(); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doROS); } /** * Save the characterization file into the database and file system * * @param particleName * @param file * @param title * @param description * @param comments * @param keywords * @param visibilities */ public CharacterizationFileBean saveCharacterizationFile( String particleName, FormFile file, String title, String description, String comments, String[] keywords, String[] visibilities, String path, String fileNumber, String rootPath) throws Exception { // TODO saves file to the file system HttpFileUploadSessionData sData = new HttpFileUploadSessionData(); String tagFileName = sData.getTimeStamp() + "_" + file.getFileName(); String outputFilename = rootPath + path + tagFileName; FileOutputStream oStream = new FileOutputStream( new File(outputFilename)); this.saveFile(file.getInputStream(), oStream); LabFile dataFile = new DerivedDataFile(); dataFile.setDescription(description); dataFile.setFilename(file.getFileName()); // TODO need to remove the predefine the root path from outputFilename dataFile.setPath(path + tagFileName); dataFile.setTitle(title); // TODO saves file to the database IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); ida.store(dataFile); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization File: "); throw e; } finally { ida.close(); } CharacterizationFileBean fileBean = new CharacterizationFileBean( dataFile); UserService userService = new UserService(CalabConstants.CSM_APP_NAME); String fileName = fileBean.getName(); if (visibilities != null) { for (String visibility : visibilities) { // by default, always set visibility to NCL_PI and // NCL_Researcher to // be true // TODO once the files is successfully saved, use fileId instead // of fileName userService.secureObject(fileBean.getId(), "NCL_PI", "R"); userService.secureObject(fileBean.getId(), "NCL_Researcher", "R"); userService.secureObject(fileBean.getId(), visibility, "R"); } } return fileBean; } /** * Save the characterization file into the database and file system * * @param fileId * @param title * @param description * @param keywords * @param visibilities */ public CharacterizationFileBean saveCharacterizationFile(String fileId, String title, String description, String[] keywords, String[] visibilities) throws Exception { CharacterizationFileBean fileBean = getFile(fileId); fileBean.setTitle(title); fileBean.setDescription(description); DerivedDataFile dataFile = fileBean.getDomainObject(); // TODO saves file to the database IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); ida.createObject(dataFile); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization File: "); throw e; } finally { ida.close(); } UserService userService = new UserService(CalabConstants.CSM_APP_NAME); fileBean = new CharacterizationFileBean(dataFile); String fileName = fileBean.getName(); if (visibilities != null) { for (String visibility : visibilities) { // by default, always set visibility to NCL_PI and // NCL_Researcher to // be true // TODO once the files is successfully saved, use fileId instead // of fileName userService.secureObject(fileBean.getId(), "NCL_PI", "R"); userService.secureObject(fileBean.getId(), "NCL_Researcher", "R"); userService.secureObject(fileBean.getId(), visibility, "R"); } } return fileBean; } public void saveFile(InputStream is, FileOutputStream os) { byte[] bytes = new byte[32768]; try { int numRead = 0; while ((numRead = is.read(bytes)) > 0) { os.write(bytes, 0, numRead); } os.close(); } catch (Exception e) { } } public void addParticleFunction(String particleType, String particleName, FunctionBean function) throws Exception { Function doFunction = function.getDomainObj(); // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; int existingViewTitleCount = -1; try { ida.open(); if (doFunction.getLinkageCollection() != null) { for (Linkage linkage : doFunction.getLinkageCollection()){ Agent agent = linkage.getAgent(); if (agent != null) { for(AgentTarget agentTarget: agent.getAgentTargetCollection()) { ida.store(agentTarget); } ida.store(agent); } ida.store(linkage); } } // check if viewTitle is already used the same type of // characterization for the same particle String viewTitleQuery = ""; if (function.getId() == null) { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + doFunction.getIdentificationName() + "' "; // and // function.type='" // doFunction.getType() } else { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + doFunction.getIdentificationName() + "' and function.id!=" + function.getId(); // + "' and function.type='" // + function.getType() } List viewTitleResult = ida.search(viewTitleQuery); for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount == 0) { // if ID exists, do update if (doFunction.getId() != null) { ida.store(doFunction); } else {// get the existing particle and compositions // from database // created // during sample // creation List results = ida .search("select particle from Nanoparticle particle left join fetch particle.functionCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { // ida.store(doFunction); particle.getFunctionCollection().add(doFunction); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization: "); throw e; } finally { ida.close(); } if (existingViewTitleCount > 0) { throw new CalabException( "The view title is already in use. Please enter a different one."); } } /** * Load the file for the given fileId from the database * * @param fileId * @return */ public CharacterizationFileBean getFile(String fileId) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); CharacterizationFileBean fileBean = null; try { ida.open(); LabFile charFile = (LabFile) ida.load(LabFile.class, StringUtils .convertToLong(fileId)); fileBean = new CharacterizationFileBean(charFile); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting file with file ID: " + fileId); throw e; } finally { ida.close(); } return fileBean; } /** * Get the list of all run output files associated with a particle * * @param particleName * @return * @throws Exception */ public List<CharacterizationFileBean> getAllRunFiles(String particleName) throws Exception { List<CharacterizationFileBean> runFiles = new ArrayList<CharacterizationFileBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String query = "select distinct outFile from Run run join run.outputFileCollection outFile join run.runSampleContainerCollection runContainer where runContainer.sampleContainer.sample.name='" + particleName + "'"; List results = ida.search(query); for (Object obj : results) { OutputFile file = (OutputFile) obj; // active status only if (file.getDataStatus() == null) { CharacterizationFileBean fileBean = new CharacterizationFileBean(); fileBean.setId(file.getId().toString()); fileBean.setName(file.getFilename()); fileBean.setPath(file.getPath()); runFiles.add(fileBean); } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting run files for particle: " + particleName); throw e; } finally { ida.close(); } return runFiles; } }
package net.fortuna.ical4j.model.component; import java.io.FileInputStream; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Calendar; import java.util.Iterator; import junit.framework.TestSuite; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentTest; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.Recur; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.WeekDay; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.util.Calendars; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.UidGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A test case for VEvents. * @author Ben Fortuna */ public class VEventTest extends ComponentTest { private static Log log = LogFactory.getLog(VEventTest.class); private VEvent event; private Period period; private Date date; private TzId tzParam; /** * @param testMethod */ public VEventTest(String testMethod) { super(testMethod, null); } /** * @param testMethod * @param component */ public VEventTest(String testMethod, VEvent event) { super(testMethod, event); this.event = event; } /** * @param testMethod * @param component * @param period */ public VEventTest(String testMethod, VEvent component, Period period) { this(testMethod, component); this.period = period; } /** * @param testMethod * @param component * @param date */ public VEventTest(String testMethod, VEvent component, Date date) { this(testMethod, component); this.date = date; } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ public void setUp() throws Exception { super.setUp(); // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); // create timezone property.. VTimeZone tz = registry.getTimeZone("Australia/Melbourne").getVTimeZone(); // create tzid parameter.. tzParam = new TzId(tz.getProperty(Property.TZID).getValue()); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_VALIDATION, false); super.tearDown(); } /** * @return */ private static Calendar getCalendarInstance() { return Calendar.getInstance(); //java.util.TimeZone.getTimeZone(TimeZones.GMT_ID)); } /** * @param filename * @return */ private net.fortuna.ical4j.model.Calendar loadCalendar(String filename) throws IOException, ParserException, ValidationException { net.fortuna.ical4j.model.Calendar calendar = Calendars.load( filename); calendar.validate(); log.info("File: " + filename); if (log.isDebugEnabled()) { log.debug("Calendar:\n=========\n" + calendar.toString()); } return calendar; } public final void testChristmas() { // create event start date.. java.util.Calendar calendar = getCalendarInstance(); calendar.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); calendar.set(java.util.Calendar.DAY_OF_MONTH, 25); DtStart start = new DtStart(new Date(calendar.getTime())); start.getParameters().add(tzParam); start.getParameters().add(Value.DATE); Summary summary = new Summary("Christmas Day; \n this is a, test\\"); VEvent christmas = new VEvent(); christmas.getProperties().add(start); christmas.getProperties().add(summary); log.info(christmas); } /** * Test creating an event with an associated timezone. */ public final void testMelbourneCup() { TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); TimeZone timezone = registry.getTimeZone("Australia/Melbourne"); java.util.Calendar cal = java.util.Calendar.getInstance(timezone); cal.set(java.util.Calendar.YEAR, 2005); cal.set(java.util.Calendar.MONTH, java.util.Calendar.NOVEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 15); cal.clear(java.util.Calendar.MINUTE); cal.clear(java.util.Calendar.SECOND); DateTime dt = new DateTime(cal.getTime()); dt.setTimeZone(timezone); VEvent melbourneCup = new VEvent(dt, "Melbourne Cup"); log.info(melbourneCup); } public final void test2() { java.util.Calendar cal = getCalendarInstance(); cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 25); VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day"); // initialise as an all-day event.. christmas.getProperty(Property.DTSTART).getParameters().add(Value.DATE); // add timezone information.. christmas.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(christmas); } public final void test3() { java.util.Calendar cal = getCalendarInstance(); // tomorrow.. cal.add(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 9); cal.set(java.util.Calendar.MINUTE, 30); VEvent meeting = new VEvent(new DateTime(cal.getTime().getTime()), new Dur(0, 1, 0, 0), "Progress Meeting"); // add timezone information.. meeting.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(meeting); } /** * Test Null Dates * Test Start today, End One month from now. * * @throws Exception */ public final void testGetConsumedTime() throws Exception { // Test Null Dates try { event.getConsumedTime(null, null); fail("Should've thrown an exception."); } catch (RuntimeException re) { log.info("Expecting an exception here."); } // Test Start 04/01/2005, End One month later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0); queryStartDate.set(Calendar.MILLISECOND, 0); DateTime queryStart = new DateTime(queryStartDate.getTime().getTime()); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.MAY, 1, 07, 15, 0); queryEndDate.set(Calendar.MILLISECOND, 0); DateTime queryEnd = new DateTime(queryEndDate.getTime().getTime()); Calendar week1EndDate = getCalendarInstance(); week1EndDate.set(2005, Calendar.APRIL, 8, 11, 15, 0); week1EndDate.set(Calendar.MILLISECOND, 0); Calendar week4StartDate = getCalendarInstance(); week4StartDate.set(2005, Calendar.APRIL, 24, 14, 47, 0); week4StartDate.set(Calendar.MILLISECOND, 0); // DateTime week4Start = new DateTime(week4StartDate.getTime().getTime()); // This range is monday to friday every three weeks, starting from // March 7th 2005, which means for our query dates we need // April 18th through to the 22nd. PeriodList weeklyPeriods = event.getConsumedTime(queryStart, queryEnd); // PeriodList dailyPeriods = dailyWeekdayEvents.getConsumedTime(queryStart, queryEnd); // week1EndDate.getTime()); // dailyPeriods.addAll(dailyWeekdayEvents.getConsumedTime(week4Start, queryEnd)); Calendar expectedCal = Calendar.getInstance(); //TimeZone.getTimeZone(TimeZones.GMT_ID)); expectedCal.set(2005, Calendar.APRIL, 1, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime().getTime()); expectedCal.set(2005, Calendar.APRIL, 1, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime().getTime()); assertNotNull(weeklyPeriods); assertTrue(weeklyPeriods.size() > 0); Period firstPeriod = (Period) weeklyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(dailyPeriods, weeklyPeriods); } public final void testGetConsumedTimeDaily() throws Exception { // Test Starts 04/03/2005, Ends One week later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 10, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every day (which has a filtering // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 10th. // PeriodList weeklyPeriods = // event.getConsumedTime(new DateTime(queryStartDate.getTime()), // new DateTime(queryEndDate.getTime())); PeriodList dailyPeriods = event.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(dailyPeriods); assertTrue(dailyPeriods.size() > 0); Period firstPeriod = (Period) dailyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(weeklyPeriods, dailyPeriods); } /** * Test whether you can select weekdays using a monthly frequency. * <p> * This test really belongs in RecurTest, but the weekly range test * in this VEventTest matches so perfectly with the daily range test * that should produce the same results for some weeks that it was * felt leveraging the existing test code was more important. * <p> * Section 4.3.10 of the iCalendar specification RFC 2445 reads: * <pre> * If an integer modifier is not present, it means all days of * this type within the specified frequency. * </pre> * This test ensures compliance. */ public final void testGetConsumedTimeMonthly() throws Exception { // Test Starts 04/03/2005, Ends two weeks later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 17, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every month (which has a multiplying // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 17th. PeriodList monthlyPeriods = event.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); // PeriodList dailyPeriods = // dailyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()), // new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(monthlyPeriods); assertTrue(monthlyPeriods.size() > 0); Period firstPeriod = (Period) monthlyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(dailyPeriods, monthlyPeriods); } public final void testGetConsumedTime2() throws Exception { String filename = "etc/samples/valid/derryn.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); Date start = new Date(); Calendar endCal = getCalendarInstance(); endCal.setTime(start); endCal.add(Calendar.WEEK_OF_YEAR, 4); // Date end = new Date(start.getTime() + (1000 * 60 * 60 * 24 * 7 * 4)); for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) { Component c = (Component) i.next(); if (c instanceof VEvent) { PeriodList consumed = ((VEvent) c).getConsumedTime(start, new Date(endCal.getTime().getTime())); log.debug("Event [" + c + "]"); log.debug("Consumed time [" + consumed + "]"); } } } public final void testGetConsumedTime3() throws Exception { String filename = "etc/samples/valid/calconnect10.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); VEvent vev = (VEvent) calendar.getComponent(Component.VEVENT); Date start = vev.getStartDate().getDate(); Calendar cal = getCalendarInstance(); cal.add(Calendar.YEAR, 1); Date latest = new Date(cal.getTime()); PeriodList pl = vev.getConsumedTime(start, latest); assertTrue(!pl.isEmpty()); } /** * Test COUNT rules. */ public void testGetConsumedTimeByCount() { Recur recur = new Recur(Recur.WEEKLY, 3); recur.setInterval(1); recur.getDayList().add(WeekDay.SU); log.info(recur); Calendar cal = getCalendarInstance(); cal.set(Calendar.DAY_OF_MONTH, 8); Date start = new DateTime(cal.getTime()); // cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 10); cal.add(Calendar.HOUR_OF_DAY, 1); Date end = new DateTime(cal.getTime()); // log.info(recur.getDates(start, end, Value.DATE_TIME)); RRule rrule = new RRule(recur); VEvent event = new VEvent(start, end, "Test recurrence COUNT"); event.getProperties().add(rrule); log.info(event); Calendar rangeCal = getCalendarInstance(); Date rangeStart = new DateTime(rangeCal.getTime()); rangeCal.add(Calendar.WEEK_OF_YEAR, 4); Date rangeEnd = new DateTime(rangeCal.getTime()); log.info(event.getConsumedTime(rangeStart, rangeEnd)); } /** * A test to confirm that the end date is calculated correctly * from a given start date and duration. */ public final void testEventEndDate() { Calendar cal = getCalendarInstance(); Date startDate = new Date(cal.getTime()); log.info("Start date: " + startDate); VEvent event = new VEvent(startDate, new Dur(3, 0, 0, 0), "3 day event"); Date endDate = event.getEndDate().getDate(); log.info("End date: " + endDate); cal.add(Calendar.DAY_OF_YEAR, 3); assertEquals(new Date(cal.getTime()), endDate); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate() throws ParseException { VEvent event1 = new VEvent(new DateTime("20050103T080000"), new Dur(0, 0, 15, 0), "Event 1"); Recur rRuleRecur = new Recur("FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR"); RRule rRule = new RRule(rRuleRecur); event1.getProperties().add(rRule); ParameterList parameterList = new ParameterList(); parameterList.add(Value.DATE); ExDate exDate = new ExDate(parameterList, "20050106"); event1.getProperties().add(exDate); Date start = new Date("20050106"); Date end = new Date("20050107"); PeriodList list = event1.getConsumedTime(start, end); assertTrue(list.isEmpty()); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate2() throws IOException, ParserException { FileInputStream fin = new FileInputStream("etc/samples/valid/friday13.ics"); net.fortuna.ical4j.model.Calendar calendar = new CalendarBuilder().build(fin); VEvent event = (VEvent) calendar.getComponent(Component.VEVENT); Calendar cal = Calendar.getInstance(); cal.set(1997, 8, 2); Date start = new Date(cal.getTime()); cal.set(1997, 8, 4); Date end = new Date(cal.getTime()); PeriodList periods = event.getConsumedTime(start, end); assertTrue(periods.isEmpty()); } /** * Test equality of events with different alarm sub-components. */ public void testEquals() { Date date = new Date(); String summary = "test event"; PropertyList props = new PropertyList(); props.add(new DtStart(date)); props.add(new Summary(summary)); VEvent e1 = new VEvent(props); VEvent e2 = new VEvent(props); assertTrue(e1.equals(e2)); e2.getAlarms().add(new VAlarm()); assertFalse(e1.equals(e2)); } public void testCalculateRecurrenceSetNotEmpty() { PeriodList recurrenceSet = event.calculateRecurrenceSet(period); assertTrue(!recurrenceSet.isEmpty()); } /** * Unit tests for {@link VEvent#getOccurrence(Date)}. */ public void testGetOccurrence() throws IOException, ParseException, URISyntaxException { VEvent occurrence = event.getOccurrence(date); assertNotNull(occurrence); assertEquals(event.getUid(), occurrence.getUid()); } /** * @return * @throws ValidationException * @throws ParseException * @throws URISyntaxException * @throws IOException */ public static TestSuite suite() throws ValidationException, ParseException, IOException, URISyntaxException { UidGenerator uidGenerator = new UidGenerator("1"); Calendar weekday9AM = getCalendarInstance(); weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0); weekday9AM.set(Calendar.MILLISECOND, 0); Calendar weekday5PM = getCalendarInstance(); weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0); weekday5PM.set(Calendar.MILLISECOND, 0); // Do the recurrence until December 31st. Calendar untilCal = getCalendarInstance(); untilCal.set(2005, Calendar.DECEMBER, 31); untilCal.set(Calendar.MILLISECOND, 0); Date until = new Date(untilCal.getTime().getTime()); // 9:00AM to 5:00PM Rule using weekly Recur recurWeekly = new Recur(Recur.WEEKLY, until); recurWeekly.getDayList().add(WeekDay.MO); recurWeekly.getDayList().add(WeekDay.TU); recurWeekly.getDayList().add(WeekDay.WE); recurWeekly.getDayList().add(WeekDay.TH); recurWeekly.getDayList().add(WeekDay.FR); recurWeekly.setInterval(1); recurWeekly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleWeekly = new RRule(recurWeekly); // 9:00AM to 5:00PM Rule using daily frequency Recur recurDaily = new Recur(Recur.DAILY, until); recurDaily.getDayList().add(WeekDay.MO); recurDaily.getDayList().add(WeekDay.TU); recurDaily.getDayList().add(WeekDay.WE); recurDaily.getDayList().add(WeekDay.TH); recurDaily.getDayList().add(WeekDay.FR); recurDaily.setInterval(1); recurDaily.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleDaily = new RRule(recurDaily); // 9:00AM to 5:00PM Rule using monthly frequency Recur recurMonthly = new Recur(Recur.MONTHLY, until); recurMonthly.getDayList().add(WeekDay.MO); recurMonthly.getDayList().add(WeekDay.TU); recurMonthly.getDayList().add(WeekDay.WE); recurMonthly.getDayList().add(WeekDay.TH); recurMonthly.getDayList().add(WeekDay.FR); recurMonthly.setInterval(1); recurMonthly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleMonthly = new RRule(recurMonthly); Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED WEEKLY"); VEvent weekdayNineToFiveEvents = new VEvent(); weekdayNineToFiveEvents.getProperties().add(rruleWeekly); weekdayNineToFiveEvents.getProperties().add(summary); DtStart dtStart = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtStart); DtEnd dtEnd = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtEnd); weekdayNineToFiveEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. weekdayNineToFiveEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED DAILY"); VEvent dailyWeekdayEvents = new VEvent(); dailyWeekdayEvents.getProperties().add(rruleDaily); dailyWeekdayEvents.getProperties().add(summary); DtStart dtStart2 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtStart2); DtEnd dtEnd2 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtEnd2); dailyWeekdayEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. dailyWeekdayEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED MONTHLY"); VEvent monthlyWeekdayEvents = new VEvent(); monthlyWeekdayEvents.getProperties().add(rruleMonthly); monthlyWeekdayEvents.getProperties().add(summary); DtStart dtStart3 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtStart3); DtEnd dtEnd3 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtEnd3); monthlyWeekdayEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. monthlyWeekdayEvents.validate(); TestSuite suite = new TestSuite(); //testCalculateRecurrenceSet.. DateTime periodStart = new DateTime("20050101T000000"); DateTime periodEnd = new DateTime("20051231T235959"); Period period = new Period(periodStart, periodEnd); suite.addTest(new VEventTest("testCalculateRecurrenceSetNotEmpty", weekdayNineToFiveEvents, period)); //testGetOccurrence.. suite.addTest(new VEventTest("testGetOccurrence", weekdayNineToFiveEvents, weekdayNineToFiveEvents.getStartDate().getDate())); //testGetConsumedTime.. suite.addTest(new VEventTest("testGetConsumedTime", weekdayNineToFiveEvents)); suite.addTest(new VEventTest("testGetConsumedTimeDaily", dailyWeekdayEvents)); suite.addTest(new VEventTest("testGetConsumedTimeMonthly", monthlyWeekdayEvents)); //test event validation.. UidGenerator ug = new UidGenerator("1"); Uid uid = ug.generateUid(); DtStart start = new DtStart(new Date()); DtEnd end = new DtEnd(new Date()); VEvent event = new VEvent(); event.getProperties().add(uid); event.getProperties().add(start); event.getProperties().add(end); suite.addTest(new VEventTest("testValidation", event)); event = (VEvent) event.copy(); // start = (DtStart) event.getProperty(Property.DTSTART); start = new DtStart(new DateTime()); start.getParameters().replace(Value.DATE_TIME); event.getProperties().remove(event.getProperty(Property.DTSTART)); event.getProperties().add(start); suite.addTest(new VEventTest("testValidation", event)); event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().remove(Value.DATE_TIME); end = (DtEnd) event.getProperty(Property.DTEND); end.getParameters().replace(Value.DATE_TIME); suite.addTest(new VEventTest("testValidation", event)); // test 1.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().replace(Value.DATE); suite.addTest(new VEventTest("testValidationException", event)); // test 2.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().replace(Value.DATE_TIME); end = (DtEnd) event.getProperty(Property.DTEND); end.getParameters().replace(Value.DATE); suite.addTest(new VEventTest("testValidationException", event)); // test 3.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().replace(Value.DATE); end = (DtEnd) event.getProperty(Property.DTEND); end.getParameters().replace(Value.DATE_TIME); suite.addTest(new VEventTest("testValidationException", event)); // test 3.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().remove(Value.DATE); end = (DtEnd) event.getProperty(Property.DTEND); end.getParameters().replace(Value.DATE); suite.addTest(new VEventTest("testValidationException", event)); suite.addTest(new VEventTest("testChristmas")); suite.addTest(new VEventTest("testMelbourneCup")); suite.addTest(new VEventTest("testGetConsumedTime2")); suite.addTest(new VEventTest("testGetConsumedTime3")); suite.addTest(new VEventTest("testGetConsumedTimeByCount")); suite.addTest(new VEventTest("testEventEndDate")); suite.addTest(new VEventTest("testGetConsumedTimeWithExDate")); suite.addTest(new VEventTest("testGetConsumedTimeWithExDate2")); suite.addTest(new VEventTest("testIsCalendarComponent")); suite.addTest(new VEventTest("testEquals")); suite.addTest(new VEventTest("testValidation")); return suite; } }
package gov.nih.nci.calab.service.submit; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.HibernateDataAccess; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.InstrumentConfiguration; import gov.nih.nci.calab.domain.Keyword; import gov.nih.nci.calab.domain.LabFile; import gov.nih.nci.calab.domain.LookupType; import gov.nih.nci.calab.domain.MeasureType; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.OutputFile; import gov.nih.nci.calab.domain.nano.characterization.Characterization; import gov.nih.nci.calab.domain.nano.characterization.CharacterizationFileType; import gov.nih.nci.calab.domain.nano.characterization.DatumName; import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData; import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayDataCategory; import gov.nih.nci.calab.domain.nano.characterization.invitro.CFU_GM; import gov.nih.nci.calab.domain.nano.characterization.invitro.Caspase3Activation; import gov.nih.nci.calab.domain.nano.characterization.invitro.CellLineType; import gov.nih.nci.calab.domain.nano.characterization.invitro.CellViability; import gov.nih.nci.calab.domain.nano.characterization.invitro.Chemotaxis; import gov.nih.nci.calab.domain.nano.characterization.invitro.Coagulation; import gov.nih.nci.calab.domain.nano.characterization.invitro.ComplementActivation; import gov.nih.nci.calab.domain.nano.characterization.invitro.CytokineInduction; import gov.nih.nci.calab.domain.nano.characterization.invitro.EnzymeInduction; import gov.nih.nci.calab.domain.nano.characterization.invitro.Hemolysis; import gov.nih.nci.calab.domain.nano.characterization.invitro.LeukocyteProliferation; import gov.nih.nci.calab.domain.nano.characterization.invitro.NKCellCytotoxicActivity; import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeBurst; import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeStress; import gov.nih.nci.calab.domain.nano.characterization.invitro.Phagocytosis; import gov.nih.nci.calab.domain.nano.characterization.invitro.PlasmaProteinBinding; import gov.nih.nci.calab.domain.nano.characterization.invitro.PlateletAggregation; import gov.nih.nci.calab.domain.nano.characterization.physical.MolecularWeight; import gov.nih.nci.calab.domain.nano.characterization.physical.Morphology; import gov.nih.nci.calab.domain.nano.characterization.physical.MorphologyType; import gov.nih.nci.calab.domain.nano.characterization.physical.Purity; import gov.nih.nci.calab.domain.nano.characterization.physical.Shape; import gov.nih.nci.calab.domain.nano.characterization.physical.ShapeType; import gov.nih.nci.calab.domain.nano.characterization.physical.Size; import gov.nih.nci.calab.domain.nano.characterization.physical.Solubility; import gov.nih.nci.calab.domain.nano.characterization.physical.SolventType; import gov.nih.nci.calab.domain.nano.characterization.physical.Surface; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ParticleComposition; import gov.nih.nci.calab.domain.nano.function.Agent; import gov.nih.nci.calab.domain.nano.function.AgentTarget; import gov.nih.nci.calab.domain.nano.function.Function; import gov.nih.nci.calab.domain.nano.function.Linkage; import gov.nih.nci.calab.domain.nano.particle.Nanoparticle; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.composition.CompositionBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.function.FunctionBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** * This class includes service calls involved in creating nanoparticle general * info and adding functions and characterizations for nanoparticles, as well as * creating reports. * * @author pansu * */ public class SubmitNanoparticleService { private static Logger logger = Logger .getLogger(SubmitNanoparticleService.class); // remove existing visibilities for the data private UserService userService; public SubmitNanoparticleService() throws Exception { userService = new UserService(CaNanoLabConstants.CSM_APP_NAME); } /** * Update keywords and visibilities for the particle with the given name and * type * * @param particleType * @param particleName * @param keywords * @param visibilities * @throws Exception */ public void addParticleGeneralInfo(String particleType, String particleName, String[] keywords, String[] visibilities) throws Exception { // save nanoparticle to the database IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // get the existing particle from database created during sample // creation List results = ida.search("from Nanoparticle where name='" + particleName + "' and type='" + particleType + "'"); Nanoparticle particle = null; for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle == null) { throw new CalabException("No such particle in the database"); } particle.getKeywordCollection().clear(); if (keywords != null) { for (String keyword : keywords) { Keyword keywordObj = new Keyword(); keywordObj.setName(keyword); particle.getKeywordCollection().add(keywordObj); } } } catch (Exception e) { ida.rollback(); logger .error("Problem updating particle with name: " + particleName); throw e; } finally { ida.close(); } userService.setVisiblity(particleName, visibilities); } /** * Save characterization to the database. * * @param particleType * @param particleName * @param achar * @throws Exception */ private void addParticleCharacterization(String particleType, String particleName, Characterization achar, CharacterizationBean charBean) throws Exception { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; int existingViewTitleCount = -1; try { ida.open(); // check if viewTitle is already used the same type of // characterization for the same particle boolean viewTitleUsed = isCharacterizationViewTitleUsed(ida, particleType, particleName, achar); if (!viewTitleUsed) { if (achar.getInstrumentConfiguration() != null) { addInstrumentConfig(achar.getInstrumentConfiguration(), ida); } // if ID exists, do update if (achar.getId() != null) { // check if ID is still valid try { Characterization storedChara = (Characterization) ida .load(Characterization.class, achar.getId()); } catch (Exception e) { throw new Exception( "This characterization is no longer in the database. Please log in again to refresh."); } ida.store(achar); } else {// get the existing particle and characterizations // from database created during sample creation List results = ida .search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getCharacterizationCollection().add(achar); } } } if (existingViewTitleCount > 0) { throw new Exception( "The view title is already in use. Please enter a different one."); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization. "); throw e; } finally { ida.close(); } // save file to the file system // if this block of code is inside the db try catch block, hibernate // doesn't persist derivedBioAssayData if (!achar.getDerivedBioAssayDataCollection().isEmpty()) { int count = 0; for (DerivedBioAssayData derivedBioAssayData : achar .getDerivedBioAssayDataCollection()) { DerivedBioAssayDataBean derivedBioAssayDataBean = new DerivedBioAssayDataBean( derivedBioAssayData); // assign visibility DerivedBioAssayDataBean unsaved = charBean .getDerivedBioAssayDataList().get(count); derivedBioAssayDataBean.setVisibilityGroups(unsaved .getVisibilityGroups()); saveCharacterizationFile(derivedBioAssayDataBean); count++; } } } public void addNewCharacterizationDataDropdowns( CharacterizationBean charBean, String characterizationName) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); if (!charBean.getDerivedBioAssayDataList().isEmpty()) { for (DerivedBioAssayDataBean derivedBioAssayDataBean : charBean .getDerivedBioAssayDataList()) { // add new characterization file type if necessary if (derivedBioAssayDataBean.getType().length() > 0) { CharacterizationFileType fileType = new CharacterizationFileType(); addLookupType(ida, fileType, derivedBioAssayDataBean .getType()); } // add new derived data cateory for (String category : derivedBioAssayDataBean .getCategories()) { addDerivedDataCategory(ida, category, characterizationName); } // add new datum name, measure type, and unit for (DatumBean datumBean : derivedBioAssayDataBean .getDatumList()) { addDatumName(ida, datumBean.getName(), characterizationName); MeasureType measureType = new MeasureType(); addLookupType(ida, measureType, datumBean .getStatisticsType()); addMeasureUnit(ida, datumBean.getUnit(), characterizationName); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization data drop downs. "); throw e; } finally { ida.close(); } } /* * check if viewTitle is already used the same type of characterization for * the same particle */ private boolean isCharacterizationViewTitleUsed(IDataAccess ida, String particleType, String particleName, Characterization achar) throws Exception { String viewTitleQuery = ""; if (achar.getId() == null) { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + achar.getIdentificationName() + "' and achar.name='" + achar.getName() + "'"; } else { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + achar.getIdentificationName() + "' and achar.name='" + achar.getName() + "' and achar.id!=" + achar.getId(); } List viewTitleResult = ida.search(viewTitleQuery); int existingViewTitleCount = -1; for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount > 0) { return true; } else { return false; } } /** * Save the file to the file system * * @param fileBean */ public void saveCharacterizationFile(DerivedBioAssayDataBean fileBean) throws Exception { byte[] fileContent = fileBean.getFileContent(); String rootPath = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); if (fileContent != null) { FileService fileService = new FileService(); fileService.writeFile(fileContent, rootPath + File.separator + fileBean.getUri()); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } private void addInstrumentConfig(InstrumentConfiguration instrumentConfig, IDataAccess ida) throws Exception { Instrument instrument = instrumentConfig.getInstrument(); // check if instrument is already in database List instrumentResults = ida .search("select instrument from Instrument instrument where instrument.type='" + instrument.getType() + "' and instrument.manufacturer='" + instrument.getManufacturer() + "'"); Instrument storedInstrument = null; for (Object obj : instrumentResults) { storedInstrument = (Instrument) obj; } if (storedInstrument != null) { instrument.setId(storedInstrument.getId()); } else { ida.createObject(instrument); } // if new instrumentConfig, save it if (instrumentConfig.getId() == null) { ida.createObject(instrumentConfig); } else { InstrumentConfiguration storedInstrumentConfig = (InstrumentConfiguration) ida .load(InstrumentConfiguration.class, instrumentConfig .getId()); storedInstrumentConfig.setDescription(instrumentConfig .getDescription()); storedInstrumentConfig.setInstrument(instrument); } } /** * Saves the particle composition to the database * * @param particleType * @param particleName * @param composition * @throws Exception */ public void addParticleComposition(String particleType, String particleName, CompositionBean composition) throws Exception { ParticleComposition doComp = composition.getDomainObj(); addParticleCharacterization(particleType, particleName, doComp, composition); } /** * O Saves the size characterization to the database * * @param particleType * @param particleName * @param size * @throws Exception */ public void addParticleSize(String particleType, String particleName, CharacterizationBean size) throws Exception { Size doSize = new Size(); size.updateDomainObj(doSize); addParticleCharacterization(particleType, particleName, doSize, size); } /** * Saves the size characterization to the database * * @param particleType * @param particleName * @param surface * @throws Exception */ public void addParticleSurface(String particleType, String particleName, CharacterizationBean surface) throws Exception { Surface doSurface = new Surface(); ((SurfaceBean) surface).updateDomainObj(doSurface); addParticleCharacterization(particleType, particleName, doSurface, surface); // addMeasureUnit(doSurface.getCharge().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_CHARGE); // addMeasureUnit(doSurface.getSurfaceArea().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_AREA); // addMeasureUnit(doSurface.getZetaPotential().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_ZETA_POTENTIAL); } private void addLookupType(IDataAccess ida, LookupType lookupType, String type) throws Exception { String className = lookupType.getClass().getSimpleName(); if (type != null && type.length() > 0) { List results = ida.search("select count(distinct name) from " + className + " type where name='" + type + "'"); lookupType.setName(type); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(lookupType); } } } private void addDatumName(IDataAccess ida, String name, String characterizationName) throws Exception { List results = ida.search("select count(distinct name) from DatumName" + " where characterizationName='" + characterizationName + "'" + " and name='" + name + "'"); DatumName datumName = new DatumName(); datumName.setName(name); datumName.setCharacterizationName(characterizationName); datumName.setDatumParsed(false); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(datumName); } } private void addDerivedDataCategory(IDataAccess ida, String name, String characterizationName) throws Exception { List results = ida .search("select count(distinct name) from DerivedBioAssayDataCategory" + " where characterizationName='" + characterizationName + "'" + " and name='" + name + "'"); DerivedBioAssayDataCategory category = new DerivedBioAssayDataCategory(); category.setName(name); category.setCharacterizationName(characterizationName); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(category); } } private void addLookupType(LookupType lookupType, String type) throws Exception { if (type != null && type.length() > 0) { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); String className = lookupType.getClass().getSimpleName(); try { ida.open(); List results = ida.search("select count(distinct name) from " + className + " type where name='" + type + "'"); lookupType.setName(type); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(lookupType); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving look up type: " + type); throw e; } finally { ida.close(); } } } // private void addMeasureUnit(String unit, String type) throws Exception { // if (unit == null || unit.length() == 0) { // return; // // if ID is not set save to the database otherwise update // IDataAccess ida = (new DataAccessProxy()) // .getInstance(IDataAccess.HIBERNATE); // MeasureUnit measureUnit = new MeasureUnit(); // try { // ida.open(); // List results = ida // .search("select count(distinct measureUnit.name) from " // + "MeasureUnit measureUnit where measureUnit.name='" // + unit + "' and measureUnit.type='" + type + "'"); // int count = -1; // for (Object obj : results) { // count = ((Integer) (obj)).intValue(); // if (count == 0) { // measureUnit.setName(unit); // measureUnit.setType(type); // ida.createObject(measureUnit); // } catch (Exception e) { // e.printStackTrace(); // ida.rollback(); // logger.error("Problem saving look up type: " + type); // throw e; // } finally { // ida.close(); private void addMeasureUnit(IDataAccess ida, String unit, String type) throws Exception { if (unit == null || unit.length() == 0) { return; } List results = ida.search("select count(distinct name) from " + " MeasureUnit where name='" + unit + "' and type='" + type + "'"); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } MeasureUnit measureUnit = new MeasureUnit(); if (count == 0) { measureUnit.setName(unit); measureUnit.setType(type); ida.createObject(measureUnit); } } /** * Saves the molecular weight characterization to the database * * @param particleType * @param particleName * @param molecularWeight * @throws Exception */ public void addParticleMolecularWeight(String particleType, String particleName, CharacterizationBean molecularWeight) throws Exception { MolecularWeight doMolecularWeight = new MolecularWeight(); molecularWeight.updateDomainObj(doMolecularWeight); addParticleCharacterization(particleType, particleName, doMolecularWeight, molecularWeight); } /** * Saves the morphology characterization to the database * * @param particleType * @param particleName * @param morphology * @throws Exception */ public void addParticleMorphology(String particleType, String particleName, CharacterizationBean morphology) throws Exception { Morphology doMorphology = new Morphology(); ((MorphologyBean) morphology).updateDomainObj(doMorphology); addParticleCharacterization(particleType, particleName, doMorphology, morphology); MorphologyType morphologyType = new MorphologyType(); addLookupType(morphologyType, doMorphology.getType()); } /** * Saves the shape characterization to the database * * @param particleType * @param particleName * @param shape * @throws Exception */ public void addParticleShape(String particleType, String particleName, CharacterizationBean shape) throws Exception { Shape doShape = new Shape(); ((ShapeBean) shape).updateDomainObj(doShape); addParticleCharacterization(particleType, particleName, doShape, shape); ShapeType shapeType = new ShapeType(); addLookupType(shapeType, doShape.getType()); } /** * Saves the purity characterization to the database * * @param particleType * @param particleName * @param purity * @throws Exception */ public void addParticlePurity(String particleType, String particleName, CharacterizationBean purity) throws Exception { Purity doPurity = new Purity(); purity.updateDomainObj(doPurity); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doPurity, purity); } /** * Saves the solubility characterization to the database * * @param particleType * @param particleName * @param solubility * @throws Exception */ public void addParticleSolubility(String particleType, String particleName, CharacterizationBean solubility) throws Exception { Solubility doSolubility = new Solubility(); ((SolubilityBean) solubility).updateDomainObj(doSolubility); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doSolubility, solubility); SolventType solventType = new SolventType(); addLookupType(solventType, doSolubility.getSolvent()); // addMeasureUnit(doSolubility.getCriticalConcentration() // .getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_CONCENTRATION); } /** * Saves the invitro hemolysis characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addHemolysis(String particleType, String particleName, CharacterizationBean hemolysis) throws Exception { Hemolysis doHemolysis = new Hemolysis(); hemolysis.updateDomainObj(doHemolysis); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doHemolysis, hemolysis); } /** * Saves the invitro coagulation characterization to the database * * @param particleType * @param particleName * @param coagulation * @throws Exception */ public void addCoagulation(String particleType, String particleName, CharacterizationBean coagulation) throws Exception { Coagulation doCoagulation = new Coagulation(); coagulation.updateDomainObj(doCoagulation); addParticleCharacterization(particleType, particleName, doCoagulation, coagulation); } /** * Saves the invitro plate aggregation characterization to the database * * @param particleType * @param particleName * @param plateletAggregation * @throws Exception */ public void addPlateletAggregation(String particleType, String particleName, CharacterizationBean plateletAggregation) throws Exception { PlateletAggregation doPlateletAggregation = new PlateletAggregation(); plateletAggregation.updateDomainObj(doPlateletAggregation); addParticleCharacterization(particleType, particleName, doPlateletAggregation, plateletAggregation); } /** * Saves the invitro Complement Activation characterization to the database * * @param particleType * @param particleName * @param complementActivation * @throws Exception */ public void addComplementActivation(String particleType, String particleName, CharacterizationBean complementActivation) throws Exception { ComplementActivation doComplementActivation = new ComplementActivation(); complementActivation.updateDomainObj(doComplementActivation); addParticleCharacterization(particleType, particleName, doComplementActivation, complementActivation); } /** * Saves the invitro chemotaxis characterization to the database * * @param particleType * @param particleName * @param chemotaxis * @throws Exception */ public void addChemotaxis(String particleType, String particleName, CharacterizationBean chemotaxis) throws Exception { Chemotaxis doChemotaxis = new Chemotaxis(); chemotaxis.updateDomainObj(doChemotaxis); addParticleCharacterization(particleType, particleName, doChemotaxis, chemotaxis); } /** * Saves the invitro NKCellCytotoxicActivity characterization to the * database * * @param particleType * @param particleName * @param nkCellCytotoxicActivity * @throws Exception */ public void addNKCellCytotoxicActivity(String particleType, String particleName, CharacterizationBean nkCellCytotoxicActivity) throws Exception { NKCellCytotoxicActivity doNKCellCytotoxicActivity = new NKCellCytotoxicActivity(); nkCellCytotoxicActivity.updateDomainObj(doNKCellCytotoxicActivity); addParticleCharacterization(particleType, particleName, doNKCellCytotoxicActivity, nkCellCytotoxicActivity); } /** * Saves the invitro LeukocyteProliferation characterization to the database * * @param particleType * @param particleName * @param leukocyteProliferation * @throws Exception */ public void addLeukocyteProliferation(String particleType, String particleName, CharacterizationBean leukocyteProliferation) throws Exception { LeukocyteProliferation doLeukocyteProliferation = new LeukocyteProliferation(); leukocyteProliferation.updateDomainObj(doLeukocyteProliferation); addParticleCharacterization(particleType, particleName, doLeukocyteProliferation, leukocyteProliferation); } /** * Saves the invitro CFU_GM characterization to the database * * @param particleType * @param particleName * @param cfu_gm * @throws Exception */ public void addCFU_GM(String particleType, String particleName, CharacterizationBean cfu_gm) throws Exception { CFU_GM doCFU_GM = new CFU_GM(); cfu_gm.updateDomainObj(doCFU_GM); addParticleCharacterization(particleType, particleName, doCFU_GM, cfu_gm); } /** * Saves the invitro OxidativeBurst characterization to the database * * @param particleType * @param particleName * @param oxidativeBurst * @throws Exception */ public void addOxidativeBurst(String particleType, String particleName, CharacterizationBean oxidativeBurst) throws Exception { OxidativeBurst doOxidativeBurst = new OxidativeBurst(); oxidativeBurst.updateDomainObj(doOxidativeBurst); addParticleCharacterization(particleType, particleName, doOxidativeBurst, oxidativeBurst); } /** * Saves the invitro Phagocytosis characterization to the database * * @param particleType * @param particleName * @param phagocytosis * @throws Exception */ public void addPhagocytosis(String particleType, String particleName, CharacterizationBean phagocytosis) throws Exception { Phagocytosis doPhagocytosis = new Phagocytosis(); phagocytosis.updateDomainObj(doPhagocytosis); addParticleCharacterization(particleType, particleName, doPhagocytosis, phagocytosis); } /** * Saves the invitro CytokineInduction characterization to the database * * @param particleType * @param particleName * @param cytokineInduction * @throws Exception */ public void addCytokineInduction(String particleType, String particleName, CharacterizationBean cytokineInduction) throws Exception { CytokineInduction doCytokineInduction = new CytokineInduction(); cytokineInduction.updateDomainObj(doCytokineInduction); addParticleCharacterization(particleType, particleName, doCytokineInduction, cytokineInduction); } /** * Saves the invitro plasma protein binding characterization to the database * * @param particleType * @param particleName * @param plasmaProteinBinding * @throws Exception */ public void addProteinBinding(String particleType, String particleName, CharacterizationBean plasmaProteinBinding) throws Exception { PlasmaProteinBinding doProteinBinding = new PlasmaProteinBinding(); plasmaProteinBinding.updateDomainObj(doProteinBinding); addParticleCharacterization(particleType, particleName, doProteinBinding, plasmaProteinBinding); } /** * Saves the invitro binding characterization to the database * * @param particleType * @param particleName * @param cellViability * @throws Exception */ public void addCellViability(String particleType, String particleName, CharacterizationBean cellViability) throws Exception { CellViability doCellViability = new CellViability(); ((CytotoxicityBean) cellViability).updateDomainObj(doCellViability); addParticleCharacterization(particleType, particleName, doCellViability, cellViability); CellLineType cellLineType = new CellLineType(); addLookupType(cellLineType, doCellViability.getCellLine()); } /** * Saves the invitro EnzymeInduction binding characterization to the * database * * @param particleType * @param particleName * @param enzymeInduction * @throws Exception */ public void addEnzymeInduction(String particleType, String particleName, CharacterizationBean enzymeInduction) throws Exception { EnzymeInduction doEnzymeInduction = new EnzymeInduction(); enzymeInduction.updateDomainObj(doEnzymeInduction); addParticleCharacterization(particleType, particleName, doEnzymeInduction, enzymeInduction); } /** * Saves the invitro OxidativeStress characterization to the database * * @param particleType * @param particleName * @param oxidativeStress * @throws Exception */ public void addOxidativeStress(String particleType, String particleName, CharacterizationBean oxidativeStress) throws Exception { OxidativeStress doOxidativeStress = new OxidativeStress(); oxidativeStress.updateDomainObj(doOxidativeStress); addParticleCharacterization(particleType, particleName, doOxidativeStress, oxidativeStress); } /** * Saves the invitro Caspase3Activation characterization to the database * * @param particleType * @param particleName * @param caspase3Activation * @throws Exception */ public void addCaspase3Activation(String particleType, String particleName, CharacterizationBean caspase3Activation) throws Exception { Caspase3Activation doCaspase3Activation = new Caspase3Activation(); caspase3Activation.updateDomainObj(doCaspase3Activation); addParticleCharacterization(particleType, particleName, doCaspase3Activation, caspase3Activation); CellLineType cellLineType = new CellLineType(); addLookupType(cellLineType, doCaspase3Activation.getCellLine()); } public void setCharacterizationFile(String particleName, String characterizationName, LabFileBean fileBean) { } public void addParticleFunction(String particleType, String particleName, FunctionBean function) throws Exception { Function doFunction = function.getDomainObj(); // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; int existingViewTitleCount = -1; try { // Have to seperate this section out in a different hibernate // session. // check linkage id object type ida.open(); if (doFunction.getId() != null && doFunction.getLinkageCollection() != null) { for (Linkage linkage : doFunction.getLinkageCollection()) { // check linkage id object type if (linkage.getId() != null) { List result = ida .search("from Linkage linkage where linkage.id = " + linkage.getId()); if (result != null && result.size() > 0) { Linkage existingObj = (Linkage) result.get(0); // the the type is different, if (existingObj.getClass() != linkage.getClass()) { linkage.setId(null); ida.removeObject(existingObj); } } } } } ida.close(); ida.open(); if (doFunction.getLinkageCollection() != null) { for (Linkage linkage : doFunction.getLinkageCollection()) { Agent agent = linkage.getAgent(); if (agent != null) { for (AgentTarget agentTarget : agent .getAgentTargetCollection()) { ida.store(agentTarget); } ida.store(agent); } ida.store(linkage); } } boolean viewTitleUsed = isFunctionViewTitleUsed(ida, particleType, particleName, doFunction); if (!viewTitleUsed) { if (doFunction.getId() != null) { ida.store(doFunction); } else {// get the existing particle and compositions // from database created during sample creation List results = ida .search("select particle from Nanoparticle particle left join fetch particle.functionCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getFunctionCollection().add(doFunction); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization: "); throw e; } finally { ida.close(); } if (existingViewTitleCount > 0) { throw new CalabException( "The view title is already in use. Please enter a different one."); } } /* * check if viewTitle is already used the same type of function for the same * particle */ private boolean isFunctionViewTitleUsed(IDataAccess ida, String particleType, String particleName, Function function) throws Exception { // check if viewTitle is already used the same type of // function for the same particle String viewTitleQuery = ""; if (function.getId() == null) { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + function.getIdentificationName() + "' and function.type='" + function.getType() + "'"; } else { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + function.getIdentificationName() + "' and function.id!=" + function.getId() + " and function.type='" + function.getType() + "'"; } List viewTitleResult = ida.search(viewTitleQuery); int existingViewTitleCount = -1; for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount > 0) { return true; } else { return false; } } /** * Load the file for the given fileId from the database * * @param fileId * @return */ public LabFileBean getFile(String fileId) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); LabFileBean fileBean = null; try { ida.open(); LabFile file = (LabFile) ida.load(LabFile.class, StringUtils .convertToLong(fileId)); fileBean = new LabFileBean(file); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting file with file ID: " + fileId); throw e; } finally { ida.close(); } // get visibilities UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = userService.getAccessibleGroups( fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups.toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); return fileBean; } /** * Load the derived data file for the given fileId from the database * * @param fileId * @return */ public DerivedBioAssayDataBean getDerivedBioAssayData(String fileId) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); DerivedBioAssayDataBean fileBean = null; try { ida.open(); DerivedBioAssayData file = (DerivedBioAssayData) ida.load( DerivedBioAssayData.class, StringUtils .convertToLong(fileId)); // load keywords file.getKeywordCollection(); fileBean = new DerivedBioAssayDataBean(file, CaNanoLabConstants.OUTPUT); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting file with file ID: " + fileId); throw e; } finally { ida.close(); } // get visibilities UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = userService.getAccessibleGroups( fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups.toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); return fileBean; } /** * Get the list of all run output files associated with a particle * * @param particleName * @return * @throws Exception */ public List<LabFileBean> getAllRunFiles(String particleName) throws Exception { List<LabFileBean> runFiles = new ArrayList<LabFileBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String query = "select distinct outFile from Run run join run.outputFileCollection outFile join run.runSampleContainerCollection runContainer where runContainer.sampleContainer.sample.name='" + particleName + "'"; List results = ida.search(query); for (Object obj : results) { OutputFile file = (OutputFile) obj; // active status only if (file.getDataStatus() == null) { LabFileBean fileBean = new LabFileBean(); fileBean.setId(file.getId().toString()); fileBean.setName(file.getFilename()); fileBean.setUri(file.getUri()); runFiles.add(fileBean); } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting run files for particle: " + particleName); throw e; } finally { ida.close(); } return runFiles; } /** * Update the meta data associated with a file stored in the database * * @param fileBean * @throws Exception */ public void updateFileMetaData(LabFileBean fileBean) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); LabFile file = (LabFile) ida.load(LabFile.class, StringUtils .convertToLong(fileBean.getId())); file.setTitle(fileBean.getTitle().toUpperCase()); file.setDescription(fileBean.getDescription()); file.setComments(fileBean.getComments()); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem updating file meta data: "); throw e; } finally { ida.close(); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } /** * Update the meta data associated with a file stored in the database * * @param fileBean * @throws Exception */ public void updateDerivedBioAssayDataMetaData( DerivedBioAssayDataBean fileBean) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); DerivedBioAssayData file = (DerivedBioAssayData) ida.load( DerivedBioAssayData.class, StringUtils .convertToLong(fileBean.getId())); file.setTitle(fileBean.getTitle().toUpperCase()); file.setDescription(fileBean.getDescription()); file.getKeywordCollection().clear(); if (fileBean.getKeywords() != null) { for (String keyword : fileBean.getKeywords()) { Keyword keywordObj = new Keyword(); keywordObj.setName(keyword); file.getKeywordCollection().add(keywordObj); } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem updating derived data file meta data: "); throw e; } finally { ida.close(); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } /** * Delete the characterization */ public void deleteCharacterization(String strCharId) throws Exception { // if ID is not set save to the database otherwise update HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // Get ID Long charId = Long.parseLong(strCharId); Object charObj = ida.load(Characterization.class, charId); ida.delete(charObj); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization: "); throw e; } finally { ida.close(); } } /** * Delete the characterizations */ public void deleteCharacterizations(String particleName, String particleType, String[] charIds) throws Exception { // if ID is not set save to the database otherwise update HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // Get ID for (String strCharId : charIds) { Long charId = Long.parseLong(strCharId); Object charObj = ida.load(Characterization.class, charId); // deassociate first String hqlString = "from Nanoparticle particle where particle.characterizationCollection.id = '" + strCharId + "'"; List results = ida.search(hqlString); for (Object obj : results) { Nanoparticle particle = (Nanoparticle) obj; particle.getCharacterizationCollection().remove(charObj); } // then delete ida.delete(charObj); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem deleting characterization: "); throw new Exception( "The characterization is no longer exist in the database, please login again to refresh the view."); } finally { ida.close(); } } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class XexunProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { XexunProtocolDecoder decoder = new XexunProtocolDecoder(new XexunProtocol(), false); verifyNothing(decoder, text( "GPRMC,215853.000,A,5304.9600,N,6.7907,E,1.43,80.67,250216,00,0000.0,A*47,F,,imei:351525018007873,")); verifyPosition(decoder, text( "GPRMC,121535.000,A,5417.2666,N,04822.1264,E,1.452,30.42,031014,0.0,A*4D\r\n,L,imei:355227042011730,")); verifyPosition(decoder, text( "GPRMC,150120.000,A,3346.4463,S,15057.3083,E,0.0,117.4,010911,,,A*76,F,imei:351525010943661,"), position("2011-09-01 15:01:20.000", true, -33.77411, 150.95514)); verifyPosition(decoder, text( "GPRMC,010203.000,A,0102.0003,N,00102.0003,E,1.02,1.02,010203,,,A*00,F,,imei:10000000000000,")); verifyPosition(decoder, text( "GPRMC,233842.000,A,5001.3060,N,01429.3243,E,0.00,,210211,,,A*74,F,imei:354776030495631,")); verifyPosition(decoder, text( "GPRMC,080303.000,A,5546.7313,N,03738.6005,E,0.56,160.13,100311,,,A*6A,L,imei:354778030461167,")); verifyPosition(decoder, text( "GPRMC,220828.678,A,5206.1446,N,02038.2403,,0,0,160912,,,E*23,L,imei:358948012501019,")); verifyPosition(decoder, text( "GNRMC,134418.000,A,5533.8973,N,03745.4398,E,0.00,308.85,160215,,,A*7A,F,, imei:864244028033115,")); verifyPosition(decoder, text( "GPRMC,093341.000,A,1344.5716,N,10033.6648,E,0.00,0.00,240215,,,A*68,F,,imei:865328028306149,")); verifyPosition(decoder, text( "GPRMC,103731.636,A,4545.5266,N,00448.8259,E,21.12,276.01,150615,,,A*57,L,, imei:013949002026675,")); verifyPosition(decoder, text( "GPRMC,014623.000,A,4710.8260,N,1948.1220,E,0.11,105.40,111212,00,0000.0,A*49,F,,imei:357713002048962,")); verifyPosition(decoder, text( "GPRMC,043435.000,A,811.299200,S,11339.9500,E,0.93,29.52,160313,00,0000.0,A*65,F,,imei:359585014597923,")); decoder = new XexunProtocolDecoder(new XexunProtocol(), true); verifyNothing(decoder, text( ",+48606717068,,L,, imei:012207005047292,,,F:4.28V,1,52,11565,247,01,000E,1FC5")); verifyPosition(decoder, text( "130302125349,+79604870506,GPRMC,085349.000,A,4503.2392,N,03858.5660,E,6.95,154.65,020313,,,A*6C,F,, imei:012207007744243,03,-1.5,F:4.15V,1,139,28048,250,01,278A,5072"), position("2013-03-02 08:53:49.000", true, 45.05399, 38.97610)); verifyPosition(decoder, text( "111111120009,+436763737552,GPRMC,120009.590,A,4639.6774,N,01418.5737,E,0.00,0.00,111111,,,A*68,F,, imei:359853000144328,04,481.2,F:4.15V,0,139,2689,232,03,2725,0576")); verifyPosition(decoder, text( "111111120009,+436763737552,GPRMC,120600.000,A,6000.0000,N,13000.0000,E,0.00,0.00,010112,,,A*68,F,help me!, imei:123456789012345,04,481.2,F:4.15V,0,139,2689,232,03,2725,0576")); verifyPosition(decoder, text( "111111120009,+436763737552,GPRMC,120600.000,A,6000.0000,N,13000.0000,E,0.00,0.00,010112,,,A*68,F,help me!, imei:123456789012345,04,481.2,L:3.5V,0,139,2689,232,03,2725,0576")); verifyPosition(decoder, text( "111111120009,436763737552,GPRMC,120600.000,A,6000.0000,N,13000.0000,E,0.00,0.00,010112,,,A*68,F,help me!, imei:123456789012345,04,481.2,L:3.5V,0,139,2689,232,03,2725,0576")); verifyPosition(decoder, text( "111111120009,+1234,GPRMC,204530.4,A,6000.0000,N,13000.0000,E,0.0,,010112,0.0,E,A*68,F,imei:123456789012345,04,123.5,F:3.55V,0,139,,232,03,272CE1,0576")); verifyPosition(decoder, text( "111111120009,+1234,GPRMC,204530.4,A,6000.000,N,01000.6288,E,0.0,0.00,230713,0.0,E,A*3C,F,imei:123456789012345,00,,F:3.88V,0,125,,262,01,224CE1,379B")); verifyPosition(decoder, text( "111111120009,+1234,GPRMC,215840.7,A,6000.000,N,01000.6253,E,0.0,0.00,230713,0.0,E,A*34,F,imei:123456789012345,00,,F:3.9V,0,124,,262,01,224CE1,379B")); verifyPosition(decoder, text( "130725134142,,GPRMC,134142.591,A,3845.6283,N,00909.8876,W,2.08,287.33,250713,,,A*71,F,, imei:013227000526784,03,-50.7,L:3.69V,0,128,65337,268,03,177A,119F")); verifyPosition(decoder, text( "140602152533,TESCO_INFO,GPRMC,152533.000,A,5145.4275,N,00000.3448,E,0.00,0.00,020614,,,A*66,F,, imei:013227002781643,06,35.1,F:4.15V,1,135,38950,234,10,10B4,5235")); verifyPosition(decoder, text( "150216154418,5277,GNRMC,134418.000,A,5533.8973,N,03745.4398,E,0.00,308.85,160215,,,A*7A,F,, imei:864244028033115,10,169.8,F:4.28V,1,132,48269,250,99,6D0D,8572")); verifyPosition(decoder, text( "150224173341,+66961544651,GPRMC,093341.000,A,1344.5716,N,10033.6648,E,0.00,0.00,240215,,,A*68,F,,imei:865328028306149,05,106.4,F:4.01V/ADC1=0.20V/ADC2=0.00V,0,159,955,520,01,5DE8,0399,6.21km")); verifyPosition(decoder, text( "150316182840,07872167745,GPRMC,182840.000,A,5126.1310,N,00055.5573,W,0.00,0.00,160315,,,A*7C,F,,imei:865328023469306,06,54.3,F:4.10V/ADC1=0.76V/ADC2=0.00V,0,157,38486,234,10,34DC,48A6,3.70km")); verifyPosition(decoder, text( "150615123731,+33647384611,GPRMC,103731.636,A,4545.5266,N,00448.8259,E,21.12,276.01,150615,,,A*57,L,, imei:013949002026675,04,3522.9,F:3.72V,0,142,21744,208,01,0702,9C8C")); } }
package org.rstudio.studio.client.common.shell; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.rstudio.core.client.ConsoleOutputWriter; import org.rstudio.core.client.ElementIds; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.TimeBufferedCommand; import org.rstudio.core.client.VirtualConsole; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.jsonrpc.RpcObjectList; import org.rstudio.core.client.widget.BottomScrollPanel; import org.rstudio.core.client.widget.FontSizer; import org.rstudio.core.client.widget.PreWidget; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.AriaLiveService; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.debugging.model.UnhandledError; import org.rstudio.studio.client.common.debugging.ui.ConsoleError; import org.rstudio.studio.client.workbench.model.ConsoleAction; import org.rstudio.studio.client.workbench.prefs.model.UserPrefs; import org.rstudio.studio.client.workbench.views.console.ConsoleResources; import org.rstudio.studio.client.workbench.views.console.events.RunCommandWithDebugEvent; import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor.NewLineMode; import org.rstudio.studio.client.workbench.views.source.editors.text.events.CursorChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.CursorChangedHandler; import org.rstudio.studio.client.workbench.views.source.editors.text.events.PasteEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.themes.AceTheme; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.SpanElement; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RequiresResize; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; public class ShellWidget extends Composite implements ShellDisplay, RequiresResize, ConsoleError.Observer { public ShellWidget(AceEditor editor, UserPrefs prefs, EventBus events, AriaLiveService ariaLive) { styles_ = ConsoleResources.INSTANCE.consoleStyles(); events_ = events; prefs_ = prefs; ariaLive_ = ariaLive; SelectInputClickHandler secondaryInputHandler = new SelectInputClickHandler(); output_ = new ConsoleOutputWriter(RStudioGinjector.INSTANCE.getVirtualConsoleFactory()); output_.getWidget().setStylePrimaryName(styles_.output()); output_.getWidget().addClickHandler(secondaryInputHandler); ElementIds.assignElementId(output_.getElement(), ElementIds.CONSOLE_OUTPUT); output_.getWidget().addPasteHandler(secondaryInputHandler); pendingInput_ = new PreWidget(); pendingInput_.setStyleName(styles_.output()); pendingInput_.addClickHandler(secondaryInputHandler); prompt_ = new HTML(); prompt_.setStylePrimaryName(styles_.prompt()); prompt_.addStyleName(KEYWORD_CLASS_NAME); input_ = editor; input_.setShowLineNumbers(false); input_.setShowPrintMargin(false); if (!Desktop.isDesktop()) input_.setNewLineMode(NewLineMode.Unix); input_.setUseWrapMode(true); input_.setPadding(0); input_.autoHeight(); final Widget inputWidget = input_.asWidget(); ElementIds.assignElementId(inputWidget.getElement(), ElementIds.CONSOLE_INPUT); input_.addClickHandler(secondaryInputHandler); inputWidget.addStyleName(styles_.input()); input_.addCursorChangedHandler(new CursorChangedHandler() { @Override public void onCursorChanged(CursorChangedEvent event) { Scheduler.get().scheduleDeferred(() -> input_.scrollToCursor(scrollPanel_, 8, 60)); } }); input_.addCapturingKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { // Don't capture keys when a completion popup is visible. if (input_.isPopupVisible()) return; // If the user hits PageUp or PageDown from inside the console // input, we need to simulate its action because focus is not contained // in the scroll panel (it's in the hidden textarea that Ace uses // under the covers). int keyCode = event.getNativeKeyCode(); switch (keyCode) { case KeyCodes.KEY_PAGEUP: { event.stopPropagation(); event.preventDefault(); // Can't scroll any further up. Return before we change focus. if (scrollPanel_.getVerticalScrollPosition() == 0) return; int newScrollTop = scrollPanel_.getVerticalScrollPosition() - scrollPanel_.getOffsetHeight() + 40; scrollPanel_.focus(); scrollPanel_.setVerticalScrollPosition(Math.max(0, newScrollTop)); break; } case KeyCodes.KEY_PAGEDOWN: { event.stopPropagation(); event.preventDefault(); if (scrollPanel_.isScrolledToBottom()) return; int newScrollTop = scrollPanel_.getVerticalScrollPosition() + scrollPanel_.getOffsetHeight() - 40; scrollPanel_.focus(); scrollPanel_.setVerticalScrollPosition(newScrollTop); break; } } } }); input_.addFocusHandler(event -> scrollToBottom()); inputLine_ = new DockPanel(); inputLine_.setHorizontalAlignment(DockPanel.ALIGN_LEFT); inputLine_.setVerticalAlignment(DockPanel.ALIGN_TOP); inputLine_.add(prompt_, DockPanel.WEST); inputLine_.setCellWidth(prompt_, "1"); inputLine_.add(input_.asWidget(), DockPanel.CENTER); inputLine_.setCellWidth(input_.asWidget(), "100%"); inputLine_.setWidth("100%"); verticalPanel_ = new VerticalPanel(); verticalPanel_.setStylePrimaryName(styles_.console()); FontSizer.applyNormalFontSize(verticalPanel_); verticalPanel_.add(output_.getWidget()); verticalPanel_.add(pendingInput_); verticalPanel_.add(inputLine_); verticalPanel_.setWidth("100%"); scrollPanel_ = new ClickableScrollPanel(); scrollPanel_.setWidget(verticalPanel_); scrollPanel_.addStyleName("ace_editor"); scrollPanel_.addStyleName("ace_scroller"); scrollPanel_.addClickHandler(secondaryInputHandler); scrollPanel_.addKeyDownHandler(secondaryInputHandler); secondaryInputHandler.setInput(editor); resizeCommand_ = new TimeBufferedCommand(5) { @Override protected void performAction(boolean shouldSchedulePassive) { scrollPanel_.onContentSizeChanged(); if (!DomUtils.selectionExists() && !scrollPanel_.isScrolledToBottom()) scrollPanel_.scrollToBottom(); } }; initWidget(scrollPanel_); addCopyHook(getElement()); } private native void addCopyHook(Element element) /*-{ if ($wnd.desktop) { var clean = function() { setTimeout(function() { $wnd.desktop.cleanClipboard(true); }, 100) }; element.addEventListener("copy", clean, true); element.addEventListener("cut", clean, true); } }-*/; public void scrollToBottom() { scrollPanel_.scrollToBottom(); } private boolean initialized_ = false; @Override protected void onLoad() { super.onLoad(); if (!initialized_) { initialized_ = true; Scheduler.get().scheduleDeferred(() -> { doOnLoad(); scrollPanel_.scrollToBottom(); }); } ElementIds.assignElementId(this.getElement(), ElementIds.SHELL_WIDGET); } protected void doOnLoad() { input_.autoHeight(); // Console scroll pos jumps on first typing without this, because the // textarea is in the upper left corner of the screen and when focus // moves to it scrolling ensues. input_.forceCursorChange(); } @Override public void setSuppressPendingInput(boolean suppressPendingInput) { suppressPendingInput_ = suppressPendingInput; } public void consoleWriteError(final String error) { clearPendingInput(); output(error, getErrorClass(), true /*isError*/, false /*ignoreLineCount*/, isAnnouncementEnabled(AriaLiveService.CONSOLE_LOG)); // Pick up the elements emitted to the console by this call. If we get // extended information for this error, we'll need to swap out the simple // error elements for the extended error element. List<Element> newElements = output_.getNewElements(); if (!newElements.isEmpty()) { if (clearErrors_) { errorNodes_.clear(); clearErrors_ = false; } errorNodes_.put(error, newElements); } } public void consoleWriteExtendedError( final String error, UnhandledError traceInfo, boolean expand, String command) { if (errorNodes_.containsKey(error)) { List<Element> errorNodes = errorNodes_.get(error); if (errorNodes.isEmpty()) return; clearPendingInput(); ConsoleError errorWidget = new ConsoleError( traceInfo, getErrorClass(), this, command); if (expand) errorWidget.setTracebackVisible(true); boolean replacedFirst = false; for (Element element: errorNodes) { if (!replacedFirst) { // swap widget for first element element.getParentNode().replaceChild(errorWidget.getElement(), element); replacedFirst = true; } else { // and delete the rest of the elements element.removeFromParent(); } } scrollPanel_.onContentSizeChanged(); errorNodes_.remove(error); } } @Override public void runCommandWithDebug(String command) { events_.fireEvent(new RunCommandWithDebugEvent(command)); } @Override public void consoleWriteOutput(final String output) { clearPendingInput(); output(output, styles_.output(), false /*isError*/, false /*ignoreLineCount*/, isAnnouncementEnabled(AriaLiveService.CONSOLE_LOG)); } @Override public void consoleWriteInput(final String input, String console) { // if coming from another console id (i.e. notebook chunk), clear the // prompt since this input hasn't been processed yet (we'll redraw when // the prompt reappears) if (!StringUtil.isNullOrEmpty(console)) prompt_.setHTML(""); clearPendingInput(); output(input, styles_.command() + KEYWORD_CLASS_NAME, false /*isError*/, false /*ignoreLineCount*/, isAnnouncementEnabled(AriaLiveService.CONSOLE_COMMAND)); } private void clearPendingInput() { pendingInput_.setText(""); pendingInput_.setVisible(false); } @Override public void consoleWritePrompt(final String prompt) { output(prompt, styles_.prompt() + KEYWORD_CLASS_NAME, false /*isError*/, false /*ignoreLineCount*/, isAnnouncementEnabled(AriaLiveService.CONSOLE_COMMAND)); clearErrors_ = true; } public static String consolify(String text) { VirtualConsole console = RStudioGinjector.INSTANCE.getVirtualConsoleFactory().create(null); console.submit(text); return console.toString(); } @Override public void consolePrompt(String prompt, boolean showInput) { if (prompt != null) prompt = consolify(prompt); prompt_.getElement().setInnerText(prompt); //input_.clear(); ensureInputVisible(); // Deal gracefully with multi-line prompts int promptLines = StringUtil.notNull(prompt).split("\\n").length; input_.asWidget().getElement().getStyle().setPaddingTop((promptLines - 1) * 15, Unit.PX); input_.setPasswordMode(!showInput); clearErrors_ = true; output_.ensureStartingOnNewLine(); } @Override public void ensureInputVisible() { scrollPanel_.scrollToBottom(); } private String getErrorClass() { return styles_.error() + " " + AceTheme.getThemeErrorClass( RStudioGinjector.INSTANCE.getUserState().theme().getValue().cast()); } /** * Send text to the console * @param text Text to output * @param className Text style * @param isError Is this an error message? * @param ignoreLineCount Output without checking buffer length? * @param ariaLiveAnnounce Include in arialive output announcement * @return was this output below the maximum buffer line count? */ private boolean output(String text, String className, boolean isError, boolean ignoreLineCount, boolean ariaLiveAnnounce) { boolean canContinue = output_.outputToConsole(text, className, isError, ignoreLineCount, ariaLiveAnnounce); // if we're currently scrolled to the bottom, nudge the timer so that we // will keep up with output if (scrollPanel_.isScrolledToBottom()) resizeCommand_.nudge(); if (liveRegion_ != null) liveRegion_.announce(output_.getNewText()); return canContinue; } private String ensureNewLine(String s) { if (s.length() == 0 || s.charAt(s.length() - 1) == '\n') return s; else return s + '\n'; } public void playbackActions(final RpcObjectList<ConsoleAction> actions) { // Server persists 1000 most recent ConsoleActions in a circular buffer. // One ConsoleAction can generate multiple lines of output, and we want // to limit number of lines added to the console's DOM; see trimExcess(). // First walk through the actions in reverse, and determine how many // lines they will generate (without actually writing anything), // then play-back in normal order. Finally, trim to the max-lines we support // to catch any rounding from final chunk. int lines = 0; int revIndex = actions.length() - 1; for (; revIndex >= 0; revIndex { ConsoleAction action = actions.get(revIndex); if (action.getType() == ConsoleAction.INPUT) lines++; lines = lines + StringUtil.newlineCount(action.getData()); if (lines > output_.getMaxOutputLines()) break; } if (revIndex < 0) revIndex = 0; final int startIndex = revIndex; final int endIndex = actions.length() - 1; Scheduler.get().scheduleIncremental(new RepeatingCommand() { private int i = startIndex; private int chunksize = 1000; @Override public boolean execute() { boolean canContinue = false; int end = i + chunksize; chunksize = 10; for (; i <= end && i <= endIndex; i++) { // User hit Ctrl+L at some point--we're done. if (cleared_) { canContinue = false; break; } ConsoleAction action = actions.get(i); switch (action.getType()) { case ConsoleAction.INPUT: canContinue = output(action.getData() + "\n", styles_.command() + " " + KEYWORD_CLASS_NAME, false /*isError*/, true /*ignoreLineCount*/, false /*announce*/); break; case ConsoleAction.OUTPUT: canContinue = output(action.getData(), styles_.output(), false /*isError*/, true /*ignoreLineCount*/, false /*announce*/); break; case ConsoleAction.ERROR: canContinue = output(action.getData(), getErrorClass(), true /*isError*/, true /*ignoreLineCount*/, false /*announce*/); break; case ConsoleAction.PROMPT: canContinue = output(action.getData(), styles_.prompt() + " " + KEYWORD_CLASS_NAME, false /*isError*/, true /*ignoreLineCount*/, false /*announce*/); break; } if (!canContinue) { break; } } if (canContinue) { canContinue = (i <= endIndex); } if (!canContinue) { output_.trimExcess(); } return canContinue; } }); } @Override public void focus() { input_.setFocus(true); } /** * Directs focus/selection to the input box when a (different) widget * is clicked.) */ private class SelectInputClickHandler implements ClickHandler, KeyDownHandler, PasteEvent.Handler { @Override public void onClick(ClickEvent event) { // If clicking on the input panel already, stop propagation. if (event.getSource() == input_) { event.stopPropagation(); return; } if (prefs_ != null && prefs_.consoleDoubleClickSelect().getValue()) { // Some clicks can result in selection (e.g. double clicks). We don't // want to grab focus for those clicks, but we don't know yet if this // click can generate a selection. Wait 400ms (unfortunately it's not // possible to get the OS double-click timeout) for a selection to // appear; if it doesn't then drive focus to the input box. if (inputFocus_.isRunning()) inputFocus_.cancel(); inputFocus_.schedule(400); } else { // No selection check needed inputFocus_.run(); } } @Override public void onKeyDown(KeyDownEvent event) { if (event.getSource() == input_) return; // Filter out some keystrokes you might reasonably expect to keep // focus inside the output pane switch (event.getNativeKeyCode()) { case KeyCodes.KEY_PAGEDOWN: case KeyCodes.KEY_PAGEUP: case KeyCodes.KEY_HOME: case KeyCodes.KEY_END: case KeyCodes.KEY_CTRL: case KeyCodes.KEY_ALT: case KeyCodes.KEY_SHIFT: case 224: // META (Command) on Firefox/Mac return; case 91: case 93: // Left/Right META (Command), but also [ and ], on Safari if (event.isMetaKeyDown()) return; break; case 'C': if (event.isControlKeyDown() || event.isMetaKeyDown()) return; break; case KeyCodes.KEY_TAB: if (prefs_ == null || prefs_.tabKeyMoveFocus().getValue()) return; } input_.setFocus(true); delegateEvent(input_.asWidget(), event); } @Override public void onPaste(PasteEvent event) { // When pasting, focus the input so it'll receive the pasted text input_.setFocus(true); } public void setInput(AceEditor input) { input_ = input; } private AceEditor input_; private final Timer inputFocus_ = new Timer() { @Override public void run() { // Don't drive focus to the input unless there is no selection. // Otherwise it would interfere with the ability to select stuff // from the output buffer for copying to the clipboard. if (DomUtils.selectionExists() || !isInputOnscreen()) return; // When focusing Ace, if the user hasn't yet typed anything into // the input line, then Ace will erroneously adjust the scroll // position upwards upon focus. Rather than patching Ace, we instead // just re-scroll to the bottom if we were already scrolled to the // bottom after giving focus to the Ace editor instance. boolean wasScrolledToBottom = scrollPanel_.isScrolledToBottom(); input_.setFocus(true); if (wasScrolledToBottom) scrollPanel_.scrollToBottom(); } }; } private boolean isInputOnscreen() { return DomUtils.isVisibleVert(scrollPanel_.getElement(), inputLine_.getElement()); } protected class ClickableScrollPanel extends BottomScrollPanel { private ClickableScrollPanel() { super(); } public HandlerRegistration addClickHandler(ClickHandler handler) { return addDomHandler(handler, ClickEvent.getType()); } public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) { return addDomHandler(handler, KeyDownEvent.getType()); } public void focus() { getElement().focus(); } } @Override public void clearOutput() { output_.clearConsoleOutput(); clearLiveRegion(); cleared_ = true; } @Override public InputEditorDisplay getInputEditorDisplay() { return input_; } @Override public String processCommandEntry() { // parse out the command text String promptText = prompt_.getElement().getInnerText(); String commandText = input_.getCode(); input_.setText(""); // Force render to avoid subtle command movement in the console, caused // by the prompt disappearing before the input line does input_.forceImmediateRender(); prompt_.setHTML(""); SpanElement pendingPrompt = Document.get().createSpanElement(); pendingPrompt.setInnerText(promptText); pendingPrompt.setClassName(styles_.prompt() + " " + KEYWORD_CLASS_NAME); if (!suppressPendingInput_ && !input_.isPasswordMode()) { SpanElement pendingInput = Document.get().createSpanElement(); String[] lines = StringUtil.notNull(commandText).split("\n"); String firstLine = lines.length > 0 ? lines[0] : ""; pendingInput.setInnerText(firstLine + "\n"); pendingInput.setClassName(styles_.command() + " " + KEYWORD_CLASS_NAME); pendingInput_.getElement().appendChild(pendingPrompt); pendingInput_.getElement().appendChild(pendingInput); pendingInput_.setVisible(true); } ensureInputVisible(); return commandText; } @Override public HandlerRegistration addCapturingKeyDownHandler(KeyDownHandler handler) { return input_.addCapturingKeyDownHandler(handler); } @Override public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) { return input_.addKeyPressHandler(handler); } @Override public HandlerRegistration addCapturingKeyUpHandler(KeyUpHandler handler) { return input_.addCapturingKeyUpHandler(handler); } @Override public HandlerRegistration addKeyUpHandler(KeyUpHandler handler) { return input_.addKeyUpHandler(handler); } @Override public int getCharacterWidth() { return DomUtils.getCharacterWidth(getElement(), styles_.console()); } @Override public boolean isPromptEmpty() { return StringUtil.isNullOrEmpty(prompt_.getText()); } @Override public String getPromptText() { return StringUtil.notNull(prompt_.getText()); } @Override public void setReadOnly(boolean readOnly) { input_.setReadOnly(readOnly); } @Override public int getMaxOutputLines() { return output_.getMaxOutputLines(); } @Override public void setMaxOutputLines(int maxLines) { output_.setMaxOutputLines(maxLines); } @Override public void setTextInputAriaLabel(String label) { input_.setTextInputAriaLabel(label); } @Override public Widget getShellWidget() { return this; } @Override public void onResize() { if (getWidget() instanceof RequiresResize) ((RequiresResize)getWidget()).onResize(); } @Override public void onErrorBoxResize() { scrollPanel_.onContentSizeChanged(); } public Widget getOutputWidget() { return output_.getWidget(); } @Override public void enableLiveReporting() { liveRegion_ = new AriaLiveShellWidget(prefs_); verticalPanel_.add(liveRegion_); } @Override public void clearLiveRegion() { if (liveRegion_ != null) liveRegion_.clearLiveRegion(); } private boolean isAnnouncementEnabled(String announcement) { return ariaLive_ != null && !ariaLive_.isDisabled(announcement); } private boolean cleared_ = false; private final ConsoleOutputWriter output_; private final PreWidget pendingInput_; private final HTML prompt_; private AriaLiveShellWidget liveRegion_ = null; protected final AceEditor input_; private final DockPanel inputLine_; protected final ClickableScrollPanel scrollPanel_; private final ConsoleResources.ConsoleStyles styles_; private final TimeBufferedCommand resizeCommand_; private boolean suppressPendingInput_; private final EventBus events_; private final UserPrefs prefs_; private final AriaLiveService ariaLive_; private VerticalPanel verticalPanel_; // A list of errors that have occurred between console prompts. private final Map<String, List<Element>> errorNodes_ = new TreeMap<>(); private boolean clearErrors_ = false; private static final String KEYWORD_CLASS_NAME = ConsoleResources.KEYWORD_CLASS_NAME; }
package info.guardianproject.otr.app.im.plugin.xmpp; import info.guardianproject.otr.app.im.engine.Address; import info.guardianproject.otr.app.im.engine.ChatGroupManager; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.ChatSessionManager; import info.guardianproject.otr.app.im.engine.Contact; import info.guardianproject.otr.app.im.engine.ContactList; import info.guardianproject.otr.app.im.engine.ContactListListener; import info.guardianproject.otr.app.im.engine.ContactListManager; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.engine.ImException; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.otr.app.im.engine.Presence; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.util.DNSUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.ReconnectionManager; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.RosterGroup; import org.jivesoftware.smack.RosterListener; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.MessageTypeFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence.Mode; import org.jivesoftware.smack.packet.Presence.Type; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.proxy.ProxyInfo.ProxyType; import org.jivesoftware.smackx.packet.VCard; import android.R; import android.content.ContentResolver; import android.content.Context; import android.os.Environment; import android.os.Parcel; import android.util.Log; public class XmppConnection extends ImConnection { private final static String TAG = "Gibberbot.XmppConnection"; private XmppContactList mContactListManager; private Contact mUser; // watch out, this is a different XMPPConnection class than XmppConnection! ;) private MyXMPPConnection mConnection; private XmppChatSessionManager mSessionManager; private ConnectionConfiguration mConfig; private boolean mNeedReconnect; private boolean mRetryLogin; private Executor mExecutor; private PacketCollector mPingCollector; private ProxyInfo mProxyInfo = null; private long mAccountId = -1; private long mProviderId = -1; private String mPasswordTemp; private final static int SOTIMEOUT = 15000; private final static String TRUSTSTORE_TYPE = "BKS"; private final static String TRUSTSTORE_PATH = "cacerts.bks"; private final static String TRUSTSTORE_PASS = "changeit"; private final static String KEYMANAGER_TYPE = "X509"; private final static String SSLCONTEXT_TYPE = "TLS"; private ServerTrustManager sTrustManager; private SSLContext sslContext; private KeyStore ks = null; private KeyManager[] kms = null; private Context aContext; public XmppConnection(Context context) { super(context); aContext = context; SmackConfiguration.setPacketReplyTimeout(SOTIMEOUT); mExecutor = Executors.newCachedThreadPool(); } public void sendMessage(org.jivesoftware.smack.packet.Message msg) { if (mConnection != null) mConnection.sendPacket(msg); } public VCard getVCard(String myJID) { // android.os.Debug.waitForDebugger(); VCard vCard = new VCard(); try { vCard.load(mConnection, myJID); // If VCard is loaded, then save the avatar to the personal folder. byte[] bytes = vCard.getAvatar(); if (bytes != null) { try { String filename = vCard.getAvatarHash() + ".jpg"; InputStream in = new ByteArrayInputStream(bytes); File sdCard = Environment.getExternalStorageDirectory(); File file = new File(sdCard, filename); new FileOutputStream(file).write(bytes); /* BufferedImage bi = javax.imageio.ImageIO.read(in); File outputfile = new File("C://Avatar.jpg"); ImageIO.write(bi, "jpg", outputfile); */ } catch (Exception e){ e.printStackTrace(); } } } catch (XMPPException ex) { ex.printStackTrace(); } return vCard; } @Override protected void doUpdateUserPresenceAsync(Presence presence) { String statusText = presence.getStatusText(); Type type = Type.available; Mode mode = Mode.available; int priority = 20; if (presence.getStatus() == Presence.AWAY) { priority = 10; mode = Mode.away; } else if (presence.getStatus() == Presence.IDLE) { priority = 15; mode = Mode.away; } else if (presence.getStatus() == Presence.DO_NOT_DISTURB) { priority = 5; mode = Mode.dnd; } else if (presence.getStatus() == Presence.OFFLINE) { priority = 0; type = Type.unavailable; statusText = "Offline"; } org.jivesoftware.smack.packet.Presence packet = new org.jivesoftware.smack.packet.Presence(type, statusText, priority, mode); mConnection.sendPacket(packet); mUserPresence = presence; notifyUserPresenceUpdated(); } @Override public int getCapability() { // TODO chat groups return 0; } @Override public ChatGroupManager getChatGroupManager() { // TODO chat groups return null; } @Override public synchronized ChatSessionManager getChatSessionManager() { if (mSessionManager == null) mSessionManager = new XmppChatSessionManager(); return mSessionManager; } @Override public synchronized XmppContactList getContactListManager() { if (mContactListManager == null) mContactListManager = new XmppContactList(); return mContactListManager; } @Override public Contact getLoginUser() { return mUser; } @Override public HashMap<String, String> getSessionContext() { return null; } @Override public int[] getSupportedPresenceStatus() { return new int[] { Presence.AVAILABLE, Presence.AWAY, Presence.IDLE, Presence.OFFLINE, Presence.DO_NOT_DISTURB, }; } @Override public void loginAsync(long accountId, String passwordTemp, long providerId, boolean retry) { mAccountId = accountId; mPasswordTemp = passwordTemp; mProviderId = providerId; mRetryLogin = retry; mExecutor.execute(new Runnable() { @Override public void run() { do_login(); } }); } private void do_login() { if (mConnection != null) { setState(getState(), new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "still trying...")); return; } ContentResolver contentResolver = mContext.getContentResolver(); Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap(contentResolver, mProviderId, false, null); // providerSettings is closed in initConnection() String userName = Imps.Account.getUserName(contentResolver, mAccountId); String password = Imps.Account.getPassword(contentResolver, mAccountId); String domain = providerSettings.getDomain(); if (mPasswordTemp != null) password = mPasswordTemp; mNeedReconnect = true; setState(LOGGING_IN, null); mUserPresence = new Presence(Presence.AVAILABLE, "", null, null, Presence.CLIENT_TYPE_DEFAULT); try { if (userName.length() == 0) throw new XMPPException("empty username not allowed"); initConnection(userName, password, providerSettings); } catch (Exception e) { Log.e(TAG, "login failed", e); mConnection = null; ImErrorInfo info = new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, e.getMessage()); if (e == null || e.getMessage() == null) { Log.w(TAG, "NPE", e); info = new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "unknown error"); disconnected(info); mRetryLogin = false; } else if (e.getMessage().contains("not-authorized")) { Log.w(TAG, "not authorized - will not retry"); info = new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "invalid user/password"); disconnected(info); mRetryLogin = false; } else if (mRetryLogin) { Log.w(TAG, "will retry"); setState(LOGGING_IN, info); } else { Log.w(TAG, "will not retry"); mConnection = null; disconnected(info); } return; } finally { mNeedReconnect = false; } // TODO should we really be using the same name for both address and name? String xmppName = userName + '@' + domain; mUser = new Contact(new XmppAddress(userName, xmppName), xmppName); setState(LOGGED_IN, null); Log.i(TAG, "logged in"); } // TODO shouldn't setProxy be handled in Imps/settings? public void setProxy (String type, String host, int port) { if (type == null) { mProxyInfo = ProxyInfo.forNoProxy(); } else { ProxyInfo.ProxyType pType = ProxyType.valueOf(type); mProxyInfo = new ProxyInfo(pType, host, port,"",""); } } private void initConnection(String userName, final String password, Imps.ProviderSettings.QueryMap providerSettings) throws Exception { boolean allowPlainAuth = providerSettings.getAllowPlainAuth(); boolean requireTls = providerSettings.getRequireTls(); boolean doDnsSrv = providerSettings.getDoDnsSrv(); boolean tlsCertVerify = providerSettings.getTlsCertVerify(); boolean allowSelfSignedCerts = !tlsCertVerify; boolean doVerifyDomain = tlsCertVerify; // TODO this should be reorged as well as the gmail.com section below String domain = providerSettings.getDomain(); String server = providerSettings.getServer(); String xmppResource = providerSettings.getXmppResource(); int serverPort = providerSettings.getPort(); providerSettings.close(); // close this, which was opened in do_login() debug(TAG, "TLS required? " + requireTls); debug(TAG, "Do SRV check? " + doDnsSrv); debug(TAG, "cert verification? " + tlsCertVerify); if (mProxyInfo == null) mProxyInfo = ProxyInfo.forNoProxy(); // TODO try getting a connection without DNS SRV first, and if that doesn't work and the prefs allow it, use DNS SRV if (doDnsSrv) { //java.lang.System.setProperty("java.net.preferIPv4Stack", "true"); //java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); debug(TAG, "(DNS SRV) resolving: "+domain); // mConfig = new ConnectionConfiguration(domain, mProxyInfo); DNSUtil.HostAddress srvHost = DNSUtil.resolveXMPPDomain(domain); server = srvHost.getHost(); //serverPort = srvHost.getPort(); debug(TAG, "(DNS SRV) resolved: "+domain+"=" + server + ":" + serverPort); } if (server == null) { // no server specified in prefs, use the domain debug(TAG, "(use domain) ConnectionConfiguration("+domain+", "+serverPort+", "+domain+", mProxyInfo);"); mConfig = new ConnectionConfiguration(domain, serverPort, domain, mProxyInfo); } else { debug(TAG, "(use server) ConnectionConfiguration("+server+", "+serverPort+", "+domain+", mProxyInfo);"); mConfig = new ConnectionConfiguration(server, serverPort, domain, mProxyInfo); //if domain of login user is the same as server doVerifyDomain = (domain.equals(server)); } //mConfig.setDebuggerEnabled(true); mConfig.setSASLAuthenticationEnabled(true); if (requireTls) { mConfig.setSecurityMode(SecurityMode.required); if(allowPlainAuth) { mConfig.setSASLAuthenticationEnabled(false); SASLAuthentication.supportSASLMechanism("PLAIN", 0); } else { mConfig.setSASLAuthenticationEnabled(true); SASLAuthentication.unsupportSASLMechanism("PLAIN"); } SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 1); } else { // if it finds a cert, still use it, but don't check anything since // TLS errors are not expected by the user mConfig.setSecurityMode(SecurityMode.enabled); tlsCertVerify = false; doVerifyDomain = false; allowSelfSignedCerts = true; // without TLS, use DIGEST-MD5 first SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0); if(allowPlainAuth) SASLAuthentication.supportSASLMechanism("PLAIN", 1); else SASLAuthentication.unsupportSASLMechanism("PLAIN"); } // Android has no support for Kerberos or GSSAPI, so disable completely SASLAuthentication.unregisterSASLMechanism("KERBEROS_V4"); SASLAuthentication.unregisterSASLMechanism("GSSAPI"); mConfig.setVerifyChainEnabled(tlsCertVerify); mConfig.setVerifyRootCAEnabled(tlsCertVerify); mConfig.setExpiredCertificatesCheckEnabled(tlsCertVerify); mConfig.setNotMatchingDomainCheckEnabled(doVerifyDomain); // Android doesn't support the default "jks" Java Key Store, it uses "bks" instead // this should probably be set to our own, if we are going to save self-signed certs mConfig.setTruststoreType(TRUSTSTORE_TYPE); mConfig.setTruststorePath(TRUSTSTORE_PATH); mConfig.setTruststorePassword(TRUSTSTORE_PASS); if (allowSelfSignedCerts) { Log.i(TAG, "allowing self-signed certs"); mConfig.setSelfSignedCertificateEnabled(true); } //reconnect please, or no? mConfig.setReconnectionAllowed(false); mConfig.setSendPresence(true); mConfig.setRosterLoadedAtLogin(true); if (server == null) initSSLContext(domain, mConfig); else initSSLContext(server, mConfig); mConnection = new MyXMPPConnection(mConfig); //Log.i(TAG, "ConnnectionConfiguration.getHost: " + mConfig.getHost() + " getPort: " + mConfig.getPort() + " getServiceName: " + mConfig.getServiceName()); Roster roster = mConnection.getRoster(); roster.setSubscriptionMode(Roster.SubscriptionMode.manual); getContactListManager().listenToRoster(roster); mConnection.connect(); //Log.i(TAG,"is secure connection? " + mConnection.isSecureConnection()); //Log.i(TAG,"is using TLS? " + mConnection.isUsingTLS()); mConnection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { org.jivesoftware.smack.packet.Message smackMessage = (org.jivesoftware.smack.packet.Message) packet; Message rec = new Message(smackMessage.getBody()); String address = parseAddressBase(smackMessage.getFrom()); ChatSession session = findOrCreateSession(address); rec.setTo(mUser.getAddress()); rec.setFrom(session.getParticipant().getAddress()); rec.setDateTime(new Date()); session.onReceiveMessage(rec); } }, new MessageTypeFilter(org.jivesoftware.smack.packet.Message.Type.chat)); mConnection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { org.jivesoftware.smack.packet.Presence presence = (org.jivesoftware.smack.packet.Presence)packet; String address = parseAddressBase(presence.getFrom()); String name = parseAddressName(presence.getFrom()); Contact contact = findOrCreateContact(name,address); if (presence.getType() == Type.subscribe) { Log.i(TAG, "sub request from " + address); mContactListManager.getSubscriptionRequestListener().onSubScriptionRequest(contact); } else { int type = parsePresence(presence); contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT)); } } }, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class)); mConnection.addConnectionListener(new ConnectionListener() { @Override public void reconnectionSuccessful() { Log.i(TAG, "reconnection success"); setState(LOGGED_IN, null); } @Override public void reconnectionFailed(Exception e) { //Log.i(TAG, "reconnection failed", e); //forced_disconnect(new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage())); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage())); mExecutor.execute(new Runnable() { @Override public void run() { reconnect(); } }); } @Override public void reconnectingIn(int seconds) { /* * Reconnect happens: * - due to network error * - but not if connectionClosed is fired */ Log.i(TAG, "reconnecting in " + seconds); setState(LOGGING_IN, null); } @Override public void connectionClosedOnError(Exception e) { /* * This fires when: * - Packet reader or writer detect an error * - Stream compression failed * - TLS fails but is required */ Log.i(TAG, "reconnect on error", e); if (e.getMessage().contains("conflict")) { disconnect(); disconnected(new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "logged in from another location")); } else { setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage())); mExecutor.execute(new Runnable() { @Override public void run() { reconnect(); } }); } } @Override public void connectionClosed() { disconnect(); /* * This can be called in these cases: * - Connection is shutting down * - because we are calling disconnect * - in do_logout * * - NOT (fixed in smack) * - because server disconnected "normally" * - we were trying to log in (initConnection), but are failing * - due to network error * - in forced disconnect * - due to login failing */ Log.i(TAG, "connection closed"); } }); // android.os.Debug.waitForDebugger(); // dangerous debug statement below, prints password! //Log.i(TAG, "mConnection.login("+userName+", "+password+", "+xmppResource+");"); mConnection.login(userName, password, xmppResource); org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.available); mConnection.sendPacket(presence); } private void initSSLContext (String server, ConnectionConfiguration config) throws Exception { ks = KeyStore.getInstance(TRUSTSTORE_TYPE); try { ks.load(new FileInputStream(TRUSTSTORE_PATH), TRUSTSTORE_PASS.toCharArray()); } catch(Exception e) { ks = null; } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYMANAGER_TYPE); try { kmf.init(ks, TRUSTSTORE_PASS.toCharArray()); kms = kmf.getKeyManagers(); } catch (NullPointerException npe) { kms = null; } sslContext = SSLContext.getInstance(SSLCONTEXT_TYPE); sTrustManager = new ServerTrustManager(aContext, server, config); sslContext.init(kms, new javax.net.ssl.TrustManager[]{sTrustManager}, new java.security.SecureRandom()); config.setCustomSSLContext(sslContext); } void disconnected(ImErrorInfo info) { Log.w(TAG, "disconnected"); setState(DISCONNECTED, info); } void forced_disconnect(ImErrorInfo info) { // UNUSED Log.w(TAG, "forced disconnect"); try { if (mConnection!= null) { XMPPConnection conn = mConnection; mConnection = null; conn.disconnect(); } } catch (Exception e) { // Ignore } disconnected(info); } protected static int parsePresence(org.jivesoftware.smack.packet.Presence presence) { int type = Presence.AVAILABLE; Mode rmode = presence.getMode(); Type rtype = presence.getType(); if (rmode == Mode.away || rmode == Mode.xa) type = Presence.AWAY; else if (rmode == Mode.dnd) type = Presence.DO_NOT_DISTURB; else if (rtype == Type.unavailable) type = Presence.OFFLINE; return type; } protected static String parseAddressBase(String from) { return from.replaceFirst("/.*", ""); } protected static String parseAddressName(String from) { return from.replaceFirst("@.*", ""); } @Override public void logoutAsync() { mExecutor.execute(new Runnable() { @Override public void run() { do_logout(); } }); } private void do_logout() { Log.w(TAG, "logout"); setState(LOGGING_OUT, null); disconnect(); setState(DISCONNECTED, null); } private void disconnect() { clearHeartbeat(); XMPPConnection conn = mConnection; mConnection = null; try { conn.disconnect(); } catch (Throwable th) { // ignore } mNeedReconnect = false; mRetryLogin = false; } @Override public void reestablishSessionAsync(Map<String, String> sessionContext) { mExecutor.execute(new Runnable() { @Override public void run() { reconnect(); } }); } @Override public void suspend() { mConnection.shutdown(); } private ChatSession findOrCreateSession(String address) { ChatSession session = mSessionManager.findSession(address); if (session == null) { Contact contact = findOrCreateContact(parseAddressName(address),address); session = mSessionManager.createChatSession(contact); } return session; } Contact findOrCreateContact(String name, String address) { Contact contact = mContactListManager.getContact(address); if (contact == null) { contact = makeContact(name, address); } return contact; } private static Contact makeContact(String name, String address) { Contact contact = new Contact(new XmppAddress(name, address), address); return contact; } private final class XmppChatSessionManager extends ChatSessionManager { @Override public void sendMessageAsync(ChatSession session, Message message) { org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message( message.getTo().getFullName(), org.jivesoftware.smack.packet.Message.Type.chat ); msg.setBody(message.getBody()); mConnection.sendPacket(msg); } ChatSession findSession(String address) { for (Iterator<ChatSession> iter = mSessions.iterator(); iter.hasNext();) { ChatSession session = iter.next(); if (session.getParticipant().getAddress().getFullName().equals(address)) return session; } return null; } } public ChatSession findSession (String address) { return mSessionManager.findSession(address); } public ChatSession createChatSession (Contact contact) { return mSessionManager.createChatSession(contact); } private final class XmppContactList extends ContactListManager { //private Hashtable<String, org.jivesoftware.smack.packet.Presence> unprocdPresence = new Hashtable<String, org.jivesoftware.smack.packet.Presence>(); @Override protected void setListNameAsync(final String name, final ContactList list) { mExecutor.execute(new Runnable() { @Override public void run() { do_setListName(name, list); } }); } private void do_setListName(String name, ContactList list) { debug(TAG, "set list name"); mConnection.getRoster().getGroup(list.getName()).setName(name); notifyContactListNameUpdated(list, name); } @Override public String normalizeAddress(String address) { return address; } @Override public void loadContactListsAsync() { mExecutor.execute(new Runnable() { @Override public void run() { do_loadContactLists(); } }); } /** * Create new list of contacts from roster entries. * * @param entryIter iterator of roster entries to add to contact list * @param skipList list of contacts which should be omitted; new contacts are added to this list automatically * @return contacts from roster which were not present in skiplist. */ private Collection<Contact> fillContacts(Collection<RosterEntry> entryIter, Set<String> skipList) { Roster roster = mConnection.getRoster(); Collection<Contact> contacts = new ArrayList<Contact>(); for (RosterEntry entry : entryIter) { String address = parseAddressBase(entry.getUser()); /* Skip entries present in the skip list */ if (skipList != null && !skipList.add(address)) continue; String name = entry.getName(); if (name == null) name = address; XmppAddress xaddress = new XmppAddress(name, address); Contact contact = mContactListManager.getContact(xaddress.getFullName()); if (contact == null) contact = new Contact(xaddress, name); org.jivesoftware.smack.packet.Presence presence = roster.getPresence(address); contact.setPresence(new Presence(parsePresence(presence), presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT)); contacts.add(contact); // getVCard(xaddress.getFullName()); // commented out to fix slow contact loading } return contacts; } private void do_loadContactLists() { debug(TAG, "load contact lists"); if (mConnection == null) return; Roster roster = mConnection.getRoster(); //Set<String> seen = new HashSet<String>(); //android.os.Debug.waitForDebugger(); for (Iterator<RosterGroup> giter = roster.getGroups().iterator(); giter.hasNext();) { RosterGroup group = giter.next(); debug(TAG, "loading group: " + group.getName() + " size:" + group.getEntryCount()); Collection<Contact> contacts = fillContacts(group.getEntries(), null); ContactList cl = new ContactList(mUser.getAddress(), group.getName(), false, contacts, this); notifyContactListCreated(cl); notifyContactsPresenceUpdated(contacts.toArray(new Contact[contacts.size()])); // for (Contact contact : contacts) // notifyContactListUpdated(cl, ContactListListener.LIST_CONTACT_ADDED, contact); //notifyContactListLoaded(cl); } if (roster.getUnfiledEntryCount() > 0) { String generalGroupName = "Buddies"; Collection<Contact> contacts = fillContacts(roster.getUnfiledEntries(), null); ContactList cl = new ContactList(mUser.getAddress(), generalGroupName, true, contacts, this); notifyContactListCreated(cl); notifyContactsPresenceUpdated(contacts.toArray(new Contact[contacts.size()])); //for (Contact contact : contacts) //notifyContactListUpdated(cl, ContactListListener.LIST_CONTACT_ADDED, contact); } notifyContactListsLoaded(); } /* * iterators through a list of contacts to see if there were any Presence * notifications sent before the contact was loaded */ /* private void processQueuedPresenceNotifications (Collection<Contact> contacts) { Roster roster = mConnection.getRoster(); //now iterate through the list of queued up unprocessed presence changes for (Contact contact : contacts) { String address = parseAddressBase(contact.getAddress().getFullName()); org.jivesoftware.smack.packet.Presence presence = roster.getPresence(address); if (presence != null) { debug(TAG, "processing queued presence: " + address + " - " + presence.getStatus()); unprocdPresence.remove(address); contact.setPresence(new Presence(parsePresence(presence), presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT)); Contact[] updatedContact = {contact}; notifyContactsPresenceUpdated(updatedContact); } } }*/ public void listenToRoster(final Roster roster) { roster.addRosterListener(rListener); } RosterListener rListener = new RosterListener() { private Stack<String> entriesToAdd = new Stack<String>(); private Stack<String> entriesToDel = new Stack<String>(); @Override public void presenceChanged(org.jivesoftware.smack.packet.Presence presence) { handlePresenceChanged(presence); } @Override public void entriesUpdated(Collection<String> addresses) { debug(TAG, "roster entries updated"); //entriesAdded(addresses); } @Override public void entriesDeleted(Collection<String> addresses) { debug(TAG, "roster entries deleted: " + addresses.size()); /* if (addresses != null) entriesToDel.addAll(addresses); if (mContactListManager.getState() == ContactListManager.LISTS_LOADED) { synchronized (entriesToDel) { while (!entriesToDel.empty()) try { Contact contact = mContactListManager.getContact(entriesToDel.pop()); mContactListManager.removeContactFromListAsync(contact, mContactListManager.getDefaultContactList()); } catch (ImException e) { Log.e(TAG,e.getMessage(),e); } } } else { debug(TAG, "roster delete entries queued"); }*/ } @Override public void entriesAdded(Collection<String> addresses) { debug(TAG, "roster entries added: " + addresses.size()); /* if (addresses != null) entriesToAdd.addAll(addresses); if (mContactListManager.getState() == ContactListManager.LISTS_LOADED) { debug(TAG, "roster entries added"); while (!entriesToAdd.empty()) try { mContactListManager.addContactToListAsync(entriesToAdd.pop(), mContactListManager.getDefaultContactList()); } catch (ImException e) { Log.e(TAG,e.getMessage(),e); } } else { debug(TAG, "roster add entries queued"); }*/ } }; private void handlePresenceChanged (org.jivesoftware.smack.packet.Presence presence) { // android.os.Debug.waitForDebugger(); String name = parseAddressName(presence.getFrom()); String address = parseAddressBase(presence.getFrom()); XmppAddress xaddress = new XmppAddress(name, address); Contact contact = getContact(xaddress.getFullName()); /* if (mConnection != null) { Roster roster = mConnection.getRoster(); // Get it from the roster - it handles priorities, etc. if (roster != null) presence = roster.getPresence(address); }*/ int type = parsePresence(presence); if (contact == null) { contact = new Contact(xaddress, name); debug(TAG, "got presence updated for NEW user: " + contact.getAddress().getFullName() + " presence:" + type); //store the latest presence notification for this user in this queue //unprocdPresence.put(user, presence); } else { debug(TAG, "Got present update for EXISTING user: " + contact.getAddress().getFullName() + " presence:" + type); Presence p = new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT); contact.setPresence(p); Contact []contacts = new Contact[] { contact }; notifyContactsPresenceUpdated(contacts); } } @Override protected ImConnection getConnection() { return XmppConnection.this; } @Override protected void doRemoveContactFromListAsync(Contact contact, ContactList list) { Roster roster = mConnection.getRoster(); String address = contact.getAddress().getFullName(); try { RosterGroup group = roster.getGroup(list.getName()); if (group == null) { Log.e(TAG, "could not find group " + list.getName() + " in roster"); return; } RosterEntry entry = roster.getEntry(address); if (entry == null) { Log.e(TAG, "could not find entry " + address + " in group " + list.getName()); return; } group.removeEntry(entry); } catch (XMPPException e) { Log.e(TAG, "remove entry failed", e); throw new RuntimeException(e); } org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(address); mConnection.sendPacket(response); notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_REMOVED, contact); } @Override protected void doDeleteContactListAsync(ContactList list) { // TODO delete contact list Log.i(TAG, "delete contact list " + list.getName()); } @Override protected void doCreateContactListAsync(String name, Collection<Contact> contacts, boolean isDefault) { // TODO create contact list Log.i(TAG, "create contact list " + name + " default " + isDefault); } @Override protected void doBlockContactAsync(String address, boolean block) { // TODO block contact } @Override protected void doAddContactToListAsync(String address, ContactList list) throws ImException { Log.i(TAG, "add contact to " + list.getName()); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.subscribed); response.setTo(address); mConnection.sendPacket(response); Roster roster = mConnection.getRoster(); String[] groups = new String[] { list.getName() }; try { roster.createEntry(address, parseAddressName(address), groups); } catch (XMPPException e) { throw new RuntimeException(e); } Contact contact = makeContact(parseAddressName(address),address); notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact); } @Override public void declineSubscriptionRequest(String contact) { debug(TAG, "decline subscription"); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(contact); mConnection.sendPacket(response); mContactListManager.getSubscriptionRequestListener().onSubscriptionDeclined(contact); } @Override public void approveSubscriptionRequest(String contact) { debug(TAG, "approve subscription"); try { // FIXME maybe need to check if already in another contact list mContactListManager.doAddContactToListAsync(contact, getDefaultContactList()); } catch (ImException e) { Log.e(TAG, "failed to add " + contact + " to default list"); } mContactListManager.getSubscriptionRequestListener().onSubscriptionApproved(contact); } @Override public Contact createTemporaryContact(String address) { debug(TAG, "create temporary " + address); return makeContact(parseAddressName(address),address); } } public static class XmppAddress extends Address { private String address; private String name; public XmppAddress() { } public XmppAddress(String name, String address) { this.name = name; this.address = address; } public XmppAddress(String address) { this.name = parseAddressName(address); this.address = address; } @Override public String getFullName() { return address; } @Override public String getScreenName() { return name; } @Override public void readFromParcel(Parcel source) { name = source.readString(); address = source.readString(); } @Override public void writeToParcel(Parcel dest) { dest.writeString(name); dest.writeString(address); } } /* * Alarm event fired * @see info.guardianproject.otr.app.im.engine.ImConnection#sendHeartbeat() */ public void sendHeartbeat() { mExecutor.execute(new Runnable() { @Override public void run() { doHeartbeat(); } }); } public void doHeartbeat() { if (mConnection == null && mRetryLogin) { Log.i(TAG, "reconnect with login"); do_login(); } if (mConnection == null) return; if (mNeedReconnect) { retry_reconnect(); } else if (mConnection.isConnected() && getState() == LOGGED_IN) { debug(TAG, "ping"); if (!sendPing()) { if (getState() == LOGGED_IN) { setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network timeout")); Log.w(TAG, "reconnect on ping failed"); force_reconnect(); } } } } private void clearHeartbeat() { debug(TAG, "clear heartbeat"); mPingCollector = null; } private boolean sendPing() { // Check ping result from previous send if (mPingCollector != null) { IQ result = (IQ)mPingCollector.nextResult(SOTIMEOUT); mPingCollector.cancel(); if (result == null || result.getError() != null) { clearHeartbeat(); Log.e(TAG, "ping timeout"); return false; } } IQ req = new IQ() { public String getChildElementXML() { return "<ping xmlns='urn:xmpp:ping'/>"; } }; req.setType(IQ.Type.GET); PacketFilter filter = new AndFilter(new PacketIDFilter(req.getPacketID()), new PacketTypeFilter(IQ.class)); mPingCollector = mConnection.createPacketCollector(filter); mConnection.sendPacket(req); return true; } // watch out, this is a different XMPPConnection class than XmppConnection! ;) // org.jivesoftware.smack.XMPPConnection // info.guardianproject.otr.app.im.plugin.xmpp.XmppConnection static class MyXMPPConnection extends XMPPConnection { public MyXMPPConnection(ConnectionConfiguration config) { super(config); //this.getConfiguration().setSocketFactory(arg0) } public void shutdown() { try { shutdown(new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unavailable)); } catch (Exception e) { Log.e(TAG, "error on shutdown()",e); } } } @Override public void networkTypeChanged() { super.networkTypeChanged(); //android.os.Debug.waitForDebugger(); Log.w(TAG, "reconnect on network change"); /* if (getState() == LOGGED_IN) setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network changed")); if (getState() != LOGGED_IN && getState() != LOGGING_IN) return; if (mNeedReconnect) return; Log.w(TAG, "reconnect on network change"); force_reconnect(); */ } /* * Force a disconnect and reconnect, unless we are already reconnecting. */ private void force_reconnect() { debug(TAG, "force_reconnect need=" + mNeedReconnect); if (mConnection == null) return; if (mNeedReconnect) return; try { if (mConnection != null && mConnection.isConnected()) { mConnection.disconnect(); // mConnection.shutdown(); } } catch (Exception e) { Log.w(TAG, "problem disconnecting on force_reconnect: " + e.getMessage()); } mNeedReconnect = true; do_login(); } /* * Reconnect unless we are already in the process of doing so. */ /* private void maybe_reconnect() { // If we already know we don't have a good connection, the heartbeat // will take care of this debug(TAG, "maybe_reconnect mNeedReconnect=" + mNeedReconnect); // for some reason the mNeedReconnect logic is flipped here, donno why. // Added the mConnection test to stop NullPointerExceptions hans@eds.org // This is checking whether we are already in the process of reconnecting --devrandom if (mNeedReconnect || mConnection == null) return; mNeedReconnect = true; reconnect(); } */ /* * Retry a reconnect on alarm event */ private void retry_reconnect() { // Retry reconnecting if we still need to debug(TAG, "retry_reconnect need=" + mNeedReconnect); if (mConnection != null && mNeedReconnect) reconnect(); } /* * Retry connecting */ private void reconnect() { clearHeartbeat(); if (mConnection != null) { if (!mConnection.isConnected()) { try { mConnection.connect(); } catch (Exception e) { mNeedReconnect = true; Log.w(TAG, "reconnection on network change failed: " + e.getMessage()); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage())); return; } } mNeedReconnect = false; Log.i(TAG, "reconnect"); Log.i(TAG, "reconnected"); setState(LOGGED_IN, null); } else { mNeedReconnect = true; Log.d(TAG, "reconnection on network change failed"); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "reconnection on network change failed")); } } public void debug (String tag, String msg) { Log.d(tag, msg); } }
package org.apache.lenya.cms.cocoon.acting; import java.io.File; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.avalon.framework.parameters.Parameters; import org.apache.avalon.framework.thread.ThreadSafe; import org.apache.cocoon.acting.AbstractConfigurableAction; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Redirector; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.SourceResolver; import org.apache.lenya.xml.DocumentHelper; import org.apache.lenya.xml.RelaxNG; import org.apache.lenya.xml.XPath; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmldb.common.xml.queries.XObject; import org.xmldb.common.xml.queries.XPathQuery; import org.xmldb.common.xml.queries.XPathQueryFactory; import org.xmldb.common.xml.queries.XUpdateQuery; import org.xmldb.xupdate.lexus.XUpdateQueryImpl; /** * @author Michael Wechner * @version $Id: HTMLFormSaveAction.java,v 1.36 2004/02/16 10:43:03 gregor Exp $ * * FIXME: org.apache.xpath.compiler.XPathParser seems to have problems when * namespaces are not declared within the root element. Unfortunately the XSLTs * (during Cocoon transformation) are moving the namespaces to the elements which use them! * One hack might be to parse the tree for namespaces (Node.getNamespaceURI), collect them * and add them to the document root element, before sending it through the * org.apache.xpath.compiler.XPathParser (called by XPathAPI) * * FIXME: There seems to be another problem with default namespaces * * WARNING: Internet Explorer does not send the name without the coordinates if * input type is equals image. Mozilla does. */ public class HTMLFormSaveAction extends AbstractConfigurableAction implements ThreadSafe { org.apache.log4j.Category log = org.apache.log4j.Category.getInstance(HTMLFormSaveAction.class); class XUpdateAttributes { public String xupdateAttrExpr = ""; public String tagID = ""; public XUpdateAttributes(String xupdateAttrExpr, String tagID) { this.xupdateAttrExpr = xupdateAttrExpr; this.tagID = tagID; } } /** * Save data to temporary file * * @param redirector a <code>Redirector</code> value * @param resolver a <code>SourceResolver</code> value * @param objectModel a <code>Map</code> value * @param source a <code>String</code> value * @param parameters a <code>Parameters</code> value * * @return a <code>Map</code> value * * @exception Exception if an error occurs */ public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception { File sitemap = new File(new URL(resolver.resolveURI("").getURI()).getFile()); File file = new File(sitemap.getAbsolutePath() + File.separator + parameters.getParameter("file")); File schema = new File(sitemap.getAbsolutePath() + File.separator + parameters.getParameter("schema")); File unnumberTagsXSL = new File(sitemap.getAbsolutePath() + File.separator + parameters.getParameter("unnumberTagsXSL")); Request request = ObjectModelHelper.getRequest(objectModel); if(request.getParameter("cancel") != null) { getLogger().warn(".act(): Editing has been canceled"); file.delete(); return null; } else { if(file.isFile()) { getLogger().debug(".act(): Save modifications to " + file.getAbsolutePath()); try { Document document = null; DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance(); parserFactory.setValidating(false); parserFactory.setNamespaceAware(true); parserFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = parserFactory.newDocumentBuilder(); document = builder.parse(file.getAbsolutePath()); System.setProperty("org.xmldb.common.xml.queries.XPathQueryFactory", "org.xmldb.common.xml.queries.xalan2.XPathQueryFactoryImpl"); XPathQuery xpath = XPathQueryFactory.newInstance().newXPathQuery(); XUpdateQuery xq = new XUpdateQueryImpl(); String editSelect = null; Enumeration params = request.getParameterNames(); while (params.hasMoreElements()) { String pname = (String) params.nextElement(); log.debug("Parameter: " + pname + " (" + request.getParameter(pname) + ")"); // Extract the xpath to edit if (editSelect == null && pname.indexOf("edit[") >= 0 && pname.endsWith("].x")) { editSelect = pname.substring(5, pname.length() - 3); log.debug("Edit: " + editSelect); } // Make sure we are dealing with an xupdate statement, else skip if (pname.indexOf("<xupdate:") == 0) { String select = pname.substring(pname.indexOf("select") + 8); select = select.substring(0, select.indexOf("\"")); log.debug(".act() Select Node: " + select); // Check if node exists xpath.setQString(select); XObject result = xpath.execute(document); NodeList selectionNodeList = result.nodeset(); if (selectionNodeList.getLength() == 0) { log.warn(".act(): Node does not exist (might have been deleted during update): " + select); } else { String xupdateModifications = null; if (pname.indexOf("xupdate:update") > 0) { log.debug(".act(): UPDATE Node: " + pname); if (pname.indexOf("<![CDATA[") > 0) { xupdateModifications = updateCDATA(request, pname); } else { xupdateModifications = update(request, pname, select, selectionNodeList); } } else if (pname.indexOf("xupdate:append") > 0 && pname.endsWith(">.x")) { xupdateModifications = append(pname.substring(0, pname.length()-2)); } else if (pname.indexOf("xupdate:insert-before") > 0 && pname.endsWith(">.x")) { xupdateModifications = insertBefore(pname.substring(0, pname.length()-2)); } else if (pname.indexOf("xupdate:insert-after") > 0 && pname.endsWith("/>")) { // QUESTIONMARK: select:option if (!request.getParameter(pname).equals("null")) { xupdateModifications = insertAfter(request.getParameter(pname)); } } else if (pname.indexOf("xupdate:insert-after") > 0 && pname.endsWith(">.x")) { xupdateModifications = insertAfter(pname.substring(0, pname.length()-2)); } else if (pname.indexOf("xupdate:remove") > 0 && pname.endsWith("/>.x")) { xupdateModifications = remove(pname.substring(0, pname.length()-2)); } if (xupdateModifications != null) { log.debug(".act(): MODIFICATIONS: " + xupdateModifications); xq.setQString(xupdateModifications); xq.execute(document); } else { log.debug(".act(): Parameter did not match any xupdate command: " + pname); } } // Check select } } // while // DEBUG: /* java.io.StringWriter writer = new java.io.StringWriter(); org.apache.xml.serialize.OutputFormat OutFormat = new org.apache.xml.serialize.OutputFormat("xml", "UTF-8", true); org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer(writer, OutFormat); serializer.asDOMSerializer().serialize((Document) document); log.error(".act(): XUpdate Result: \n"+writer.toString()); */ DocumentHelper.writeDocument(document, file); if (schema.isFile()) { String message = validateDocument(schema, file, unnumberTagsXSL); if (message != null) { log.error("RELAX NG Validation failed: " + message); HashMap hmap = new HashMap(); hmap.put("message", "RELAX NG Validation failed: " + message); return hmap; } } else { log.warn("No such schema: " + schema.getAbsolutePath()); } if(request.getParameter("save") != null) { getLogger().info(".act(): Save"); return null; } else { /* There are potentially multiple xupdate statements for every save. Continue to loop * if there are multiple ones. */ HashMap hmap = new HashMap(); if (editSelect != null) { hmap.put("editSelect", editSelect); } return hmap; } } catch (NullPointerException e) { getLogger().error(".act(): NullPointerException", e); HashMap hmap = new HashMap(); hmap.put("message", "NullPointerException"); return hmap; } catch (Exception e) { getLogger().error(".act(): Exception: " + e.getMessage(), e); HashMap hmap = new HashMap(); if (e.getMessage() != null) { hmap.put("message", e.getMessage()); } else { hmap.put("message", "No message (" + e.getClass().getName() + ")"); } return hmap; } } else { getLogger().error(".act(): No such file: " + file.getAbsolutePath()); HashMap hmap = new HashMap(); hmap.put("message", "No such file: " + file.getAbsolutePath()); return hmap; } } } /** * Get attributes */ private XUpdateAttributes getAttributes(Node node) { String xupdateString = ""; String tagID = ""; org.w3c.dom.NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { for (int i = 0;i < attributes.getLength();i++) { org.w3c.dom.Attr attribute = (org.w3c.dom.Attr)attributes.item(i); log.debug(".getAttributes(): " + attribute.getName() + " " + attribute.getValue()); if (!attribute.getName().equals("tagID")) { String namespace = attribute.getNamespaceURI(); log.debug(".getAttributes(): Namespace: " + namespace); String namespaceAttribute = ""; if (namespace != null) { namespaceAttribute = " namespace=\"" + namespace + "\""; } xupdateString = xupdateString + "<xupdate:attribute name=\"" + attribute.getName() + "\"" + namespaceAttribute + ">" + attribute.getValue() + "</xupdate:attribute>"; } else { xupdateString = xupdateString + "<xupdate:attribute name=\"tagID\">temp</xupdate:attribute>"; tagID = attribute.getValue(); } } } else { xupdateString = ""; } log.debug(".getAttributes(): " + xupdateString); return new XUpdateAttributes(xupdateString, tagID); } private String update(Request request, String pname, String select, NodeList selectionNodeList) { // FIXME: Lexus seems to have trouble with mixed content. As Workaround we insert-after new, remove original and replace temporary tagID by original tagID Node nodeToCopy = selectionNodeList.item(0); String namespace = nodeToCopy.getNamespaceURI(); log.debug(".update(): Update Node (namespace): " + namespace); String namespaceAttribute = ""; if (namespace != null) { namespaceAttribute = " namespace=\"" + namespace + "\""; } // WARNING: getAttributes adds the attribute tagID with value "temp" XUpdateAttributes xa = getAttributes(nodeToCopy); String xupdateInsertAfter = "<xupdate:insert-after select=\"" + select + " \"><xupdate:element name=\"" + new XPath(select).getNameWithoutPredicates() + "\"" + namespaceAttribute + ">" + xa.xupdateAttrExpr + request.getParameter(pname) + "</xupdate:element></xupdate:insert-after>"; log.debug(".update(): Update Node (insert-after): " + xupdateInsertAfter); String xupdateRemove = "<xupdate:remove select=\"" + select + " \"/>"; log.debug(".update(): Update Node (remove): " + xupdateRemove); String xupdateUpdateAttribute = "<xupdate:update select=\"" + new XPath(select).removePredicates(select) + "[@tagID='temp']/@tagID" + " \">" + xa.tagID + "</xupdate:update>"; log.debug(".update(): Update Node (update tagID attribute): " + xupdateUpdateAttribute); return "<?xml version=\"1.0\"?><xupdate:modifications xmlns:xupdate=\"http: } private String updateCDATA(Request request, String pname) { String xupdateUpdate = pname + request.getParameter(pname) + "]]></xupdate:update>"; return "<?xml version=\"1.0\"?><xupdate:modifications xmlns:xupdate=\"http: } private String append(String pname) { log.debug(".append() APPEND Node: " + pname); return "<?xml version=\"1.0\"?><xupdate:modifications xmlns:xupdate=\"http: } private String insertBefore(String pname) { log.debug(".insertBefore() INSERT-BEFORE Node: " + pname); return "<?xml version=\"1.0\"?><xupdate:modifications xmlns:xupdate=\"http: } private String insertAfter(String pname) { log.debug(".insertAfter() INSERT-AFTER Node: " + pname); return "<?xml version=\"1.0\"?><xupdate:modifications xmlns:xupdate=\"http: } private String remove(String pname) { log.debug(".remove() REMOVE Node: " + pname); return "<?xml version=\"1.0\"?><xupdate:modifications xmlns:xupdate=\"http: } /** * Validate document */ private String validateDocument(File schema, File file, File unnumberTagsXSL) { try { // Remove tagIDs TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(new StreamSource(unnumberTagsXSL)); t.transform(new StreamSource(file), new StreamResult(new File(file.getAbsolutePath() + ".validate"))); // Validate return RelaxNG.validate(schema, new File(file.getAbsolutePath() + ".validate")); } catch (Exception e) { log.error(e); return "" + e; } } }
package org.wyona.cms.cocoon.acting; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.lang.String; import java.util.HashMap; import java.util.Map; import org.apache.avalon.excalibur.io.FileUtil; import org.apache.avalon.excalibur.io.IOUtil; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentSelector; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.acting.ConfigurableComposerAction; import org.apache.cocoon.components.parser.Parser; import org.apache.cocoon.environment.http.HttpRequest; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Redirector; import org.apache.cocoon.environment.Source; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.serialization.Serializer; import org.apache.cocoon.util.IOUtils; import org.apache.cocoon.util.PostInputStream; import org.apache.cocoon.xml.dom.DOMStreamer; import org.dom4j.io.DOMReader; import org.dom4j.io.XMLWriter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Interfaces with Xopus: handles the requests and replies to them * * @author Memo Birgi * @created 2002.02.21 * @version 0.1 */ public class XopusHandlerAction extends ConfigurableComposerAction { private String xmlRoot=null; private String xslRoot=null; private String xsdRoot=null; private String tempRoot=null; private Map relRootDirs = new HashMap(); /** * Gets the configuration from the sitemap */ public void configure(Configuration conf) throws ConfigurationException{ super.configure(conf); xmlRoot=conf.getChild("xml").getAttribute("href"); xslRoot=conf.getChild("xsl").getAttribute("href"); xsdRoot=conf.getChild("xsd").getAttribute("href"); tempRoot=conf.getChild("temp").getAttribute("href"); getLogger().debug("CONFIGURATION:\n" + "Relative XML Root Directory: " + xmlRoot + "\n" + "Relative XSL Root Directory: " + xslRoot + "\n" + "Relative XSD Root Directory: " + xsdRoot + "\n" + "Relative Temp Directory: " + tempRoot); // Encode File types and their root directories, relative to the sitemap directory relRootDirs.put("xml", xmlRoot); relRootDirs.put("xsl", xslRoot); relRootDirs.put("xsd", xsdRoot); relRootDirs.put("temp", tempRoot); } public java.util.Map act (Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters params) throws IOException, ComponentException, SAXException, ProcessingException { // Get absolute path of sitemap directory org.apache.cocoon.environment.Source input_source=resolver.resolve(""); String sitemapPath=input_source.getSystemId(); sitemapPath=sitemapPath.substring(5); // Remove "file:" protocol getLogger().debug("Absolute SITEMAP Directory: " + sitemapPath); getLogger().debug("Absolute XML Root Directory: " + sitemapPath + xmlRoot); getLogger().debug("Absolute XSL Root Directory: " + sitemapPath + xslRoot); getLogger().debug("Absolute XSD Root Directory: " + sitemapPath + xsdRoot); getLogger().debug("Absolute Temp Root Directory: " + sitemapPath + tempRoot); // Get request object HttpRequest httpReq = (HttpRequest)objectModel.get(ObjectModelHelper.REQUEST_OBJECT); if(httpReq == null){ getLogger().error ("Could not get HTTP_REQUEST_OBJECT from objectModel"); return null; } int length = httpReq.getContentLength(); PostInputStream reqContent = new PostInputStream(httpReq.getInputStream(), length); // construct DOM document from the request contents Parser parser = (Parser) this.manager.lookup(Parser.ROLE); InputSource saxSource = new InputSource(reqContent); Document requestDoc = parser.parseDocument(saxSource); Element root = requestDoc.getDocumentElement(); getLogger().debug ("root element (should be 'request'): " + root.getTagName()); String reqId = root.getAttribute("id"); getLogger().debug ("Request ID: " + reqId); String reqType = root.getAttribute("type"); getLogger().debug ("Request Type: " + reqType); Element data = (Element) root.getFirstChild(); getLogger().debug ("first child element (should be 'data'): " + data.getTagName()); String reqFile = data.getAttribute("id"); getLogger().debug ("Requested File: " + reqFile); String fileType = data.getAttribute("type"); getLogger().debug ("Requested File's Type: " + fileType); // close the input stream reqContent.close(); // Define Files File tempFileDir = new File(sitemapPath + relRootDirs.get("temp") + "/" + relRootDirs.get(fileType)); if (!(tempFileDir.exists())) tempFileDir.mkdir(); File tempFile = IOUtils.createFile(tempFileDir, reqFile); File permFile = new File(sitemapPath + relRootDirs.get(fileType) + "/" + reqFile); // make a temporary copy of the file to be edited if ("xml".equals(fileType) && "open".equals(reqType)) { FileUtil.copyFile(permFile, tempFile); getLogger().debug("PERMANENT FILE: " + permFile.getAbsolutePath()); getLogger().debug("TEMPORARY FILE: " + tempFile.getAbsolutePath()); } // set sitemap params for response routing Map sitemapParams = new HashMap(); sitemapParams.put("reqId", reqId); sitemapParams.put("reqType", reqType); sitemapParams.put("reqFile", reqFile); if ("xml".equals(fileType) && ("open".equals(reqType) || "save".equals(reqType))) { sitemapParams.put("reqFilePath", (String)relRootDirs.get("temp") + "/" + (String)relRootDirs.get(fileType) + "/" + reqFile); } else { sitemapParams.put("reqFilePath", (String)relRootDirs.get(fileType) + "/" + reqFile); } sitemapParams.put("fileType", fileType); getLogger().debug ("File to be edited (in temp dir): " + sitemapParams.get("reqFilePath")); // save to temporary file, if needed if ("save".equals(reqType) || "checkin".equals(reqType)) { //FIXME(): remove hard coding final OutputStream os = new FileOutputStream(tempFile); ComponentSelector selector = (ComponentSelector)super.manager.lookup(Serializer.ROLE + "Selector"); //FIXME: remove hardcoding stuff Serializer serializer = (Serializer)selector.select("xml"); serializer.setOutputStream(os); serializer.startDocument(); DOMStreamer domStreamer = new DOMStreamer(serializer); Element contentNode = (Element) data.getFirstChild(); domStreamer.stream(contentNode); serializer.endDocument(); getLogger().debug("NODE IS: \n" + contentNode.toString()); selector.release(serializer); super.manager.release(selector); os.flush(); os.close(); } // save to permanent file, if needed if ("checkin".equals(reqType)) { FileUtil.copyFile(tempFile, permFile); } return sitemapParams; } }
package org.jdesktop.swingx.autocomplete; import static org.jdesktop.swingx.autocomplete.ObjectToStringConverter.DEFAULT_IMPLEMENTATION; import javax.swing.UIManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.EventListenerList; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.PlainDocument; import javax.swing.text.Position; import javax.swing.text.Segment; import org.jdesktop.swingx.util.Contract; /** * A document that can be plugged into any JTextComponent to enable automatic completion. * It finds and selects matching items using any implementation of the AbstractAutoCompleteAdaptor. */ public class AutoCompleteDocument implements Document { private class Handler implements DocumentListener, UndoableEditListener { private final EventListenerList listenerList = new EventListenerList(); public void addDocumentListener(DocumentListener listener) { listenerList.add(DocumentListener.class, listener); } public void addUndoableEditListener(UndoableEditListener listener) { listenerList.add(UndoableEditListener.class, listener); } /** * {@inheritDoc} */ public void removeDocumentListener(DocumentListener listener) { listenerList.remove(DocumentListener.class, listener); } /** * {@inheritDoc} */ public void removeUndoableEditListener(UndoableEditListener listener) { listenerList.remove(UndoableEditListener.class, listener); } /** * {@inheritDoc} */ public void changedUpdate(DocumentEvent e) { e = new DelegatingDocumentEvent(AutoCompleteDocument.this, e); // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==DocumentListener.class) { // Lazily create the event: // if (e == null) // e = new ListSelectionEvent(this, firstIndex, lastIndex); ((DocumentListener)listeners[i+1]).changedUpdate(e); } } } /** * {@inheritDoc} */ public void insertUpdate(DocumentEvent e) { e = new DelegatingDocumentEvent(AutoCompleteDocument.this, e); // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==DocumentListener.class) { // Lazily create the event: // if (e == null) // e = new ListSelectionEvent(this, firstIndex, lastIndex); ((DocumentListener)listeners[i+1]).insertUpdate(e); } } } /** * {@inheritDoc} */ public void removeUpdate(DocumentEvent e) { e = new DelegatingDocumentEvent(AutoCompleteDocument.this, e); // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==DocumentListener.class) { // Lazily create the event: // if (e == null) // e = new ListSelectionEvent(this, firstIndex, lastIndex); ((DocumentListener)listeners[i+1]).removeUpdate(e); } } } /** * {@inheritDoc} */ public void undoableEditHappened(UndoableEditEvent e) { e = new UndoableEditEvent(AutoCompleteDocument.this, e.getEdit()); // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==UndoableEditListener.class) { // Lazily create the event: // if (e == null) // e = new ListSelectionEvent(this, firstIndex, lastIndex); ((UndoableEditListener)listeners[i+1]).undoableEditHappened(e); } } } } /** Flag to indicate if adaptor.setSelectedItem has been called. * Subsequent calls to remove/insertString should be ignored * as they are likely have been caused by the adapted Component that * is trying to set the text for the selected component.*/ boolean selecting=false; /** * true, if only items from the adaptors's list can be entered * false, otherwise (selected item might not be in the adaptors's list) */ protected boolean strictMatching; /** * The adaptor that is used to find and select items. */ AbstractAutoCompleteAdaptor adaptor; ObjectToStringConverter stringConverter; private final Handler handler; protected final Document delegate; /** * Creates a new AutoCompleteDocument for the given AbstractAutoCompleteAdaptor. * @param adaptor The adaptor that will be used to find and select matching * items. * @param strictMatching true, if only items from the adaptor's list should * be allowed to be entered * @param stringConverter the converter used to transform items to strings * @param delegate the {@code Document} delegate backing this document */ public AutoCompleteDocument(AbstractAutoCompleteAdaptor adaptor, boolean strictMatching, ObjectToStringConverter stringConverter, Document delegate) { this.adaptor = Contract.asNotNull(adaptor, "adaptor cannot be null"); this.strictMatching = strictMatching; this.stringConverter = stringConverter == null ? DEFAULT_IMPLEMENTATION : stringConverter; this.delegate = delegate == null ? createDefaultDocument() : delegate; handler = new Handler(); this.delegate.addDocumentListener(handler); // Handle initially selected object Object selected = adaptor.getSelectedItem(); if (selected!=null) setText(this.stringConverter.getPreferredStringForItem(selected)); this.adaptor.markEntireText(); } /** * Creates a new AutoCompleteDocument for the given AbstractAutoCompleteAdaptor. * @param adaptor The adaptor that will be used to find and select matching * items. * @param strictMatching true, if only items from the adaptor's list should * be allowed to be entered * @param stringConverter the converter used to transform items to strings */ public AutoCompleteDocument(AbstractAutoCompleteAdaptor adaptor, boolean strictMatching, ObjectToStringConverter stringConverter) { this(adaptor, strictMatching, stringConverter, null); } /** * Creates a new AutoCompleteDocument for the given AbstractAutoCompleteAdaptor. * @param strictMatching true, if only items from the adaptor's list should * be allowed to be entered * @param adaptor The adaptor that will be used to find and select matching * items. */ public AutoCompleteDocument(AbstractAutoCompleteAdaptor adaptor, boolean strictMatching) { this(adaptor, strictMatching, null); } /** * Creates the default backing document when no delegate is passed to this * document. * * @return the default backing document */ protected Document createDefaultDocument() { return new PlainDocument(); } public void remove(int offs, int len) throws BadLocationException { // return immediately when selecting an item if (selecting) return; delegate.remove(offs, len); if (!strictMatching) { setSelectedItem(getText(0, getLength()), getText(0, getLength())); adaptor.getTextComponent().setCaretPosition(offs); } } public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { // return immediately when selecting an item if (selecting) return; // insert the string into the document delegate.insertString(offs, str, a); // lookup and select a matching item LookupResult lookupResult = lookupItem(getText(0, getLength())); if (lookupResult.matchingItem != null) { setSelectedItem(lookupResult.matchingItem, lookupResult.matchingString); } else { if (strictMatching) { // keep old item selected if there is no match lookupResult.matchingItem = adaptor.getSelectedItem(); lookupResult.matchingString = adaptor.getSelectedItemAsString(); // imitate no insert (later on offs will be incremented by // str.length(): selection won't move forward) offs = offs-str.length(); // provide feedback to the user that his input has been received but can not be accepted UIManager.getLookAndFeel().provideErrorFeedback(adaptor.getTextComponent()); } else { // no item matches => use the current input as selected item lookupResult.matchingItem=getText(0, getLength()); lookupResult.matchingString=getText(0, getLength()); setSelectedItem(lookupResult.matchingItem, lookupResult.matchingString); } } setText(lookupResult.matchingString); // select the completed part adaptor.markText(offs+str.length()); } /** * Sets the text of this AutoCompleteDocument to the given text. * * @param text the text that will be set for this document */ private void setText(String text) { try { // remove all text and insert the completed string delegate.remove(0, getLength()); delegate.insertString(0, text, null); } catch (BadLocationException e) { throw new RuntimeException(e.toString()); } } /** * Selects the given item using the AbstractAutoCompleteAdaptor. * @param itemAsString string representation of the item to be selected * @param item the item that is to be selected */ private void setSelectedItem(Object item, String itemAsString) { selecting = true; adaptor.setSelectedItem(item); adaptor.setSelectedItemAsString(itemAsString); selecting = false; } /** * Searches for an item that matches the given pattern. The AbstractAutoCompleteAdaptor * is used to access the candidate items. The match is not case-sensitive * and will only match at the beginning of each item's string representation. * * @param pattern the pattern that should be matched * @return the first item that matches the pattern or <code>null</code> if no item matches */ private LookupResult lookupItem(String pattern) { Object selectedItem = adaptor.getSelectedItem(); String[] possibleStrings; // iterate over all items to find an exact match for (int i=0, n=adaptor.getItemCount(); i < n; i++) { Object currentItem = adaptor.getItem(i); possibleStrings = stringConverter.getPossibleStringsForItem(currentItem); if (possibleStrings!=null) { // current item exactly matches the pattern? for (int j=0; j<possibleStrings.length; j++) { if (possibleStrings[j].equalsIgnoreCase(pattern)) { return new LookupResult(currentItem, possibleStrings[j]); } } } } // check if the currently selected item matches possibleStrings = stringConverter.getPossibleStringsForItem(selectedItem); if (possibleStrings!=null) { for (int i=0; i<possibleStrings.length; i++) { if (startsWithIgnoreCase(possibleStrings[i], pattern)) { return new LookupResult(selectedItem, possibleStrings[i]); } } } // search for any matching item, if the currently selected does not match for (int i=0, n=adaptor.getItemCount(); i < n; i++) { Object currentItem = adaptor.getItem(i); possibleStrings = stringConverter.getPossibleStringsForItem(currentItem); if (possibleStrings!=null) { for (int j=0; j<possibleStrings.length; j++) { if (startsWithIgnoreCase(possibleStrings[j], pattern)) { return new LookupResult(currentItem, possibleStrings[j]); } } } } // no item starts with the pattern => return null return new LookupResult(null, ""); } private static class LookupResult { Object matchingItem; String matchingString; public LookupResult(Object matchingItem, String matchingString) { this.matchingItem = matchingItem; this.matchingString = matchingString; } } /** * Returns true if <code>base</code> starts with <code>prefix</code> (ignoring case). * @param base the string to be checked * @param prefix the prefix to check for * @return true if <code>base</code> starts with <code>prefix</code>; false otherwise */ //TODO entry point for handling 739 private boolean startsWithIgnoreCase(String base, String prefix) { if (base.length() < prefix.length()) return false; return base.regionMatches(true, 0, prefix, 0, prefix.length()); } /** * {@inheritDoc} */ public void addDocumentListener(DocumentListener listener) { handler.addDocumentListener(listener); } /** * {@inheritDoc} */ public void addUndoableEditListener(UndoableEditListener listener) { handler.addUndoableEditListener(listener); } /** * {@inheritDoc} */ public Position createPosition(int offs) throws BadLocationException { return delegate.createPosition(offs); } /** * {@inheritDoc} */ public Element getDefaultRootElement() { return delegate.getDefaultRootElement(); } /** * {@inheritDoc} */ public Position getEndPosition() { return delegate.getEndPosition(); } /** * {@inheritDoc} */ public int getLength() { return delegate.getLength(); } /** * {@inheritDoc} */ public Object getProperty(Object key) { return delegate.getProperty(key); } /** * {@inheritDoc} */ public Element[] getRootElements() { return delegate.getRootElements(); } /** * {@inheritDoc} */ public Position getStartPosition() { return delegate.getStartPosition(); } /** * {@inheritDoc} */ public String getText(int offset, int length) throws BadLocationException { return delegate.getText(offset, length); } /** * {@inheritDoc} */ public void getText(int offset, int length, Segment txt) throws BadLocationException { delegate.getText(offset, length, txt); } /** * {@inheritDoc} */ public void putProperty(Object key, Object value) { delegate.putProperty(key, value); } /** * {@inheritDoc} */ public void removeDocumentListener(DocumentListener listener) { handler.removeDocumentListener(listener); } /** * {@inheritDoc} */ public void removeUndoableEditListener(UndoableEditListener listener) { handler.removeUndoableEditListener(listener); } /** * {@inheritDoc} */ public void render(Runnable r) { delegate.render(r); } /** * Returns if only items from the adaptor's list should be allowed to be entered. * @return if only items from the adaptor's list should be allowed to be entered */ public boolean isStrictMatching() { return strictMatching; } }
package algorithms.optimization; import algorithms.graphs.HierholzersEulerCircuit; import algorithms.msts.KruskalsMinimumSpanningTree; import algorithms.msts.PrimsMST; import algorithms.tsp.TSPPrimsMST; import algorithms.util.PairInt; import algorithms.util.SimpleLinkedListNode; import gnu.trove.iterator.TIntIntIterator; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntDoubleMap; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TObjectDoubleMap; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import thirdparty.HungarianAlgorithm; public class TSPChristofidesSerdyukov { /** * find a Hamiltonian tour of the given graph (simple cycle including all vertexes) * that is 3/2 - approximate for minimum total cost. * @param nVertexes * @param adjCostMap * @return the Hamiltonian cycle within a factor of no more than 1.5 of the * optimal tour's minimum cost. the array returned contains the vertex numbers * from the adjacency cost map. */ public int[] approxTSPTour(final int nVertexes, final TIntObjectMap<TIntIntMap> adjCostMap) { //(1) T = mst(G) Map<Integer, LinkedList<Integer>> mstTree = buildMST(adjCostMap); //(2) W = odd degree vertices in T int[] degrees = calculateDegrees(mstTree, nVertexes); int[] oddDVertexes = oddPassFilter(degrees); // there are an even number of odd vertexes assert((oddDVertexes.length & 1) != 1); int i; //(3) O is subgraph of G induced by the vertices in oddDVertexes. // make perfect min-cost matching from it // format: [nMatcings][2] int[][] m = bipartiteMinCostMatchingFromSubgraph(oddDVertexes, adjCostMap); //(4) H is the union of graphs T and M // where each edges present in both T and M are present twice in H TIntObjectMap<TIntSet> h = unionMSTAndAssignments(mstTree, m); //(5) EC is the eulerian circuit in H. each edge is visited exactly once. HierholzersEulerCircuit hec = new HierholzersEulerCircuit(); int[] ec = hec.createCircuit(h); // assuming start node = 0. //(6) T2 is the hamiltonian circuit of EC made by skipping over previously visited vertices. TIntSet visited = new TIntHashSet(); TIntList t2 = new TIntArrayList(); for (i = 0; i < ec.length; ++i) { if (!visited.contains(ec[i])) { t2.add(ec[i]); visited.add(ec[i]); } } t2.add(t2.get(0)); int[] _t2 = t2.toArray(); return t2.toArray(); } /** * return an array of the indexes which have odd degrees. * @param degrees array where indexes are the vertex number and values are * the degree for the vertex. * @return array of indexes in degrees which have odd values stored in the degrees array. */ protected int[] oddPassFilter(int[] degrees) { int[] odd = new int[degrees.length]; int i, c = 0; for (i = 0; i < degrees.length; ++i) { if ((degrees[i] & 1) == 1) { odd[c] = i; c++; } } odd = Arrays.copyOf(odd, c); return odd; } protected int[] calculateDegrees(Map<Integer, LinkedList<Integer>> mstTree, int nVertexes) { int[] d = new int[nVertexes]; int u, v; LinkedList<Integer> neighbors; Iterator<Integer> iter = mstTree.keySet().iterator(); Iterator<Integer> iterV; while (iter.hasNext()) { u = iter.next(); neighbors = mstTree.get(u); iterV = neighbors.iterator(); while (iterV.hasNext()) { v = iterV.next(); d[u]++; d[v]++; } } return d; } /** * create a cost matrix from the vertexes listed in oddDVertexes where the * adjacency and costs are within adjCostMap. * @param oddDVertexes values are the vertex numbers with odd degrees * @param adjCostMap the cost map within the original adjacency map. * @return a cost matrix whose indexes are relative to oddDVertexes. * Note that non-existing connections have a cost of Float.MAX_VALUE. */ protected float[][] buildCostMatrix(int[] oddDVertexes, TIntObjectMap<TIntIntMap> adjCostMap) { int i, u, v, uvCost; float[][] out = new float[oddDVertexes.length][]; for (i = 0; i < oddDVertexes.length; ++i) { out[i] = new float[oddDVertexes.length]; Arrays.fill(out[i], Float.MAX_VALUE); } // a reverse index map to find where v is in oddDVertexes TIntIntMap rIdxs = new TIntIntHashMap(); for (i = 0; i < oddDVertexes.length; ++i) { u = oddDVertexes[i]; rIdxs.put(u, i); } int idxV; TIntIntMap neighborCost; TIntIntIterator iter; for (i = 0; i < oddDVertexes.length; ++i) { u = oddDVertexes[i]; neighborCost = adjCostMap.get(u); if (neighborCost != null) { iter = neighborCost.iterator(); while (iter.hasNext()) { iter.advance(); v = iter.key(); if (!rIdxs.containsKey(v)) { continue; } uvCost = iter.value(); idxV = rIdxs.get(v); out[i][idxV] = uvCost; } } } return out; } protected Map<Integer, LinkedList<Integer>> buildMST(TIntObjectMap<TIntIntMap> adjCostMap) { // finding the max cost in the graph G needed for a trie used in Prim's MST int maxCost = PrimsMST.maxEdgeCost(adjCostMap); PrimsMST prims = new PrimsMST(); prims.calculateMinimumSpanningTree(adjCostMap, maxCost); //(1) T = mst(G) Map<Integer, LinkedList<Integer>> mstTree = prims.makeTreeFromPrev(); //print(mstTree); //TIntList treeWalk = prims.getPreorderIndexes(); //System.out.printf("treeWalk=%s\n", Arrays.toString(treeWalk.toArray())); return mstTree; } /* protected Map<Integer, LinkedList<Double>> buildMST2(TIntObjectMap<TIntDoubleMap> adjCostMap) { SimpleLinkedListNode[] graph, TObjectDoubleMap<PairInt> edgeWeights; TIntObjectMap<SimpleLinkedListNode> mst = KruskalsMinimumSpanningTree.mst( graph, edgeWeights); return mstTree; }*/ /** * perfect min-cost bipartite matchings of the subgraph of G induced by the * odd vertexes. The results are in a double array where each row * is a pair of matching vertexes in context of graph G. * @param oddDVertexes * @param adjCostMap * @return */ protected int[][] bipartiteMinCostMatchingFromSubgraph( int[] oddDVertexes, TIntObjectMap<TIntIntMap> adjCostMap) { // building O as a cost matrix for input to the Hungarian algorithm float[][] oCostMatrix = buildCostMatrix(oddDVertexes, adjCostMap); // indexes of the oCostMatrix are the values of oddDVertexes // so should be transformed back to vertex numbers after // mincost matching. // for min-cost perfect matching can use Hungarian Algorithm. // alternatively, can use MinCostUnbalancedAssignment. // hungarian algorithm accepts argument: computeAssignments(float[][] matrix). // MinCostUnbalancedAssignment needs a Graph g. int[][] assignmentsM = new HungarianAlgorithm().computeAssignments(oCostMatrix); int i, n = 0, k, v; TIntIntMap keep = new TIntIntHashMap(); TIntSet included = new TIntHashSet(); for (i = 0; i < assignmentsM.length; ++i) { k = assignmentsM[i][0]; v = assignmentsM[i][1]; //System.out.printf("%d, %d\n", k, v); if (included.contains(k) || included.contains(v)) { continue; } keep.put(k, v); included.add(k); included.add(v); n++; } int[][] m = new int[n][]; TIntIntIterator iterK = keep.iterator(); for (i = 0; i < n; ++i) { iterK.advance(); k = iterK.key(); v = iterK.value(); m[i] = new int[]{oddDVertexes[k], oddDVertexes[v]}; } return m; } protected TIntObjectMap<TIntSet> unionMSTAndAssignments( Map<Integer, LinkedList<Integer>> mstTree, int[][] m) { int i, u, v; TIntObjectMap<TIntSet> h = new TIntObjectHashMap<TIntSet>(); Iterator<Integer> iterMST = mstTree.keySet().iterator(); LinkedList<Integer> lList; Iterator<Integer> iterList; TIntSet s; while (iterMST.hasNext()) { u = iterMST.next(); lList = mstTree.get(u); iterList = lList.iterator(); while (iterList.hasNext()) { v = iterList.next(); s = h.get(u); if (s == null) { s = new TIntHashSet(); h.put(u, s); } s.add(v); } } for (i = 0; i < m.length; ++i) { s = h.get(m[i][0]); if (s == null) { s = new TIntHashSet(); h.put(m[i][0], s); } s.add(m[i][1]); } return h; } public static long totalCost(int[] hamiltonian, TIntObjectMap<TIntIntMap> adjCostMap) { long sum = 0; int i, u, v, cost; TIntIntMap assoc; for (i = 1; i < hamiltonian.length;++i) { u = hamiltonian[i - 1]; v = hamiltonian[i]; assoc = adjCostMap.get(u); if (assoc == null) { throw new IllegalStateException("node " + u + " is not a key in the adjCostMap"); } if (!assoc.containsKey(v)) { throw new IllegalStateException("node " + v + " is not a value in the adjCostMapfor key=" + u); } sum += assoc.get(v); } return sum; } private void print(Map<Integer, LinkedList<Integer>> mstTree) { Iterator<Integer> intIter = mstTree.keySet().iterator(); Iterator<Integer> intIter2; int u, v; System.out.println("MST:"); while (intIter.hasNext()) { u = intIter.next(); intIter2 = mstTree.get(u).iterator(); while (intIter2.hasNext()) { v = intIter2.next(); System.out.printf("%d:%d\n", u, v); } } } }
package au.gov.dto.dibp.appointments.config; import org.springframework.boot.autoconfigure.mustache.web.MustacheViewResolver; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("redirect:/login"); } /** * PWS requires this override to resolve mustache views, * otherwise it produces the following error: * "Circular view path [login]: would dispatch back to the current handler URL [/login] again" */ @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.viewResolver(new MustacheViewResolver()); } }
package cn.org.rapid_framework.generator; import cn.org.rapid_framework.generator.Generator.GeneratorModel; import cn.org.rapid_framework.generator.provider.db.sql.model.Sql; import cn.org.rapid_framework.generator.provider.db.table.TableFactory; import cn.org.rapid_framework.generator.provider.db.table.model.Table; import cn.org.rapid_framework.generator.provider.java.model.JavaClass; import cn.org.rapid_framework.generator.util.BeanHelper; import cn.org.rapid_framework.generator.util.GLogger; import cn.org.rapid_framework.generator.util.GeneratorException; import cn.org.rapid_framework.generator.util.typemapping.DatabaseTypeUtils; import java.io.*; import java.util.*; /** * * @author badqiu * */ public class GeneratorFacade { public Generator g = new Generator(); public GeneratorFacade(){ g.setOutRootDir(GeneratorProperties.getProperty("outRoot")); } public static void printAllTableNames() throws Exception { PrintUtils.printAllTableNames(TableFactory.getInstance().getAllTables()); } public void deleteOutRootDir() throws IOException { g.deleteOutRootDir(); } public void generateByMap(Map map,String templateRootDir) throws Exception { new ProcessUtils().processByMap(map, templateRootDir,false); } public void deleteByMap(Map map,String templateRootDir) throws Exception { new ProcessUtils().processByMap(map, templateRootDir,true); } public void generateByAllTable(String templateRootDir) throws Exception { new ProcessUtils().processByAllTable(templateRootDir,false); } public void deleteByAllTable(String templateRootDir) throws Exception { new ProcessUtils().processByAllTable(templateRootDir,true); } public void generateByTable(String tableName,String templateRootDir) throws Exception { new ProcessUtils().processByTable(tableName,templateRootDir,false); } public void deleteByTable(String tableName,String templateRootDir) throws Exception { new ProcessUtils().processByTable(tableName,templateRootDir,true); } public void generateByClass(Class clazz,String templateRootDir) throws Exception { new ProcessUtils().processByClass(clazz, templateRootDir,false); } public void deleteByClass(Class clazz,String templateRootDir) throws Exception { new ProcessUtils().processByClass(clazz, templateRootDir,true); } public void generateBySql(Sql sql,String templateRootDir) throws Exception { new ProcessUtils().processBySql(sql,templateRootDir,false); } public void deleteBySql(Sql sql,String templateRootDir) throws Exception { new ProcessUtils().processBySql(sql,templateRootDir,true); } private Generator getGenerator(String templateRootDir) { g.setTemplateRootDir(new File(templateRootDir).getAbsoluteFile()); return g; } public static class GeneratorContext { static ThreadLocal<Map> context = new ThreadLocal<Map>(); public static void clear() { Map m = context.get(); if(m != null) m.clear(); } public static Map getContext() { Map map = context.get(); if(map == null) { setContext(new HashMap()); } return context.get(); } public static void setContext(Map map) { context.set(map); } public static void put(String key,Object value) { getContext().put(key, value); } } public class ProcessUtils { public void processByMap(Map params, String templateRootDir,boolean isDelete) throws Exception, FileNotFoundException { Generator g = getGenerator(templateRootDir); GeneratorModel m = GeneratorModelUtils.newFromMap(params); try { if(isDelete) g.deleteBy(m.templateModel, m.filePathModel); else g.generateBy(m.templateModel, m.filePathModel); }catch(GeneratorException ge) { PrintUtils.printExceptionsSumary(ge.getMessage(),getGenerator(templateRootDir).getOutRootDir(),ge.getExceptions()); } } public void processBySql(Sql sql,String templateRootDir,boolean isDelete) throws Exception { Generator g = getGenerator(templateRootDir); GeneratorModel m = GeneratorModelUtils.newFromSql(sql); PrintUtils.printBeginProcess("sql:"+sql.getSourceSql(),isDelete); try { if(isDelete) { g.deleteBy(m.templateModel, m.filePathModel); }else { g.generateBy(m.templateModel, m.filePathModel); } }catch(GeneratorException ge) { PrintUtils.printExceptionsSumary(ge.getMessage(),getGenerator(templateRootDir).getOutRootDir(),ge.getExceptions()); } } public void processByClass(Class clazz, String templateRootDir,boolean isDelete) throws Exception, FileNotFoundException { Generator g = getGenerator(templateRootDir); GeneratorModel m = GeneratorModelUtils.newFromClass(clazz); PrintUtils.printBeginProcess("JavaClass:"+clazz.getSimpleName(),isDelete); try { if(isDelete) g.deleteBy(m.templateModel, m.filePathModel); else g.generateBy(m.templateModel, m.filePathModel); }catch(GeneratorException ge) { PrintUtils.printExceptionsSumary(ge.getMessage(),getGenerator(templateRootDir).getOutRootDir(),ge.getExceptions()); } } public void processByTable(String tableName,String templateRootDir,boolean isDelete) throws Exception { if("*".equals(tableName)) { generateByAllTable(templateRootDir); return; } Generator g = getGenerator(templateRootDir); Table table = TableFactory.getInstance().getTable(tableName); try { processByTable(g,table,isDelete); }catch(GeneratorException ge) { PrintUtils.printExceptionsSumary(ge.getMessage(),getGenerator(templateRootDir).getOutRootDir(),ge.getExceptions()); } } public void processByAllTable(String templateRootDir,boolean isDelete) throws Exception { List<Table> tables = TableFactory.getInstance().getAllTables(); List exceptions = new ArrayList(); for(int i = 0; i < tables.size(); i++ ) { try { processByTable(getGenerator(templateRootDir),tables.get(i),isDelete); }catch(GeneratorException ge) { exceptions.addAll(ge.getExceptions()); } } PrintUtils.printExceptionsSumary("",getGenerator(templateRootDir).getOutRootDir(),exceptions); } public void processByTable(Generator g, Table table,boolean isDelete) throws Exception { // renfufei String sqlName = table.getSqlName(); String prefixs = GeneratorProperties.getProperty("skipTablePrefixes", ""); for(String prefix : prefixs.split(",")) { if(null != prefix && !prefix.trim().isEmpty() && sqlName.startsWith(prefix)) { GLogger.println("[skip] matches prefix: " + prefix + "; skipTable: " + sqlName); return ; } } GeneratorModel m = GeneratorModelUtils.newFromTable(table); PrintUtils.printBeginProcess(table.getSqlName()+" => "+table.getClassName(),isDelete); if(isDelete) g.deleteBy(m.templateModel,m.filePathModel); else g.generateBy(m.templateModel,m.filePathModel); } } @SuppressWarnings("all") public static class GeneratorModelUtils { public static GeneratorModel newFromTable(Table table) { Map templateModel = new HashMap(); templateModel.put("table", table); setShareVars(templateModel); Map filePathModel = new HashMap(); setShareVars(filePathModel); filePathModel.putAll(BeanHelper.describe(table)); return new GeneratorModel(templateModel,filePathModel); } public static GeneratorModel newFromSql(Sql sql) throws Exception { Map templateModel = new HashMap(); templateModel.put("sql", sql); setShareVars(templateModel); Map filePathModel = new HashMap(); setShareVars(filePathModel); filePathModel.putAll(BeanHelper.describe(sql)); return new GeneratorModel(templateModel,filePathModel); } public static GeneratorModel newFromClass(Class clazz) { Map templateModel = new HashMap(); templateModel.put("clazz", new JavaClass(clazz)); setShareVars(templateModel); Map filePathModel = new HashMap(); setShareVars(filePathModel); filePathModel.putAll(BeanHelper.describe(new JavaClass(clazz))); return new GeneratorModel(templateModel,filePathModel); } public static GeneratorModel newFromMap(Map params) { Map templateModel = new HashMap(); templateModel.putAll(params); setShareVars(templateModel); Map filePathModel = new HashMap(); setShareVars(filePathModel); filePathModel.putAll(params); return new GeneratorModel(templateModel,filePathModel); } public static void setShareVars(Map templateModel) { templateModel.putAll(GeneratorProperties.getProperties()); templateModel.putAll(System.getProperties()); templateModel.put("env", System.getenv()); templateModel.put("now", new Date()); templateModel.put("databaseType", getDatabaseType("databaseType")); templateModel.putAll(GeneratorContext.getContext()); } private static String getDatabaseType(String key) { return GeneratorProperties.getProperty(key,DatabaseTypeUtils.getDatabaseTypeByJdbcDriver(GeneratorProperties.getProperty("jdbc.driver"))); } } private static class PrintUtils { private static void printExceptionsSumary(String msg,String outRoot,List<Exception> exceptions) throws FileNotFoundException { File errorFile = new File(outRoot,"generator_error.log"); if(exceptions != null && exceptions.size() > 0) { System.err.println("[Generate Error Summary] : "+msg); PrintStream output = new PrintStream(new FileOutputStream(errorFile)); for(int i = 0; i < exceptions.size(); i++) { Exception e = exceptions.get(i); System.err.println("[GENERATE ERROR]:"+e); if(i == 0) e.printStackTrace(); e.printStackTrace(output); } output.close(); System.err.println("***************************************************************"); System.err.println("* "+"* generator_error.log "); System.err.println("***************************************************************"); } } private static void printBeginProcess(String displayText,boolean isDatele) { GLogger.println("***************************************************************"); GLogger.println("* BEGIN " + (isDatele ? " delete by " : " generate by ")+ displayText); GLogger.println("***************************************************************"); } public static void printAllTableNames(List<Table> tables) throws Exception { GLogger.println("\n for(int i = 0; i < tables.size(); i++ ) { String sqlName = ((Table)tables.get(i)).getSqlName(); GLogger.println("g.generateTable(\""+sqlName+"\");"); } GLogger.println(" } } }
package co.phoenixlab.discord.api; import co.phoenixlab.common.lang.SafeNav; import co.phoenixlab.discord.api.entities.*; import co.phoenixlab.discord.api.entities.voice.VoiceServerUpdate; import co.phoenixlab.discord.api.entities.voice.VoiceStateUpdate; import co.phoenixlab.discord.api.event.*; import co.phoenixlab.discord.api.event.ServerBanChangeEvent.BanChange; import co.phoenixlab.discord.api.event.voice.VoiceServerUpdateEvent; import co.phoenixlab.discord.api.event.voice.VoiceStateUpdateEvent; import co.phoenixlab.discord.stats.RunningAverage; import com.google.gson.Gson; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_10; import org.java_websocket.handshake.ServerHandshake; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.time.ZonedDateTime; import java.util.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.LongAdder; import java.util.stream.Collectors; import static co.phoenixlab.discord.api.DiscordApiClient.*; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; public class DiscordWebSocketClient extends WebSocketClient { private static final Logger LOGGER = LoggerFactory.getLogger("DiscordApiWebSocketClient"); private static Map<String, String> header; static { header = new HashMap<>(); header.put("Accept-Encoding", "gzip"); } private final DiscordApiClient apiClient; private final JSONParser parser; private final Gson gson; private final Statistics statistics; private ScheduledFuture keepAliveFuture; public DiscordWebSocketClient(DiscordApiClient apiClient, URI serverUri) { super(serverUri, new Draft_10(), header, 0); this.apiClient = apiClient; this.parser = new JSONParser(); this.gson = new Gson(); statistics = new Statistics(); } @Override public void onOpen(ServerHandshake handshakedata) { Thread.currentThread().setName("WebSocketClient"); LOGGER.info("WebSocket connection opened"); org.json.JSONObject connectObj = new org.json.JSONObject(); connectObj.put("op", 2); org.json.JSONObject dataObj = new org.json.JSONObject(); dataObj.put("token", apiClient.getToken()); dataObj.put("v", 3); dataObj.put("large_threshold", 250); dataObj.put("compress", false); org.json.JSONObject properties = new org.json.JSONObject(); properties.put("$os", "Linux"); properties.put("$browser", "Java"); properties.put("$device", "Java"); properties.put("$referrer", ""); properties.put("$referring_domain", ""); dataObj.put("properties", properties); connectObj.put("d", dataObj); send(connectObj.toString()); } @Override public void onMessage(String message) { long start = System.nanoTime(); try { LOGGER.trace("Recieved message: {}", message); statistics.messageReceiveCount.increment(); try { JSONObject msg = (JSONObject) parser.parse(message); String errorMessage = (String) msg.get("message"); if (errorMessage != null) { if (errorMessage.isEmpty()) { LOGGER.warn("[0] '': Discord returned an unknown error"); } else { LOGGER.warn("[0] '': Discord returned error: {}", errorMessage); } statistics.errorCount.increment(); return; } int opCode = ((Number) msg.get("op")).intValue(); if (opCode != 0) { LOGGER.warn("Unknown opcode {} received: {}", opCode, message); return; } String type = (String) msg.get("t"); JSONObject data = (JSONObject) msg.get("d"); switch (type) { case "READY": handleReadyMessage(data); break; case "GUILD_MEMBERS_CHUNK": handleGuildMembersChunk(data); break; case "USER_UPDATE": handleUserUpdate(data); break; case "USER_SETTINGS_UPDATE": // Don't care break; case "MESSAGE_CREATE": handleMessageCreate(data); break; case "MESSAGE_UPDATE": handleMessageUpdate(data); break; case "MESSAGE_DELETE": handleMessageDelete(data); break; case "BULK_MESSAGE_DELETE": handleBulkMessageDelete(data); break; case "TYPING_START": // Don't care break; case "GUILD_CREATE": handleGuildCreate(data); break; case "GUILD_DELETE": handleGuildDelete(data); break; case "GUILD_UPDATE": handleGuildUpdate(data); break; case "GUILD_MEMBER_ADD": handleGuildMemberAdd(data); break; case "GUILD_MEMBER_REMOVE": handleGuildMemberRemove(data); break; case "GUILD_MEMBER_UPDATE": handleGuildMemberUpdate(data); break; case "GUILD_ROLE_CREATE": handleGuildRoleCreate(data); break; case "GUILD_ROLE_DELETE": handleGuildRoleDelete(data); break; case "GUILD_ROLE_UPDATE": handleGuildRoleUpdate(data); break; case "CHANNEL_CREATE": handleChannelCreate(data); break; case "CHANNEL_DELETE": handleChannelDelete(data); break; case "CHANNEL_UPDATE": handleChannelUpdate(data); break; case "PRESENCE_UPDATE": handlePresenceUpdate(data, message); break; case "VOICE_STATE_UPDATE": handleVoiceStateUpdate(data); break; case "VOICE_SERVER_UPDATE": handleVoiceServerUpdate(data); break; case "GUILD_BAN_ADD": handleGuildBanAdd(data); break; case "GUILD_BAN_DELETE": handleGuildBanDelete(data); break; case "MESSAGE_ACK": // Ignored break; // TODO default: LOGGER.warn("[0] '': Unknown message type {}:\n{}", type, data.toJSONString()); } } catch (Exception e) { LOGGER.warn("[0] '': Unable to parse message", e); } } finally { statistics.avgMessageHandleTime.add(MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS)); } } private void handleGuildUpdate(JSONObject data) { Server server = jsonObjectToObject(data, Server.class); Server localServer = apiClient.getServerByID(server.getId()); SafeNav.of(server.getIcon()).ifPresent(localServer::setIcon); SafeNav.of(server.getOwnerId()).ifPresent(localServer::setOwnerId); SafeNav.of(server.getRegion()).ifPresent(localServer::setRegion); } private void handleGuildBanDelete(JSONObject data) { String serverId = (String) data.get("guild_id"); JSONObject userJSON = (JSONObject) data.get("user"); User user = jsonObjectToObject(userJSON, User.class); Server server = apiClient.getServerByID(serverId); apiClient.getEventBus().post(new ServerBanChangeEvent(user, server, BanChange.DELETED)); } private void handleGuildBanAdd(JSONObject data) { String serverId = (String) data.get("guild_id"); JSONObject userJSON = (JSONObject) data.get("user"); User user = jsonObjectToObject(userJSON, User.class); Server server = apiClient.getServerByID(serverId); apiClient.getEventBus().post(new ServerBanChangeEvent(user, server, BanChange.ADDED)); } private void handleMessageDelete(JSONObject data) { String messageId = (String) data.get("id"); String channelId = (String) data.get("channel_id"); LOGGER.debug("Message {} deleted from {}", messageId, channelId); apiClient.getEventBus().post(new MessageDeleteEvent(messageId, channelId)); } private void handleBulkMessageDelete(JSONObject data) { Object[] idsObjs = (Object[]) data.get("ids"); List<String> collect = Arrays.stream(idsObjs) .map(o -> (o instanceof String ? (String) o : o.toString())) .collect(Collectors.toList()); String channelId = (String) data.get("channel_id"); LOGGER.debug("{} messages deleted from {}", collect.size(), channelId); collect.stream() .map(id -> new MessageDeleteEvent(id, channelId)) .forEach(apiClient.getEventBus()::post); } private void handleMessageUpdate(JSONObject data) { LOGGER.debug("Message edited: {}", data.toJSONString()); Message message = jsonObjectToObject(data, Message.class); Channel channel = apiClient.getChannelById(message.getChannelId()); if (channel == null || channel == NO_CHANNEL || channel.isPrivate()) { message.setPrivateMessage(true); } else { message.setPrivateMessage(false); } apiClient.getEventBus().post(new MessageEditEvent(message)); } private void handleGuildMembersChunk(JSONObject data) { String serverId = (String) data.get("guild_id"); JSONArray array = (JSONArray) data.get("members"); Member[] members = new Member[array.size()]; for (int i = 0; i < array.size(); i++) { Object object = array.get(i); Member m = jsonObjectToObject((JSONObject) object, Member.class); members[i] = m; } Server server = apiClient.getServerByID(serverId); Collections.addAll(server.getMembers(), members); LOGGER.debug("[{}] '{}': Received guild member chunk size {}", server.getId(), server.getName(), members.length); } private void handleUserUpdate(JSONObject data) { UserUpdate update = jsonObjectToObject(data, UserUpdate.class); LOGGER.debug("[0] '': Received user account update: username={} id={} avatar={} email={}", update.getUsername(), update.getId(), update.getAvatar(), update.getEmail()); apiClient.getEventBus().post(new UserUpdateEvent(update)); } private void handleVoiceStateUpdate(JSONObject data) { VoiceStateUpdate update = jsonObjectToObject(data, VoiceStateUpdate.class); update.fix(apiClient); Server server = update.getServer(); LOGGER.debug("[{}] '{}': Received voice status update for {} ({})", server.getId(), server.getName(), update.getUser().getUsername(), update.getUser().getId()); apiClient.getEventBus().post(new VoiceStateUpdateEvent(update)); } private void handleVoiceServerUpdate(JSONObject data) { VoiceServerUpdate update = jsonObjectToObject(data, VoiceServerUpdate.class); update.fix(apiClient); Server server = update.getServer(); LOGGER.debug("[{}] '{}': Received voice server update: endpoint={} token={}", server.getId(), server.getName(), update.getEndpoint(), update.getToken()); apiClient.getEventBus().post(new VoiceServerUpdateEvent(update)); } private void handleGuildRoleUpdate(JSONObject data) { Role role = jsonObjectToObject((JSONObject) data.get("role"), Role.class); String serverId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(serverId); if (server != NO_SERVER) { // Literally just shove it in because Set server.getRoles().remove(role); server.getRoles().add(role); LOGGER.debug("[{}] '{}': Updated role {} ({})", server.getId(), server.getName(), role.getName(), role.getId()); apiClient.getEventBus().post(new RoleChangeEvent(role, server, RoleChangeEvent.RoleChange.UPDATED)); } else { LOGGER.warn("[{}] '': Orphan role update received, ignored (roleid={} rolename={})", serverId, role.getId(), role.getName()); } } private void handleGuildRoleDelete(JSONObject data) { String roleId = (String) data.get("role_id"); String serverId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(serverId); if (server != NO_SERVER) { Role removed = null; for (Iterator<Role> iterator = server.getRoles().iterator(); iterator.hasNext(); ) { Role role = iterator.next(); if (role.getId().equals(roleId)) { removed = role; iterator.remove(); break; } } if (removed != null) { LOGGER.debug("[{}] '{}': Deleted role {} ({})", server.getId(), server.getName(), removed.getName(), removed.getId()); apiClient.getEventBus().post(new RoleChangeEvent(removed, server, RoleChangeEvent.RoleChange.DELETED)); } else { LOGGER.warn("[{}] '{}': No such role to delete (roleid={})", server.getId(), server.getName(), roleId); } } else { LOGGER.warn("[{}] '': Orphan role delete received, ignored (roleid={})", serverId, roleId); } } private void handleGuildRoleCreate(JSONObject data) { Role role = jsonObjectToObject((JSONObject) data.get("role"), Role.class); String serverId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(serverId); if (server != NO_SERVER) { server.getRoles().add(role); LOGGER.debug("[{}] '{}': Added new role {} ({})", server.getId(), server.getName(), role.getName(), role.getId()); apiClient.getEventBus().post(new RoleChangeEvent(role, server, RoleChangeEvent.RoleChange.CREATED)); } else { LOGGER.warn("[{}] '': Orphan role create received, ignored (roleid={} rolename={})", serverId, role.getId(), role.getName()); } } private void handlePresenceUpdate(JSONObject data, String raw) { PresenceUpdate update = jsonObjectToObject(data, PresenceUpdate.class); Server server = apiClient.getServerByID(update.getServerId()); if (server != NO_SERVER) { User updateUser = update.getUser(); User user = apiClient.getUserById(updateUser.getId(), server); String oldUsername = user.getUsername(); SafeNav.of(updateUser.getAvatar()).ifPresent(user::setAvatar); SafeNav.of(updateUser.getUsername()).ifPresent(user::setUsername); Member member = apiClient.getUserMember(user, server); if (member != NO_MEMBER && member.getUser().equals(user)) { member.getRoles().clear(); member.getRoles().addAll(update.getRoles()); LOGGER.debug("[{}] '{}': {}'s ({}) presence changed", server.getId(), server.getName(), user.getUsername(), user.getId()); apiClient.getUserGames().put(user.getId(), SafeNav.of(update.getGame()). next(Game::getName). orElse("[misc.nothing]")); apiClient.getUserPresences().put(user.getId(), update.getStatus()); apiClient.getEventBus().post(new PresenceUpdateEvent(oldUsername, update, server)); } else { // LOGGER.warn("[{}] '{}': Orphan presence update received, ignored (userid={} username={}): Not found", // server.getId(), server.getName(), // update.getUser().getId(), update.getUser().getUsername()); } } else { // LOGGER.warn("[{}] '{}': Orphan presence update received, ignored (userid={} username={})", // update.getServerId(), (server == null ? "" : server.getName()), // update.getUser().getId(), update.getUser().getUsername()); } } private void handleGuildMemberUpdate(JSONObject data) { Member member = jsonObjectToObject(data, Member.class); String serverId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(serverId); if (server != NO_SERVER) { Member oldMember = apiClient.getUserMember(member.getUser(), server); String oldNickname = null; if (oldMember != null) { oldNickname = oldMember.getNick(); if (member.getJoinedAt() == null) { member.setJoinedAt(oldMember.getJoinedAt()); } } server.getMembers().remove(member); server.getMembers().add(member); LOGGER.debug("[{}] '{}': Updated {}'s ({}) membership", server.getId(), server.getName(), member.getUser().getUsername(), member.getUser().getId()); apiClient.getEventBus().post(new MemberChangeEvent(member, server, MemberChangeEvent.MemberChange.UPDATED, oldNickname)); } else { LOGGER.warn("[{}] '': Orphan member update received, ignored (userid={} username={})", serverId, member.getUser().getId(), member.getUser().getUsername()); } } private void handleGuildMemberRemove(JSONObject data) { Member member = jsonObjectToObject(data, Member.class); String serverId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(serverId); if (server != NO_SERVER) { if (server.getMembers().remove(member)) { LOGGER.debug("[{}] '{}': Removed {}'s ({}) membership", server.getId(), server.getName(), member.getUser().getUsername(), member.getUser().getId()); apiClient.getEventBus().post(new MemberChangeEvent(member, server, MemberChangeEvent.MemberChange.DELETED)); } else { LOGGER.warn("[{}] '{}': Member {} ({}) could not be removed: Not found", server.getId(), server.getName(), member.getUser().getId(), member.getUser().getUsername()); } } else { LOGGER.warn("[{}] '': Orphan member remove received, ignored (userid={} username={})", serverId, member.getUser().getId(), member.getUser().getUsername()); } } private void handleGuildMemberAdd(JSONObject data) { Member member = jsonObjectToObject(data, Member.class); String serverId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(serverId); if (server != NO_SERVER) { // Fix missing join date time if (member.getJoinedAt() == null) { member = new Member(member.getUser(), member.getRoles(), ZonedDateTime.now().toString(), member.getNick()); } server.getMembers().add(member); LOGGER.debug("[{}] '{}': Added {}'s ({}) membership", server.getId(), server.getName(), member.getUser().getUsername(), member.getUser().getId()); apiClient.getEventBus().post(new MemberChangeEvent(member, server, MemberChangeEvent.MemberChange.ADDED)); } else { LOGGER.warn("[{}] '': Orphan member add received, ignored (userid={} username={})", serverId, member.getUser().getId(), member.getUser().getUsername()); } } private void handleChannelUpdate(JSONObject data) { Channel channel = jsonObjectToObject(data, Channel.class); if (channel.isPrivate()) { // TODO LOGGER.debug("[0] '': Updated private channel with {}", channel.getRecipient().getUsername()); return; } String parentServerId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(parentServerId); if (server != NO_SERVER) { channel.setParent(server); server.getChannels().add(channel); LOGGER.debug("[{}] '{}': Channel {} ({}) updated", server.getId(), server.getName(), channel.getName(), channel.getId()); apiClient.getEventBus().post(new ChannelChangeEvent(channel, ChannelChangeEvent.ChannelChange.UPDATED)); } else { LOGGER.warn("[{}] '': Orphan update channel received, ignored (id={}, name={})", parentServerId, channel.getId(), channel.getName()); } } private void handleChannelDelete(JSONObject data) { Channel channel = jsonObjectToObject(data, Channel.class); if (channel.isPrivate()) { apiClient.getPrivateChannels().remove(channel.getId()); apiClient.getPrivateChannelsByUserMap().remove(channel.getRecipient()); LOGGER.debug("[0] '': Deleted private channel with {}", channel.getRecipient().getUsername()); return; } String parentServerId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(parentServerId); if (server != NO_SERVER) { channel.setParent(server); if (server.getChannels().remove(channel)) { LOGGER.debug("[{}] '{}': Channel {} ({}) deleted", server.getId(), server.getName(), channel.getName(), channel.getId()); apiClient.getEventBus().post(new ChannelChangeEvent(channel, ChannelChangeEvent.ChannelChange.DELETED)); } else { LOGGER.warn("[{}] '{}': Channel {} ({}) could not be deleted (not found)", server.getId(), server.getName(), channel.getName(), channel.getId()); } } else { LOGGER.warn("[{}] '': Orphan delete channel received, ignored (id={}, name={})", parentServerId, channel.getId(), channel.getName()); } } private void handleChannelCreate(JSONObject data) { Channel channel = jsonObjectToObject(data, Channel.class); if (channel.isPrivate()) { LOGGER.debug("[0] '': New private channel with {}", channel.getRecipient().getUsername()); apiClient.getPrivateChannels().put(channel.getId(), channel); apiClient.getPrivateChannelsByUserMap().put(channel.getRecipient(), channel); return; } String parentServerId = (String) data.get("guild_id"); Server server = apiClient.getServerByID(parentServerId); if (server != NO_SERVER) { channel.setParent(server); server.getChannels().add(channel); LOGGER.debug("[{}] '{}': New channel {} ({})", server.getId(), server.getName(), channel.getName(), channel.getId()); apiClient.getEventBus().post(new ChannelChangeEvent(channel, ChannelChangeEvent.ChannelChange.ADDED)); } else { LOGGER.warn("[{}] '': Orphan create channel received, ignored (id={}, name={})", parentServerId, channel.getId(), channel.getName()); } } private void handleReadyMessage(JSONObject data) { ReadyMessage readyMessage = jsonObjectToObject(data, ReadyMessage.class); startKeepAlive(readyMessage.getHeartbeatInterval()); LOGGER.info("[0] '': Sending keepAlive every {} ms", readyMessage.getHeartbeatInterval()); LogInEvent event = new LogInEvent(readyMessage); apiClient.onLogInEvent(event); apiClient.getEventBus().post(event); } private void handleGuildCreate(JSONObject data) { ReadyServer server = jsonObjectToObject(data, ReadyServer .class); server.getChannels().forEach(channel -> channel.setParent(server)); // Update presences if (server.getPresences() != null) { Arrays.stream(server.getPresences()).forEach(p -> { String id = p.getUser().getId(); apiClient.getUserPresences().put(id, p.getStatus()); apiClient.getUserGames().put(id, SafeNav.of(p.getGame()).next(Game::getName).orElse("[misc.nothing]")); }); } else { LOGGER.warn("No presences received on new server"); } // need to delete the null named versions for (Iterator<Server> iterator = apiClient.getServers().iterator(); iterator.hasNext();) { if (iterator.next().getId().equals(server.getId())) { iterator.remove(); } } apiClient.getServers().add(server); apiClient.getServerMap().put(server.getId(), server); apiClient.requestLargerServerUsers(server); LOGGER.info("[{}] '{}': Joined server", server.getId(), server.getName()); apiClient.getEventBus().post(new ServerJoinLeaveEvent(server, true)); } private void handleGuildDelete(JSONObject data) { Server server = jsonObjectToObject(data, Server.class); apiClient.getServers().remove(server); Server removed = apiClient.getServerMap().remove(server.getId()); LOGGER.info("[{}] '{}': Left server", removed.getId(), removed.getName()); apiClient.getEventBus().post(new ServerJoinLeaveEvent(server, false)); } @SuppressWarnings("unchecked") private void startKeepAlive(long keepAliveInterval) { if (keepAliveFuture != null) { keepAliveFuture.cancel(true); } keepAliveFuture = apiClient.getExecutorService().scheduleAtFixedRate(() -> { JSONObject keepAlive = new JSONObject(); keepAlive.put("op", 1); keepAlive.put("d", System.currentTimeMillis()); LOGGER.debug("[0] '': Sending keepAlive"); send(keepAlive.toJSONString()); statistics.keepAliveCount.increment(); }, 0, keepAliveInterval, MILLISECONDS); } private void handleMessageCreate(JSONObject data) { Message message = jsonObjectToObject(data, Message.class); Channel channel = apiClient.getChannelById(message.getChannelId()); if (channel == null || channel == NO_CHANNEL || channel.isPrivate()) { LOGGER.debug("[0] '': Recieved direct message from {}: {}", message.getAuthor().getUsername(), message.getContent()); message.setPrivateMessage(true); } else { LOGGER.debug("[{}] '{}': Recieved message from {} in channel.getParent().getId(), channel.getParent().getName(), message.getAuthor().getUsername(), channel.getName(), message.getContent()); message.setPrivateMessage(false); } apiClient.getEventBus().post(new MessageReceivedEvent(message)); } @Override public void onClose(int code, String reason, boolean remote) { LOGGER.info("[0] '': Closing WebSocket {}: '{}' {}", code, reason, remote ? "remote" : "local"); if (keepAliveFuture != null) { keepAliveFuture.cancel(true); } statistics.deathCount.increment(); apiClient.getEventBus().post(new WebSocketCloseEvent(code, reason, remote)); } @Override public void onError(Exception ex) { LOGGER.warn("[0] '': WebSocket error", ex); statistics.errorCount.increment(); } void sendNowPlayingUpdate(String message) { org.json.JSONObject data = new org.json.JSONObject(); if (message == null) { data.put("game", org.json.JSONObject.NULL); } else { org.json.JSONObject game = new org.json.JSONObject(); game.put("name", message); data.put("game", game); } data.put("idle_since", org.json.JSONObject.NULL); org.json.JSONObject outer = new org.json.JSONObject(); outer.put("op", 3); outer.put("d", data); String out = outer.toString(); send(out); } private <T> T jsonObjectToObject(JSONObject object, Class<T> clazz) { // Because this doesnt come too often and to simplify matters // we'll serialize the object to string and have Gson parse out the object // Eventually come up with a solution that allows for direct creation String j = object.toJSONString(); return gson.fromJson(j, clazz); } public Statistics getStatistics() { return statistics; } public static class Statistics { public final RunningAverage avgMessageHandleTime = new RunningAverage(); public final LongAdder messageReceiveCount = new LongAdder(); public final LongAdder keepAliveCount = new LongAdder(); public final LongAdder errorCount = new LongAdder(); public final LongAdder deathCount = new LongAdder(); } }
package com.amaranth.structlog.config; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.lang.StringUtils; public class StructLogAppConfig { private static XMLConfiguration appConfig; /** * XML formatted fileName is parsed to initialize XMLCOnfiguration object * appConfig. If for any reason parsing fails, then appConfig will be null * and that will be interpreted as StuctLogAppConfig is disabled. To Enable * the StructLogAppConfig, call setAppConfig with correct file name. * * @param fileName */ public static void setAppConfig(String fileName) { try { if (!StringUtils.isEmpty(fileName)) { appConfig = new XMLConfiguration(fileName); } else { appConfig = null; } } catch (ConfigurationException e) { appConfig = null; // TODO Auto-generated catch block e.printStackTrace(); } } public static String getMongoDBUrl() { return getAppConfig().getString("databases.mongodb.url"); } public static String getMongoDBName() { return getAppConfig().getString("databases.mongodb.name"); } public static String getDatabaseToUse() { return getAppConfig().getString("databaseToUse"); } public static boolean isStructLogConfigInitialized() { if (null == appConfig) { return false; } return true; } public static XMLConfiguration getAppConfig() { return appConfig; } public static void setAppConfig(XMLConfiguration appConfig) { StructLogAppConfig.appConfig = appConfig; } }
package com.blamejared.mcbot.commands.api; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.blamejared.mcbot.MCBot; import com.blamejared.mcbot.util.NonNull; import com.blamejared.mcbot.util.Nullable; import lombok.Getter; import lombok.experimental.Wither; import sx.blah.discord.api.internal.json.objects.EmbedObject; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.util.RequestBuffer; import sx.blah.discord.util.RequestBuffer.IRequest; import sx.blah.discord.util.RequestBuffer.RequestFuture; @Getter public class CommandContext { private final IMessage message; @Wither(onMethod = @__({ @NonNull })) private final Map<Flag, String> flags; @Wither(onMethod = @__({ @NonNull })) private final Map<Argument<?>, String> args; public CommandContext(IMessage message) { this(message, new HashMap<>(), new HashMap<>()); } public CommandContext(IMessage message, Map<Flag, String> flags, Map<Argument<?>, String> args) { this.message = message; this.flags = Collections.unmodifiableMap(flags); this.args = Collections.unmodifiableMap(args); } public IGuild getGuild() { return getMessage().getGuild(); } public IChannel getChannel() { return getMessage().getChannel(); } public IUser getAuthor() { return getMessage().getAuthor(); } public boolean hasFlag(Flag flag) { return getFlags().containsKey(flag); } public @Nullable String getFlag(Flag flag) { return getFlags().get(flag); } public int argCount() { return getArgs().size(); } public <T> T getArg(Argument<T> arg) { return arg.parse(getArgs().get(arg)); } public <T> T getArgOrElse(Argument<T> arg, T def) { return getArgOrGet(arg, (Supplier<T>) () -> def); } public <T> T getArgOrGet(Argument<T> arg, Supplier<T> def) { return Optional.ofNullable(getArgs().get(arg)).map(s -> arg.parse(s)).orElseGet(def); } public RequestFuture<IMessage> replyBuffered(String message) { return RequestBuffer.request((IRequest<IMessage>) () -> reply(message)); } public RequestFuture<IMessage> replyBuffered(EmbedObject message) { return RequestBuffer.request((IRequest<IMessage>) () -> reply(message)); } public IMessage reply(String message) { return getMessage().getChannel().sendMessage(sanitize(message)); } public IMessage reply(EmbedObject message) { return getMessage().getChannel().sendMessage(message); } private static final Pattern REGEX_MENTION = Pattern.compile("<@&?!?([0-9]+)>"); private static final String REGEX_BLACKLIST_CHARS = "[\u202e\u0000]"; public String sanitize(String message) { return sanitize(getGuild(), message); } public static String sanitize(IChannel channel, String message) { return channel.isPrivate() ? message : sanitize(channel.getGuild(), message); } public static String sanitize(@Nullable IGuild guild, String message) { if (message == null) return null; if (guild == null) return message; Matcher matcher = REGEX_MENTION.matcher(message); while (matcher.find()) { long id = Long.parseLong(matcher.group(1)); String name; if (matcher.group().contains("&")) { name = "the " + MCBot.instance.getRoleByID(id).getName(); } else { IUser user = guild.getUserByID(id); if (matcher.group().contains("!")) { name = user.getDisplayName(guild).replaceAll("@", "@\u200B"); } else { name = user.getName(); } } message = message.replace(matcher.group(), name); } return message.replace("@here", "everyone").replace("@everyone", "everyone").replace("@", "@\u200B"); } public EmbedObject sanitize(EmbedObject embed) { return sanitize(getGuild(), embed); } public static EmbedObject sanitize(IChannel channel, EmbedObject embed) { return channel.isPrivate() ? embed : sanitize(channel.getGuild(), embed); } public static EmbedObject sanitize(IGuild guild, EmbedObject embed) { if (embed == null) return null; embed.title = sanitize(guild, embed.title); embed.description = sanitize(guild, embed.description); return embed; } }
package com.cloudmine.api.rest.response; import com.cloudmine.api.CMObject; import com.cloudmine.api.exceptions.ConversionException; import com.cloudmine.api.exceptions.JsonConversionException; import com.cloudmine.api.rest.JsonUtilities; import com.cloudmine.api.rest.response.code.ObjectLoadCode; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class CMObjectResponse extends SuccessErrorResponse<ObjectLoadCode> { private static final Logger LOG = LoggerFactory.getLogger(CMObjectResponse.class); public static final ResponseConstructor<CMObjectResponse> CONSTRUCTOR = new ResponseConstructor<CMObjectResponse>() { @Override public CMObjectResponse construct(HttpResponse response) { return new CMObjectResponse(response); } }; public static final String COUNT_KEY = "count"; public static final int NO_COUNT = -1; private final Map<String, ? extends CMObject> objectMap; /** * Instantiate a new CMObjectResponse. You probably should not be calling this yourself. * @param response a response to an object fetch request */ public CMObjectResponse(HttpResponse response) { super(response); if(hasSuccess()) { String success = JsonUtilities.jsonMapToKeyMap(getMessageBody()).get(SUCCESS); Map<String, ? extends CMObject> tempMap; try { tempMap = JsonUtilities.jsonToClassMap(success); }catch(ConversionException jce) { tempMap = Collections.emptyMap(); LOG.error("Trouble converting: " + success + ", using empty map"); } objectMap = tempMap; } else { objectMap = Collections.emptyMap(); } } protected CMObjectResponse(String response, int code) { super(response, code); //TODO this is copy pasta code from above :( thats bad if(hasSuccess()) { String success = JsonUtilities.jsonMapToKeyMap(getMessageBody()).get(SUCCESS); Map<String, ? extends CMObject> tempMap; try { tempMap = JsonUtilities.jsonToClassMap(success); }catch(JsonConversionException jce) { tempMap = Collections.emptyMap(); LOG.error("Trouble converting: " + success + ", using empty map"); } objectMap = tempMap; } else { objectMap = Collections.emptyMap(); } } @Override public ObjectLoadCode getResponseCode() { return ObjectLoadCode.codeForStatus(getStatusCode()); } /** * Returns a List of all the CMObjects fetched by the request * @return a List of all the CMObjects fetched by the request */ public List<CMObject> getObjects() { return new ArrayList<CMObject>(objectMap.values()); } /** * Returns the object with the given objectId, or null if it doesn't exist * @param objectId the objectId for the object * @return the object, or null if it was not retrieved */ public CMObject getCMObject(String objectId) { return objectMap.get(objectId); } /** * If this load was made with count=true (specified by using {@link com.cloudmine.api.rest.options.CMPagingOptions}) * then this will return the number of entries for the query that was made, regardless of how many results * were returned. * @return the number of entries for the query that was made, or {@link #NO_COUNT} if count=true wasn't requested, or if unable to parse the count property as an Integer */ public int getCount() { Object countObject = getObject(COUNT_KEY); if(countObject != null && countObject instanceof Integer) { return ((Integer)countObject).intValue(); } return NO_COUNT; } }
package com.codeborne.selenide.impl; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.commands.Commands; import com.codeborne.selenide.ex.InvalidStateException; import com.codeborne.selenide.ex.UIAssertionError; import com.codeborne.selenide.logevents.SelenideLog; import com.codeborne.selenide.logevents.SelenideLogger; import org.openqa.selenium.InvalidElementStateException; import org.openqa.selenium.WebDriverException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import static com.codeborne.selenide.Condition.exist; import static com.codeborne.selenide.Configuration.AssertionMode.SOFT; import static com.codeborne.selenide.Configuration.*; import static com.codeborne.selenide.Selenide.sleep; import static com.codeborne.selenide.logevents.LogEvent.EventStatus.PASS; import static java.lang.System.currentTimeMillis; import static java.util.Arrays.asList; class SelenideElementProxy implements InvocationHandler { private static final Set<String> methodsToSkipLogging = new HashSet<>(asList( "toWebElement", "toString" )); private static final Set<String> methodsForSoftAssertion = new HashSet<>(asList( "should", "shouldBe", "shouldHave", "shouldNot", "shouldNotHave", "shouldNotBe", "waitUntil", "waitWhile" )); private final WebElementSource webElementSource; protected SelenideElementProxy(WebElementSource webElementSource) { this.webElementSource = webElementSource; } @Override public Object invoke(Object proxy, Method method, Object... args) throws Throwable { if (methodsToSkipLogging.contains(method.getName())) return Commands.collection.execute(proxy, webElementSource, method.getName(), args); long timeoutMs = getTimeoutMs(method, args); SelenideLog log = SelenideLogger.beginStep(webElementSource.getSearchCriteria(), method.getName(), args); try { Object result = dispatchAndRetry(timeoutMs, proxy, method, args); SelenideLogger.commitStep(log, PASS); return result; } catch (Error error) { SelenideLogger.commitStep(log, error); if (assertionMode == SOFT && methodsForSoftAssertion.contains(method.getName())) return proxy; else throw UIAssertionError.wrap(error, timeoutMs); } catch (RuntimeException error) { SelenideLogger.commitStep(log, error); throw error; } } protected Object dispatchAndRetry(long timeoutMs, Object proxy, Method method, Object[] args) throws Throwable { final long startTime = currentTimeMillis(); Throwable lastError; do { try { if (SelenideElement.class.isAssignableFrom(method.getDeclaringClass())) { return Commands.collection.execute(proxy, webElementSource, method.getName(), args); } return method.invoke(webElementSource.getWebElement(), args); } catch (Throwable e) { if (Cleanup.of.isInvalidSelectorError(e)) { throw Cleanup.of.wrap(e); } lastError = e; sleep(pollingInterval); } } while (currentTimeMillis() - startTime <= timeoutMs); if (lastError instanceof InvocationTargetException) { Throwable cause = lastError.getCause(); if (cause != null) { lastError = cause; } } if (lastError instanceof UIAssertionError) { throw lastError; } else if (lastError instanceof InvalidElementStateException) { throw new InvalidStateException(lastError); } else if (lastError instanceof WebDriverException) { throw webElementSource.createElementNotFoundError(exist, lastError); } throw lastError; } private long getTimeoutMs(Method method, Object[] args) { return "waitUntil".equals(method.getName()) || "waitWhile".equals(method.getName()) ? (Long) args[args.length - 1] : timeout; } }
package com.datalogics.pdf.samples.util; import com.adobe.internal.io.ByteWriter; import com.adobe.internal.io.RandomAccessFileByteWriter; import com.adobe.pdfjt.core.exceptions.PDFIOException; import com.adobe.pdfjt.core.exceptions.PDFInvalidDocumentException; import com.adobe.pdfjt.core.exceptions.PDFInvalidParameterException; import com.adobe.pdfjt.core.exceptions.PDFSecurityException; import com.adobe.pdfjt.core.exceptions.PDFUnableToCompleteOperationException; import com.adobe.pdfjt.core.types.ASName; import com.adobe.pdfjt.pdf.document.PDFDocument; import com.adobe.pdfjt.pdf.document.PDFSaveFullOptions; import com.adobe.pdfjt.pdf.document.PDFSaveOptions; import com.adobe.pdfjt.pdf.filters.PDFFilterFlate; import com.adobe.pdfjt.pdf.filters.PDFFilterList; import com.adobe.pdfjt.pdf.graphics.colorspaces.PDFColorSpaceICCBased; import com.adobe.pdfjt.pdf.graphics.colorspaces.PDFICCProfile; import com.adobe.pdfjt.pdf.graphics.colorspaces.PDFRenderingIntent; import com.adobe.pdfjt.pdf.interchange.prepress.PDFOutputIntent; import com.adobe.pdfjt.services.pdfa.PDFAConformanceLevel; import com.adobe.pdfjt.services.pdfa.PDFAConversionOptions; import com.adobe.pdfjt.services.pdfa.PDFADefaultConversionHandler; import com.adobe.pdfjt.services.pdfa.PDFAErrorSetFileStructure; import com.adobe.pdfjt.services.pdfa.PDFAOCConversionMode; import com.adobe.pdfjt.services.pdfa.PDFAService; import com.adobe.pdfjt.services.pdfa.error.PDFAFileStructureErrorCode; import java.awt.color.ICC_Profile; import java.io.IOException; import java.io.RandomAccessFile; import java.util.EnumSet; import java.util.logging.Logger; /** * This utility class opens a document and uses the PDFAService to convert it to a PDF/A-1b document. * PDFAConversionHandler derives from a default implementation (i.e., PDFADefaultConversionHandler). The non-public * class MyPDFAConversionHandler, only overrides those methods that it needs. * */ public final class ConvertPdfA1Util { private static final Logger LOGGER = Logger.getLogger(ConvertPdfA1Util.class.getName()); // constants for setting color space profiles private static final String RGB_PROFILE = "sRGB Color Space Profile.icm"; private static final String CMYK_PROFILE = "USWebCoatedSWOP.icc"; private static final String GRAY_PROFILE = "AdobeGray20.icm"; private static ICC_Profile iccRGBProfile; private static ICC_Profile iccCMYKProfile; private static ICC_Profile iccGrayProfile; /** * This is a utility class, and won't be instantiated. */ private ConvertPdfA1Util() {} /** * In this method we take an input PDF Document and attempt to convert it into PDF/A-1b format using PDFAService. * * @param pdfDoc - PDF Document to be converted * @param outputFilePath - name and path to the output file * @throws IOException an I/O operation failed or was interrupted * @throws PDFSecurityException some general security issue occurred during the processing of the request * @throws PDFIOException there was an error reading or writing a PDF file or temporary caches * @throws PDFInvalidDocumentException a general problem with the PDF document, which may now be in an invalid state * @throws PDFUnableToCompleteOperationException the operation was unable to be completed * @throws PDFInvalidParameterException one or more of the parameters passed to a method is invalid */ public static void convertPdfA1(final PDFDocument pdfDoc, final String outputFilePath) throws IOException, PDFInvalidDocumentException, PDFIOException, PDFSecurityException, PDFInvalidParameterException, PDFUnableToCompleteOperationException { ByteWriter writer = null; try { // Load up icc profiles for the default colorspaces. iccRGBProfile = ICC_Profile.getInstance(ConvertPdfA1Util.class.getResourceAsStream(RGB_PROFILE)); iccCMYKProfile = ICC_Profile.getInstance(ConvertPdfA1Util.class.getResourceAsStream(CMYK_PROFILE)); iccGrayProfile = ICC_Profile.getInstance(ConvertPdfA1Util.class.getResourceAsStream(GRAY_PROFILE)); // Setup the conversion options and handler. final PDFAConversionOptions options = createConversionOptions(pdfDoc); final MyPdfAConversionHandler handler = new MyPdfAConversionHandler(); handler.setDefaultColorSpaceProfiles(iccRGBProfile, iccCMYKProfile, iccGrayProfile); // attempt to convert the PDF to PDF/A-1b if (PDFAService.convert(pdfDoc, PDFAConformanceLevel.Level_1b, options, handler)) { final PDFSaveOptions saveOpt = PDFSaveFullOptions.newInstance(); // if the pdf contains compressed object streams, we should // decompress these so that the pdf can be converted to PDF/A-1b if (handler.requiresObjectDecompression()) { saveOpt.setObjectCompressionMode(PDFSaveOptions.OBJECT_COMPRESSION_NONE); } final RandomAccessFile outputPdf = new RandomAccessFile(outputFilePath, "rw"); writer = new RandomAccessFileByteWriter(outputPdf); pdfDoc.save(writer, saveOpt); final String successMsg = "\nConverted output written to: " + outputFilePath; LOGGER.info(successMsg); } else { LOGGER.info("Errors encountered when converting document."); } } finally { if (writer != null) { writer.close(); } if (pdfDoc != null) { pdfDoc.close(); } } } /** * This method sets the options for the pdf document that is to be converted. Such options include removing certain * annotations and javascript from the pdf. * * @param doc - PDF document to be converted * @return PDFAConversionOptions * @throws IOException an I/O operation failed or was interrupted * @throws PDFSecurityException some general security issue occurred during the processing of the request * @throws PDFIOException there was an error reading or writing a PDF file or temporary caches * @throws PDFInvalidDocumentException a general problem with the PDF document, which may now be in an invalid state */ private static PDFAConversionOptions createConversionOptions(final PDFDocument doc) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException, IOException { final PDFAConversionOptions options = new PDFAConversionOptions(); setPdfAOutputIntent(doc, options); setDefaultColorSpaces(doc, options); options.setUpdatePDFAMetadataOnPartialConversion(false); options.setOCConversionMode(PDFAOCConversionMode.ConvertOCUsingDefaultConfigIncludingUsageApp, ASName.k_View); options.setRemoveIllegalAnnotations(true); options.setRemoveInvisibleNonStandardAnnots(true); options.setRemoveHiddenAnnots(true); options.setRemoveNoViewAnnots(true); options.setOverrideAnnotationFlags(true); options.setRemoveNonNormalAnnotAppearances(true); options.setRemoveIllegalActions(true); options.setRemoveIllegalAdditionalActions(true); options.setRemoveJavaScriptNameTree(true); options.setOverrideRenderingIntent(PDFRenderingIntent.RELATIVE_COLORIMETRIC); options.setRemoveFormXObjectPSData(true); options.setRemoveIllegalInterpolation(true); options.setRemoveImageAlternates(true); options.setRemoveTransferFunctions(true); options.setRemoveXFA(true); options.setRemoveXObjectOPI(true); options.setRemoveEmbeddedFilesNameTree(true); options.setShouldEmbedFonts(true); options.setRemoveInvalidXMPProperties(true); final PDFFilterList list = PDFFilterList.newInstance(doc); list.add(PDFFilterFlate.newInstance(doc, null)); options.setLZWReplacementFilterList(list); return options; } private static void setPdfAOutputIntent(final PDFDocument doc, final PDFAConversionOptions options) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException, IOException { final PDFOutputIntent outputIntent = PDFOutputIntent.newInstance(doc, "GTS_PDFA1", "CGATS TR 001"); outputIntent.setOutputCondition("U.S. Web Coated(SWOP)v2"); outputIntent.setRegistryName("http: final ICC_Profile profile = ICC_Profile.getInstance(ConvertPdfA1Util.class.getResourceAsStream(RGB_PROFILE)); final PDFICCProfile destProfile = PDFICCProfile.newInstance(doc, profile); outputIntent.setDestOutputProfile(destProfile); outputIntent.setOutputConditionIdentifier("CGATS TR 001"); options.setPDFAOutputIntent(outputIntent, false); } /** * Sets the default color spaces for graphics objects that relate to RGB, CMYK, or Grayscale color models. * * @param doc - PDF document to be converted into PDF/A-1b format * @param options - PDFA conversion options * @throws PDFInvalidDocumentException a general problem with the PDF document, which may now be in an invalid state * @throws PDFIOException there was an error reading or writing a PDF file or temporary caches * @throws PDFSecurityException some general security issue occurred during the processing of the request */ private static void setDefaultColorSpaces(final PDFDocument doc, final PDFAConversionOptions options) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException { final PDFColorSpaceICCBased defaultRgbProfile = PDFColorSpaceICCBased.newInstance(doc, iccRGBProfile); final PDFColorSpaceICCBased defaultCmykProfile = PDFColorSpaceICCBased.newInstance(doc, iccCMYKProfile); final PDFColorSpaceICCBased defaultGrayProfile = PDFColorSpaceICCBased.newInstance(doc, iccGrayProfile); options.setDefaultColorSpaces(defaultRgbProfile, defaultCmykProfile, defaultGrayProfile); } /** * Static inner class MyPDFAConversionHandler overrides the methods from PDFAConversionHandler that it needs. * */ private static class MyPdfAConversionHandler extends PDFADefaultConversionHandler { private static final Logger LOGGER = Logger.getLogger(MyPdfAConversionHandler.class.getName()); private boolean decompressObjectStreams; private ICC_Profile iccRgbProfile; private ICC_Profile iccCmykProfile; private ICC_Profile iccGrayProfile; /** * Sets ICC Color Space Profiles. * * @param rgbProfile - ICC_Profile * @param cmykProfile - ICC_Profile * @param grayProfile - ICC_Profile */ public void setDefaultColorSpaceProfiles(final ICC_Profile rgbProfile, final ICC_Profile cmykProfile, final ICC_Profile grayProfile) { iccRgbProfile = rgbProfile; iccCmykProfile = cmykProfile; iccGrayProfile = grayProfile; } /** * If a PDF contains compressed object streams, they need to be decompressed, as PDF/A-1 doesn't convert PDFs * with these compressed streams. This method returns true if compressed object streams exist in the PDF. * * @return true (need to decompress) or false */ public boolean requiresObjectDecompression() { return this.decompressObjectStreams; } /** * After running the file structure validation and conversion this is the mechanism where we report the errors * we found and fixed. * * @param errorsFound - errors found during file structure validation * @param errorsFixed - errors that will be fixed with a save or were fixed during conversion. * @return true */ @Override public boolean fileStructureErrorsFixed(final PDFAErrorSetFileStructure errorsFound, final PDFAErrorSetFileStructure errorsFixed) { @SuppressWarnings("unchecked") final EnumSet<PDFAFileStructureErrorCode> errorCodes = errorsFound.getErrorCodes(); if (errorCodes.contains(PDFAFileStructureErrorCode.nonCompressedXRefNotPresent)) { // this problem is resolved in a post-processing step. this.decompressObjectStreams = true; errorsFound.unSetErrorFlag(PDFAFileStructureErrorCode.nonCompressedXRefNotPresent); } return true; } /** * Method to get a new valid PDFICCProfile from a given PDFICCProfile based on the number of components. * * @param pdficcProfile - the PDFICCProfile that will be replicated * @return PDFICCProfile */ @Override public PDFICCProfile getValidICCProfile(final PDFICCProfile pdficcProfile) { PDFICCProfile fixedProfile = null; try { if (pdficcProfile.getNumberOfComponents() == 1) { fixedProfile = PDFICCProfile.newInstance(pdficcProfile.getPDFDocument(), iccGrayProfile); } if (pdficcProfile.getNumberOfComponents() == 2) { fixedProfile = PDFICCProfile.newInstance(pdficcProfile.getPDFDocument(), iccRgbProfile); } if (pdficcProfile.getNumberOfComponents() == 4) { fixedProfile = PDFICCProfile.newInstance(pdficcProfile.getPDFDocument(), iccCmykProfile); } } catch (PDFIOException | PDFSecurityException | PDFInvalidDocumentException e) { LOGGER.severe(e.getMessage()); } if (fixedProfile == null) { return null; } else { return fixedProfile; } } } }
package com.datastax.driver.mapping; import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker; import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ColumnDefinitions.Definition; import com.datastax.driver.core.DataType; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import com.datastax.driver.core.querybuilder.Insert; import com.datastax.driver.core.schemabuilder.Create; import com.datastax.driver.core.schemabuilder.SchemaBuilder; import com.datastax.driver.mapping.annotations.Column; import io.smartcat.cassandra_audit.AuditExclusion; /** * This is an implementation of {@link AuditLogger} that stores audit * events in Cassandra tables. */ public class CassandraAuditLogger implements AuditLogger { private static CassandraAuditLogger INSTANCE; private final Session session; private volatile Map<String, PreparedStatement> preparedQueries = new HashMap<String, PreparedStatement>(); private volatile Map<String, List<String>> primaryKeyColumns = new HashMap<String, List<String>>(); private volatile Map<String, List<String>> excludedColumns = new HashMap<String, List<String>>(); public static class AuditRow { static String COL_TIMESTAMP = "time"; static String COL_EXEC_TIME = "exec"; static String COL_ERROR = "err"; static String COL_MUTATION_TYPE = "type"; static String COL_CQL_STRING = "cql"; static String COL_STATEMENT_VALUES = "values"; static String INSERT_MUTATION = "INSERT"; static String UPDATE_MUTATION = "UPDATE"; static String DELETE_MUTATION = "DELETE"; static String UKNOWN_MUTATION = "UNKNOWN"; } /** * Returns the singleton instance. * * @param session Cassandra session used to save audit events * @return {@link CassandraAuditLogger} singleton instance */ public static CassandraAuditLogger getInstance(Session session) { if (INSTANCE == null) { INSTANCE = new CassandraAuditLogger(session); } return INSTANCE; } /** * Constructs {@link CassandraAuditLogger} instance using the given * session for storing audit events. * * @param session Cassandra session */ public CassandraAuditLogger(Session session) { this.session = session; } public <T> void init(AuditMapper<T> mapper) { // audited entity is identified by its keyspace and table name String entityName = trim(mapper.mapper.getKeyspace()) + "." + trim(mapper.mapper.getTable()); // if the logger is already initialized for this event, // silently ignore if (preparedQueries.containsKey(entityName)) { return; } // create audit table and wait till schema change is propagated String keyspace = mapper.auditOptions.keyspaceName; String table = mapper.auditOptions.tableName; session.execute(createAuditTable(keyspace, table, mapper.mapper)) .getExecutionInfo().isSchemaInAgreement(); // save the entity's primary key column names synchronized (primaryKeyColumns) { primaryKeyColumns.put(entityName, getKeyColumns(mapper.mapper)); } // prepare statement for inserting audit events PreparedStatement stmt = session.prepare( makePreparedStatement(keyspace, table, mapper.mapper)); synchronized (preparedQueries) { preparedQueries.put(entityName, stmt); } synchronized (excludedColumns) { excludedColumns.put(entityName, getExcludedColumns(mapper.mapper)); } } /* (non-Javadoc) * @see io.smartcat.cassandra_audit.AuditLogger#log(com.datastax.driver.core.Statement, com.datastax.driver.mapping.Mapper) */ @Override public void log(long execTime, String error, BoundStatement origStatement) { PreparedStatement origPreparedStatement = origStatement.preparedStatement(); String entityName = trim(origPreparedStatement.getVariables().getKeyspace(0)) + "." + trim(origPreparedStatement.getVariables().getTable(0)); PreparedStatement ps = preparedQueries.get(entityName); if (ps == null) { throw new IllegalStateException("AuditLogger has not been initilized for " + entityName); } BoundStatement bs = ps.bind(); List<String> pkc = primaryKeyColumns.get(entityName); List<String> exc = excludedColumns.get(entityName); StringBuffer values = new StringBuffer(); ColumnDefinitions columns = origPreparedStatement.getVariables(); for (Definition def : columns) { String colName = def.getName(); // if column is part of the entity's primary key // inject it into the audit statement if (pkc.contains(colName)) { // audit key is constructed from the entity's schema so type // checking is not necessary bs.setBytesUnsafe(colName, origStatement.getBytesUnsafe(colName)); } // collect the original statemenet's values for this column // unless it is excluded if (!exc.contains(colName)) { values.append(colName); values.append(":"); values.append(origStatement.getObject(colName)); values.append("; "); } } String cqlString = origPreparedStatement.getQueryString(); bs.setDate(AuditRow.COL_TIMESTAMP, new Date()); bs.setString(AuditRow.COL_MUTATION_TYPE, getMutationType(cqlString)); bs.setLong(AuditRow.COL_EXEC_TIME, execTime); bs.setString(AuditRow.COL_ERROR, error); bs.setString(AuditRow.COL_CQL_STRING, cqlString); bs.setString(AuditRow.COL_STATEMENT_VALUES, values.toString()); session.executeAsync(bs); } /** * Returns mutation type based on the given CQL string. * * @param cql a CQL statement string * @return mutation type */ private static String getMutationType(String cql) { switch(cql.substring(0, 3).toUpperCase()) { case "INS": return AuditRow.INSERT_MUTATION; case "UPD": return AuditRow.UPDATE_MUTATION; case "DEL": return AuditRow.DELETE_MUTATION; default: return AuditRow.UKNOWN_MUTATION; } } /** * Removes embracing double quotes chars from the given * input string. * * @param str an string to be trimmed * @return the trimmed value */ private static String trim(String str) { return str != null ? str.replaceAll("\"", "") : str; } /** * Creates CQL statement string for inserting an audit row. * * @param keyspaceName audit keyspace name * @param tableName audit table name * @param mapper entity's mapper * @return CQL INSERT statement string */ private <T> String makePreparedStatement(String keyspaceName, String tableName, EntityMapper<T> mapper) { Insert insert = insertInto(keyspaceName, tableName); for (ColumnMapper<T> cm : mapper.partitionKeys) { insert.value(cm.getColumnName(), bindMarker()); } for (ColumnMapper<T> cm : mapper.clusteringColumns) { insert.value(cm.getColumnName(), bindMarker()); } insert.value(AuditRow.COL_TIMESTAMP, bindMarker()); insert.value(AuditRow.COL_MUTATION_TYPE, bindMarker()); insert.value(AuditRow.COL_EXEC_TIME, bindMarker()); insert.value(AuditRow.COL_ERROR, bindMarker()); insert.value(AuditRow.COL_CQL_STRING, bindMarker()); insert.value(AuditRow.COL_STATEMENT_VALUES, bindMarker()); return insert.toString(); } /** * Creates a CQL table create statement for the designated entity auditing. * * @param keyspaceName audit table keyspace * @param tableName audit table name * @param mapper entity's mapper * @return table create statement */ private <T> Statement createAuditTable(String keyspaceName, String tableName, EntityMapper<T> mapper) { Create create = SchemaBuilder.createTable(keyspaceName, tableName).ifNotExists(); for (ColumnMapper<T> cm : mapper.partitionKeys) { create.addPartitionKey(cm.getColumnName(), cm.getDataType()); } for (ColumnMapper<T> cm : mapper.clusteringColumns) { create.addPartitionKey(cm.getColumnName(), cm.getDataType()); } create .addClusteringColumn(AuditRow.COL_TIMESTAMP, DataType.timestamp()) .addColumn(AuditRow.COL_MUTATION_TYPE, DataType.text()) .addColumn(AuditRow.COL_EXEC_TIME, DataType.bigint()) .addColumn(AuditRow.COL_ERROR, DataType.text()) .addColumn(AuditRow.COL_CQL_STRING, DataType.text()) .addColumn(AuditRow.COL_STATEMENT_VALUES, DataType.text()); return create; } /** * Returns a combined list partition and clustering columns, that is, * a list of primary key columns. * * @param mapper the entity's mapper * @return a list of primary key columns */ private <T> List<String> getKeyColumns(EntityMapper<T> mapper) { List<String> columns = new ArrayList<String>(); for (ColumnMapper<T> cm : mapper.partitionKeys) { columns.add(trim(cm.getColumnName())); } for (ColumnMapper<T> cm : mapper.clusteringColumns) { columns.add(trim(cm.getColumnName())); } return columns; } /** * Returns a list of columns (cells) whose values should not be * included into the audit log. * * @param mapper entity mapper * @return a list of column names */ private <T> List<String> getExcludedColumns(EntityMapper<T> mapper) { ArrayList<String> excludedColumns = new ArrayList<String>(); for (Field f : mapper.entityClass.getDeclaredFields()) { if (f.getAnnotation(AuditExclusion.class) != null) { String name = f.getName(); Column colAnnotation = f.getAnnotation(Column.class); if (colAnnotation != null && !colAnnotation.name().isEmpty()) { name = colAnnotation.name(); } excludedColumns.add(name); } } return excludedColumns; } }
package com.docusign.esign.client.auth; import com.migcomponents.migbase64.Base64; import java.util.Map; import javax.ws.rs.core.Response.Status.Family; import org.apache.oltu.oauth2.client.HttpClient; import org.apache.oltu.oauth2.client.response.OAuthClientResponse; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; public class OAuthJerseyClient implements HttpClient { private Client client; public OAuthJerseyClient() { this.client = new Client(null, null); } public OAuthJerseyClient(Client client) { this.client = client; } public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException { String contentType = headers.get("Content-Type"); String url = request.getLocationUri(); String body = request.getBody(); Builder builder = this.client.resource(url).getRequestBuilder(); for (String key : headers.keySet()) { builder = builder.header(key, headers.get(key)); } String grantType = null, code = null, clientId = null, clientSecret = null; for (String entry : body.split("&")) { String key = entry.split("=")[0]; String value = entry.split("=")[1]; if ("grant_type".equals(key)) { grantType = value; } else if ("code".equals(key)) { code = value; } else if ("client_id".equals(key)) { clientId = value; } else if ("client_secret".equals(key)) { clientSecret = value; } } if (grantType == null) { throw new OAuthSystemException("Missing grant_type"); } if (!grantType.equals(GrantType.REFRESH_TOKEN.toString()) && code == null) { throw new OAuthSystemException("Missing code for grant_type="+grantType); } if (code == null) { body = "grant_type=" + grantType; } else { body = "grant_type=" + grantType + "&code=" + code; } if (clientId == null || clientSecret == null) { throw new OAuthSystemException("Missing clientId/secret"); } else { byte[] bytes = (clientId + ":" + clientSecret).getBytes(); builder.header("Authorization", "Basic " + Base64.encodeToString(bytes, false)); } ClientResponse response = null; if ("GET".equals(requestMethod)) { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(requestMethod)) { response = builder.type(contentType).post(ClientResponse.class, body); } else if ("PUT".equals(requestMethod)) { response = builder.type(contentType).put(ClientResponse.class, body); } else if ("DELETE".equals(requestMethod)) { response = builder.type(contentType).delete(ClientResponse.class, body); } if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if (responseClass == null) return null; else { String respBody = response.getEntity(String.class); return OAuthClientResponseFactory.createCustomResponse( respBody, contentType, response.getStatus(), response.getHeaders(), responseClass ); } } else { String message = "error"; String respBody = null; if (response.hasEntity()) { try { respBody = response.getEntity(String.class); message = respBody; System.err.println(message); } catch (RuntimeException e) { e.printStackTrace(); } } } return null; } public void shutdown() { // Nothing to do here } }
package com.github.davidmoten.aws.maven; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Settings; import org.apache.maven.settings.crypto.SettingsDecrypter; @Mojo(name = "deployLambda") public final class LambdaDeployMojo extends AbstractMojo { @Parameter(property = "awsAccessKey") private String awsAccessKey; @Parameter(property = "awsSecretAccessKey") private String awsSecretAccessKey; @Parameter(property = "serverId") private String serverId; @Parameter(property = "functionName") private String functionName; @Parameter(property = "artifact") private String artifact; @Parameter(property = "region") private String region; @Parameter(property = "httpsProxyHost") private String httpsProxyHost; @Parameter(property = "httpsProxyPort") private int httpsProxyPort; @Parameter(property = "httpsProxyUsername") private String httpsProxyUsername; @Parameter(property = "httpsProxyPassword") private String httpsProxyPassword; @Parameter(defaultValue = "${project}", required = true) private MavenProject project; @Component private Settings settings; @Component private SettingsDecrypter decrypter; @Override public void execute() throws MojoExecutionException, MojoFailureException { Proxy proxy = new Proxy(httpsProxyHost, httpsProxyPort, httpsProxyUsername, httpsProxyPassword); LambdaDeployer deployer = new LambdaDeployer(getLog()); AwsKeyPair keys = Util.getAwsKeyPair(serverId, awsAccessKey, awsSecretAccessKey, settings, decrypter); deployer.deploy(keys, region, artifact, functionName, proxy); } }
package com.google.gcloud.datastore; import com.google.api.services.datastore.DatastoreV1; import com.google.api.services.datastore.client.Datastore; import com.google.api.services.datastore.client.DatastoreException; import com.google.common.collect.AbstractIterator; import com.google.protobuf.ByteString; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; final class DatastoreServiceImpl implements DatastoreService { static final Key[] EMPTY_KEY_ARRAY = {}; static final PartialKey[] EMPTY_PARTIAL_KEY_ARRAY = {}; private final DatastoreServiceOptions options; private final Datastore datastore; DatastoreServiceImpl(DatastoreServiceOptions options, Datastore datastore) { this.options = options; this.datastore = datastore; } @Override public DatastoreServiceOptions options() { return options; } @Override public KeyBuilder newKeyBuilder(String kind) { return new KeyBuilder(this, kind); } @Override public BatchWriter newBatchWriter(BatchWriteOption... batchWriteOption) { return new BatchWriterImpl(this, batchWriteOption); } @Override public Transaction newTransaction(TransactionOption... transactionOption) { return new TransactionImpl(this, transactionOption); } @Override public <T> QueryResult<T> runQuery(Query<T> query) { return runQuery(null, query); } <T> QueryResult<T> runQuery(DatastoreV1.ReadOptions readOptionsPb, Query<T> query) { return new QueryResultImpl<>(this, readOptionsPb, query); } DatastoreV1.RunQueryResponse runQuery(DatastoreV1.RunQueryRequest requestPb) { try { return datastore.runQuery(requestPb); } catch (DatastoreException e) { throw DatastoreServiceException.translateAndThrow(e); } } @Override public Key allocateId(PartialKey key) { return allocateId(key, EMPTY_PARTIAL_KEY_ARRAY).next(); } @Override public Iterator<Key> allocateId(PartialKey key, PartialKey... others) { DatastoreV1.AllocateIdsRequest.Builder requestPb = DatastoreV1.AllocateIdsRequest.newBuilder(); requestPb.addKey(trimNameOrId(key).toPb()); for (PartialKey other : others) { requestPb.addKey(trimNameOrId(other).toPb()); } // TODO(ozarov): will need to populate "force" after b/18594027 is fixed. try { DatastoreV1.AllocateIdsResponse responsePb = datastore.allocateIds(requestPb.build()); final Iterator<DatastoreV1.Key> keys = responsePb.getKeyList().iterator(); return new AbstractIterator<Key>() { @Override protected Key computeNext() { if (keys.hasNext()) { return Key.fromPb(keys.next()); } return endOfData(); } }; } catch (DatastoreException e) { throw DatastoreServiceException.translateAndThrow(e); } } private PartialKey trimNameOrId(PartialKey key) { if (key instanceof Key) { return PartialKey.builder(key).build(); } return key; } @Override public Entity get(Key key) { return get(key, EMPTY_KEY_ARRAY).next(); } @Override public Iterator<Entity> get(Key key, Key... others) { return get(null, key, others); } Iterator<Entity> get(DatastoreV1.ReadOptions readOptionsPb, final Key key, final Key... others) { DatastoreV1.LookupRequest.Builder requestPb = DatastoreV1.LookupRequest.newBuilder(); if (readOptionsPb != null) { requestPb.setReadOptions(readOptionsPb); } LinkedHashSet<Key> dedupKeys = new LinkedHashSet<>(); dedupKeys.add(key); dedupKeys.addAll(Arrays.asList(others)); for (Key k : dedupKeys) { requestPb.addKey(k.toPb()); } try { DatastoreV1.LookupResponse responsePb = datastore.lookup(requestPb.build()); final Map<Key, Entity> result = new HashMap<>(); for (DatastoreV1.EntityResult entityResultPb : responsePb.getFoundList()) { Entity entity = Entity.fromPb(entityResultPb.getEntity()); result.put(entity.key(), entity); } return new AbstractIterator<Entity>() { int index = -2; @Override protected Entity computeNext() { ++index; if (index < 0) { return result.get(key); } if (index < others.length) { return result.get(others[index]); } return endOfData(); } }; } catch (DatastoreException e) { throw DatastoreServiceException.translateAndThrow(e); } } @Override public void add(Entity... entities) { DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); LinkedHashSet<Key> keys = new LinkedHashSet<>(); for (Entity entity : entities) { if (!keys.add(entity.key())) { throw DatastoreServiceException.throwInvalidRequest( "Duplicate entity with the key %s", entity.key()); } mutationPb.addInsert(entity.toPb()); } commitMutation(mutationPb); } @Override public void update(Entity... entities) { DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); LinkedHashMap<Key, Entity> dedupEntities = new LinkedHashMap<>(); for (Entity entity : entities) { dedupEntities.put(entity.key(), entity); } for (Entity entity : dedupEntities.values()) { mutationPb.addUpdate(entity.toPb()); } commitMutation(mutationPb); } @Override public void put(Entity... entities) { DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); LinkedHashMap<Key, Entity> dedupEntities = new LinkedHashMap<>(); for (Entity entity : entities) { dedupEntities.put(entity.key(), entity); } for (Entity e : dedupEntities.values()) { mutationPb.addUpsert(e.toPb()); } commitMutation(mutationPb); } @Override public void delete(Key... keys) { DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); LinkedHashSet<Key> dedupKeys = new LinkedHashSet<>(Arrays.asList(keys)); for (Key key : dedupKeys) { mutationPb.addDelete(key.toPb()); } commitMutation(mutationPb); } private void commitMutation(DatastoreV1.Mutation.Builder mutationPb) { if (options.force()) { mutationPb.setForce(true); } DatastoreV1.CommitRequest.Builder requestPb = DatastoreV1.CommitRequest.newBuilder(); requestPb.setMode(DatastoreV1.CommitRequest.Mode.NON_TRANSACTIONAL); requestPb.setMutation(mutationPb); commitMutation(requestPb); } void commitMutation(DatastoreV1.CommitRequest.Builder requestPb) { try { datastore.commit(requestPb.build()); } catch (DatastoreException e) { throw DatastoreServiceException.translateAndThrow(e); } } ByteString requestTransactionId(DatastoreV1.BeginTransactionRequest.Builder requestPb) { try { DatastoreV1.BeginTransactionResponse responsePb = datastore.beginTransaction(requestPb.build()); return responsePb.getTransaction(); } catch (DatastoreException e) { throw DatastoreServiceException.translateAndThrow(e); } } void rollbackTransaction(ByteString transaction) { DatastoreV1.RollbackRequest.Builder requestPb = DatastoreV1.RollbackRequest.newBuilder(); requestPb.setTransaction(transaction); try { datastore.rollback(requestPb.build()); } catch (DatastoreException e) { throw DatastoreServiceException.translateAndThrow(e); } } }
package me.ryanhamshire.ExtraHardMode.config; import java.util.ArrayList; import org.bukkit.Material; import me.ryanhamshire.ExtraHardMode.service.ConfigNode; /** * Configuration options of the root config.yml file. */ public enum RootNode implements ConfigNode { /** * list of worlds where extra hard mode rules apply */ WORLDS("ExtraHardMode.Worlds", VarType.LIST, new ArrayList<String>()), /** * minimum y for placing standard torches */ STANDARD_TORCH_MIN_Y("ExtraHardMode.PermanentFlameMinYCoord", VarType.INTEGER, 30), /** * whether stone is hardened to encourage cave exploration over tunneling */ SUPER_HARD_STONE("ExtraHardMode.HardenedStone", VarType.BOOLEAN, true), /** * whether players take additional damage and/or debuffs from environmental * injuries */ ENHANCED_ENVIRONMENTAL_DAMAGE("ExtraHardMode.EnhancedEnvironmentalInjuries", VarType.BOOLEAN, true), /** * whether players catch fire when extinguishing a fire up close */ EXTINGUISHING_FIRE_IGNITES_PLAYERS("ExtraHardMode.ExtinguishingFiresIgnitesPlayers", VarType.BOOLEAN, true), /** * whether TNT should be more powerful and plentiful */ BETTER_TNT("ExtraHardMode.BetterTNT", VarType.BOOLEAN, true), /** * whether monster grinders (or "farms") should be inhibited */ INHIBIT_MONSTER_GRINDERS("ExtraHardMode.InhibitMonsterGrinders", VarType.BOOLEAN, true), /** * whether players may place blocks directly underneath themselves */ LIMITED_BLOCK_PLACEMENT("ExtraHardMode.LimitedBlockPlacement", VarType.BOOLEAN, true), /** * whether players are limited to placing torches against specific materials */ LIMITED_TORCH_PLACEMENT("ExtraHardMode.LimitedTorchPlacement", VarType.BOOLEAN, true), /** * whether rain should break torches */ RAIN_BREAKS_TORCHES("ExtraHardMode.RainBreaksTorches", VarType.BOOLEAN, true), /** * percent chance for broken netherrack to start a fire */ BROKEN_NETHERRACK_CATCHES_FIRE_PERCENT("ExtraHardMode.NetherrackCatchesFirePercent", VarType.INTEGER, 20), /** * max y value for extra monster spawns */ MORE_MONSTERS_MAX_Y("ExtraHardMode.MoreMonsters.MaxYCoord", VarType.INTEGER, 55), /** * what to multiply monster spawns by */ MORE_MONSTERS_MULTIPLIER("ExtraHardMode.MoreMonsters.Multiplier", VarType.INTEGER, 2), /** * max y value for monsters to spawn in the light */ MONSTER_SPAWNS_IN_LIGHT_MAX_Y("ExtraHardMode.MonstersSpawnInLightMaxY", VarType.INTEGER, 50), /** * whether zombies apply a debuff to players on hit */ ZOMBIES_DEBILITATE_PLAYERS("ExtraHardMode.Zombies.SlowPlayers", VarType.BOOLEAN, true), /** * percent chance for a zombie to reanimate after death */ ZOMBIES_REANIMATE_PERCENT("ExtraHardMode.Zombies.ReanimatePercent", VarType.INTEGER, 50), /** * percent chance skeletons have a chance to knock back targets with arrows */ SKELETONS_KNOCK_BACK_PERCENT("ExtraHardMode.Skeletons.ArrowsKnockBackPercent", VarType.INTEGER, 30), /** * percent chance skeletons will release silverfish instead of firing arrows */ SKELETONS_RELEASE_SILVERFISH("ExtraHardMode.Skeletons.ReleaseSilverfishPercent", VarType.INTEGER, 30), /** * whether or not arrows will pass harmlessly through skeletons */ SKELETONS_DEFLECT_ARROWS("ExtraHardMode.Skeletons.DeflectArrowsPercent", VarType.INTEGER, 100), /** * percentage of zombies which will be replaced with spiders under sea level */ BONUS_UNDERGROUND_SPIDER_SPAWN_PERCENT("ExtraHardMode.Spiders.BonusUndergroundSpawnPercent", VarType.INTEGER, 20), /** * whether spiders drop webbing when they die */ SPIDERS_DROP_WEB_ON_DEATH("ExtraHardMode.Spiders.DropWebOnDeath", VarType.BOOLEAN, true), /** * percentage of surface zombies which spawn as witches */ BONUS_WITCH_SPAWN_PERCENT("ExtraHardMode.Witches.BonusSpawnPercent", VarType.INTEGER, 5), /** * percentage of creepers which will spawn charged */ CHARGED_CREEPER_SPAWN_PERCENT("ExtraHardMode.Creepers.ChargedCreeperSpawnPercent", VarType.INTEGER, 5), /** * percentage of creepers which spawn activated TNT on death */ CREEPERS_DROP_TNT_ON_DEATH_PERCENT("ExtraHardMode.Creepers.DropTNTOnDeathPercent", VarType.INTEGER, 20), /** * whether charged creepers explode when damaged */ CHARGED_CREEPERS_EXPLODE_ON_HIT("ExtraHardMode.Creepers.ChargedCreepersExplodeOnDamage", VarType.BOOLEAN, true), /** * whether creepers explode when caught on fire */ FLAMING_CREEPERS_EXPLODE("ExtraHardMode.Creepers.FireTriggersExplosion", VarType.BOOLEAN, true), /** * percentage of skeletons near bedrock which will be replaced with blazes */ NEAR_BEDROCK_BLAZE_SPAWN_PERCENT("ExtraHardMode.Blazes.NearBedrockSpawnPercent", VarType.INTEGER, 50), /** * percentage of pig zombies which will be replaced with blazes */ BONUS_NETHER_BLAZE_SPAWN_PERCENT("ExtraHardMode.Blazes.BonusNetherSpawnPercent", VarType.INTEGER, 20), /** * percentage chance that a blaze spawn will trigger a flame slime spawn as * well */ FLAME_SLIMES_SPAWN_WITH_NETHER_BLAZE_PRESENT("ExtraHardMode.MagmaCubes.SpawnWithNetherBlazePercent", VarType.INTEGER, 100), /** * whether damaging a magma cube turns it into a blaze */ MAGMA_CUBES_BECOME_BLAZES_ON_DAMAGE("ExtraHardMode.MagmaCubes.GrowIntoBlazesOnDamage", VarType.BOOLEAN, true), /** * whether blazes explode and spread fire when they die */ BLAZES_EXPLODE_ON_DEATH("ExtraHardMode.Blazes.ExplodeOnDeath", VarType.BOOLEAN, true), /** * whether blazes drop fire when damaged */ BLAZES_DROP_FIRE_ON_DAMAGE("ExtraHardMode.Blazes.DropFireOnDamage", VarType.BOOLEAN, true), /** * whether blazes drop extra loot */ BLAZES_DROP_BONUS_LOOT("ExtraHardMode.Blazes.BonusLoot", VarType.BOOLEAN, true), /** * percentage chance that a blaze slain in the nether will split into two * blazes */ NETHER_BLAZES_SPLIT_ON_DEATH_PERCENT("ExtraHardMode.Blazes.NetherSplitOnDeathPercent", VarType.INTEGER, 25), /** * whether pig zombies are always hostile */ ALWAYS_ANGRY_PIG_ZOMBIES("ExtraHardMode.PigZombies.AlwaysAngry", VarType.BOOLEAN, true), /** * whether pig zombies drop nether wart in nether fortresses */ FORTRESS_PIGS_DROP_WART("ExtraHardMode.PigZombies.DropWartInFortresses", VarType.BOOLEAN, true), /** * whether ghasts should deflect arrows and drop extra loot TODO make this a * percentage like skeleton deflect */ GHASTS_DEFLECT_ARROWS("ExtraHardMode.Ghasts.DeflectArrows", VarType.BOOLEAN, true), /** * whether endermen may teleport players */ IMPROVED_ENDERMAN_TELEPORTATION("ExtraHardMode.Endermen.MayTeleportPlayers", VarType.BOOLEAN, true), /** * whether the ender dragon respawns */ RESPAWN_ENDER_DRAGON("ExtraHardMode.EnderDragon.Respawns", VarType.BOOLEAN, true), /** * whether it drops an egg when slain */ ENDER_DRAGON_DROPS_EGG("ExtraHardMode.EnderDragon.DropsEgg", VarType.BOOLEAN, true), /** * whether it drops a pair of villager eggs when slain */ ENDER_DRAGON_DROPS_VILLAGER_EGGS("ExtraHardMode.EnderDragon.DropsVillagerEggs", VarType.BOOLEAN, true), /** * whether the dragon spits fireballs and summons minions */ ENDER_DRAGON_ADDITIONAL_ATTACKS("ExtraHardMode.EnderDragon.HarderBattle", VarType.BOOLEAN, true), /** * whether server wide messages will broadcast player victories and defeats */ ENDER_DRAGON_COMBAT_ANNOUNCEMENTS("ExtraHardMode.EnderDragon.BattleAnnouncements", VarType.BOOLEAN, true), /** * whether players will be allowed to build in the end */ ENDER_DRAGON_NO_BUILDING("ExtraHardMode.EnderDragon.NoBuildingAllowed", VarType.BOOLEAN, true), /** * whether food crops die more easily */ WEAK_FOOD_CROPS("ExtraHardMode.Farming.WeakCrops", VarType.BOOLEAN, true), /** * whether bonemeal may be used on mushrooms */ NO_BONEMEAL_ON_MUSHROOMS("ExtraHardMode.Farming.NoBonemealOnMushrooms", VarType.BOOLEAN, true), /** * whether nether wart will ever drop more than 1 wart when broken */ NO_FARMING_NETHER_WART("ExtraHardMode.Farming.NoFarmingNetherWart", VarType.BOOLEAN, true), /** * whether sheep will always regrow white wool */ SHEEP_REGROW_WHITE_WOOL("ExtraHardMode.Farming.SheepGrowOnlyWhiteWool", VarType.BOOLEAN, true), /** * whether players may move water source blocks */ DONT_MOVE_WATER_SOURCE_BLOCKS("ExtraHardMode.Farming.BucketsDontMoveWaterSources", VarType.BOOLEAN, true), /** * whether players may swim while wearing armor */ NO_SWIMMING_IN_ARMOR("ExtraHardMode.NoSwimmingWhenHeavy", VarType.BOOLEAN, true), /** * percentage of item stacks lost on death */ PLAYER_DEATH_ITEM_STACKS_FORFEIT_PERCENT("ExtraHardMode.PlayerDeath.ItemStacksForfeitPercent", VarType.INTEGER, 10), /** * how much health after respawn */ PLAYER_RESPAWN_HEALTH("ExtraHardMode.PlayerDeath.RespawnHealth", VarType.INTEGER, 15), /** * how much food bar after respawn */ PLAYER_RESPAWN_FOOD_LEVEL("ExtraHardMode.PlayerDeath.RespawnFoodLevel", VarType.INTEGER, 15), /** * whether tree logs respect gravity */ BETTER_TREE_CHOPPING("ExtraHardMode.BetterTreeFelling", VarType.BOOLEAN, true), /** * explosions disable option, needed to dodge bugs in popular plugins */ WORK_AROUND_EXPLOSION_BUGS("ExtraHardMode.WorkAroundOtherPluginsExplosionBugs", VarType.BOOLEAN, false), /** * which materials beyond sand and gravel should be subject to gravity */ MORE_FALLING_BLOCKS("ExtraHardMode.AdditionalFallingBlocks", VarType.LIST, new DefaultFallingBlocks()); /** * Path. */ private final String path; /** * Variable type. */ private final VarType type; /** * Default value. */ private final Object defaultValue; /** * Constructor. * * @param path * - Configuration path. * @param type * - Variable type. * @param def * - Default value. */ private RootNode(String path, VarType type, Object def) { this.path = path; this.type = type; this.defaultValue = def; } @Override public String getPath() { return path; } @Override public VarType getVarType() { return type; } @Override public Object getDefaultValue() { return defaultValue; } /** * Default list of falling blocks. */ private static class DefaultFallingBlocks extends ArrayList<String> { /** * Serial Version UID. */ private static final long serialVersionUID = 1L; /** * Constructor. */ public DefaultFallingBlocks() { super(); this.add(Material.DIRT.toString()); this.add(Material.GRASS.toString()); this.add(Material.COBBLESTONE.toString()); this.add(Material.MOSSY_COBBLESTONE.toString()); this.add(Material.MYCEL.toString()); this.add(Material.JACK_O_LANTERN.toString()); } } }
package com.indexdata.mkjsf.pazpar2.commands; import com.indexdata.mkjsf.pazpar2.commands.sp.ServiceProxyCommand; public class ShowCommand extends Pazpar2Command implements ServiceProxyCommand { private static final long serialVersionUID = -8242768313266051307L; public ShowCommand() { super("show"); setParameterInState(new CommandParameter("start","=","0")); } /** * Sets the sort order for results, the updates the 'show' data object * from pazpar2. Set valid sort options in the documentation for pazpar2. * * The parts of the UI that display 'show' data should be rendered following * this request. * * @param sortOption */ public void setSort (String sort) { setParameter(new CommandParameter("sort","=",sort)); } /** * Retrieves the current sort order for results * @return sort order - i.e. 'relevance' */ public String getSort () { return getParameter("sort") != null ? getParameter("sort").value : "relevance"; } /** * Sets the number of records that pazpar2 should show at a time. Is * followed by an update of the show data object from pazpar2. * * To be used by the UI for paging. After setting page size the parts * of the UI that displays 'show' data should be rendered. * * @param perPageOption i.e. 10, default is 20. */ public void setPageSize (String perPageOption) { setParameters(new CommandParameter("num","=",perPageOption), new CommandParameter("start","=",0)); } /** * Retrieves the currently defined number of items to show at a time * * @return number of result records that will be shown from pazpar2 */ public String getPageSize () { return getParameter("num") != null ? getParameter("num").value : "20"; } /** * Sets the first record to show - starting at record '0'. After setting * first record number, the 'show' data object will be updated from pazpar2, * and the parts of the UI displaying show data should be re-rendered. * * To be used by the UI for paging. * * @param start first record to show */ public void setStart (int start) { setParameter(new CommandParameter("start","=",start)); } /** * Retrieves the sequence number of the record that pazpaz2 will return as * the first record in 'show' * * @return sequence number of the first record to be shown (numbering starting at '0') * */ public int getStart() { return getParameter("start") != null ? Integer.parseInt(getParameter("start").value) : 0; } public void setNum (int num) { setParameter(new CommandParameter("num","=",num)); } public int getNum () { return getParameter("num") != null ? Integer.parseInt(getParameter("num").value) : 0; } public void setBlock(String block) { setParameterInState(new CommandParameter("block","=",block)); } public String getBlock() { return getParameterValue("block"); } public void setMergekey (String mergekey) { setParameter(new CommandParameter("mergekey","=",mergekey)); } public String getMergekey () { return getParameterValue("mergekey"); } public void setRank (String rank) { setParameter(new CommandParameter("rank","=",rank)); } public String getRank () { return getParameterValue("rank"); } public ShowCommand copy () { ShowCommand newCommand = new ShowCommand(); for (String parameterName : parameters.keySet()) { newCommand.setParameterInState(parameters.get(parameterName).copy()); } return newCommand; } @Override public ServiceProxyCommand getSp() { return this; } @Override public boolean spOnly() { return false; } }
package com.j256.ormlite.jdbc; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.j256.ormlite.db.DatabaseType; import com.j256.ormlite.logger.Log.Level; import com.j256.ormlite.logger.Logger; import com.j256.ormlite.logger.LoggerFactory; import com.j256.ormlite.misc.IOUtils; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.support.DatabaseConnection; /** * Implementation of the ConnectionSource interface that supports basic pooled connections. New connections are created * on demand only if there are no dormant connections otherwise released connections will be reused. This class is * reentrant and can handle requests from multiple threads. * * <p> * <b> NOTE: </b> If you are using the Spring type wiring in Java, {@link #initialize} should be called after all of the * set methods. In Spring XML, init-method="initialize" should be used. * </p> * * <p> * <b> NOTE: </b> This class spawns a thread to test the pooled connections that are in the free-list as a keep-alive * mechanism. It will test any dormant connections every so often to see if they are still valid. If this is not the * behavior that you want then call {@link #setCheckConnectionsEveryMillis(long)} with 0 to disable the thread. You can * also call {@link #setTestBeforeGet(boolean)} and set it to true to test the connection before it is handed back to * you. * </p> * * @author graywatson */ public class JdbcPooledConnectionSource extends JdbcConnectionSource implements ConnectionSource { private static Logger logger = LoggerFactory.getLogger(JdbcPooledConnectionSource.class); private final static int DEFAULT_MAX_CONNECTIONS_FREE = 5; // maximum age that a connection can be before being closed private final static int DEFAULT_MAX_CONNECTION_AGE_MILLIS = 60 * 60 * 1000; private final static int CHECK_CONNECTIONS_EVERY_MILLIS = 30 * 1000; private int maxConnectionsFree = DEFAULT_MAX_CONNECTIONS_FREE; private long maxConnectionAgeMillis = DEFAULT_MAX_CONNECTION_AGE_MILLIS; private List<ConnectionMetaData> connFreeList = new ArrayList<ConnectionMetaData>(); protected final Map<DatabaseConnection, ConnectionMetaData> connectionMap = new HashMap<DatabaseConnection, ConnectionMetaData>(); private final Object lock = new Object(); private ConnectionTester tester = null; private String pingStatment; private int openCount = 0; private int releaseCount = 0; private int closeCount = 0; private int maxEverUsed = 0; private int testLoopCount = 0; private long checkConnectionsEveryMillis = CHECK_CONNECTIONS_EVERY_MILLIS; private boolean testBeforeGetFromPool = false; private volatile boolean isOpen = true; public JdbcPooledConnectionSource() { // for spring type wiring } public JdbcPooledConnectionSource(String url) throws SQLException { this(url, null, null, null); } public JdbcPooledConnectionSource(String url, DatabaseType databaseType) throws SQLException { this(url, null, null, databaseType); } public JdbcPooledConnectionSource(String url, String username, String password) throws SQLException { this(url, username, password, null); } public JdbcPooledConnectionSource(String url, String username, String password, DatabaseType databaseType) throws SQLException { super(url, username, password, databaseType); } @Override public void initialize() throws SQLException { super.initialize(); pingStatment = databaseType.getPingStatement(); } @Override public void close() throws IOException { if (!initialized) { throw new IOException(getClass().getSimpleName() + " was not initialized properly"); } logger.debug("closing"); synchronized (lock) { // close the outstanding connections in the list for (ConnectionMetaData connMetaData : connFreeList) { closeConnectionQuietly(connMetaData); } connFreeList.clear(); connFreeList = null; // NOTE: We can't close the ones left in the connectionMap because they may still be in use. connectionMap.clear(); isOpen = false; } } @Override public DatabaseConnection getReadOnlyConnection(String tableName) throws SQLException { // set the connection to be read-only in JDBC-land? would need to set read-only or read-write return getReadWriteConnection(tableName); } @Override public DatabaseConnection getReadWriteConnection(String tableName) throws SQLException { checkInitializedSqlException(); DatabaseConnection conn = getSavedConnection(); if (conn != null) { return conn; } synchronized (lock) { while (connFreeList.size() > 0) { // take the first one off of the list ConnectionMetaData connMetaData = getFreeConnection(); if (connMetaData == null) { // need to create a new one } else if (testBeforeGetFromPool && !testConnection(connMetaData)) { // close expired connection closeConnectionQuietly(connMetaData); } else { logger.debug("reusing connection {}", connMetaData); return connMetaData.connection; } } // if none in the free list then make a new one DatabaseConnection connection = makeConnection(logger); openCount++; // add it to our connection map connectionMap.put(connection, new ConnectionMetaData(connection, maxConnectionAgeMillis)); int maxInUse = connectionMap.size(); if (maxInUse > maxEverUsed) { maxEverUsed = maxInUse; } return connection; } } @Override public void releaseConnection(DatabaseConnection connection) throws SQLException { checkInitializedSqlException(); if (isSavedConnection(connection)) { // ignore the release when we are in a transaction return; } /* * If the connection is not close and has auto-commit turned off then we must roll-back any outstanding * statements and set auto-commit back to true. */ boolean isClosed = connection.isClosed(); if (!isClosed && !connection.isAutoCommit()) { connection.rollback(null); connection.setAutoCommit(true); } synchronized (lock) { releaseCount++; if (isClosed) { // it's already closed so just drop it ConnectionMetaData meta = connectionMap.remove(connection); if (meta == null) { logger.debug("dropping already closed unknown connection {}", connection); } else { logger.debug("dropping already closed connection {}", meta); } return; } if (connFreeList == null) { // if we've already closed the pool then just close the connection closeConnection(connection); return; } ConnectionMetaData meta = connectionMap.get(connection); if (meta == null) { logger.error("should have found connection {} in the map", connection); closeConnection(connection); } else { meta.noteUsed(); connFreeList.add(meta); logger.debug("cache released connection {}", meta); if (connFreeList.size() > maxConnectionsFree) { // close the first connection in the queue meta = connFreeList.remove(0); logger.debug("cache too full, closing connection {}", meta); closeConnection(meta.connection); } if (checkConnectionsEveryMillis > 0 && tester == null) { tester = new ConnectionTester(); tester.setName(getClass().getSimpleName() + " connection tester"); tester.setDaemon(true); tester.start(); } } } } @Override public boolean saveSpecialConnection(DatabaseConnection connection) throws SQLException { checkInitializedIllegalStateException(); boolean saved = saveSpecial(connection); if (logger.isLevelEnabled(Level.DEBUG)) { ConnectionMetaData meta = connectionMap.get(connection); logger.debug("saved special connection {}", meta); } return saved; } @Override public void clearSpecialConnection(DatabaseConnection connection) { checkInitializedIllegalStateException(); boolean cleared = clearSpecial(connection, logger); if (logger.isLevelEnabled(Level.DEBUG)) { ConnectionMetaData meta = connectionMap.get(connection); if (cleared) { logger.debug("cleared special connection {}", meta); } else { logger.debug("special connection {} not saved", meta); } } // release should then called after the clear } @Override public boolean isOpen(String tableName) { return isOpen; } @Override public boolean isSingleConnection(String tableName) { return false; } /** * Set the number of connections that can be unused in the available list. */ public void setMaxConnectionsFree(int maxConnectionsFree) { this.maxConnectionsFree = maxConnectionsFree; } /** * Set the number of milliseconds that a connection can stay open before being closed. Set to Long.MAX_VALUE to have * the connections never expire. */ public void setMaxConnectionAgeMillis(long maxConnectionAgeMillis) { this.maxConnectionAgeMillis = maxConnectionAgeMillis; } /** * Return the approximate number of connections opened over the life of the pool. */ public int getOpenCount() { return openCount; } /** * Return the approximate number of connections released over the life of the pool. */ public int getReleaseCount() { return releaseCount; } /** * Return the approximate number of connections closed over the life of the pool. */ public int getCloseCount() { return closeCount; } /** * Return the approximate maximum number of connections in use at one time. */ public int getMaxConnectionsEverUsed() { return maxEverUsed; } /** * Return the number of currently freed connections in the free list. */ public int getCurrentConnectionsFree() { synchronized (lock) { return connFreeList.size(); } } /** * Return the number of current connections that we are tracking. */ public int getCurrentConnectionsManaged() { synchronized (lock) { return connectionMap.size(); } } /** * There is an internal thread which checks each of the database connections as a keep-alive mechanism. This set the * number of milliseconds it sleeps between checks -- default is 30000. To disable the checking thread, set this to * 0 before you start using the connection source. */ public void setCheckConnectionsEveryMillis(long checkConnectionsEveryMillis) { this.checkConnectionsEveryMillis = checkConnectionsEveryMillis; } public void setTestBeforeGet(boolean testBeforeGetFromPool) { this.testBeforeGetFromPool = testBeforeGetFromPool; } /** * Mostly for testing purposes to see how many times our test loop ran. */ public int getTestLoopCount() { return testLoopCount; } /** * This should be inside of synchronized (lock) stanza. */ protected void closeConnection(DatabaseConnection connection) throws SQLException { // this can return null if we are closing the pool ConnectionMetaData meta = connectionMap.remove(connection); IOUtils.closeThrowSqlException(connection, "SQL connection"); logger.debug("closed connection {}", meta); closeCount++; } /** * Must be called inside of synchronized(lock) */ protected void closeConnectionQuietly(ConnectionMetaData connMetaData) { try { // close expired connection closeConnection(connMetaData.connection); } catch (SQLException e) { // we ignore this } } protected boolean testConnection(ConnectionMetaData connMetaData) { try { // issue our ping statement long result = connMetaData.connection.queryForLong(pingStatment); logger.trace("tested connection {}, got {}", connMetaData, result); return true; } catch (Exception e) { logger.debug(e, "testing connection {} threw exception", connMetaData); return false; } } private ConnectionMetaData getFreeConnection() { synchronized (lock) { long now = System.currentTimeMillis(); while (connFreeList.size() > 0) { // take the first one off of the list ConnectionMetaData connMetaData = connFreeList.remove(0); // is it already expired if (connMetaData.isExpired(now)) { // close expired connection closeConnectionQuietly(connMetaData); } else { connMetaData.noteUsed(); return connMetaData; } } } return null; } private void checkInitializedSqlException() throws SQLException { if (!initialized) { throw new SQLException(getClass().getSimpleName() + " was not initialized properly"); } } private void checkInitializedIllegalStateException() { if (!initialized) { throw new IllegalStateException(getClass().getSimpleName() + " was not initialized properly"); } } /** * Class to hold the connection and its meta data. */ protected static class ConnectionMetaData { public final DatabaseConnection connection; private final long expiresMillis; private long lastUsed; public ConnectionMetaData(DatabaseConnection connection, long maxConnectionAgeMillis) { this.connection = connection; long now = System.currentTimeMillis(); if (maxConnectionAgeMillis > Long.MAX_VALUE - now) { this.expiresMillis = Long.MAX_VALUE; } else { this.expiresMillis = now + maxConnectionAgeMillis; } this.lastUsed = now; } public boolean isExpired(long now) { return (expiresMillis <= now); } public long getLastUsed() { return lastUsed; } public void noteUsed() { this.lastUsed = System.currentTimeMillis(); } @Override public String toString() { return "#" + hashCode(); } } /** * Tester thread that checks the connections that we have queued to make sure they are still good. */ private class ConnectionTester extends Thread { // class field to reduce gc private Set<ConnectionMetaData> testedSet = new HashSet<ConnectionMetaData>(); @Override public void run() { while (checkConnectionsEveryMillis > 0) { try { Thread.sleep(checkConnectionsEveryMillis); if (!testConnections()) { return; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); // quit if we've been interrupted return; } } } /** * Test the connections, returning true if we should continue. */ private boolean testConnections() { // clear our tested set testedSet.clear(); long now = System.currentTimeMillis(); ConnectionMetaData connMetaData = null; boolean closeLast = false; while (true) { testLoopCount++; synchronized (lock) { if (closeLast) { if (connMetaData != null) { closeConnectionQuietly(connMetaData); connMetaData = null; } closeLast = false; } if (connFreeList == null) { // we're closed return false; } // add a tested connection back into the free-list if (connMetaData != null) { // we do this so we don't have to double lock in the loop connFreeList.add(connMetaData); } if (connFreeList.isEmpty()) { // nothing to do, return to sleep and go again return true; } connMetaData = connFreeList.get(0); if (testedSet.contains(connMetaData)) { // we are done if we've tested it before on this pass return true; } // otherwise, take the first one off the list connMetaData = connFreeList.remove(0); // see if it is expires so it can be closed immediately if (connMetaData.isExpired(now)) { // close expired connection closeConnectionQuietly(connMetaData); // don't return the connection to the free list connMetaData = null; continue; } } if (testConnection(connMetaData)) { testedSet.add(connMetaData); } else { // we close this inside of the synchronized block closeLast = true; } } } } }
package com.scienceminer.nerd.disambiguation; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.scienceminer.nerd.kb.LowerKnowledgeBase; import com.scienceminer.nerd.kb.LowerKnowledgeBase.Direction; import com.scienceminer.nerd.kb.UpperKnowledgeBase; import com.scienceminer.nerd.kb.model.Article; import com.scienceminer.nerd.kb.model.Label; import com.scienceminer.nerd.kb.model.Page; import com.scienceminer.nerd.utilities.NerdConfig; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.scienceminer.nerd.kb.UpperKnowledgeBase.TARGET_LANGUAGES; /** * Provide semantic relatedness measures, which is an adaptation of the original Relateness measure from * Milne and Witten. * */ public class Relatedness { private static final Logger LOGGER = LoggerFactory.getLogger(Relatedness.class); private static volatile Relatedness instance = null; // all the maps use the language code as a key private Map<String, LowerKnowledgeBase> wikipedias = null; private Map<String, LoadingCache<ArticlePair, Double>> caches = null; private long comparisonsRequested = 0; private long comparisonsCalculated = 0; private final static int MAX_CACHE_SIZE = 5000000; public static Relatedness getInstance() { if (instance == null) { getNewInstance(); } return instance; } /** * Creates a new instance. */ private static synchronized void getNewInstance() { LOGGER.debug("Get new instance of Relatedness"); instance = new Relatedness(); } /** * Hidden constructor */ private Relatedness() { wikipedias = UpperKnowledgeBase.getInstance().getWikipediaConfs(); caches = new HashMap<>(); for (String lang : TARGET_LANGUAGES) { caches.put(lang, CacheBuilder.newBuilder() .maximumSize(MAX_CACHE_SIZE) // if cache reach the max, then remove the older elements .build( new CacheLoader<ArticlePair, Double>() { @Override public Double load(ArticlePair articlePair) throws Exception { return getRelatednessWithoutCache(articlePair.getArticleA(),articlePair.getArtticleB() ,lang); } } ) ); } } /** * Calculate the relatedness of a candidate with a context */ public double getRelatednessTo(NerdCandidate candidate, NerdContext context, String lang) { double totalRelatedness = 0.0; double currentRelatedness = 0.0; int totalComparisons = 0; if (context == null) { return 0.0; } List<Article> contextArticles = context.getArticles(); Label.Sense sense = candidate.getWikiSense(); Article article = null; if (sense.getType() == Page.PageType.article) article = (Article) sense; else return 0.0; if ( (contextArticles == null) || (contextArticles.size() == 0) ) { // if there is no context, we can set an arbitrary score return 0.1; } for (Article contextArticle : contextArticles) { //if (article.getId() != contextArticle.getId()){ currentRelatedness = 0.0; try { currentRelatedness = getRelatedness(article, contextArticle, lang); } catch (Exception e) { LOGGER.error("Error computing semantic relatedness for " + article + " and " + contextArticle, e); } totalRelatedness += currentRelatedness; totalComparisons++; } if (totalComparisons == 0) { return 0.0; } return totalRelatedness / totalComparisons; } /** * Calculate the relatedness between two articles */ public double getRelatedness(Article art1, Article art2, String lang) throws ExecutionException{ comparisonsRequested++; LoadingCache<ArticlePair, Double> relatednessCache = caches.get(lang); return relatednessCache.get(new ArticlePair(art1,art2)); } public double getRelatednessWithoutCache(Article artA, Article artB, String lang) { comparisonsCalculated++; if (artA.getId() == artB.getId()) return 1.0; LowerKnowledgeBase wikipedia = wikipedias.get(lang); NerdConfig conf = wikipedia.getConfig(); EntityPairRelatedness epr = getEntityPairRelatedness(artA, artB, wikipedia); if (epr == null) return 0.0; if ( (epr.getInLinkIntersectionProportion() == 0.0) && (epr.getOutLinkIntersectionProportion() == 0.0) ) return 0.0; //System.out.println("gi " + epr.getInLinkmilneWittenMeasure()); //System.out.println("go " + epr.getOutLinkmilneWittenMeasure()); int count = 0; double total = 0.0; count++; total = total + epr.getInLinkMilneWittenMeasure(); if (conf.getUseLinkOut()) { count++; total = total + epr.getOutLinkMilneWittenMeasure(); } if (count == 0) return 0.0; else return total/count; } public EntityPairRelatedness getEntityPairRelatedness(Article artA, Article artB, LowerKnowledgeBase wikipedia) { EntityPairRelatedness epr = new EntityPairRelatedness(artA, artB); NerdConfig conf = wikipedia.getConfig(); epr = setPageLinkFeatures(epr, Direction.In, wikipedia); if (conf.getUseLinkOut()) epr = setPageLinkFeatures(epr, Direction.Out, wikipedia); if (!epr.inLinkFeaturesSet() && !epr.outLinkFeaturesSet()) return null; return epr; } /** * Following Milne anf Witten relatedness measurement as implemented in WikipediaMiner */ private EntityPairRelatedness setPageLinkFeatures(EntityPairRelatedness epr, Direction dir, LowerKnowledgeBase wikipedia) { if (epr.getArticleA().getId() == epr.getArticleB().getId()) { // nothing to do return epr; } List<Integer> linksA = wikipedia.getLinks(epr.getArticleA().getId(), dir); List<Integer> linksB = wikipedia.getLinks(epr.getArticleB().getId(), dir); //we can't do anything if there are no links if (linksA.isEmpty() || linksB.isEmpty()) return epr; NerdConfig conf = wikipedia.getConfig(); //System.out.println("#linksA: " + linksA.size() + " / " + "#linksB: " + linksB.size()); int intersection = 0; //int sentenceIntersection = 0; int union = 0; int indexA = 0; int indexB = 0; List<Double> vectA = new ArrayList<>(); List<Double> vectB = new ArrayList<>(); while (indexA < linksA.size() || indexB < linksB.size()) { //identify which links to use (A, B, or both) boolean useA = false; boolean useB = false; boolean mutual = false; Integer linkA = null; Integer linkB = null; if (indexA < linksA.size()) linkA = linksA.get(indexA); if (indexB < linksB.size()) linkB = linksB.get(indexB); if ( (linkA != null) && (linkB != null) && (linkA.equals(linkB)) ) { useA = true; useB = true; intersection ++; } else { if (linkA != null && (linkB == null || linkA < linkB)) { useA = true; if (linkA.equals(epr.getArticleB().getId())) { intersection++; mutual = true; } } else { useB = true; if (linkB.equals(epr.getArticleA().getId())) { intersection++; mutual = true; } } } union++; if (useA) indexA++; if (useB) indexB++; } // this is the famous Milne & Witten relatedness measure double milneWittenMeasure = 1.0; if (intersection == 0) { milneWittenMeasure = 1.0; } else { double a = Math.log(linksA.size()); double b = Math.log(linksB.size()); double ab = Math.log(intersection); double m = Math.log(wikipedia.getArticleCount()); milneWittenMeasure = (Math.max(a, b) - ab) / (m - Math.min(a, b)); } // normalization if (milneWittenMeasure >= 1) milneWittenMeasure = 0.0; else milneWittenMeasure = 1 - milneWittenMeasure; double intersectionProportion; if (union == 0) intersectionProportion = 0; else intersectionProportion = (double)intersection/union; if (dir == Direction.Out) epr.setOutLinkFeatures(milneWittenMeasure, intersectionProportion); else epr.setInLinkFeatures(milneWittenMeasure, intersectionProportion); return epr; } public Set<Article> collectAllContextTerms(List<NerdCandidate> candidates, String lang) { // unambiguous context articles Set<Article> context = new HashSet<Article>(); LowerKnowledgeBase wikipedia = wikipedias.get(lang); for (NerdCandidate candidate : candidates) { int bestSense = candidate.getWikipediaExternalRef(); if (bestSense == -1) continue; //Article bestArticle = wikipedia.getArticleByTitle(bestSense.replace("_", " ")); Article bestArticle = (Article)wikipedia.getPageById(bestSense); if (bestArticle == null) continue; try { if (context.contains(bestArticle)) { continue; } context.add(bestArticle); } catch (Exception e) { System.out.println("Error computing senses for " + candidate.toString()); e.printStackTrace(); } } return context; } /** * Get a context from a text based on the unambiguous labels and the * certain disambiguated entities. * */ public NerdContext getContext(Map<NerdEntity, List<NerdCandidate>> candidates, List<NerdEntity> userEntities, String lang, boolean shortText) { List<Label.Sense> unambig = new ArrayList<>(); List<Integer> unambigIds = new ArrayList<>(); List<Label.Sense> extraSenses = new ArrayList<>(); List<Integer> extraSensesIds = new ArrayList<>(); LowerKnowledgeBase wikipedia = wikipedias.get(lang); double minSenseProbability = wikipedia.getConfig().getMinSenseProbability(); // we add the "certain" senses List<Article> certainPages = new ArrayList<Article>(); List<Integer> certainPagesIds = new ArrayList<Integer>(); if ( (userEntities != null) && (userEntities.size() > 0) ){ for(NerdEntity ent : userEntities) { if (ent.getWikipediaExternalRef() != -1) { Page thePage = wikipedia.getPageById(ent.getWikipediaExternalRef()); if (thePage.getType() == Page.PageType.article) { if (!certainPagesIds.contains(thePage.getId())) { certainPages.add((Article)thePage); certainPagesIds.add(thePage.getId()); } } } //TODO: wikidata id } } // first pass for non-ambiguous candidates for (Map.Entry<NerdEntity, List<NerdCandidate>> entry : candidates.entrySet()) { List<NerdCandidate> cands = entry.getValue(); NerdEntity entity = entry.getKey(); if ( (cands == null) || (cands.size() == 0) ) continue; else if (cands.size() == 1) { NerdCandidate cand = cands.get(0); if (cand.getProb_c() >= (1-minSenseProbability)) { // conditional prob of candidate sense must also be above the acceptable threshold if (!unambigIds.contains(cand.getWikiSense().getId())) { Label.Sense theSense = cands.get(0).getWikiSense(); unambig.add(theSense); unambigIds.add(theSense.getId()); } } } if (unambig.size()+certainPages.size() > NerdEngine.maxContextSize) break; } if (unambig.size()+certainPages.size() < NerdEngine.maxContextSize) { // second pass for not so ambiguous candidates for (Map.Entry<NerdEntity, List<NerdCandidate>> entry : candidates.entrySet()) { List<NerdCandidate> cands = entry.getValue(); NerdEntity entity = entry.getKey(); if ( (cands == null) || (cands.size() == 0) ) continue; else if (cands.size() == 1) { continue; } else { for(NerdCandidate cand : cands) { if (cand.getProb_c() >= (1-minSenseProbability)) { Label.Sense theSense = cands.get(0).getWikiSense(); if (!unambigIds.contains(theSense.getId())) { unambig.add(theSense); unambigIds.add(theSense.getId()); } //extraSenses.add(cands.get(0).getWikiSense()); break; } /*else if (cand.getProb_c() >= 0.8) { // we store some extra "good" senses in case we need more of them Label.Sense theSense = cands.get(0).getWikiSense(); if ( !extraSensesIds.contains(theSense.getId()) && !unambigIds.contains(theSense.getId()) ) { extraSenses.add(theSense); extraSensesIds.add(theSense.getId()); } break; }*/ } } if (unambig.size()+certainPages.size() > NerdEngine.maxContextSize) break; } } // if the context is still too small, we add some of the top sense of ambiguous labels if (shortText) { if (unambig.size()+certainPages.size() < NerdEngine.maxContextSize) { if (CollectionUtils.isNotEmpty(extraSenses)) { for(Label.Sense sense : extraSenses) { Integer theId = sense.getId(); if (!unambigIds.contains(theId)) { unambig.add(sense); unambigIds.add(theId); } if (unambig.size()+certainPages.size() > NerdEngine.maxContextSize) break; } } } } NerdContext resultContext = new NerdContext(unambig, certainPages, lang); return resultContext; } /** * Get a context from a text based on the unambiguous labels and the certain disambiguated entities. * * Note: To be removed ! * */ public NerdContext getContextFromText(String content, List<NerdEntity> userEntities, String lang) { List<Label.Sense> unambig = new ArrayList<>(); //String targetString = content.substring(entity.getOffsetStart(), entity.getOffsetEnd()); String s = "$ " + content + " $"; Pattern p = Pattern.compile("[\\s\\{\\}\\(\\)\"\'\\.\\,\\;\\:\\-\\_]"); //would just match all non-word chars, but we dont want to match utf chars Matcher m = p.matcher(s); List<Integer> matchIndexes = new ArrayList<>(); List<Label.Sense> extraSenses = new ArrayList<>(); LowerKnowledgeBase wikipedia = wikipedias.get(lang); double minSenseProbability = wikipedia.getConfig().getMinSenseProbability(); double minLinkProbability = wikipedia.getConfig().getMinLinkProbability(); while (m.find()) matchIndexes.add(m.start()); for (int i=0; i<matchIndexes.size(); i++) { int startIndex = matchIndexes.get(i) + 1; for (int j=Math.min(i + NerdEngine.maxLabelLength, matchIndexes.size()-1); j > i; j int currIndex = matchIndexes.get(j); String ngram = s.substring(startIndex, currIndex); if (! (ngram.length()==1 && s.substring(startIndex-1, startIndex).equals("'")) && !ngram.trim().equals("")) { Label label = new Label(wikipedia.getEnvironment(), ngram); if (label.getLinkProbability() > minLinkProbability) { Label.Sense[] senses = label.getSenses(); if ( senses.length == 1 || (senses[0].getPriorProbability() >= (1-minSenseProbability)) ) unambig.add(senses[0]); // we store some extra senses in case the context is too small if ( (senses.length > 1) && (senses[0].getPriorProbability() >= 0.8 ) ) { extraSenses.add(senses[0]); } } } } } // we add the "certain" senses List<Article> certainPages = new ArrayList<Article>(); for(NerdEntity ent : userEntities) { if (ent.getWikipediaExternalRef() != -1) { //resultContext.addPage(wikipedia.getPageById(ent.getWikipediaExternalRef())); Page thePage = wikipedia.getPageById(ent.getWikipediaExternalRef()); if (thePage.getType() == Page.PageType.article) { certainPages.add((Article)thePage); } } } NerdContext resultContext = new NerdContext(unambig, certainPages, lang); // if the context is still too small, we had the best senses of ambiguous labels if (resultContext.getSenseNumber() < (NerdEngine.maxContextSize/2)) { for(Label.Sense sense : extraSenses) { resultContext.addSense(sense); if (resultContext.getSenseNumber() > (NerdEngine.maxContextSize/2)) break; } } return resultContext; } /** * Get a context from a vector of terms based on the unambiguous labels and the * certain disambiguated entities. * */ public NerdContext getContext(List<WeightedTerm> terms, List<NerdEntity> userEntities, String lang) { Vector<Label.Sense> unambig = new Vector<>(); List<Label.Sense> extraSenses = new ArrayList<>(); LowerKnowledgeBase wikipedia = wikipedias.get(lang); double minSenseProbability = wikipedia.getConfig().getMinSenseProbability(); double minLinkProbability = wikipedia.getConfig().getMinLinkProbability(); for (WeightedTerm term : terms) { String termString = term.getTerm(); if ((termString.length()!=1) && (!termString.trim().equals(""))) { //Label label = new Label(wikipedia.getEnvironment(), ngram, tp); Label label = new Label(wikipedia.getEnvironment(), termString); if (label.getLinkProbability() > minLinkProbability) { Label.Sense[] senses = label.getSenses(); if ( senses.length == 1 || (senses[0].getPriorProbability() >= (1-minSenseProbability)) ) unambig.add(senses[0]); // we store some extra senses if needed if ( senses.length > 1 && (senses[0].getPriorProbability() >= 0.8 ) ) { //if ( senses.length > 1 ) extraSenses.add(senses[0]); } } } } // we add the "certain" senses List<Article> certainPages = new ArrayList<Article>(); for(NerdEntity ent : userEntities) { if (ent.getWikipediaExternalRef() != -1) { //resultContext.addPage(wikipedia.getPageById(ent.getWikipediaExternalRef())); Page thePage = wikipedia.getPageById(ent.getWikipediaExternalRef()); if (thePage.getType() == Page.PageType.article) { certainPages.add((Article)thePage); } } } NerdContext resultContext = new NerdContext(unambig, certainPages, lang); // if the context is still too small, we had the best senses of ambiguous labels if (((NerdContext)resultContext).getSenseNumber() < NerdEngine.maxContextSize) { for(Label.Sense sense : extraSenses) { ((NerdContext)resultContext).addSense(sense); if (((NerdContext)resultContext).getSenseNumber() == NerdEngine.maxContextSize) break; } } return resultContext; } public long getTermOccurrence(String text, String lang) { LowerKnowledgeBase wikipedia = wikipedias.get(lang); Label label = wikipedia.getLabel(text); if (label != null) return label.getOccCount(); else return 0; } public long getComparisonsCalculated() { return comparisonsCalculated; } public long getComparisonsRequested() { return comparisonsRequested; } public double getCachedProportion() { double p = (double)comparisonsCalculated/comparisonsRequested; return 1-p; } public void resetCache(String lang) { LoadingCache<ArticlePair,Double> cache = caches.get(lang); if (cache != null) { cache.invalidateAll(); } comparisonsCalculated = 0; comparisonsRequested = 0; } public void close() { Iterator it = wikipedias.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); LowerKnowledgeBase wikipedia = (LowerKnowledgeBase)pair.getValue(); wikipedia.close(); it.remove(); // avoids a ConcurrentModificationException } } /** * A POJO for calculation of relatedness between two articles, not so useful maybe */ public class EntityPairRelatedness { private final Article articleA; private final Article articleB; private boolean inLinkFeaturesSet = false; private double inLinkMilneWittenMeasure = 0.0; private double inLinkIntersectionProportion = 0.0; private boolean outLinkFeaturesSet = false; private double outLinkMilneWittenMeasure = 0.0; private double outLinkIntersectionProportion = 0.0; public EntityPairRelatedness(Article artA, Article artB) { articleA = artA; articleB = artB; } public Article getArticleA() { return articleA; } public Article getArticleB() { return articleB; } public boolean inLinkFeaturesSet() { return inLinkFeaturesSet; } public double getInLinkMilneWittenMeasure() { return inLinkMilneWittenMeasure; } public double getInLinkIntersectionProportion() { return inLinkIntersectionProportion; } public boolean outLinkFeaturesSet() { return outLinkFeaturesSet; } public double getOutLinkMilneWittenMeasure() { return outLinkMilneWittenMeasure; } public double getOutLinkIntersectionProportion() { return outLinkIntersectionProportion; } public void setInLinkFeatures(double milneWittenMeasure, double intersectionProportion) { inLinkFeaturesSet = true; inLinkMilneWittenMeasure = milneWittenMeasure; inLinkIntersectionProportion = intersectionProportion; } public void setOutLinkFeatures(double milneWittenMeasure, double intersectionProportion) { outLinkFeaturesSet = true; outLinkMilneWittenMeasure = milneWittenMeasure; outLinkIntersectionProportion = intersectionProportion; } }; }
package com.simpleFunctions.android.Location; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Point; import android.location.*; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import com.simpleFunctions.android.R; import java.util.List; import java.util.Locale; public class GeoLocation extends Service implements LocationListener { private final Context myContext; private final Activity myActivity; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; //flag for asking location services boolean askedBefore = false; Location location; // location double latitude; // latitude double longitude; // longitude // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GeoLocation(Activity activity) { Context myContext1; this.myActivity = activity; try { myContext1 = activity.getApplicationContext(); } catch(NullPointerException e){ myContext1 = activity.getBaseContext(); } this.myContext = myContext1; getLocation(); } public GeoLocation(Activity activity, boolean stopMessages) { Context myContext1; this.myActivity = activity; try { myContext1 = activity.getApplicationContext(); } catch(NullPointerException e){ myContext1 = activity; } this.myContext = myContext1; setAskedBefore(stopMessages); getLocation(); } public GeoLocation(Context context) { this.myContext = context; myActivity = null; getLocation(); } /** * Deactivates/Activates the automatic settings dialog call. * @param bol True for not asking next time, false for asking. */ public void setAskedBefore(boolean bol){ askedBefore = bol; } public boolean isEnabled() { locationManager = (LocationManager) myContext .getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if(!isGPSEnabled && !isNetworkEnabled) return false; else return true; } public Location getLocation() { try { if(!isEnabled() && !askedBefore && isActivityValid(myActivity)) showSettingsAlert(); if(isEnabled()) { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Allows to get the locality where the device is, based in location data. * @return a String */ public String getLocality() { Geocoder geocoder = new Geocoder(myContext, Locale.getDefault()); try { List<Address> place = geocoder.getFromLocation(getLatitude(), getLongitude(), 1); if (place.size() > 0) { String locality = place.get(0).getLocality(); return locality; } return "Here"; } catch (java.io.IOException | NullPointerException e) { return ""; } } /** * Allows to get the locality where the device is, based in location data. * @return a String */ public String getLocalityByLatlng(Double lat, Double lng) { Geocoder geocoder = new Geocoder(myContext, Locale.getDefault()); try { List<Address> place = geocoder.getFromLocation(lat, lng, 1); if (place.size() > 0) { String locality; if(place.get(0).getSubLocality()==null || place.get(0).getSubLocality().equalsIgnoreCase("")){ locality = place.get(0).getLocality(); }else{ locality = place.get(0).getSubLocality(); } return locality; } return "Here"; } catch (java.io.IOException | NullPointerException e) { return ""; } } /** * Allows to get the locality where the device is, based in location data. * @return a Place */ public Address getFullLocalityByLatlng(Double lat, Double lng) { Geocoder geocoder = new Geocoder(myContext, Locale.getDefault()); try { List<Address> place = geocoder.getFromLocation(lat, lng, 1); if (place.size() > 0) { return place.get(0); } return null; } catch (java.io.IOException | NullPointerException e) { return null; } } /** * Allows to get the address where the device is, based in location data. * @return a String */ public String getAddress() { Geocoder geocoder = new Geocoder(myContext, Locale.getDefault()); try { List<Address> place = geocoder.getFromLocation(getLatitude(), getLongitude(), 1); if (place.size() > 0) { String referencePoint = place.get(0).getCountryName() + " " + place.get(0).getLocality() + " " + place.get(0).getAddressLine(0); return referencePoint; } return "Here"; } catch (java.io.IOException | NullPointerException e) { return ""; } } /** * Allows to get the address where the device is, based in location data. * @return a String */ public String getAddress(Double latitude, Double longitude) { Geocoder geocoder = new Geocoder(myContext, Locale.getDefault()); try { List<Address> place = geocoder.getFromLocation(latitude, longitude, 1); if (place.size() > 0) { String referencePoint = place.get(0).getCountryName() + " " + place.get(0).getLocality() + " " + place.get(0).getAddressLine(0); return referencePoint; } return "Here"; } catch (java.io.IOException | NullPointerException e) { return ""; } } /** * Testing method. Determines if the conduct of the getAddress() Method is callable. * @return */ public int ShowAddress() { Geocoder geocoder = new Geocoder(myContext, Locale.getDefault()); try { List<Address> place = geocoder.getFromLocation(getLatitude(), getLongitude(), 1); if (place.size() > 0) { String referencePoint = place.get(0).getCountryName() + " " + place.get(0).getLocality() + " " + place.get(0).getAddressLine(0); Toast.makeText(myContext, referencePoint, Toast.LENGTH_LONG); return 2; } return 1; } catch (java.io.IOException | NullPointerException e) { return 0; } } /** * Shows a google map windows with the current location. * @param activity a subclass of Activity to provide access to the services. * @param <T> any subtype of activity. */ public <T extends Activity> void showLocation(T activity) { Intent googleMaps = new Intent(Intent.ACTION_VIEW, android.net.Uri.parse("http://maps.google.com/maps?q=loc:" + getLatitude() + "," + getLongitude() + "(" + location + ")")); googleMaps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(googleMaps); } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GeoLocation.this); } } /** * Allows to get the current latitude. The getLocation() method must be called at least once before. * @return a double representing the latitude. */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } public void setLatitude(Double Latitude){ latitude = Latitude; } /** * Allows to get the current longitude. The getLocation() method must be called at least once before. * @return a double representing the longitude. */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } public void setLongitude(Double Longitude){ longitude = Longitude; } public screenPoints getScreenPoints(MapView mapView){ float pisteX; float pisteY; Projection projection = mapView.getProjection(); Point pt = new Point(); GeoPoint gie = new GeoPoint((int)latitude, (int)longitude); projection.toPixels(gie, pt); pisteX = pt.x; pisteY = pt.y; screenPoints screen = new screenPoints(); screen.setX(pisteX); screen.setY(pisteY); return screen; } /** * Checks if GPS/wifi are enabled. * @return a boolean representing the possibility to get location data. * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Shows the settings alert dialog to enable wifi/GPS. When pressed, * Settings button will launch the Settings Options. * */ public void showSettingsAlert(){ if(isActivityValid(myActivity)){ askedBefore = true; AlertDialog.Builder alertDialog = new AlertDialog.Builder(myActivity); // Setting Dialog Title alertDialog.setTitle(R.string.setting_location); // Setting Dialog Message alertDialog.setMessage(R.string.ask_location); // On pressing Settings button alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); myActivity.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } } private boolean isActivityValid(Activity activity){ boolean result = true; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){ if(activity == null || activity.isFinishing() || activity.isDestroyed() ){ result = false; } } else{ if(activity == null || activity.isFinishing()){ result = false; } } return result; } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } }
package com.twocentsforthoughts.dropzone.client; import java.util.ArrayList; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.shared.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.twocentsforthoughts.dropzone.client.data.FileJS; import com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler; import com.twocentsforthoughts.dropzone.client.injector.ResourceInjector; import com.twocentsforthoughts.dropzone.client.injector.resources.Resources; import com.twocentsforthoughts.dropzone.client.interfaces.DropzoneDictonary; import com.twocentsforthoughts.dropzone.client.interfaces.DropzoneOptions; import com.twocentsforthoughts.dropzone.client.interfaces.File; public class Dropzone extends Composite { /** * Create the object that contains the Dictionary used by {@link Dropzone} * * @return a default (en-us) {@link DropzoneDictonary} instance */ public static DropzoneDictonary dictionary() { return Dictionary.create(); } /** * Create the object that contains the Options used by {@link Dropzone} * * @return a default {@link DropzoneOptions} instance */ public static DropzoneOptions options() { return Options.create(); } private DropzoneOptions options; private DropzoneEventHandler handler; private DropzoneDictonary dictionary; public Dropzone(DropzoneOptions options) { this(options, null, null, (Resources) GWT.create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneDictonary dictionary) { this(options, null, dictionary, (Resources) GWT.create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneEventHandler handler) { this(options, handler, null, (Resources) GWT.create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneEventHandler handler, DropzoneDictonary dictionary) { this(options, handler, dictionary, (Resources) GWT .create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneEventHandler handler, DropzoneDictonary dictionary, Resources resources) { this.options = options; this.handler = handler; this.dictionary = dictionary; injectResources(resources); initWidget(); } private native void initDropzone(Element e, DropzoneOptions options, DropzoneEventHandler handler, DropzoneDictonary dictionary) /*-{ //if there is a dictionary, iterate over it and transfer the values if (dictionary) { for ( var key in dictionary) { if (dictionary.hasOwnProperty(key)) { options[key] = dictionary[key]; } } } var dropzone = new $wnd.Dropzone(e, options); //If not loaded, don't add the handlers. if (!(dropzone instanceof $wnd.Dropzone)) { return; } //I'm loaded, add the eventHandlers //TODO: refactor this to another method if (this.@com.twocentsforthoughts.dropzone.client.Dropzone::handler) { dropzone .on( "addedfile", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onAddedFile(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "removedfile", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onRemovedfile(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "thumbnail", function(file, dataUri) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onThumbnail(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Ljava/lang/String;)(file,dataUri); }); dropzone .on( "error", function(file, message, xhrObject) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onError(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Ljava/lang/String;Lcom/twocentsforthoughts/dropzone/client/interfaces/XHRObjet;)(file,message,xhrObject); }); dropzone .on( "processing", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onProcessing(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "uploadprogress", function(file, progress, bytesSent) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onUploadProgress(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;II)(file,progress,bytesSent); }); dropzone .on( "sending", function(file, xhrObject, formData) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onSending(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Lcom/twocentsforthoughts/dropzone/client/interfaces/FormData;Lcom/twocentsforthoughts/dropzone/client/interfaces/XHRObjet;)(file,xhrObject,formData); }); dropzone .on( "success", function(file, response) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onSuccess(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Ljava/lang/String;)(file,response); }); dropzone .on( "complete", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onComplete(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "canceled", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onCancelled(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "maxfilesreached", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onMaxFilesReached(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "maxfilesexceeded", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onMaxFilesExceeded(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); } }-*/; private void initWidget() { HTML widget = new HTML(); widget.setStylePrimaryName("dropzone"); initWidget(widget); }; private void injectResources(Resources resources) { ResourceInjector.configure(resources); } @Override protected void onAttach() { initDropzone(getElement(), options, handler, dictionary); super.onAttach(); } /** * Add file information manually to Dropzone. Added file is not uploaded, it is just shown in the dropzone. * This feature is useful for displaying e.g. files that already exists on the server. * * @param fileName name of file to add * @param fileSize size of file to add * @param thumbnail_url thumbnail image for file */ public void addFile(String fileName, Integer fileSize, String thumbnail_url) { addfileNative(getElement(), fileName, fileSize, thumbnail_url); } /** * Native implementation of {@link addFile} method. * * @param e dropzone element * @param fileName name of file to add * @param fileSize size of file to add * @param thumbnail_url thumbnail image for file */ private native void addfileNative(Element e, String fileName, Integer fileSize, String thumbnail_url) /*-{ var mockFile = { name: fileName, size: fileSize, status: $wnd.Dropzone.SUCCESS }; e.dropzone.files.push(mockFile); e.dropzone.emit("addedfile", mockFile); e.dropzone.emit("thumbnail", mockFile, thumbnail_url); e.dropzone.emit("complete", mockFile); e.dropzone.emit("success", mockFile); }-*/; /** * Return array if all files added to dropzone. * * @return all files added to dropzone. */ public ArrayList<File> getFiles() { JsArray<FileJS> filesJS = getFilesNative(getElement()); ArrayList<File> files = new ArrayList<File>(); if (filesJS != null) for (int i=0; i<filesJS.length(); i++) files.add(filesJS.get(i)); return files; } /** * Return information about particular file added to dropzone. * * @param i index of the file * @return file information */ public File getFile(int i) { return getFilesNative(getElement()).get(i); } /** * Return number of added files. * * @return number of files */ public int getFilesCount() { JsArray<FileJS> files = getFilesNative(getElement()); return files != null ? files.length() : 0; } /** * Native implementation of {@link getFiles} * * @param e dropzone element * @return array of {@link FileJS} elements */ private native JsArray<FileJS> getFilesNative(Element e) /*-{ return e.dropzone.files; }-*/; /** * Removes file at index i. * * @param i index of the file to remove. */ public void removeFile(int i) { removeFileNative(getElement(), i); } /** * Native implementation of {@link removeFile} * * @param e dropzone element * @param i index of the file to remove */ private native void removeFileNative(Element e, int i) /*-{ if (e.dropzone.files[i]!=null){ e.dropzone.removeFile(e.dropzone.files[0]); } }-*/; /** * Removes all files from dropzone. */ public void removeAllfiles() { removeAllFilesNative(getElement()); } /** * Native implementation of {@link removeAllfiles} * * @param e dropzone element */ private native void removeAllFilesNative(Element e) /*-{ e.dropzone.removeAllFiles(true); }-*/; }
package crazypants.enderio.fluid; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import buildcraft.api.fuels.BuildcraftFuelRegistry; import buildcraft.api.fuels.ICoolant; import buildcraft.api.fuels.IFuel; import crazypants.enderio.fluid.FluidFuelRegister.CoolantImpl; import crazypants.enderio.fluid.FluidFuelRegister.FuelImpl; public class BuildCraftFluidRegister implements IFluidRegister { public BuildCraftFluidRegister() throws Exception { //Make it go splat in object construction if an older version of //build craft is installed Class.forName("buildcraft.api.fuels.BuildcraftFuelRegistry"); } @Override public void addCoolant(Fluid fluid, float degreesCoolingPerMB) { if(BuildcraftFuelRegistry.coolant != null && BuildcraftFuelRegistry.coolant.getCoolant(fluid) == null) { BuildcraftFuelRegistry.coolant.addCoolant(fluid, degreesCoolingPerMB); } } @Override public IFluidCoolant getCoolant(Fluid fluid) { if(fluid != null && BuildcraftFuelRegistry.coolant != null) { ICoolant bcCool = BuildcraftFuelRegistry.coolant.getCoolant(fluid); if(bcCool != null) { return new CoolantBC(bcCool); } } return null; } @Override public IFluidCoolant getCoolant(FluidStack fluid) { if(fluid == null || fluid.getFluid() == null) { return null; } return getCoolant(fluid.getFluid()); } @Override public void addFuel(Fluid fluid, int powerPerCycleRF, int totalBurnTime) { if(BuildcraftFuelRegistry.fuel != null && BuildcraftFuelRegistry.fuel.getFuel(fluid) == null) { BuildcraftFuelRegistry.fuel.addFuel(fluid, powerPerCycleRF, totalBurnTime); } } @Override public IFluidFuel getFuel(Fluid fluid) { if(fluid == null) { return null; } if(BuildcraftFuelRegistry.fuel != null) { IFuel bcFuel = BuildcraftFuelRegistry.fuel.getFuel(fluid); if(bcFuel != null) { return new FuelBC(bcFuel); } } return null; } @Override public IFluidFuel getFuel(FluidStack fluid) { if(fluid == null || fluid.getFluid() == null) { return null; } return getFuel(fluid.getFluid()); } private static class FuelBC extends FuelImpl { FuelBC(IFuel fuel) { super(fuel.getFluid(), fuel.getPowerPerCycle(), fuel.getTotalBurningTime()); } } private static class CoolantBC extends CoolantImpl { CoolantBC(ICoolant coolant) { //NB: in the current BC impl the temperature to getDegreesCoolingPerMB is ignored super(coolant.getFluid(), coolant.getDegreesCoolingPerMB(100)); } } }
package cubicchunks.converter.lib.util; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; import cubicchunks.regionlib.api.region.IRegion; import cubicchunks.regionlib.api.region.IRegionProvider; import cubicchunks.regionlib.api.region.key.IKey; import cubicchunks.regionlib.api.region.key.IKeyProvider; import cubicchunks.regionlib.api.region.key.RegionKey; import cubicchunks.regionlib.lib.Region; import cubicchunks.regionlib.lib.RegionEntryLocation; import cubicchunks.regionlib.util.CheckedConsumer; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Optional; public class MemoryWriteRegion<K extends IKey<K>> implements IRegion<K> { private static final int SIZE_BITS = 8; private static final int OFFSET_BITS = Integer.SIZE - SIZE_BITS; private static final int SIZE_MASK = (1 << SIZE_BITS) - 1; private static final int MAX_SIZE = SIZE_MASK; private static final int OFFSET_MASK = (1 << OFFSET_BITS) - 1; private static final int MAX_OFFSET = OFFSET_MASK; private final SeekableByteChannel file; private final int sectorSize; private final int keyCount; private WriteEntry[] writeEntries; private MemoryWriteRegion(SeekableByteChannel file, RegionKey regionKey, IKeyProvider<K> keyProvider, int sectorSize) throws IOException { this.keyCount = keyProvider.getKeyCount(regionKey); this.file = file; this.sectorSize = sectorSize; } @Override public synchronized void writeValue(K key, ByteBuffer value) throws IOException { if (value == null) { return; } if (writeEntries == null) { writeEntries = new WriteEntry[keyCount]; if (file.size() >= keyCount * Integer.BYTES) { ByteBuffer fileBuffer = ByteBuffer.allocate((int) file.size()); file.position(0); file.read(fileBuffer); fileBuffer.clear(); for (int i = 0; i < keyCount; i++) { fileBuffer.limit(i * Integer.BYTES + Integer.BYTES); fileBuffer.position(i * Integer.BYTES); int loc = fileBuffer.getInt(); if (loc == 0) { continue; } int sizeBytes = unpackSize(loc) * sectorSize; ByteBuffer data = ByteBuffer.allocate(sizeBytes); int offsetBytes = unpackOffset(loc) * sectorSize; fileBuffer.limit(offsetBytes + sizeBytes); fileBuffer.position(offsetBytes); data.put(fileBuffer); writeEntries[i] = new WriteEntry(data); } } } int size = value.remaining(); int sizeWithSizeInfo = size + Integer.BYTES; int numSectors = getSectorNumber(sizeWithSizeInfo); ByteBuffer data = ByteBuffer.allocate(numSectors * sectorSize); data.putInt(size); data.put(value); writeEntries[key.getId()] = new WriteEntry(data); } @Override public void writeSpecial(K key, Object marker) throws IOException { throw new UnsupportedOperationException("writeSpecial not supported"); } @Override public synchronized Optional<ByteBuffer> readValue(K key) throws IOException { throw new UnsupportedOperationException("readValue not supported"); } /** * Returns true if something was stored there before within this region. */ @Override public synchronized boolean hasValue(K key) { throw new UnsupportedOperationException("hasValue not supported"); } @Override public void forEachKey(CheckedConsumer<? super K, IOException> cons) throws IOException { throw new UnsupportedOperationException("forEachKey not supported"); } private int getSectorNumber(int bytes) { return ceilDiv(bytes, sectorSize); } @Override public void close() throws IOException { ByteBuffer header = ByteBuffer.allocate(keyCount * Integer.BYTES); int writePos = ceilDiv(keyCount * Integer.BYTES, sectorSize); for (WriteEntry writeEntry : writeEntries) { if (writeEntry == null) { header.putInt(0); continue; } int sectorCount = ceilDiv(writeEntry.buffer.remaining(), sectorSize); header.putInt(packed(new RegionEntryLocation(writePos, sectorCount))); writePos += sectorCount; } file.position(0); file.write(header); for (WriteEntry writeEntry : writeEntries) { if (writeEntry == null) { continue; } file.write(writeEntry.buffer); } Arrays.fill(writeEntries, null); this.file.close(); } private static int ceilDiv(int x, int y) { return -Math.floorDiv(-x, y); } public static <L extends IKey<L>> Region.Builder<L> builder() { return new Region.Builder<>(); } private static int unpackOffset(int sectorLocation) { return sectorLocation >>> SIZE_BITS; } private static int unpackSize(int sectorLocation) { return sectorLocation & SIZE_MASK; } private static int packed(RegionEntryLocation location) { if ((location.getSize() & SIZE_MASK) != location.getSize()) { throw new IllegalArgumentException("Supported entry size range is 0 to " + MAX_SIZE + ", but got " + location.getSize()); } if ((location.getOffset() & OFFSET_MASK) != location.getOffset()) { throw new IllegalArgumentException("Supported entry offset range is 0 to " + MAX_OFFSET + ", but got " + location.getOffset()); } return location.getSize() | (location.getOffset() << SIZE_BITS); } private static class WriteEntry { final ByteBuffer buffer; private WriteEntry(ByteBuffer buffer) { this.buffer = buffer; } } /** * Internal Region builder. Using it is very unsafe, there are no safeguards against using it improperly. Should only be used by * {@link IRegionProvider} implementations. */ // TODO: make a safer to use builder public static class Builder<K extends IKey<K>> { private Path directory; private int sectorSize = 512; private RegionKey regionKey; private IKeyProvider<K> keyProvider; public MemoryWriteRegion.Builder<K> setDirectory(Path path) { this.directory = path; return this; } public MemoryWriteRegion.Builder<K> setRegionKey(RegionKey key) { this.regionKey = key; return this; } public MemoryWriteRegion.Builder<K> setKeyProvider(IKeyProvider<K> keyProvider) { this.keyProvider = keyProvider; return this; } public MemoryWriteRegion.Builder<K> setSectorSize(int sectorSize) { this.sectorSize = sectorSize; return this; } public MemoryWriteRegion<K> build() throws IOException { SeekableByteChannel file = Files.newByteChannel(directory.resolve(regionKey.getName()), CREATE, READ, WRITE); return new MemoryWriteRegion<>(file, this.regionKey, keyProvider, this.sectorSize); } } }
package distributed.systems.network.logging; import static java.util.stream.Collectors.toList; import java.util.List; import java.util.concurrent.TimeUnit; import distributed.systems.core.LogMessage; import distributed.systems.core.Message; import distributed.systems.das.units.Unit; import distributed.systems.network.Address; import distributed.systems.network.NodeAddress; import org.influxdb.InfluxDB; import org.influxdb.InfluxDBFactory; import org.influxdb.dto.Database; import org.influxdb.dto.Serie; public class InfluxLogger implements Logger { public static boolean FLAG_USE_INFLUX = true; private static final String DATABASE_DATA = "data"; private static final String DATABASE_GRAFANA = "grafana"; private final InfluxDB influxDB; private final Address databaseLocation; private final String username; private static InfluxLogger performanceLogging; public static InfluxLogger getInstance() { if(performanceLogging == null) { performanceLogging = new InfluxLogger(new Address("localhost", 8086), "root", "root"); } return performanceLogging; } public InfluxLogger(Address databaseLocation, String username, String password) { this.databaseLocation = databaseLocation; this.username = username; // Connect to influx InfluxDB temptInfluxDB = InfluxDBFactory.connect(databaseLocation.toString(), username, password); // Create required databases if they are not present try { List<String> databases = temptInfluxDB.describeDatabases().stream().map(Database::getName).collect(toList()); if (!databases.contains(DATABASE_DATA)) { temptInfluxDB.createDatabase(DATABASE_DATA); } if (!databases.contains(DATABASE_GRAFANA)) { temptInfluxDB.createDatabase(DATABASE_GRAFANA); } } catch(Exception e) { temptInfluxDB = null; } influxDB = temptInfluxDB; } public boolean checkConnection() { return (influxDB.ping().getStatus().equalsIgnoreCase("ok")); } public void logMessageDuration(Message message, NodeAddress messageHandler, long duration) { String origin = message.getOrigin() != null ? message.getOrigin().getName() : ""; Serie serie = new Serie.Builder("messagePerformance") .columns("duration", "messagetype", "messagehandler", "origin", "time","receivedtime") .values(duration, message.getMessageType(), messageHandler.getName(), origin, message.getTimestamp().getTime(), message.getReceivedTimestamp().getTime()) .build(); writeToInflux(serie); } @Override public void log(LogMessage message) { String origin = message.getOrigin() != null ? message.getOrigin().getName() : ""; Serie serie = new Serie.Builder("log") .columns("message","logtype","origin","time") .values(message.getLogMessage(), message.getLogType(), origin, message.getTimestamp().getTime()) .build(); writeToInflux(serie); } public void logUnitRoundDuration(Unit unit, NodeAddress server, long duration) { Serie serie = new Serie.Builder("unitRoundDuration") .columns("duration", "unit", "server", "time") .values(duration, unit.getUnitID(), server.getName(), System.currentTimeMillis()) .build(); writeToInflux(serie); } private void writeToInflux(Serie serie) { if(FLAG_USE_INFLUX && influxDB != null) { influxDB.write(DATABASE_DATA, TimeUnit.MILLISECONDS, serie); } } }
package ljdp.minechem.api.core; import static ljdp.minechem.api.core.EnumElement.*; import java.util.ArrayList; import java.util.Random; // import ljdp.minechem.api.recipe.DecomposerRecipe; // import ljdp.minechem.api.recipe.SynthesisRecipe; // Na2OLi2O(SiO2)2(B2O3)3H2O // MOLECULE IDS MUST BE CONTINIOUS OTHERWISE THE ARRAY WILL BE MISALIGNED. public enum EnumMolecule { cellulose(0, "Cellulose", 0, 1, 0, 0, 0.25F, 0, new Element(C, 6), new Element(H, 10), new Element(O, 5)), water(1, "Water", 0, 0, 1, 0, 0, 1, new Element(H, 2), new Element(O)), carbonDioxide(2, "Carbon Dioxide", 0.5F, 0.5F, 0.5F, 0.25F, 0.25F, 0.25F, new Element(C), new Element(O, 2)), nitrogenDioxide(3, "Nitrogen Dioxide", 1, 0.65F, 0, 0.5F, 0.1412F, 0.1843F, new Element(N), new Element(O, 2)), toluene(4, "Toluene", 1, 1, 1, 0.8F, 0.8F, 0.8F, new Element(C, 7), new Element(H, 8)), potassiumNitrate(5, "Potassium Nitrate", 0.9F, 0.9F, 0.9F, 0.8F, 0.8F, 0.8F, new Element(K), new Element(N), new Element(O, 3)), tnt(6, "Trinitrotoluene", new Element(C, 6), new Element(H, 2), new Molecule(nitrogenDioxide, 3), new Molecule(toluene)), siliconDioxide(7, "Silicon Dioxide", new Element(Si), new Element(O, 2)), calcite(8, "Calcite", new Element(Ca), new Element(C), new Element(O, 3)), pyrite(9, "Pyrite", new Element(Fe), new Element(S, 2)), nepheline(10, "Nepheline", new Element(Al), new Element(Si), new Element(O, 4)), sulfate(11, "Sulfate (ion)", new Element(S), new Element(O, 4)), noselite(12, "Noselite", new Element(Na, 8), new Molecule(nepheline, 6), new Molecule(sulfate)), sodalite(13, "Sodalite", new Element(Na, 8), new Molecule(nepheline, 6), new Element(Cl, 2)), nitrate(14, "Nitrate (ion)", new Element(N), new Element(O, 3)), carbonate(15, "Carbonate (ion)", new Element(C), new Element(O, 3)), cyanide(16, "Potassium Cyanide", new Element(K), new Element(C), new Element(N)), phosphate(17, "Phosphate (ion)", new Element(P), new Element(O, 4)), acetate(18, "Acetate (ion)", new Element(C, 2), new Element(H, 3), new Element(O, 2)), chromate(19, "Chromate (ion)", new Element(Cr), new Element(O, 4)), hydroxide(20, "Hydroxide (ion)", new Element(O), new Element(H)), ammonium(21, "Ammonium (ion)", new Element(N), new Element(H, 4)), hydronium(22, "Hydronium (ion)", new Element(H, 3), new Element(O)), peroxide(23, "Hydrogen Peroxide", new Element(H, 2), new Element(O, 2)), calciumOxide(24, "Calcium Oxide", new Element(Ca), new Element(O)), calciumCarbonate(25, "Calcium Carbonate", new Element(Ca), new Molecule(carbonate)), magnesiumCarbonate(26, "Magnesium Carbonate", new Element(Mg), new Molecule(carbonate)), lazurite(27, "Lazurite", new Element(Na, 8), new Molecule(nepheline), new Molecule(sulfate)), isoprene(28, "Isoprene", new Element(C, 5), new Element(H, 8)), butene(29, "Butene", new Element(C, 4), new Element(H, 8)), polyisobutylene(30, "Polyisobutylene Rubber", new Molecule(butene, 16), new Molecule(isoprene)), malicAcid(31, "Malic Acid", new Element(C, 4), new Element(H, 6), new Element(O, 5)), vinylChloride(32, "Vinyl Chloride Monomer", new Element(C, 2), new Element(H, 3), new Element(Cl)), polyvinylChloride(33, "Polyvinyl Chloride", new Molecule(vinylChloride, 64)), methamphetamine(34, "Methamphetamine", new Element(C, 10), new Element(H, 15), new Element(N)), psilocybin(35, "Psilocybin", new Element(C, 12), new Element(H, 17), new Element(N, 2), new Element(O, 4), new Element(P)), iron3oxide(36, "Iron (III) Oxide", new Element(Fe, 2), new Element(O, 3)), strontiumNitrate(37, "Strontium Nitrate", new Element(Sr), new Molecule(nitrate, 2)), magnetite(38, "Magnetite", new Element(Fe, 3), new Element(O, 4)), magnesiumOxide(39, "Magnesium Oxide", new Element(Mg), new Element(O)), cucurbitacin(40, "Cucurbitacin", new Element(C, 30), new Element(H, 42), new Element(O, 7)), asparticAcid(41, "Aspartic Acid", new Element(C, 4), new Element(H, 7), new Element(N), new Element(O, 4)), hydroxylapatite(42, "Hydroxylapatite", new Element(Ca, 5), new Molecule(phosphate, 3), new Element(O), new Element(H)), alinine(43, "Alinine (amino acid)", new Element(C, 3), new Element(H, 7), new Element(N), new Element(O, 2)), glycine(44, "Glycine (amino acid)", new Element(C, 2), new Element(H, 5), new Element(N), new Element(O, 2)), serine(45, "Serine (amino acid)", new Element(C, 3), new Element(H, 7), new Molecule(nitrate)), mescaline(46, "Mescaline", new Element(C, 11), new Element(H, 17), new Molecule(nitrate)), methyl(47, "Methyl (ion)", new Element(C), new Element(H, 3)), methylene(48, "Methylene (ion)", new Element(C), new Element(H, 2)), cyanoacrylate(49, "Cyanoacrylate", new Molecule(methyl), new Molecule(methylene), new Element(C, 3), new Element(N), new Element(H), new Element(O, 2)), polycyanoacrylate(50, "Poly-cyanoacrylate", new Molecule(cyanoacrylate, 3)), redPigment(51, "Cobalt(II) nitrate", new Element(Co), new Molecule(nitrate, 2)), orangePigment(52, "Potassium Dichromate", new Element(K, 2), new Element(Cr, 2), new Element(O, 7)), yellowPigment(53, "Potassium Chromate", new Element(Cr), new Element(K, 2), new Element(O, 4)), limePigment(54, "Nickel(II) Chloride", new Element(Ni), new Element(Cl, 2)), lightbluePigment(55, "Copper(II) Sulfate", new Element(Cu), new Molecule(sulfate)), purplePigment(56, "Potassium Permanganate", new Element(K), new Element(Mn), new Element(O, 4)), greenPigment(57, "Zinc Green", new Element(Co), new Element(Zn), new Element(O, 2)), blackPigment(58, "Carbon Black", new Element(C), new Element(H, 2), new Element(O)), whitePigment(59, "Titanium Dioxide", new Element(Ti), new Element(O, 2)), metasilicate(60, "Metasilicate", new Element(Si), new Element(O, 3)), beryl(61, "Beryl", new Element(Be, 3), new Element(Al, 2), new Molecule(metasilicate, 6)), ethanol(62, "Ethyl Alcohol", new Element(C, 2), new Element(H, 6), new Element(O)), amphetamine(63, "Amphetamine", new Element(C, 9), new Element(H, 13), new Element(N)), theobromine(64, "Theobromine", new Element(C, 7), new Element(H, 8), new Element(N, 4), new Element(O, 2)), starch(65, "Starch", new Molecule(cellulose, 2), new Molecule(cellulose, 1)), sucrose(66, "Sucrose", new Element(C, 12), new Element(H, 22), new Element(O, 11)), pantherine(67, "Pantherine", new Element(C, 4), new Element(H, 6), new Element(N, 2), new Element(O, 2)), //LJDP you fail! There is not enought muscarine in a shroom to cause harm! The main active chemical is Muscimol (Pantherine). This chemical is similar to benzodiazapines! aluminiumOxide(68, "Aluminium Oxide", new Element(Al, 2), new Element(O, 3)), fullrene(69, "Carbon Nanotubes", new Element(C, 64), new Element(C, 64), new Element(C, 64), new Element(C, 64)), keratin(70, "Keratin", new Element(C, 2), new Molecule(water), new Element(N)), penicillin(71, "Penicillin", new Element(C, 16), new Element(H, 18), new Element(N, 2), new Element(O, 4), new Element(S)), testosterone(72, "Testosterone", new Element(C, 19), new Element(H, 28), new Element(O, 2)), kaolinite(73, "Kaolinite", new Element(Al, 2), new Element(Si, 2), new Element(O, 5), new Molecule(hydroxide, 4)), fingolimod(74, "Fingolimod", new Element(C, 19), new Element(H, 33), new Molecule(nitrogenDioxide)), // LJDP, You ment to say fingolimod not myrocin. arginine(75, "Arginine (amino acid)", new Element(C, 6), new Element(H, 14), new Element(N, 4), new Element(O, 2)), shikimicAcid(76, "Shikimic Acid", new Element(C, 7), new Element(H, 10), new Element(O, 5)), sulfuricAcid(77, "Sulfuric Acid", new Element(H, 2), new Element(S), new Element(O, 4)), glyphosate(78, "Glyphosate", new Element(C, 3), new Element(H, 8), new Element(N), new Element(O, 5), new Element(P)), asprin(79, "Aspirin", new Element(C, 9), new Element(H, 8), new Element(O, 4)), ddt(80, "DDT", new Element(C, 14), new Element(H, 9), new Element(Cl, 5)), dota(81, "DOTA", new Element(C, 16), new Element(H, 28), new Element(N, 4), new Element(O, 8)), poison(82, "T-2 Mycotoxin", new Element(C, 24), new Element(H, 34), new Element(O, 9)), salt(83, "Salt", new Element(Na, 1), new Element(Cl, 1)), nhthree(84, "Ammonia", new Element(N, 1), new Element(H, 3)), nod(85, "Nodularin", new Element(C, 41), new Element(H, 60), new Element(N, 8), new Element(O, 10)), ttx(86, "TTX (Tetrodotoxin)", new Element(C, 11), new Element(H, 11), new Element(N, 3), new Element(O, 8)), afroman(87, "THC", new Element(C, 21), new Element(H, 30), new Element(O, 2)), mt(88, "Methylcyclopentadienyl Manganese Tricarbonyl", new Element(C, 9), new Element(H, 7), new Element(Mn, 1), new Element(O, 3)), // Level 1 buli(89, "Tert-Butyllithium", new Element(Li, 1), new Element(C, 4), new Element(H, 9)), // Level 2 plat(90, "Chloroplatinic acid", new Element(H, 2), new Element(Pt, 1), new Element(Cl, 6)), // Level 3 phosgene(91, "Phosgene", new Element(C, 1), new Element(O, 1), new Element(Cl, 2)), aalc(92, "Allyl alcohol", new Element(C, 3), new Element(H, 6), new Element(O, 1)), hist(93, "Diphenhydramine", new Element(C, 17), new Element(H, 21), new Element(N), new Element(O)), pal2(94, "Batrachotoxin", new Element(C, 31), new Element(H, 42), new Element(N, 2), new Element(O, 6)), ret(95, "Retinol", new Element(C, 20), new Element(H, 30), new Element(O)), stevenk(96, "Xylitol", new Element(C, 5), new Element(H, 12), new Element(O, 5)), weedex(97, "Aminocyclopyrachlor", new Element(C,8), new Element(H,8), new Element(Cl), new Element(N,3), new Element(O,2)), biocide(98, "Ptaquiloside", new Element(C, 20), new Element(H, 30), new Element(O, 8)), xanax(99, "Alprazolam", new Element(C,17), new Element(H,13), new Element(Cl), new Element(N,4)), hcl(100, "Hydrogen Chloride", new Element(H), new Element(Cl)), redrocks(101, "Cocaine", new Element(C,17), new Element(H,21), new Element(N), new Element(O,4)), coke(102, "Cocaine Hydrochloride", new Molecule(redrocks), new Molecule(hcl)), blueorgodye(103, "1,4-dimethyl-7-isopropylazulene (Guaiazulene)", new Element(C,15), new Element(H,18)), redorgodye(104, "Pelargonidin", new Element(C,15), new Element(H,11), new Element(O,11)), purpleorgodye(105, "Delphinidin", new Element(C,15), new Element(H,11), new Element(O,7)), olivine(106, "Olivine", new Element(Fe,2), new Element(Si), new Element(O,4)), metblue(107, "Methylene Blue", new Element(C,16), new Element(H,18), new Element(N,3), new Element(S), new Element(Cl)), meoh(108, "Methyl Alcohol", new Molecule(methyl), new Molecule(hydroxide)), nicotine(109, "Nicotine", new Element(C,10), new Element(H,14), new Element(N,2)) ; public static EnumMolecule[] molecules = values(); private final String descriptiveName; private final ArrayList<Chemical> components; private int id; public float red; public float green; public float blue; public float red2; public float green2; public float blue2; EnumMolecule(int id, String descriptiveName, float colorRed, float colorGreen, float colorBlue, float colorRed2, float colorGreen2, float colorBlue2, Chemical... chemicals) { this.id = id; this.components = new ArrayList<Chemical>(); this.descriptiveName = descriptiveName; for (Chemical chemical : chemicals) { this.components.add(chemical); } Random random = new Random(id); this.red = colorRed; this.green = colorGreen; this.blue = colorBlue; this.red2 = colorRed2; this.green2 = colorGreen2; this.blue2 = colorBlue2; } @Deprecated EnumMolecule(int id, String descriptiveName, Chemical... chemicals) { this(id, descriptiveName, 0.545f, 0.2705f, 0.0745f, 0, 0, 0, chemicals); // Your molecule will literally look like shit until you give it a proper color code. } public static EnumMolecule getById(int id) { for (EnumMolecule molecule : molecules) { if (molecule.id == id) return molecule; } return null; } public int id() { return this.id; } public String descriptiveName() { return this.descriptiveName; } public ArrayList<Chemical> components() { return this.components; } }
package net.coobird.thumbnailator.filters; import java.awt.image.BufferedImage; /** * This interface is to be implemented by classes which performs an image * filtering operation on a {@link BufferedImage}. * <p> * The general contract for classes implementing {@link ImageFilter} is that * they should not change the contents of the {@link BufferedImage} which is * given as the argument for the {@link #apply(BufferedImage)} method. * <p> * The filter should make a copy of the given {@link BufferedImage}, and * perform the filtering operations on the copy, then return the copy. * * @author coobird * */ public interface ImageFilter { /** * Applies a image filtering operation on an image. * * @param img The image to apply the filtering on. * @return The resulting image after applying this filter. */ public BufferedImage apply(BufferedImage img); }
//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, //permit persons to whom the Software is furnished to do so, subject to //the following conditions: //in all copies or substantial portions of the Software. //EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. //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 net.kenevans.android.misc; import java.io.InputStream; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * Class to display a single message. */ public class DisplayCallActivity extends Activity implements IConstants { /** Set this to not make any changes to the database. */ private boolean dryRun = false; /** The Uri to use. */ public Uri uri; private TextView mTitleTextView; private TextView mSubtitleTextView; private TextView mContactTextView; private ImageView mImageView; private Long mRowId; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.displaycall); // Get the saved state // SharedPreferences prefs = getPreferences(MODE_PRIVATE); mTitleTextView = (TextView) findViewById(R.id.titleview); mSubtitleTextView = (TextView) findViewById(R.id.subtitleview); mContactTextView = (TextView) findViewById(R.id.contactview); mImageView = (ImageView) findViewById(R.id.imageview); // mSubtitleTextView.setMovementMethod(new ScrollingMovementMethod()); // mContactTextView.setMovementMethod(new ScrollingMovementMethod()); mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(COL_ID); Bundle extras = getIntent().getExtras(); if (mRowId == null && extras != null) { mRowId = extras.getLong(COL_ID); } if (extras != null) { String uriPath = extras.getString(URI_KEY); if (uriPath != null) { uri = Uri.parse(uriPath); } } if (uri == null) { Utils.errMsg(this, "Null content provider database Uri"); return; } mRowId = extras != null ? extras.getLong(COL_ID) : null; // Call refresh to set the contents refresh(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.displaycallsmenu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.prev: navigate(RESULT_PREV); return true; case R.id.next: navigate(RESULT_NEXT); return true; case R.id.delete: deleteCall(); return true; } return false; } @Override protected void onPause() { super.onPause(); // Retain the offset so the user can use it again // SharedPreferences.Editor editor = // getPreferences(MODE_PRIVATE).edit(); // editor.putInt("timeOffset", lastTimeOffset); // editor.putBoolean("dryrun", dryRun); // editor.commit(); } @Override protected void onResume() { // Restore the offset so the user can use it again super.onResume(); // SharedPreferences prefs = getPreferences(MODE_PRIVATE); // lastTimeOffset = prefs.getInt("timeOffset", lastTimeOffset); // dryRun = prefs.getBoolean("dryrun", dryRun); } /** * Gets a bitmap of a contact photo * * @param cr * @param id * @return */ public static Bitmap loadContactPhoto(ContentResolver cr, long id) { if (id < 0 || cr == null) { return null; } Uri uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, id); InputStream input = ContactsContract.Contacts .openContactPhotoInputStream(cr, uri); if (input == null) { return null; } return BitmapFactory.decodeStream(input); } /** * Gets a String representation for the given Phone type. * * @param type * One of the ContactsContract.CommonDataKinds.Phone.TYPE_xxx * types. * @return */ public static String getPhoneType(int type) { String stringType = null; switch (type) { case ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT: stringType = "Assistant"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK: stringType = "Callback"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_CAR: stringType = "Car"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN: stringType = "Company Main"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME: stringType = "Fax Home"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK: stringType = "Fax Work"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_HOME: stringType = "Home"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_ISDN: stringType = "ISDN"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_MAIN: stringType = "Main"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_MMS: stringType = "MMS"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE: stringType = "Mobile"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER: stringType = "Other"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX: stringType = "Other Fax"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_PAGER: stringType = "Pager"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_RADIO: stringType = "Radio"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_TELEX: stringType = "TELEX"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD: stringType = "TTY TDD"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_WORK: stringType = "Work"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE: stringType = "Work Mobile"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER: stringType = "Work Pager"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM: stringType = "Custom"; break; default: stringType = "Type " + type; } return stringType; } /** * Gets a String representation for the Email given type. * * @param type * One of the ContactsContract.CommonDataKinds.Email.TYPE_xxx * types. * @return */ public static String getEmailType(int type) { String stringType = null; switch (type) { case ContactsContract.CommonDataKinds.Email.TYPE_HOME: stringType = "Home"; break; case ContactsContract.CommonDataKinds.Email.TYPE_MOBILE: stringType = "Mobile"; break; case ContactsContract.CommonDataKinds.Email.TYPE_WORK: stringType = "Work"; break; case ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM: stringType = "Custom"; break; case ContactsContract.CommonDataKinds.Email.TYPE_OTHER: stringType = "Other"; break; default: stringType = "Type " + type + ""; } return stringType; } /** * Get contact information about the given name. * * @param name * @return The information or null on failure. */ private String getContactInfo(String name) { if (name == null || name.length() == 0) { return null; } String info = "Contact Information for " + name + "\n"; String selection = ContactsContract.Contacts.DISPLAY_NAME + "=\"" + name + "\""; Cursor cursor = getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, null, selection, null, null); if (cursor.getCount() == 0) { info += name + " not found\n"; return info; } int indexId = cursor.getColumnIndex(COL_ID); int indexDisplayName = cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); int indexPhotoId = cursor .getColumnIndex(ContactsContract.Contacts.PHOTO_ID); // int indexTmesContacted = cursor // .getColumnIndex(ContactsContract.Contacts.TIMES_CONTACTED); // int indexLastTimeContacted = cursor // .getColumnIndex(ContactsContract.Contacts.LAST_TIME_CONTACTED); cursor.moveToNext(); String id = cursor.getString(indexId); info += "_id: " + id + "\n"; String photoId = "Not found"; if (indexPhotoId > -1) { photoId = cursor.getString(indexPhotoId); if (photoId == null) { photoId = "Not found"; } } info += ContactsContract.Contacts.PHOTO_ID + ": " + photoId + "\n"; String displayName = "Not found"; if (indexDisplayName > -1) { displayName = cursor.getString(indexDisplayName); if (displayName == null) { displayName = "Not found"; } } // These are not kept track of on the EVO 3D // info += ContactsContract.Contacts.DISPLAY_NAME + ": " + displayName // String timesContacted = "Not found"; // if (indexTmesContacted > -1) { // timesContacted = cursor.getString(indexTmesContacted); // if (timesContacted == null) { // timesContacted = "Not found"; // info += ContactsContract.Contacts.TIMES_CONTACTED + ": " // + timesContacted + "\n"; // String lastTimeContacted = "Not found"; // if (indexTmesContacted > -1) { // lastTimeContacted = cursor.getString(indexTmesContacted); // if (lastTimeContacted == null) { // lastTimeContacted = "Not found"; // info += ContactsContract.Contacts.LAST_TIME_CONTACTED + ": " // + lastTimeContacted + "\n"; // Phones info += "Phones:\n"; if (Integer.parseInt(cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { Cursor pCursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null); while (pCursor.moveToNext()) { String phoneNumber = pCursor .getString(pCursor .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); int phoneType = pCursor .getInt(pCursor .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)); info += " " + getPhoneType(phoneType) + ": " + phoneNumber + "\n"; } pCursor.close(); } // Email info += "Email Addresses:\n"; Cursor emailCur = getContentResolver().query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null); while (emailCur.moveToNext()) { // This would allow you get several email addresses // if the email addresses were stored in an array String email = emailCur .getString(emailCur .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); int emailType = emailCur .getInt(emailCur .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); info += " " + getEmailType(emailType) + ": " + email + "\n"; } emailCur.close(); cursor.close(); return info; } /** * Gets the id for the given name. * * @param name * @return The id or -1 on failure. */ private long getContactId(String name) { if (name == null || name.length() == 0) { return -1; } String selection = ContactsContract.Contacts.DISPLAY_NAME + "=\"" + name + "\""; String[] desiredColumns = { COL_ID, }; Cursor cursor = getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, desiredColumns, selection, null, null); if (cursor.getCount() == 0) { return -1; } int indexId = cursor.getColumnIndex(COL_ID); cursor.moveToNext(); long id = cursor.getLong(indexId); cursor.close(); return id; } /** * Sets the result code to send back to the calling Activity. One of: * <ul> * <li>RESULT_PREV * <li>RESULT_NEXT * </ul> * * @param resultCode * The result code to send. */ private void navigate(int resultCode) { setResult(resultCode); finish(); } /** * Deletes the message and navigates to the next message. */ private void deleteCall() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage( "Are you sure you want to delete " + "this call from the call log database? " + "It cannot be undone.") .setCancelable(false) .setPositiveButton(getText(R.string.yes_label), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (dryRun) { Toast.makeText(getApplicationContext(), "Dry run:\n" + "Message deleted", Toast.LENGTH_LONG).show(); navigate(RESULT_NEXT); } else { try { // The following change the database getContentResolver().delete(uri, "_id = " + mRowId, null); navigate(RESULT_NEXT); // This was used temporarily to change // one record // ContentValues values = new // ContentValues(); // values.put(COL_NAME, "Susan Semrod"); // Long idd = 790l; // getContentResolver().update(uri, // values, // "_id = " + idd, null); } catch (Exception ex) { Utils.excMsg(DisplayCallActivity.this, "Problem deleting call", ex); } } } }) .setNegativeButton(getText(R.string.cancel_label), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } /** * Gets a new cursor and redraws the view. Closes the cursor after it is * done with it. */ private void refresh() { try { // Only get the row with mRowId String selection = COL_ID + "=" + mRowId.longValue(); // First get the names of all the columns in the database Cursor cursor = getContentResolver().query(uri, null, selection, null, null); String[] columns = cursor.getColumnNames(); cursor.close(); // Then get the columns for this row String sort = COL_DATE + " DESC"; cursor = getContentResolver().query(uri, columns, selection, null, sort); int indexId = cursor.getColumnIndex(COL_ID); int indexDate = cursor.getColumnIndex(COL_DATE); int indexNumber = cursor.getColumnIndex(COL_NUMBER); int indexDuration = cursor.getColumnIndex(COL_DURATION); int indexType = cursor.getColumnIndex(COL_TYPE); int indexName = cursor.getColumnIndex(COL_NAME); Log.d(TAG, this.getClass().getSimpleName() + ".refresh: " + " mRowId=" + mRowId + " uri=" + uri.toString()); // There should only be one row returned, the last will be the most // recent if more are returned owing to the sort above boolean found = cursor.moveToFirst(); if (!found) { mTitleTextView.setText("<Error>"); mSubtitleTextView.setText(""); } else { String id = cursor.getString(indexId); String number = "<Number NA>"; if (indexNumber > -1) { number = cursor.getString(indexNumber); } Long dateNum = -1L; if (indexDate > -1) { dateNum = cursor.getLong(indexDate); } String duration = "<Duration NA>"; if (indexDuration > -1) { duration = cursor.getString(indexDuration); } int type = -1; if (indexType > -1) { type = cursor.getInt(indexType); } String name = "Unknown"; if (indexName > -1) { name = cursor.getString(indexName); if (name == null) { name = "Unknown"; } } String title = id; // Indicate if more than one found if (cursor.getCount() > 1) { title += " [1/" + cursor.getCount() + "]"; } title += ": " + SMSActivity.formatAddress(number) + " (" + CallHistoryActivity.formatType(type) + ") " + name + "\n" + SMSActivity.formatDate(CallHistoryActivity.formatter, dateNum) + " Duration: " + CallHistoryActivity.formatDuration(duration); String subTitle = ""; Log.d(TAG, getClass().getSimpleName() + ".refresh" + " id=" + id + " address=" + number + " dateNum=" + dateNum); // Add all the fields in the database for (String colName : columns) { try { int index = cursor.getColumnIndex(colName); // Don't do a LF the first time if (subTitle.length() != 0) { subTitle += "\n"; } // Don't print the body if (colName.equals("body")) { subTitle += colName + ": <" + cursor.getString(index).length() + " chars>"; } else { subTitle += colName + ": " + cursor.getString(index); } } catch (Exception ex) { // Shouldn't happen subTitle += colName + ": Not found"; } } // Set the TextViews mTitleTextView.setText(title); mSubtitleTextView.setText(subTitle); // Set the contact view if (mContactTextView != null) { String contactInfo = null; if (name != null && name.length() > 0) { contactInfo = getContactInfo(name); } else { contactInfo = "Unknown Contact"; } if (contactInfo != null) { mContactTextView.setText(contactInfo); } } // Set the image view if (mImageView != null) { long contactId = getContactId(name); Bitmap bitmap = loadContactPhoto(getContentResolver(), contactId); if (bitmap == null) { // bitmap = // BitmapFactory.decodeFile("/sdcard/test2.png"); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android_icon); } if (bitmap != null) { mImageView.setImageBitmap(bitmap); } } } // We are through with the cursor cursor.close(); } catch (Exception ex) { Utils.excMsg(this, "Error finding message", ex); if (mTitleTextView != null) { mTitleTextView.setText("<Error>"); } if (mSubtitleTextView != null) { mSubtitleTextView.setText(""); } } } }
package edu.stanford.bmir.styledstring.html; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import edu.stanford.bmir.styledstring.Style; import edu.stanford.bmir.styledstring.StyledString; import edu.stanford.bmir.styledstring.StyledStringMarkup; import edu.stanford.bmir.styledstring.attributes.StyleAttribute; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.*; /** * Matthew Horridge * Stanford Center for Biomedical Informatics Research * 05/12/14 */ public class HtmlRenderer { public String toHTML(StyledString styledString) { StringWriter sw = new StringWriter(); renderIntoHTML(sw, styledString); return sw.getBuffer().toString(); } private void renderIntoHTML(Writer writer, StyledString styledString) { StringBuilder pw = new StringBuilder(); List<StyledStringMarkup> sortedMarkups = new ArrayList<StyledStringMarkup>(styledString.getMarkup()); Collections.sort(sortedMarkups); Set<Style> currentStyles = Sets.newHashSet(); List<Integer> runLimits = Lists.newArrayList(); for (int i = 0; i < styledString.length(); i++) { Set<Style> iStyles = Sets.newHashSet(); for (StyledStringMarkup markup : sortedMarkups) { if (markup.getStart() <= i && i < markup.getEnd()) { iStyles.add(markup.getStyle()); } } if (!iStyles.equals(currentStyles) || styledString.charAt(i) == '\n') { runLimits.add(i); currentStyles.clear(); currentStyles.addAll(iStyles); } } runLimits.add(styledString.length()); int lastLimit = 0; for (Integer runLimit : runLimits) { List<StyleAttribute> styleAttributes = styledString.getMergedStyle(runLimit - 1).getStyleAttributes(); if (!styleAttributes.isEmpty()) { pw.append("<span style=\""); for (StyleAttribute styleAttribute : styleAttributes) { String propName = styleAttribute.getCssPropertyName(); String propValue = styleAttribute.getCssPropertyValue(); pw.append(propName); pw.append(": "); pw.append(propValue); pw.append("; "); } pw.append("\">"); } String substring = styledString.substring(lastLimit, runLimit).getString(); pw.append(substring); if (!styleAttributes.isEmpty()) { pw.append("</span>"); } lastLimit = runLimit; } String[] lines = pw.toString().split("\\n"); PrintWriter p = new PrintWriter(writer); p.append("<div\">"); for (String line : lines) { if (!line.equals("\n")) { p.append("<div class=\"line\">\n"); p.append(line.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")); p.append("\n"); p.append("</div>\n"); } } p.append("</div>"); p.flush(); } }
package edu.vt.middleware.crypt.x509.types; /** * Describes the registered values of AttributeType that may appear in a * RelativeDistinguishedName (RDN) as defined in section 2 of RFC 2253. * * <p>Enumeration values include attributes likely to appear in an X.509 RDN, * which were obtained from the following sources:</p> * * <ul> * <li>RFC 4519 Lightweight Directory Access Protocol (LDAP): Schema for User * Applications</li> * <li>RFC 4524 COSINE LDAP/X.500 Schema</li> * <li>PKCS #9 v2.0: Selected Object Classes and Attribute Types</li> * </ul> * * @author Middleware Services * @version $Revision: 578 $ */ public enum AttributeType { /** CN - RFC 4519 section 2.3. */ CommonName("2.5.4.3", "CN"), /** C - RFC 4519 section 2.2. */ CountryName("2.5.4.6", "C"), /** DNQUALIFIER - RFC 4519 section 2.8. */ DnQualifier("2.5.4.46", "DNQUALIFIER"), /** DC - RFC 4519 section 2.4. */ DomainComponent("0.9.2342.19200300.100.1.25", "DC"), /** Email address - PKCS#9 v2.0 section B.3.5. */ EmailAddress("1.2.840.113549.1.9.1", "EMAILADDRESS"), /** GenerationQualifier - RFC 4519 section 2.11. */ GenerationQualifier("2.5.4.44", "GENERATIONQUALIFIER"), /** GIVENNAME - RFC 4519 section 2.12. */ GivenName("2.5.4.42", "GIVENNAME"), /** INITIALS - RFC 4519 section 2.14. */ Initials("2.5.4.43", "INITIALS"), /** L - RFC 4519 section 2.16. */ LocalityName("2.5.4.7", "L"), /** MAIL - RFC 4524 section 2.16. */ Mail("0.9.2342.19200300.100.1.3", "MAIL"), /** NAME - RFC 4519 section 2.18. */ Name("2.5.4.41", "NAME"), /** O - RFC 4519 section 2.19. */ OrganizationName("2.5.4.10", "O"), /** OU - RFC 4519 section 2.20. */ OrganizationalUnitName("2.5.4.11", "OU"), /** POSTALADDRESS - RFC 4519 section 2.23. */ PostalAddress("2.5.4.16", "POSTALADDRESS"), /** POSTALCODE - RFC 4519 section 2.24. */ PostalCode("2.5.4.17", "POSTALCODE"), /** POSTOFFICEBOX - RFC 4519 section 2.25. */ PostOfficeBox("2.5.4.18", "POSTOFFICEBOX"), /** SERIALNUMBER - RFC 4519 section 2.31. */ SerialNumber("2.5.4.5", "SERIALNUMBER"), /** ST - RFC 4519 section 2.33. */ StateOrProvinceName("2.5.4.8", "ST"), /** STREET - RFC 4519 section 2.34. */ StreetAddress("2.5.4.9", "STREET"), /** SN - RFC 4519 section 2.32. */ Surname("2.5.4.4", "SN"), /** TITLE - RFC 4519 section 2.38. */ Title("2.5.4.12", "TITLE"), /** UNIQUEIDENTIFIER - RFC 4524 section 2.24. */ UniqueIdentifier("0.9.2342.19200300.100.1.44", "UNIQUEIDENTIFIER"), /** UID - RFC 4519 section 2.39. */ UserId("0.9.2342.19200300.100.1.1", "UID"); /** OID of RDN attribute type. */ private String oid; /** Display string of the type in an RDN. */ private String name; /** * Creates a new type for the given OID. * * @param attributeTypeOid OID of attribute type. * @param shortName Registered short name for the attribute type. */ AttributeType(final String attributeTypeOid, final String shortName) { oid = attributeTypeOid; name = shortName; } /** @return OID of attribute type. */ public String getOid() { return oid; } /** @return Registered short name of attribute type. */ public String getName() { return name; } public static AttributeType fromOid(final String oid) { for (AttributeType t : AttributeType.values()) { if (t.getOid().equals(oid)) { return t; } } throw new IllegalArgumentException("Unknown AttributeType for OID " + oid); } public static AttributeType fromName(final String name) { for (AttributeType t : AttributeType.values()) { if (t.getName().equals(name)) { return t; } } throw new IllegalArgumentException( "Unknown AttributeType for name " + name); } }
package net.mossan.java.reversi.component; import javax.swing.*; import java.awt.*; public class BoardDrawer extends JPanel { private final int CELL_SIZE; private final int BOARD_ROWS; private final int LEFT_RIGHT_MARGIN; private final int TOP_BOTTOM_MARGIN; private final int BOARD_SIZE; private final JFrame window; public BoardDrawer(final int board_rows, final int cell_size, final String window_title) { // Arguments Check assert board_rows > 0 && board_rows % 2 == 0 : "board rows must be greater than 0 and divisible by 2."; assert cell_size > 0 : "cell size must be greater than 0."; // Board Settings this.CELL_SIZE = cell_size; this.BOARD_ROWS = board_rows; this.BOARD_SIZE = CELL_SIZE * BOARD_ROWS; // Create Window Frame this.window = new JFrame(); this.window.getContentPane().add(this); this.window.getContentPane().setPreferredSize(new Dimension(CELL_SIZE + BOARD_SIZE, CELL_SIZE + BOARD_SIZE)); this.window.setLocationRelativeTo(null); this.window.setResizable(false); this.window.setTitle(window_title); this.window.setBackground(Color.BLACK); this.window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.window.pack(); this.window.setVisible(true); // Calculate Margin this.LEFT_RIGHT_MARGIN = (this.window.getContentPane().getWidth() - BOARD_SIZE) / 2; this.TOP_BOTTOM_MARGIN = (this.window.getContentPane().getHeight() - BOARD_SIZE) / 2; } public void paintComponent(Graphics g) { // Create Buffer Image Image buffer_image = createImage(this.window.getContentPane().getWidth(), this.window.getContentPane().getHeight()); Graphics2D buffer_graphics = (Graphics2D) buffer_image.getGraphics(); // Set Rendering Options buffer_graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); buffer_graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // Fill Board Background buffer_graphics.setColor(new Color(40, 128, 40)); buffer_graphics.fillRect(LEFT_RIGHT_MARGIN, TOP_BOTTOM_MARGIN, BOARD_SIZE, BOARD_SIZE); // Draw Board Lines buffer_graphics.setColor(Color.BLACK); for (int i = 1; i < BOARD_ROWS; i++) { // Horizontal Lines buffer_graphics.drawLine( LEFT_RIGHT_MARGIN, TOP_BOTTOM_MARGIN + CELL_SIZE * i, LEFT_RIGHT_MARGIN + CELL_SIZE * BOARD_ROWS, TOP_BOTTOM_MARGIN + CELL_SIZE * i ); // Vertical Lines buffer_graphics.drawLine( LEFT_RIGHT_MARGIN + CELL_SIZE * i, TOP_BOTTOM_MARGIN, LEFT_RIGHT_MARGIN + CELL_SIZE * i, TOP_BOTTOM_MARGIN + CELL_SIZE * BOARD_ROWS ); } // Draw Buffer Image to Panel g.drawImage(buffer_image, 0, 0, this); } }
package net.sf.jaer.eventio.ros; import com.github.swrirobotics.bags.reader.BagFile; import com.github.swrirobotics.bags.reader.BagReader; import com.github.swrirobotics.bags.reader.TopicInfo; import com.github.swrirobotics.bags.reader.exceptions.BagReaderException; import com.github.swrirobotics.bags.reader.exceptions.UninitializedFieldException; import com.github.swrirobotics.bags.reader.messages.serialization.ArrayType; import com.github.swrirobotics.bags.reader.messages.serialization.BoolType; import com.github.swrirobotics.bags.reader.messages.serialization.Field; import com.github.swrirobotics.bags.reader.messages.serialization.Float32Type; import com.github.swrirobotics.bags.reader.messages.serialization.Float64Type; import com.github.swrirobotics.bags.reader.messages.serialization.Int32Type; import com.github.swrirobotics.bags.reader.messages.serialization.MessageType; import com.github.swrirobotics.bags.reader.messages.serialization.TimeType; import com.github.swrirobotics.bags.reader.messages.serialization.UInt16Type; import com.github.swrirobotics.bags.reader.messages.serialization.UInt32Type; import com.google.common.collect.HashMultimap; import eu.seebetter.ini.chips.davis.DavisBaseCamera; import eu.seebetter.ini.chips.davis.imu.IMUSample; import eu.seebetter.ini.chips.davis.imu.IMUSampleType; import java.awt.Point; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.BufferedInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.FileChannel; import java.sql.Timestamp; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ProgressMonitor; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEFileInputStreamInterface; import net.sf.jaer.eventio.AEInputStream; import org.apache.commons.lang3.mutable.MutableBoolean; public class RosbagFileInputStream implements AEFileInputStreamInterface, RosbagTopicMessageSupport { private static final Logger log = Logger.getLogger("RosbagFileInputStream"); private final PropertyChangeSupport support = new PropertyChangeSupport(this); /** * File name extension for ROS bag files, excluding ".", i.e. "bag". Note * this lack of . is different than for AEDataFile.DATA_FILE_EXTENSION. */ public static final String DATA_FILE_EXTENSION = "bag"; // for converting ROS units to jAER units private static final float DEG_PER_RAD = 180f / (float) Math.PI, G_PER_MPS2 = 1 / 9.8f; /** * The AEChip object associated with this stream. This field was added for * supported jAER 3.0 format files to support translating bit locations in * events. */ private AEChip chip = null; private File file = null; BagFile bagFile = null; // the most recently read event timestamp and the largest one read so far in this playback cycle private int mostRecentTimestamp, largestTimestampReadSinceRewind = Integer.MIN_VALUE; // first and last timestamp in the entire recording private long firstTimestampUs, lastTimestampUs; private double startAbsoluteTimeS, endAbsoluteTimeS, durationS; private Timestamp startAbsoluteTimestamp; private long firstTimestampUsAbsolute; // the absolute (ROS) first timestamp in us private boolean firstTimestampWasRead = false; // marks the present read time for packets private int currentStartTimestamp; private final ApsDvsEventPacket<ApsDvsEvent> eventPacket; private AEPacketRaw aePacketRawBuffered = new AEPacketRaw(), aePacketRawOutput = new AEPacketRaw(), aePacketRawTmp = new AEPacketRaw(); private AEPacketRaw emptyPacket = new AEPacketRaw(); private int nextMessageNumber = 0, numMessages = 0; private long absoluteStartingTimeMs = 0; // in system time since 1970 in ms /** * The ZoneID of this file; for ROS bag files there is no recorded time zone * so the zoneId is systemDefault() */ private ZoneId zoneId = ZoneId.systemDefault(); private FileChannel channel = null; // private static final String[] TOPICS = {"/dvs/events"};\ private static final String RPG_TOPIC_HEADER = "/dvs/", MVSEC_TOPIC_HEADER = "/davis/left/"; // TODO arbitrarily choose left camera for MVSEC for now private static final String TOPIC_EVENTS = "events", TOPIC_IMAGE = "image_raw", TOPIC_IMU = "imu", TOPIC_EXPOSURE = "exposure"; private static String[] STANARD_TOPICS = {TOPIC_EVENTS, TOPIC_IMAGE/*, TOPIC_IMU, TOPIC_EXPOSURE*/}; // tobi 4.1.21 commented out the IMU and EXPOSURE (never seen) topics since they cause problems with nonmonotonic timestamps in the MVSEC recrordings. Cause unknown. TODO fix IMU reading. // private static String[] TOPICS = {TOPIC_HEADER + TOPIC_EVENTS, TOPIC_HEADER + TOPIC_IMAGE}; private ArrayList<String> topicList = new ArrayList(); private ArrayList<String> topicFieldNames = new ArrayList(); private boolean wasIndexed = false; private List<BagFile.MessageIndex> msgIndexes = new ArrayList(); private HashMultimap<String, PropertyChangeListener> msgListeners = HashMultimap.create(); private boolean firstReadCompleted = false; private ArrayList<String> extraTopics = null; // extra topics that listeners can subscribe to private String rosbagInfoString = null; private boolean nonMonotonicTimestampExceptionsChecked = true; private boolean nonMonotonicTimestampDetected = false; // flag set by nonmonotonic timestamp if detection enabled private boolean rewindFlag = false; // FIFOs to buffer data so that we only let out data from any stream if there is definitely later data from both other streams private MutableBoolean hasDvs = new MutableBoolean(false), hasAps = new MutableBoolean(false), hasImu = new MutableBoolean(false); // flags to say what data is in this stream private long lastDvsTimestamp = 0, lastApsTimestamp = 0, lastImuTimestamp = 0; // used to check monotonicity private AEFifo dvsFifo = new AEFifo(), apsFifo = new AEFifo(), imuFifo = new AEFifo(); private MutableBoolean[] hasDvsApsImu = {hasDvs, hasAps, hasImu}; private AEFifo[] aeFifos = {dvsFifo, apsFifo, imuFifo}; private int MAX_RAW_EVENTS_BUFFER_SIZE = 1000000; private enum RosbagFileType { RPG(RPG_TOPIC_HEADER), MVSEC(MVSEC_TOPIC_HEADER), Unknown("???"); private String header; private RosbagFileType(String header) { this.header = header; } } // two types of topics depending on format of rosbag RosbagFileType rosbagFileType = RosbagFileType.Unknown; /** * Interval for logging warnings about nonmonotonic timestamps. */ public static final int NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL = 1000000; private int nonmonotonicTimestampCounter = 0; private int lastExposureUs; // holds last exposure value (in us?) to use for creating SOE and EOE events for frames private int markIn = 0; private int markOut; private boolean repeatEnabled = true; /** * Makes a new instance for a file and chip. A progressMonitor can pop up a * dialog for the long indexing operation * * @param f the file * @param chip the AEChip * @param progressMonitor an optional ProgressMonitor, set to null if not * desired * @throws BagReaderException * @throws java.lang.InterruptedException if constructing the stream which * requires indexing the topics takes a long time and the operation is * canceled */ public RosbagFileInputStream(File f, AEChip chip, ProgressMonitor progressMonitor) throws BagReaderException, InterruptedException { this.eventPacket = new ApsDvsEventPacket<>(ApsDvsEvent.class); setFile(f); this.chip = chip; log.info("reading rosbag file " + f + " for chip " + chip); bagFile = BagReader.readFile(file); StringBuilder sb = new StringBuilder("Bagfile information:\n"); for (TopicInfo topic : bagFile.getTopics()) { sb.append(topic.getName() + " \t\t" + topic.getMessageCount() + " msgs \t: " + topic.getMessageType() + " \t" + (topic.getConnectionCount() > 1 ? ("(" + topic.getConnectionCount() + " connections)") : "") + "\n"); if (topic.getName().contains(RosbagFileType.MVSEC.header)) { rosbagFileType = RosbagFileType.MVSEC; } else if (topic.getName().contains(RosbagFileType.RPG.header)) { rosbagFileType = RosbagFileType.RPG; } } sb.append("Duration: " + bagFile.getDurationS() + "s\n"); sb.append("Chunks: " + bagFile.getChunks().size() + "\n"); sb.append("Num messages: " + bagFile.getMessageCount() + "\n"); sb.append("File type is detected as " + rosbagFileType); rosbagInfoString = sb.toString(); for (String s : STANARD_TOPICS) { String topic = rosbagFileType.header + s; topicList.add(topic); topicFieldNames.add(topic.substring(topic.lastIndexOf("/") + 1)); // strip off header to get to field name for the ArrayType } generateMessageIndexes(progressMonitor); log.info(rosbagInfoString); } @Override public Collection<String> getMessageListenerTopics() { return msgListeners.keySet(); } // // causes huge memory usage by building hashmaps internally, using index instead by prescanning file // private MsgIterator getMsgIterator() throws BagReaderException { //// messages=bagFile.getMessages(); // conns = bagFile.getConnections(); // ArrayList<Connection> myConnections = new ArrayList(); // for (Connection conn : conns) { // String topic = conn.getTopic(); //// log.info("connection "+conn+" has topic "+topic); // for (String t : TOPICS) { // if (t.equals(topic)) { //// log.info("topic matches " + t + "; adding this connection to myConnections. This message has definition " + conn.getMessageDefinition()); // log.info("topic matches " + t + "; adding this connection to myConnections"); // myConnections.appendCopy(conn); // chunkInfos = bagFile.getChunkInfos(); // try { // channel = bagFile.getChannel(); // } catch (IOException ex) { // Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex); // throw new BagReaderException(ex.toString()); // MsgIterator itr = new MsgIterator(chunkInfos, myConnections, channel); // return itr; /** * Adds information to a message from the index entry for it */ public class MessageWithIndex { public MessageType messageType; public BagFile.MessageIndex messageIndex; public int ourIndex; public MessageWithIndex(MessageType messageType, BagFile.MessageIndex messageIndex, int ourIndex) { this.messageType = messageType; this.messageIndex = messageIndex; this.ourIndex = ourIndex; } @Override public String toString() { return String.format("MessagesWithIndex with ourIndex=%d, MessageType [package=%s, name=%s, type=%s], MessageIndex %s", ourIndex, messageType.getPackage(), messageType.getName(), messageType.getType(), messageIndex.toString()); //To change body of generated methods, choose Tools | Templates. } } synchronized private MessageWithIndex getMsg(int msgIndex) throws BagReaderException, EOFException { MessageType msg = null; try { if (nextMessageNumber == markOut) { // TODO check exceptions here for markOut set before markIn throw new EOFException("Hit OUT marker at messange number " + markOut); } msg = bagFile.getMessageFromIndex(msgIndexes, msgIndex); } catch (ArrayIndexOutOfBoundsException e) { throw new EOFException("Hit ArrayIndexOutOfBoundsException, probably at end of file"); } catch (IOException e) { throw new EOFException("Hit IOException at end of file"); } MessageWithIndex rtn = new MessageWithIndex(msg, msgIndexes.get(msgIndex), msgIndex); return rtn; } private MessageWithIndex getNextMsg() throws BagReaderException, EOFException { if (nextMessageNumber >= numMessages) { throw new EOFException(String.format("tried to read message %,d past end of file", nextMessageNumber)); } MessageWithIndex rtn = getMsg(nextMessageNumber); nextMessageNumber++; // inc after read so nexx read gets next msg return rtn; } private MessageWithIndex getPrevMsg() throws BagReaderException, EOFException { nextMessageNumber--; // dec before read so we get the previous packet, fwd-rev-fwd gives the same packet 3 times if (nextMessageNumber < 0) { throw new EOFException(String.format("trying to read message from %,d before start of file", nextMessageNumber)); } MessageWithIndex rtn = getMsg(nextMessageNumber); return rtn; } /** * Given ROS Timestamp, this method computes the us timestamp relative to * the first timestamp in the recording * * @param timestamp a ROS Timestamp from a Message, either header or DVS * event * @param updateLargestTimestamp true if we want to update the largest * timestamp with this value, false if we leave it unchanged * @param checkNonmonotonic checks if timestamp is earlier that last one * read. Set false for reverse mode. * * @return timestamp for jAER in us */ private int getTimestampUsRelative(Timestamp timestamp, boolean updateLargestTimestamp, boolean checkNonmonotonic) { // updateLargestTimestamp = true; // TODO hack before removing long tsNs = timestamp.getNanos(); // gets the fractional seconds in ns long tsMs = timestamp.getTime(); // the time in ms including ns, i.e. time(s)*1000+ns/1000000. long timestampUsAbsolute = (1000000 * (tsMs / 1000)) + tsNs / 1000; // truncate ms back to s, then turn back to us, then appendCopy fractional part of s in us if (!firstTimestampWasRead) { firstTimestampUsAbsolute = timestampUsAbsolute; firstTimestampWasRead = true; } int ts = (int) (timestampUsAbsolute - firstTimestampUsAbsolute); // if (ts == 0) { // log.warning("zero timestamp detected for Image "); if (updateLargestTimestamp && ts >= largestTimestampReadSinceRewind) { largestTimestampReadSinceRewind = ts; } final int dt = ts - mostRecentTimestamp; if (checkNonmonotonic && dt < 0 && nonMonotonicTimestampExceptionsChecked) { if (nonmonotonicTimestampCounter % NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL == 0) { log.warning("Nonmonotonic timestamp=" + timestamp + " with dt=" + dt + "; replacing with largest timestamp=" + largestTimestampReadSinceRewind + "; skipping next " + NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL + " warnings"); } nonmonotonicTimestampCounter++; ts = largestTimestampReadSinceRewind; // replace actual timestamp with largest one so far nonMonotonicTimestampDetected = true; } else { nonMonotonicTimestampDetected = false; } mostRecentTimestamp = ts; return ts; } /** * Typical file info about contents of a bag file recorded on Traxxas slash * platform INFO: Bagfile information: * /davis_ros_driver/parameter_descriptions 1 msgs : * dynamic_reconfigure/ConfigDescription /davis_ros_driver/parameter_updates * 1 msgs : dynamic_reconfigure/Config /dvs/events 8991 msgs : * dvs_msgs/EventArray /dvs/exposure 4751 msgs : std_msgs/Int32 * /dvs/image_raw 4758 msgs : sensor_msgs/Image /dvs/imu 298706 msgs : * sensor_msgs/Imu /dvs_accumulated_events 124 msgs : sensor_msgs/Image * /dvs_accumulated_events_edges 124 msgs : sensor_msgs/Image /dvs_rendering * 4034 msgs : sensor_msgs/Image /events_off_mean_1 186 msgs : * std_msgs/Float32 /events_off_mean_5 56 msgs : std_msgs/Float32 * /events_on_mean_1 186 msgs : std_msgs/Float32 /events_on_mean_5 56 msgs : * std_msgs/Float32 /raw_pwm 2996 msgs : rally_msgs/Pwm /rosout 12 msgs : * rosgraph_msgs/Log (4 connections) /rosout_agg 12 msgs : rosgraph_msgs/Log * duration: 299.578s Chunks: 0 Num messages: 324994 */ /** * Gets the next raw packet. The packets are buffered to ensure that all the * data is monotonic in time. * * @param forwards true to look forwards, false to look backwards * * @return the packet */ synchronized private AEPacketRaw getNextRawPacket(boolean forwards) throws EOFException, BagReaderException { DavisBaseCamera davisCamera = null; if (chip instanceof DavisBaseCamera) { davisCamera = (DavisBaseCamera) chip; } OutputEventIterator<ApsDvsEvent> outItr = eventPacket.outputIterator(); // to hold output events ApsDvsEvent e = new ApsDvsEvent(); try { boolean gotEventsOrFrame = false; while (!gotEventsOrFrame) { MessageWithIndex message = forwards ? getNextMsg() : getPrevMsg(); // send to listeners if topic is one we have subscribers for String topic = message.messageIndex.topic; Set<PropertyChangeListener> listeners = msgListeners.get(topic); if (!listeners.isEmpty()) { for (PropertyChangeListener l : listeners) { l.propertyChange(new PropertyChangeEvent(this, topic, null, message)); } } // now deal with standard DAVIS data String pkg = message.messageType.getPackage(); String type = message.messageType.getType(); switch (pkg) { case "std_msgs": { // exposure MessageType messageType = message.messageType; // List<String> fieldNames = messageType.getFieldNames(); try { int exposureUs = messageType.<Int32Type>getField("data").getValue(); lastExposureUs = (int) (exposureUs); } catch (Exception ex) { float exposureUs = messageType.<Float32Type>getField("data").getValue(); lastExposureUs = (int) (exposureUs); // hack to deal with recordings made with pre-Int32 version of rpg-ros-dvs } } break; case "sensor_msgs": switch (type) { case "Image": { // Make sure the image is from APS, otherwise some other image topic will be also processed here. if (!(topic.equalsIgnoreCase(MVSEC_TOPIC_HEADER + "image_raw") || topic.equalsIgnoreCase(RPG_TOPIC_HEADER + "image_raw"))) { continue; } hasAps.setTrue(); MessageType messageType = message.messageType; // List<String> fieldNames = messageType.getFieldNames(); MessageType header = messageType.getField("header"); ArrayType data = messageType.<ArrayType>getField("data"); // int width = (int) (messageType.<UInt32Type>getField("width").getValue()).intValue(); // int height = (int) (messageType.<UInt32Type>getField("height").getValue()).intValue(); Timestamp timestamp = header.<TimeType>getField("stamp").getValue(); int ts = getTimestampUsRelative(timestamp, true, forwards); // don't update largest timestamp with frame time gotEventsOrFrame = true; byte[] bytes = data.getAsBytes(); final int sizey1 = chip.getSizeY() - 1, sizex = chip.getSizeX(); // construct frames as events, so that reconstuction as raw packet results in frame again. // what a hack... // start of frame e.setReadoutType(ApsDvsEvent.ReadoutType.SOF); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts); maybePushEvent(e, apsFifo, outItr); // start of exposure e.setReadoutType(ApsDvsEvent.ReadoutType.SOE); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts); maybePushEvent(e, apsFifo, outItr); Point firstPixel = new Point(0, 0), lastPixel = new Point(chip.getSizeX() - 1, chip.getSizeY() - 1); if (davisCamera != null) { firstPixel.setLocation(davisCamera.getApsFirstPixelReadOut()); lastPixel.setLocation(davisCamera.getApsLastPixelReadOut()); } int xinc = firstPixel.x < lastPixel.x ? 1 : -1; int yinc = firstPixel.y < lastPixel.y ? 1 : -1; // see AEFrameChipRenderer for putting event streams into textures to be drawn, // in particular AEFrameChipRenderer.renderApsDvsEvents // and AEFrameChipRenderer.updateFrameBuffer for how cooked event stream is interpreted // see ChipRendererDisplayMethodRGBA for OpenGL drawing of textures of frames // see DavisBaseCamera.DavisEventExtractor for extraction of event stream // See specific chip classes, e.g. Davis346mini for setup of first and last pixel adddresses for readout order of APS images // The order is important because in AEFrameChipRenderer the frame buffer is cleared at the first // pixel and copied to output after the last pixel, so the pixels must be written in correct order // to the packet... // Also, y is flipped for the rpg-dvs driver which is based on libcaer where the frame starts at // upper left corner as in most computer vision, // unlike jaer that starts like in cartesian coordinates at lower left. for (int f = 0; f < 2; f++) { // reset/signal pixels samples // now we start at for (int y = firstPixel.y; (yinc > 0 ? y <= lastPixel.y : y >= lastPixel.y); y += yinc) { for (int x = firstPixel.x; (xinc > 0 ? x <= lastPixel.x : x >= lastPixel.x); x += xinc) { // above x and y are in jAER image space final int yrpg = sizey1 - y; // flips y to get to rpg from jaer coordinates (jaer uses 0,0 as lower left, rpg-dvs uses 0,0 as upper left) final int idx = yrpg * sizex + x; e.setReadoutType(f == 0 ? ApsDvsEvent.ReadoutType.ResetRead : ApsDvsEvent.ReadoutType.SignalRead); e.x = (short) x; e.y = (short) y; e.setAdcSample(f == 0 ? 255 : (255 - (0xff & bytes[idx]))); if (davisCamera == null) { e.setTimestamp(ts); } else { if (davisCamera.lastFrameAddress((short) x, (short) y)) { e.setTimestamp(ts + lastExposureUs); // set timestamp of last event written out to the frame end timestamp, TODO complete hack to have 1 pixel with larger timestamp } else { e.setTimestamp(ts); } } maybePushEvent(e, apsFifo, outItr); // debug // if(x==firstPixel.x && y==firstPixel.y){ // log.info("pushed first frame pixel event "+e); // }else if(x==lastPixel.x && y==lastPixel.y){ // log.info("pushed last frame pixel event "+e); } } } // end of exposure event // e = outItr.nextOutput(); e.setReadoutType(ApsDvsEvent.ReadoutType.EOE); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts + lastExposureUs); // TODO should really be end of exposure timestamp, have to get that from last exposure message maybePushEvent(e, apsFifo, outItr); // end of frame event // e = outItr.nextOutput(); e.setReadoutType(ApsDvsEvent.ReadoutType.EOF); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts + lastExposureUs); maybePushEvent(e, apsFifo, outItr); } break; case "Imu": { hasImu.setTrue(); MessageType messageType = message.messageType; // List<String> fieldNames = messageType.getFieldNames(); // for(String s:fieldNames){ // System.out.println("fieldName: "+s); // List<String> fieldNames = messageType.getFieldNames(); MessageType header = messageType.getField("header"); Timestamp timestamp = header.<TimeType>getField("stamp").getValue(); int ts = getTimestampUsRelative(timestamp, true, forwards); // do update largest timestamp with IMU time MessageType angular_velocity = messageType.getField("angular_velocity"); // List<String> angvelfields=angular_velocity.getFieldNames(); // for(String s:angvelfields){ // System.out.println("angular_velocity field: "+s); float xrot = (float) (angular_velocity.<Float64Type>getField("x").getValue().doubleValue()); float yrot = (float) (angular_velocity.<Float64Type>getField("y").getValue().doubleValue()); float zrot = (float) (angular_velocity.<Float64Type>getField("z").getValue().doubleValue()); MessageType linear_acceleration = messageType.getField("linear_acceleration"); // List<String> linaccfields=linear_acceleration.getFieldNames(); // for(String s:linaccfields){ // System.out.println("linaccfields field: "+s); float xacc = (float) (angular_velocity.<Float64Type>getField("x").getValue().doubleValue()); float yacc = (float) (angular_velocity.<Float64Type>getField("y").getValue().doubleValue()); float zacc = (float) (angular_velocity.<Float64Type>getField("z").getValue().doubleValue()); short[] buf = new short[7]; buf[IMUSampleType.ax.code] = (short) (G_PER_MPS2 * xacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb()); // TODO set these scales from caer parameter messages in stream buf[IMUSampleType.ay.code] = (short) (G_PER_MPS2 * yacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb()); buf[IMUSampleType.az.code] = (short) (G_PER_MPS2 * zacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb()); buf[IMUSampleType.gx.code] = (short) (DEG_PER_RAD * xrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb()); buf[IMUSampleType.gy.code] = (short) (DEG_PER_RAD * yrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb()); buf[IMUSampleType.gz.code] = (short) (DEG_PER_RAD * zrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb()); // ApsDvsEvent e = null; // e = outItr.nextOutput(); IMUSample imuSample = new IMUSample(ts, buf); e.setImuSample(imuSample); e.setTimestamp(ts); maybePushEvent(e, imuFifo, outItr); } break; } break; case "dvs_msgs": hasDvs.setTrue(); switch (type) { case "EventArray": MessageType messageType = message.messageType; ArrayType data = messageType.<ArrayType>getField("events"); if (data == null) { log.warning("got null data for field events in message " + message); continue; } List<Field> eventFields = data.getFields(); gotEventsOrFrame = true; int sizeY = chip.getSizeY(); int eventIdxThisPacket = 0; // int nEvents = eventFields.size(); for (Field eventField : eventFields) { MessageType eventMsg = (MessageType) eventField; int x = eventMsg.<UInt16Type>getField("x").getValue(); int y = eventMsg.<UInt16Type>getField("y").getValue(); boolean pol = eventMsg.<BoolType>getField("polarity").getValue(); // false==off, true=on Timestamp timestamp = (Timestamp) eventMsg.<TimeType>getField("ts").getValue(); int ts = getTimestampUsRelative(timestamp, true, forwards); // sets nonMonotonicTimestampDetected flag, faster than throwing exception, updates largest timestamp // ApsDvsEvent e = outItr.nextOutput(); e.setReadoutType(ApsDvsEvent.ReadoutType.DVS); e.timestamp = ts; e.x = (short) x; e.y = (short) (sizeY - y - 1); e.polarity = pol ? PolarityEvent.Polarity.Off : PolarityEvent.Polarity.On; e.type = (byte) (pol ? 0 : 1); maybePushEvent(e, dvsFifo, outItr); eventIdxThisPacket++; } } break; } } } catch (UninitializedFieldException ex) { Logger.getLogger(ExampleRosBagReader.class.getName()).log(Level.SEVERE, null, ex); throw new BagReaderException(ex); } // if we were not checking time order, then events were directly copied to output packet oe already if (nonMonotonicTimestampExceptionsChecked) { // now pop events in time order from the FIFOs to the output packet and then reconstruct the raw packet ApsDvsEvent ev; while ((ev = popOldestEvent()) != null) { ApsDvsEvent oe = outItr.nextOutput(); oe.copyFrom(ev); } } AEPacketRaw aePacketRawCollecting = chip.getEventExtractor().reconstructRawPacket(eventPacket); fireInitPropertyChange(); return aePacketRawCollecting; } /** * Either pushes event to fifo or just directly writes it to output packet, * depending on flag nonMonotonicTimestampExceptionsChecked. * * @param ev the event * @param fifo the fifo to write to * @param outItr the output packet iterator, if events are directly written * to output */ private void maybePushEvent(ApsDvsEvent ev, AEFifo fifo, OutputEventIterator<ApsDvsEvent> outItr) { if (nonMonotonicTimestampExceptionsChecked) { fifo.pushEvent(ev); } else { ApsDvsEvent oe = outItr.nextOutput(); oe.copyFrom(ev); } } /** * returns the oldest event (earliest in time) from all of the fifos if * there are younger events in all other fifos * * @return oldest valid event (and first one pushed to any one particular * sub-fifo for identical timestamps) or null if there is none */ private ApsDvsEvent popOldestEvent() { // find oldest event over all fifos ApsDvsEvent ev = null; int ts = Integer.MAX_VALUE; int fifoIdx = -1; int numStreamsWithData = 0; for (int i = 0; i < 3; i++) { boolean hasData = hasDvsApsImu[i].isTrue(); if (hasData) { numStreamsWithData++; } int t; if (hasData && !aeFifos[i].isEmpty() && (t = aeFifos[i].peekNextTimestamp()) <= /* check <= */ ts) { fifoIdx = i; ts = t; } } if (fifoIdx < 0) { return null; // no fifo has event } // if only one stream has data then just return it if (numStreamsWithData == 1) { ev = aeFifos[fifoIdx].popEvent(); } else {// if any of the other fifos for which we actually have sensor data don't have younger event then return null for (int i = 0; i < 3; i++) { if (i == fifoIdx) { // don't compare with ourselves continue; } if (hasDvsApsImu[i].isTrue() && (!aeFifos[i].isEmpty()) // if other stream ever has had data but none is available now && aeFifos[i].getLastTimestamp() <= ts // or if last event in other stream data is still older than we are ) { return null; } } ev = aeFifos[fifoIdx].popEvent(); } return ev; } /** * Called to signal first read from file. Fires PropertyChange * AEInputStream.EVENT_INIT, with new value this. */ protected void fireInitPropertyChange() { if (firstReadCompleted) { return; } getSupport().firePropertyChange(AEInputStream.EVENT_INIT, null, this); firstReadCompleted = true; } @Override synchronized public AEPacketRaw readPacketByNumber(int numEventsToRead) throws IOException { int oldPosition = nextMessageNumber; if (numEventsToRead < 0) { return emptyPacket; } aePacketRawOutput.setNumEvents(0); while (aePacketRawBuffered.getNumEvents() < numEventsToRead && aePacketRawBuffered.getNumEvents() < AEPacketRaw.MAX_PACKET_SIZE_EVENTS) { try { aePacketRawBuffered.append(getNextRawPacket(numEventsToRead > 0)); } catch (EOFException ex) { rewind(); return readPacketByNumber(numEventsToRead); } catch (BagReaderException ex) { throw new IOException(ex); } } AEPacketRaw.copy(aePacketRawBuffered, 0, aePacketRawOutput, 0, numEventsToRead); // copy over collected events // now use tmp packet to copy rest of buffered to, and then make that the new buffered aePacketRawTmp.setNumEvents(0); AEPacketRaw.copy(aePacketRawBuffered, numEventsToRead, aePacketRawTmp, 0, aePacketRawBuffered.getNumEvents() - numEventsToRead); AEPacketRaw tmp = aePacketRawBuffered; aePacketRawBuffered = aePacketRawTmp; aePacketRawTmp = tmp; getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, position()); if (aePacketRawOutput.getNumEvents() > 0) { currentStartTimestamp = aePacketRawOutput.getLastTimestamp(); } maybeSendRewoundEvent(oldPosition); return aePacketRawOutput; } private boolean lastDirectionForwards = true; @Override synchronized public AEPacketRaw readPacketByTime(int dt) throws IOException { int oldPosition = nextMessageNumber; int newEndTime = currentStartTimestamp + dt; boolean directionForwards = dt > 0; boolean changedDirection = directionForwards ^ lastDirectionForwards; if (changedDirection) { // xor them, if different then clear events so far clearAccumulatedEvents(); } if (newEndTime < 0) { newEndTime = 0; // so we don't trh to read before 0 } // keep getting ros messages until we get a timestamp later (or earlier for negative dt) the desired new end time if (directionForwards) { while (aePacketRawBuffered.isEmpty() || aePacketRawBuffered.getLastTimestamp() < newEndTime && aePacketRawBuffered.getNumEvents() < MAX_RAW_EVENTS_BUFFER_SIZE) { try { AEPacketRaw p = getNextRawPacket(directionForwards); if (p.isEmpty()) { continue; } aePacketRawBuffered.append(p); // reaching EOF here will throw EOFException } catch (BagReaderException ex) { if (ex.getCause() instanceof ClosedByInterruptException) { // ignore, caussed by interrupting ViewLoop to change rendering mode return emptyPacket; } throw new IOException(ex); } } if (!changedDirection) { // copy off events that are too late int[] ts = aePacketRawBuffered.getTimestamps(); int idx = aePacketRawBuffered.getNumEvents() - 1; while (idx > 0 && ts[idx] > newEndTime) { idx } aePacketRawOutput.clear(); // just in case 0 copied to packet //public static void copy(AEPacketRaw src, int srcPos, AEPacketRaw dest, int destPos, int length) { AEPacketRaw.copy(aePacketRawBuffered, 0, aePacketRawOutput, 0, idx); // copy over collected events // now use tmp packet to copy rest of buffered to, and then make that the new buffered aePacketRawTmp.setNumEvents(0); // in case we copy 0 events over AEPacketRaw.copy(aePacketRawBuffered, idx, aePacketRawTmp, 0, aePacketRawBuffered.getNumEvents() - idx); AEPacketRaw tmp = aePacketRawBuffered; aePacketRawBuffered = aePacketRawTmp; aePacketRawTmp = tmp; } else { aePacketRawOutput.clear(); // just in case 0 copied to packet //public static void copy(AEPacketRaw src, int srcPos, AEPacketRaw dest, int destPos, int length) { AEPacketRaw.copy(aePacketRawBuffered, 0, aePacketRawOutput, 0, aePacketRawBuffered.getNumEvents()); // copy over collected events clearAccumulatedEvents(); } if (aePacketRawOutput.isEmpty()) { currentStartTimestamp = newEndTime; } else { currentStartTimestamp = aePacketRawOutput.getLastTimestamp(); } } else { // backwards, only read one packet try { aePacketRawOutput = getNextRawPacket(false);// read one packet backwards. leaving nextMessageNumber at this same messsage. Reaching EOF here will throw EOFException that AEPlayer will handle if (aePacketRawOutput != null && !aePacketRawOutput.isEmpty()) { currentStartTimestamp = aePacketRawOutput.getFirstTimestamp(); // update according to what we actually got } } catch (BagReaderException ex) { if (ex.getCause() instanceof ClosedByInterruptException) { // ignore, caussed by interrupting ViewLoop to change rendering mode return emptyPacket; } throw new IOException(ex); } } getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, nextMessageNumber); maybeSendRewoundEvent(oldPosition); lastDirectionForwards = directionForwards; return aePacketRawOutput; } @Override public boolean isNonMonotonicTimeExceptionsChecked() { return nonMonotonicTimestampExceptionsChecked; } /** * If this option is set, then non-monotonic timestamps are replaced with * the newest timestamp in the file, ensuring monotonicity. It seems that * the frames and IMU samples are captured or timestamped out of order in * the file, resulting in DVS packets that contain timestamps younger than * earlier frames or IMU samples. * * @param yes to guarantee monotonicity */ @Override public void setNonMonotonicTimeExceptionsChecked(boolean yes) { nonMonotonicTimestampExceptionsChecked = yes; } /** * Returns starting time of file since epoch, in UTC time * * @return the time in ms since epoch (1970) */ @Override public long getAbsoluteStartingTimeMs() { return bagFile.getStartTime().getTime(); } @Override public ZoneId getZoneId() { return zoneId; // TODO implement setting time zone from file } @Override public int getDurationUs() { return (int) (bagFile.getDurationS() * 1e6); } @Override public int getFirstTimestamp() { return (int) firstTimestampUs; } @Override public PropertyChangeSupport getSupport() { return support; } @Override public float getFractionalPosition() { return (float) mostRecentTimestamp / getDurationUs(); } @Override public long position() { return nextMessageNumber; } @Override public void position(long n) { if (n < 0) { n = 0; } else if (n >= numMessages) { n = numMessages - 1; } nextMessageNumber = (int) n; } @Override synchronized public void rewind() throws IOException { position(isMarkInSet() ? getMarkInPosition() : 0); clearAccumulatedEvents(); largestTimestampReadSinceRewind = 0; // timestamps start at 0 by constuction of timestamps try { MessageWithIndex msg = getNextMsg(); if (msg != null) { currentStartTimestamp = getTimestampUsRelative(msg.messageIndex.timestamp, true, false); // reind, so update the largest timestamp read in this cycle to first timestamp position(isMarkInSet() ? getMarkInPosition() : 0); } } catch (BagReaderException e) { log.warning(String.format("Exception %s getting timestamp after rewind from ROS message", e.toString())); } clearAccumulatedEvents(); rewindFlag = true; } private void maybeSendRewoundEvent(long oldPosition) { if (rewindFlag) { getSupport().firePropertyChange(AEInputStream.EVENT_REWOUND, oldPosition, position()); rewindFlag = false; } } private void clearAccumulatedEvents() { aePacketRawBuffered.clear(); for (AEFifo f : aeFifos) { f.clear(); } } @Override synchronized public void setFractionalPosition(float frac) { position((int) (frac * numMessages)); // must also clear partially accumulated events in collecting packet and reset the timestamp clearAccumulatedEvents(); try { AEPacketRaw raw = getNextRawPacket(true); while (raw == null) { log.warning(String.format("got null packet at fractional position %.2f which should have been message number %d, trying next packet", frac, nextMessageNumber)); raw = getNextRawPacket(true); } aePacketRawBuffered.append(raw); // reaching EOF here will throw EOFException } catch (EOFException ex) { try { aePacketRawBuffered.clear(); rewind(); } catch (IOException ex1) { Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex1); } } catch (BagReaderException ex) { Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex); } } @Override public long size() { return 0; } @Override public void clearMarks() { markIn = -1; markOut = -1; getSupport().firePropertyChange(AEInputStream.EVENT_MARKS_CLEARED, null, null); } @Override public long setMarkIn() { int old = markIn; markIn = nextMessageNumber; getSupport().firePropertyChange(AEInputStream.EVENT_MARK_IN_SET, old, markIn); return markIn; } @Override public long setMarkOut() { int old = markOut; markOut = nextMessageNumber; getSupport().firePropertyChange(AEInputStream.EVENT_MARK_OUT_SET, old, markOut); return markOut; } @Override public long getMarkInPosition() { return markIn; } @Override public long getMarkOutPosition() { return markOut; } @Override public boolean isMarkInSet() { return markIn > 0; } @Override public boolean isMarkOutSet() { return markOut <= numMessages; } @Override public void setRepeat(boolean repeat) { this.repeatEnabled = repeat; } @Override public boolean isRepeat() { return repeatEnabled; } /** * Returns the File that is being read, or null if the instance is * constructed from a FileInputStream */ public File getFile() { return file; } /** * Sets the File reference but doesn't open the file */ public void setFile(File f) { this.file = f; } @Override public int getLastTimestamp() { return (int) lastTimestampUs; // TODO, from last DVS event timestamp } @Override public int getMostRecentTimestamp() { return (int) mostRecentTimestamp; } @Override public int getTimestampResetBitmask() { return 0; // TODO } @Override public void setTimestampResetBitmask(int timestampResetBitmask) { // TODO } @Override synchronized public void close() throws IOException { if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException e) { // ignore this error } } bagFile = null; file = null; System.gc(); } @Override public int getCurrentStartTimestamp() { return (int) lastTimestampUs; } @Override synchronized public void setCurrentStartTimestamp(int currentStartTimestamp) { this.currentStartTimestamp = currentStartTimestamp; nextMessageNumber = (int) (numMessages * (float) currentStartTimestamp / getDurationUs()); aePacketRawBuffered.clear(); } @Override protected void finalize() throws Throwable { super.finalize(); close(); } private void generateMessageIndexes(ProgressMonitor progressMonitor) throws BagReaderException, InterruptedException { if (wasIndexed) { return; } log.info("creating or loading cached index for all topics"); if (!maybeLoadCachedMsgIndexes(progressMonitor)) { msgIndexes = bagFile.generateIndexesForTopicList(topicList, progressMonitor); cacheMsgIndexes(); } numMessages = msgIndexes.size(); markIn = 0; markOut = numMessages; startAbsoluteTimestamp = msgIndexes.get(0).timestamp; startAbsoluteTimeS = 1e-3 * startAbsoluteTimestamp.getTime(); endAbsoluteTimeS = 1e-3 * msgIndexes.get(numMessages - 1).timestamp.getTime(); durationS = endAbsoluteTimeS - startAbsoluteTimeS; firstTimestampUs = getTimestampUsRelative(msgIndexes.get(0).timestamp, true, false); lastTimestampUs = getTimestampUsRelative(msgIndexes.get(numMessages - 1).timestamp, false, false); // don't update largest timestamp with last timestamp wasIndexed = true; StringBuilder sb = new StringBuilder(); String s = String.format("%nRecording start Date %s%nRecording start time since epoch %,.3fs%nDuration %,.3fs", startAbsoluteTimestamp.toString(), startAbsoluteTimeS, durationS); rosbagInfoString = rosbagInfoString + s; } @Override public String toString() { return super.toString() + Character.LINE_SEPARATOR + rosbagInfoString; } public void addPropertyChangeListener(PropertyChangeListener listener) { this.support.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { this.support.removePropertyChangeListener(listener); } /** * Adds a topic for which listeners should be informed. The PropertyChange * has this as the source and the new value is the MessageType message. * * @param topics a string topic, e.g. "/dvs/events" * @param listener a PropertyChangeListener that gets the messages * @throws java.lang.InterruptedException since generating the topic index * is a long-running process, the method throws * @throws com.github.swrirobotics.bags.reader.exceptions.BagReaderException * if there is an exception for the BagFile * @see MessageType */ @Override synchronized public void addSubscribers(List<String> topics, PropertyChangeListener listener, ProgressMonitor progressMonitor) throws InterruptedException, BagReaderException { List<String> topicsToAdd = new ArrayList(); for (String topic : topics) { if (msgListeners.containsKey(topic) && msgListeners.get(topic).contains(listener)) { log.warning("topic " + topic + " and listener " + listener + " already added, ignoring"); continue; } topicsToAdd.add(topic); } if (topicsToAdd.isEmpty()) { log.warning("nothing to add"); return; } addPropertyChangeListener(listener); List<BagFile.MessageIndex> idx = bagFile.generateIndexesForTopicList(topicsToAdd, progressMonitor); msgIndexes.addAll(idx); for (String topic : topics) { msgListeners.put(topic, listener); } Collections.sort(msgIndexes); } /** * Removes a topic * * @param topic * @param listener */ @Override public void removeTopic(String topic, PropertyChangeListener listener) { log.warning("cannot remove topic parsing, just removing listener"); if (msgListeners.containsValue(listener)) { log.info("removing listener " + listener); removePropertyChangeListener(listener); } } /** * Set if nonmonotonic timestamp was detected. Cleared at start of * collecting each new packet. * * @return the nonMonotonicTimestampDetected true if a nonmonotonic * timestamp was detected. */ public boolean isNonMonotonicTimestampDetected() { return nonMonotonicTimestampDetected; } synchronized private void cacheMsgIndexes() { try { File file = new File(messageIndexesCacheFileName()); if (file.exists() && file.canRead() && file.isFile()) { log.info("cached indexes " + file + " for file " + getFile() + " already exists, not storing it again"); return; } log.info("caching the index for rosbag file " + getFile() + " in " + file); FileOutputStream out = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(msgIndexes); oos.flush(); log.info("cached the index for rosbag file " + getFile() + " in " + file); } catch (Exception e) { log.warning("could not cache the message index to disk: " + e.toString()); } } synchronized private boolean maybeLoadCachedMsgIndexes(ProgressMonitor progressMonitor) { try { File file = new File(messageIndexesCacheFileName()); if (!file.exists() || !file.canRead() || !file.isFile()) { log.info("cached indexes " + file + " for file " + getFile() + " does not exist"); return false; } log.info("reading cached index for rosbag file " + getFile() + " from " + file); long startTime = System.currentTimeMillis(); if (progressMonitor != null) { if (progressMonitor.isCanceled()) { progressMonitor.setNote("canceling"); throw new InterruptedException("canceled loading caches"); } progressMonitor.setNote("reading cached index from " + file); } FileInputStream in = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(in)); List<BagFile.MessageIndex> tmpIdx = (List<BagFile.MessageIndex>) ois.readObject(); msgIndexes = tmpIdx; long ms = System.currentTimeMillis() - startTime; log.info("done after " + ms + "ms with reading cached index for rosbag file " + getFile() + " from " + file); if (progressMonitor != null) { if (progressMonitor.isCanceled()) { progressMonitor.setNote("canceling"); throw new InterruptedException("canceled loading caches"); } progressMonitor.setNote("done reading cached index"); progressMonitor.setProgress(progressMonitor.getMaximum()); } return true; } catch (Exception e) { log.warning("could load cached message index from disk: " + e.toString()); return false; } } private String messageIndexesCacheFileName() { return System.getProperty("java.io.tmpdir") + File.separator + getFile().getName() + ".rosbagidx"; } /** * A FIFO for ApsDvsEvent events. */ private final class AEFifo extends ApsDvsEventPacket { private final int MAX_EVENTS = 1 << 20; int nextToPopIndex = 0; private boolean full = false; public AEFifo() { super(ApsDvsEvent.class); } /** * Adds a new event to end * * @param event */ public final void pushEvent(ApsDvsEvent event) { if (full) { return; } if (size == MAX_EVENTS) { full = true; log.warning(String.format("FIFO has reached capacity RosbagFileInputStream.MAX_EVENTS=%,d events: %s", MAX_EVENTS, toString())); return; } appendCopy(event); } @Override public boolean isEmpty() { return size == 0 || nextToPopIndex >= size; //To change body of generated methods, choose Tools | Templates. } @Override public void clear() { super.clear(); nextToPopIndex = 0; full = false; } /** * @return next event, or null if there are no more */ public final ApsDvsEvent popEvent() { if (isEmpty()) { clear(); return null; } ApsDvsEvent event = (ApsDvsEvent) getEvent(nextToPopIndex++); if (isEmpty()) { clear(); } return event; } public final int peekNextTimestamp() { return getEvent(nextToPopIndex).timestamp; } @Override final public String toString() { return "AEFifo with capacity " + MAX_EVENTS + " nextToPopIndex=" + nextToPopIndex + " holding " + super.toString(); } } /** * * Returns the absolute time since the 1979 unix epoch in double seconds. * * @return the startAbsoluteTimeS */ public double getStartAbsoluteTimeS() { return startAbsoluteTimeS; } /** * Returns the absolute time of first message in unix absolute time since * 1970 epoch * * @return the startAbsoluteTimestamp */ public Timestamp getStartAbsoluteTimestamp() { return startAbsoluteTimestamp; } }
package eu.musesproject.server.dataminer; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import eu.musesproject.server.db.handler.DBManager; import eu.musesproject.server.entity.Decision; import eu.musesproject.server.entity.DecisionTrustvalues; import eu.musesproject.server.entity.EventType; import eu.musesproject.server.entity.PatternsKrs; import eu.musesproject.server.entity.SecurityViolation; import eu.musesproject.server.entity.SimpleEvents; import eu.musesproject.server.entity.Users; import eu.musesproject.server.scheduler.ModuleType; import org.apache.log4j.Logger; /** * The Class DataMiningUtils. * * @author Paloma de las Cuevas (UGR) * @version Aug 30, 2015 */ public class DataMiningUtils { private static DBManager dbManager = new DBManager(ModuleType.KRS); private static final String MUSES_TAG = "MUSES_TAG"; private Logger logger = Logger.getLogger(DataMiner.class); /** * obtainLabel - For every event, an access request is built by the Event Processor, so the RT2AE can make a final decision about it. * This method obtains the associated label to an event. * * @param accessRequestId Is the access request number associated to an event. * * @return label * */ public String obtainLabel(String accessRequestId){ List<Decision> decisions = dbManager.findDecisionByAccessRequestId(accessRequestId); if (decisions.size() > 0) { return decisions.get(0).getValue(); } else { return "ALLOW"; } } /** * obtainDecisionCause - For every event, it may be several security violations, and each one contains the cause of the violation. * This method returns the decision cause for an event, either if the security violation is linked to a decision id * or not. * * @param accessRequestId Is the access request number associated to an event. * @param eventId The event Id * * @return decisionCause * */ public String obtainDecisionCause(String accessRequestId, String eventId){ List<Decision> decisions = dbManager.findDecisionByAccessRequestId(accessRequestId); if (decisions.size() > 0) { String decisionId = decisions.get(0).getValue(); SecurityViolation securityViolation = dbManager.findSecurityViolationByDecisionId(decisionId); Pattern p = Pattern.compile("<(.+?)>(.+?)</(.+?)>"); if (securityViolation != null) { Matcher matcher = p.matcher(securityViolation.getConditionText()); if (matcher.find()) { return matcher.group(1); } else { return null; } } else { List<SecurityViolation> secViolations = dbManager.findSecurityViolationByEventId(eventId); if (secViolations.size() > 0) { return null; } else { return "ALLOW"; } } } else { return null; } } /** * obtainEventType - For every event, this method obtains its type. * * @param event The event as a Simple Events object. * * @return eventType * */ public String obtainEventType(SimpleEvents event){ EventType eventTypeId = event.getEventType(); String eventType = null; eventType = eventTypeId.getEventTypeKey(); return eventType; } /** * obtainEventLevel - For every event, this method obtains its level (simple or complex). * * @param event The event as a Simple Events object. * * @return eventLevel * */ public String obtainEventLevel(SimpleEvents event){ EventType eventTypeId = event.getEventType(); String eventLevel = null; eventLevel = eventTypeId.getEventLevel(); return eventLevel; } /** * obtainUsername - For every event, this method obtains who is responsible for the event, but maintaining the anonymity. * * @param user The user as a User object. * * @return username * */ public String obtainUsername(Users user){ String username = null; username = user.getUsername(); return username; } /** * passwdLength - This method measures the length of the user password. * * @param user The user as a User object. * * @return passwordLength * */ public int passwdLength(Users user){ int passwordLength = 0; String userPassword = user.getPassword(); // Characters (numbers, letters, and symbols) in the password if (userPassword != null) { passwordLength = 0;userPassword.length(); } return passwordLength; } /** * passwdDigits - This method measures the number of digits (0-9) in the user password. * * @param user The user as a User object. * * @return digitsCount * */ public int passwdDigits(Users user){ int digitsCount = 0; String userPassword = user.getPassword(); String digits = "\\d"; Pattern digitPattern = Pattern.compile(digits); Matcher digitsMatcher = digitPattern.matcher(userPassword); while (digitsMatcher.find()) { digitsCount++; } return digitsCount; } /** * passwdLetters - This method measures the number of letters (a-z) in the user password. * * @param user The user as a User object. * * @return lettersCount * */ public int passwdLetters(Users user){ int lettersCount = 0; String userPassword = user.getPassword(); String letters = "[a-zA-Z]"; Pattern letterPattern = Pattern.compile(letters); Matcher lettersMatcher = letterPattern.matcher(userPassword); while (lettersMatcher.find()) { lettersCount++; } return lettersCount; } /** * passwdCapLetters - This method measures the number of capital letters (A-Z) in the user password. * * @param user The user as a User object. * * @return capLettersCount * */ public int passwdCapLetters(Users user){ int capLettersCount = 0; String userPassword = user.getPassword(); String capLetters = "[A-Z]"; Pattern capLetterPattern = Pattern.compile(capLetters); Matcher capLettersMatcher = capLetterPattern.matcher(userPassword); while (capLettersMatcher.find()) { capLettersCount++; } return capLettersCount; } /** * obtainingUserTrust - This method gathers the user trust value associated to the user, at the time of the decision. * * @param accessRequestId Is the access request number associated to an event. * * @return trustValue * */ public double obtainingUserTrust(String accessRequestId){ double trustValue = Double.NaN; List<Decision> decisions = dbManager.findDecisionByAccessRequestId(accessRequestId); if (decisions.size() > 0) { String decisionId = decisions.get(0).getValue(); List<DecisionTrustvalues> trustValues = dbManager.findDecisionTrustValuesByDecisionId(decisionId); if (trustValues.size() > 0) { trustValue = trustValues.get(0).getUsertrustvalue(); } } return trustValue; } /** * obtainingDeviceTrust - This method gathers the user trust value associated to the device, at the time of the decision. * * @param accessRequestId Is the access request number associated to an event. * * @return trustValue * */ public double obtainingDeviceTrust(String accessRequestId){ double trustValue = Double.NaN; List<Decision> decisions = dbManager.findDecisionByAccessRequestId(accessRequestId); if (decisions.size() > 0) { String decisionId = decisions.get(0).getValue(); List<DecisionTrustvalues> trustValues = dbManager.findDecisionTrustValuesByDecisionId(decisionId); if (trustValues.size() > 0) { trustValue = trustValues.get(0).getDevicetrustvalue(); } } return trustValue; } }
package org.apache.cocoon.components.cron; import com.thoughtworks.xstream.XStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.avalon.framework.CascadingRuntimeException; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.ParameterException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.components.cron.ConfigurableCronJob; import org.apache.cocoon.components.cron.QueueProcessorCronJob.JobConfig; import org.apache.cocoon.components.cron.QueueProcessorCronJob.Task; import static org.apache.cocoon.components.cron.QueueProcessorCronJob.getXStreamJobConfig; import org.apache.cocoon.components.cron.ServiceableCronJob; /** * * Submit a job to a queue. * * @author <a href="mailto:huib.verweij@koop.overheid.nl">Huib Verweij</a> * */ public class QueueAddJob extends ServiceableCronJob implements Configurable, ConfigurableCronJob { public static final String ROLE = "org.apache.cocoon.components.cron.CronJob/queueadd"; private static final String PARAMETER_QUEUE_PATH = "queue-path"; private static final String JOBURI_PARAMETER = "job-uri"; private static final String JOBNAME_PARAMETER = "job-name"; private static final String JOBDESCRIPTION_PARAMETER = "job-description"; private static final String inDirName = "in"; private File queuePath; private String uri; private String jobName; private String jobDescription; @SuppressWarnings("rawtypes") @Override public void setup(Parameters params, Map objects) { try { if (this.getLogger().isInfoEnabled()) { this.getLogger().info(String.format("params = %s", params)); } this.uri = params.getParameter(JOBURI_PARAMETER); this.jobName = params.getParameter(JOBNAME_PARAMETER, "Auto-generated job"); this.jobDescription = params.getParameter(JOBDESCRIPTION_PARAMETER, "Automatically added by QueueAddJob."); if (this.getLogger().isInfoEnabled()) { this.getLogger().info(String.format("job-uri = %s", uri)); this.getLogger().info(String.format("job-name = %s", jobName)); this.getLogger().info(String.format("job-description = %s", jobDescription)); } } catch (ParameterException ex) { Logger.getLogger(QueueAddJob.class.getName()).log(Level.SEVERE, null, ex); } } /** * Return File object for parent/path, creating it if necessary. * * @param parent * @param path * @return Resulting File object. */ private File getOrCreateDirectory(File parent, String path) { File dir = new File(parent, path); if (!dir.exists()) { dir.mkdirs(); } return dir; } /** * Get path to queue folder. * * @param config * @throws ConfigurationException */ @Override public void configure(final Configuration config) throws ConfigurationException { String actualQueuesDirName = config.getChild(PARAMETER_QUEUE_PATH).getValue(); queuePath = new File(actualQueuesDirName); } /** * Create a new job in the inDir. */ private void createJob(String name) throws IOException { /* Create subdirs if necessary. */ File queueDir = getOrCreateDirectory(this.queuePath, ""); File inDir = getOrCreateDirectory(queueDir, inDirName); UUID jobID = UUID.randomUUID(); Task[] tasks = new Task[1]; Task task = new Task(); task.id = UUID.randomUUID().toString(); task.uri = this.uri; tasks[0] = task; JobConfig job = new JobConfig(); job.id = jobID.toString(); job.description = this.jobDescription; job.maxConcurrent = 1; job.name = this.jobName; job.created = new Date(); job.tasks = tasks; File currentJobFile = new File(inDir, String.format("job-%s.xml", jobID)); if (this.getLogger().isInfoEnabled()) { this.getLogger().info(String.format("New job: %s", currentJobFile.getAbsolutePath())); } XStream xstream = getXStreamJobConfig(); FileOutputStream fos = new FileOutputStream(currentJobFile); xstream.toXML(job, fos); fos.close(); } /** * Main entrypoint for CronJob. * * @param name */ @Override public void execute(String name) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("CronJob " + name + " launched at " + new Date()); } try { createJob(name); } catch (IOException e) { throw new CascadingRuntimeException("CronJob " + name + " raised an exception.", e); } } }
package hudson.plugins.analysis.collector; // NOPMD import hudson.model.AbstractBuild; import hudson.plugins.analysis.core.BuildHistory; import hudson.plugins.analysis.core.BuildResult; import hudson.plugins.analysis.core.ParserResult; import hudson.plugins.analysis.core.ResultAction; import hudson.plugins.analysis.util.model.FileAnnotation; import java.lang.ref.WeakReference; import java.util.Map; import com.google.common.collect.Maps; /** * Stores the results of the analysis plug-ins. One instance of this class is * persisted for each build via an XML file. * * @author Ulli Hafner */ public class AnalysisResult extends BuildResult { /** Unique identifier of this class. */ private static final long serialVersionUID = 847650789493429154L; /** Number of annotations by origin mapping. */ private transient WeakReference<Map<String, Integer>> annotationsByOrigin; private transient Object mappingLock = new Object(); /** * Creates a new instance of {@link AnalysisResult}. * * @param build * the current build as owner of this action * @param defaultEncoding * the default encoding to be used when reading and parsing files * @param result * the parsed result with all annotations * @param history * the plug-in history */ public AnalysisResult(final AbstractBuild<?, ?> build, final String defaultEncoding, final ParserResult result, final BuildHistory history) { super(build, defaultEncoding, result, history); annotationsByOrigin = newReference(countAnnotations()); } /** * Creates a new instance of {@link AnalysisResult}. * * @param build * the current build as owner of this action * @param defaultEncoding * the default encoding to be used when reading and parsing files * @param result * the parsed result with all annotations */ public AnalysisResult(final AbstractBuild<?, ?> build, final String defaultEncoding, final ParserResult result) { super(build, defaultEncoding, result); annotationsByOrigin = newReference(countAnnotations()); } /** {@inheritDoc} */ @Override protected Object readResolve() { super.readResolve(); mappingLock = new Object(); return this; } /** * Count the annotations by origin. * * @return the mapping */ private Map<String, Integer> countAnnotations() { Map<String, Integer> mapping = Maps.newHashMap(); for (FileAnnotation annotation : getAnnotations()) { if (!mapping.containsKey(annotation.getOrigin())) { mapping.put(annotation.getOrigin(), 0); } mapping.put(annotation.getOrigin(), mapping.get(annotation.getOrigin()) + 1); } return mapping; } private WeakReference<Map<String, Integer>> newReference(final Map<String, Integer> mapping) { return new WeakReference<Map<String, Integer>>(mapping); } /** * Returns a summary message for the summary.jelly file. * * @return the summary message */ public String getSummary() { return AnalysisResultSummary.createSummary(this); } /** {@inheritDoc} */ @Override protected String createDeltaMessage() { return AnalysisResultSummary.createDeltaMessage(this); } /** {@inheritDoc} */ @Override protected String getSerializationFileName() { return "analysis.xml"; } /** {@inheritDoc} */ public String getDisplayName() { return Messages.Analysis_ProjectAction_Name(); } /** {@inheritDoc} */ @Override protected Class<? extends ResultAction<? extends BuildResult>> getResultActionType() { return AnalysisResultAction.class; } /** * Returns the number of annotations from the specified origin. If there are no annotations * * @param origin * the origin * @return the number of annotations from the specified origin */ public int getNumberOfAnnotationsByOrigin(final String origin) { Map<String, Integer> mapping = getMapping(); if (mapping.containsKey(origin)) { return mapping.get(origin); } return 0; } private Map<String, Integer> getMapping() { synchronized (mappingLock) { if (annotationsByOrigin == null || annotationsByOrigin.get() == null) { Map<String, Integer> mapping = countAnnotations(); annotationsByOrigin = newReference(mapping); return mapping; } return annotationsByOrigin.get(); } } }
package org.apache.qpid.contrib.json; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.FileBasedConfiguration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.Parameters; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.qpid.contrib.json.utils.BZip2Utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; /** * * @author * ampq 4.0 */ public class SendMessageUtils { /** * * * @param queueName * * @param object * * @throws Exception */ public static void sendMessage(String queueName, Object... object) throws Exception { Configuration config = null; boolean isCompress = false; Parameters params = new Parameters(); FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>( PropertiesConfiguration.class).configure(params.properties().setFileName("rabbitmq.properties")); try { config = builder.getConfiguration(); } catch (ConfigurationException cex) { cex.printStackTrace(); } ConnectionFactory factory = new ConnectionFactory(); // System.out.println(); factory.setHost(config.getString("hostname")); factory.setUsername(config.getString("username")); factory.setPassword(config.getString("password")); factory.useNio(); if (config.containsKey("isCompress")) { isCompress = config.getBoolean("isCompress"); } if (config.containsKey("port")) { factory.setPort(config.getInt("port")); } else { factory.setPort(AMQP.PROTOCOL.PORT); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(queueName, true, false, false, null); String jsonMessage; Object[] messages = object; for (Object object2 : messages) { jsonMessage = JSON.toJSONString(object2, SerializerFeature.WriteClassName); if (isCompress) { channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, BZip2Utils.compress(jsonMessage.getBytes())); } else { channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, jsonMessage.getBytes()); } } channel.close(); connection.close(); } }
package hudson.plugins.disk_usage; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Run; import hudson.model.ItemGroup; import hudson.model.ProminentProjectAction; import hudson.util.ChartUtil.NumberOnlyBuildLabel; import hudson.util.DataSetBuilder; import hudson.util.Graph; import hudson.util.RunList; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.TreeMap; import jenkins.model.Jenkins; import org.jfree.data.category.DefaultCategoryDataset; /** * Disk usage of a project * * @author dvrzalik */ public class ProjectDiskUsageAction implements ProminentProjectAction { AbstractProject<? extends AbstractProject, ? extends AbstractBuild> project; public ProjectDiskUsageAction(AbstractProject<? extends AbstractProject, ? extends AbstractBuild> project) { this.project = project; } public String getIconFileName() { return null; } public String getDisplayName() { return Messages.DisplayName(); } public String getUrlName() { return Messages.UrlName(); } public Long getDiskUsageWorkspace(){ DiskUsageProperty property = project.getProperty(DiskUsageProperty.class); if(property==null) return 0l; return property.getAllWorkspaceSize(); } public Long getAllSlaveWorkspaces(){ return getAllDiskUsageWorkspace() - getAllCustomOrNonSlaveWorkspaces(); } public Long getAllCustomOrNonSlaveWorkspaces(){ Long diskUsage = 0l; DiskUsageProperty property = project.getProperty(DiskUsageProperty.class); if(property!=null){ diskUsage += property.getAllNonSlaveOrCustomWorkspaceSize(); } if(project instanceof ItemGroup){ ItemGroup group = (ItemGroup) project; for(Object i:group.getItems()){ if(i instanceof AbstractProject){ AbstractProject p = (AbstractProject) i; DiskUsageProperty prop = (DiskUsageProperty) p.getProperty(DiskUsageProperty.class); if(prop!=null){ diskUsage += prop.getAllNonSlaveOrCustomWorkspaceSize(); } } } } return diskUsage; } /** * Returns all workspace disku usage including workspace usage its sub-projects * * @return disk usage project and its sub-projects */ public Long getAllDiskUsageWorkspace(){ Long diskUsage = 0l; DiskUsageProperty property = project.getProperty(DiskUsageProperty.class); if(property!=null){ diskUsage += property.getAllWorkspaceSize(); } if(project instanceof ItemGroup){ ItemGroup group = (ItemGroup) project; for(Object i:group.getItems()){ if(i instanceof AbstractProject){ AbstractProject p = (AbstractProject) i; DiskUsageProperty prop = (DiskUsageProperty) p.getProperty(DiskUsageProperty.class); if(prop!=null){ diskUsage += prop.getAllWorkspaceSize(); } } } } return diskUsage; } public String getSizeInString(Long size){ return DiskUsageUtil.getSizeString(size); } public Long getDiskUsageWithoutBuilds(){ DiskUsageProperty property = project.getProperty(DiskUsageProperty.class); if(property==null) return 0l; return property.getDiskUsageWithoutBuilds(); } public Long getAllDiskUsageWithoutBuilds(){ DiskUsageProperty property = project.getProperty(DiskUsageProperty.class); if(property==null) return 0l; return property.getAllDiskUsageWithoutBuilds(); } public Long getJobRootDirDiskUsage(){ return getBuildsDiskUsage().get("all") + getDiskUsageWithoutBuilds(); } private Map<String,Long> getBuildsDiskUsageAllSubItems(ItemGroup group, Date older, Date yonger){ Map<String,Long> diskUsage = new TreeMap<String,Long>(); Long buildsDiskUsage = 0l; Long locked = 0l; for(Object item: group.getItems()){ if(item instanceof ItemGroup){ ItemGroup subGroup = (ItemGroup) item; buildsDiskUsage += getBuildsDiskUsageAllSubItems(subGroup, older, yonger).get("all"); locked += getBuildsDiskUsageAllSubItems(subGroup, older, yonger).get("locked"); } if(item instanceof AbstractProject){ AbstractProject p = (AbstractProject) item; List<AbstractBuild> builds = p.getBuilds(); for(AbstractBuild build : builds){ BuildDiskUsageAction action = build.getAction(BuildDiskUsageAction.class); if(older!=null && !build.getTimestamp().getTime().before(older)) continue; if(yonger!=null && !build.getTimestamp().getTime().after(yonger)) continue; if (action != null) { buildsDiskUsage += action.getDiskUsage(); if(build.isKeepLog()) locked += action.getDiskUsage(); } } } } diskUsage.put("all", buildsDiskUsage); diskUsage.put("locked", locked); return diskUsage; } public Map<String, Long> getBuildsDiskUsage() { return getBuildsDiskUsage(null, null); } public Long getAllBuildsDiskUsage(){ return getBuildsDiskUsage(null, null).get("all"); } /** * @return Disk usage for all builds */ public Map<String, Long> getBuildsDiskUsage(Date older, Date yonger) { Map<String,Long> diskUsage = new TreeMap<String,Long>(); Long buildsDiskUsage = 0l; Long locked = 0l; if (project != null) { for(AbstractBuild build: project.getBuilds()){ if(older!=null && !build.getTimestamp().getTime().before(older)) continue; if(yonger!=null && !build.getTimestamp().getTime().after(yonger)) continue; BuildDiskUsageAction action = build.getAction(BuildDiskUsageAction.class); if (action != null) { buildsDiskUsage += action.getDiskUsage(); if(build.isKeepLog()) locked += action.getDiskUsage(); } } if(project instanceof ItemGroup){ ItemGroup group = (ItemGroup) project; buildsDiskUsage += getBuildsDiskUsageAllSubItems(group, older, yonger).get("all"); locked += getBuildsDiskUsageAllSubItems(group,older, yonger).get("locked"); } } diskUsage.put("all", buildsDiskUsage); diskUsage.put("locked", locked); return diskUsage; } public BuildDiskUsageAction getLastBuildAction() { Run run = project.getLastBuild(); if (run != null) { return run.getAction(BuildDiskUsageAction.class); } return null; } /** * Generates a graph with disk usage trend * */ public Graph getGraph() throws IOException { //TODO if(nothing_changed) return; List<Object[]> usages = new ArrayList<Object[]>(); long maxValue = 0; long maxValueWorkspace = 0; maxValueWorkspace = Math.max(getAllCustomOrNonSlaveWorkspaces(), getAllSlaveWorkspaces()); maxValue = getJobRootDirDiskUsage(); //First iteration just to get scale of the y-axis RunList<? extends AbstractBuild> builds = project.getBuilds(); //do it in reverse order for (int i=builds.size()-1; i>=0; i AbstractBuild build = builds.get(i); BuildDiskUsageAction dua = build.getAction(BuildDiskUsageAction.class); if (dua != null) { usages.add(new Object[]{build, getJobRootDirDiskUsage(), dua.getAllDiskUsage(), getAllSlaveWorkspaces(), getAllCustomOrNonSlaveWorkspaces()}); maxValue = Math.max(maxValue, dua.getAllDiskUsage()); } } int floor = (int) DiskUsageUtil.getScale(maxValue); String unit = DiskUsageUtil.getUnitString(floor); int workspaceFloor = (int) DiskUsageUtil.getScale(maxValueWorkspace); String workspaceUnit = DiskUsageUtil.getUnitString(workspaceFloor); double base = Math.pow(1024, floor); double workspaceBase = Math.pow(1024, workspaceFloor); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); DefaultCategoryDataset dataset2 = new DefaultCategoryDataset(); for (Object[] usage : usages) { NumberOnlyBuildLabel label = new NumberOnlyBuildLabel((AbstractBuild) usage[0]); dataset.addValue(((Long) usage[1]) / base, "job directory", label); dataset.addValue(((Long) usage[2]) / base, "build directory", label); dataset2.addValue(((Long) usage[3]) / workspaceBase, "all slave workspaces of job", label); dataset2.addValue(((Long) usage[4]) / workspaceBase, "all non slave workspaces of job", label); } return new DiskUsageGraph(dataset, unit, dataset2, workspaceUnit); } /** Shortcut for the jelly view */ public boolean showGraph() { return Jenkins.getInstance().getPlugin(DiskUsagePlugin.class).getConfiguration().isShowGraph(); } }
package org.apache.xerces.impl.dv.xs; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.impl.dv.DatatypeException; import org.apache.xerces.impl.dv.InvalidDatatypeFacetException; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.ValidationContext; import org.apache.xerces.impl.dv.XSFacets; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.xpath.regex.RegularExpression; import org.apache.xerces.impl.xs.psvi.StringList; import org.apache.xerces.impl.xs.psvi.XSAnnotation; import org.apache.xerces.impl.xs.psvi.XSConstants; import org.apache.xerces.impl.xs.psvi.XSFacet; import org.apache.xerces.impl.xs.psvi.XSMultiValueFacet; import org.apache.xerces.impl.xs.psvi.XSNamespaceItem; import org.apache.xerces.impl.xs.psvi.XSObjectList; import org.apache.xerces.impl.xs.psvi.XSSimpleTypeDefinition; import org.apache.xerces.impl.xs.psvi.XSTypeDefinition; import org.apache.xerces.impl.xs.util.StringListImpl; import org.apache.xerces.impl.xs.util.XSObjectListImpl; import org.apache.xerces.util.XMLChar; import org.apache.xerces.xni.NamespaceContext; /** * @author Sandy Gao, IBM * @author Neeraj Bajaj, Sun Microsystems, inc. * * @version $Id$ */ public class XSSimpleTypeDecl implements XSSimpleType { static final short DV_STRING = PRIMITIVE_STRING; static final short DV_BOOLEAN = PRIMITIVE_BOOLEAN; static final short DV_DECIMAL = PRIMITIVE_DECIMAL; static final short DV_FLOAT = PRIMITIVE_FLOAT; static final short DV_DOUBLE = PRIMITIVE_DOUBLE; static final short DV_DURATION = PRIMITIVE_DURATION; static final short DV_DATETIME = PRIMITIVE_DATETIME; static final short DV_TIME = PRIMITIVE_TIME; static final short DV_DATE = PRIMITIVE_DATE; static final short DV_GYEARMONTH = PRIMITIVE_GYEARMONTH; static final short DV_GYEAR = PRIMITIVE_GYEAR; static final short DV_GMONTHDAY = PRIMITIVE_GMONTHDAY; static final short DV_GDAY = PRIMITIVE_GDAY; static final short DV_GMONTH = PRIMITIVE_GMONTH; static final short DV_HEXBINARY = PRIMITIVE_HEXBINARY; static final short DV_BASE64BINARY = PRIMITIVE_BASE64BINARY; static final short DV_ANYURI = PRIMITIVE_ANYURI; static final short DV_QNAME = PRIMITIVE_QNAME; static final short DV_NOTATION = PRIMITIVE_NOTATION; static final short DV_ANYSIMPLETYPE = 0; static final short DV_ID = DV_NOTATION + 1; static final short DV_IDREF = DV_NOTATION + 2; static final short DV_ENTITY = DV_NOTATION + 3; static final short DV_INTEGER = DV_NOTATION + 4; static final short DV_LIST = DV_NOTATION + 5; static final short DV_UNION = DV_NOTATION + 6; static final TypeValidator[] fDVs = { new AnySimpleDV(), new StringDV(), new BooleanDV(), new DecimalDV(), new FloatDV(), new DoubleDV(), new DurationDV(), new DateTimeDV(), new TimeDV(), new DateDV(), new YearMonthDV(), new YearDV(), new MonthDayDV(), new DayDV(), new MonthDV(), new HexBinaryDV(), new Base64BinaryDV(), new AnyURIDV(), new QNameDV(), new QNameDV(), // notation use the same one as qname new IDDV(), new IDREFDV(), new EntityDV(), new IntegerDV(), new ListDV(), new UnionDV() }; static final short NORMALIZE_NONE = 0; static final short NORMALIZE_TRIM = 1; static final short NORMALIZE_FULL = 2; static final short[] fDVNormalizeType = { NORMALIZE_NONE, //AnySimpleDV(), NORMALIZE_FULL, //StringDV(), NORMALIZE_TRIM, //BooleanDV(), NORMALIZE_TRIM, //DecimalDV(), NORMALIZE_TRIM, //FloatDV(), NORMALIZE_TRIM, //DoubleDV(), NORMALIZE_TRIM, //DurationDV(), NORMALIZE_TRIM, //DateTimeDV(), NORMALIZE_TRIM, //TimeDV(), NORMALIZE_TRIM, //DateDV(), NORMALIZE_TRIM, //YearMonthDV(), NORMALIZE_TRIM, //YearDV(), NORMALIZE_TRIM, //MonthDayDV(), NORMALIZE_TRIM, //DayDV(), NORMALIZE_TRIM, //MonthDV(), NORMALIZE_TRIM, //HexBinaryDV(), NORMALIZE_NONE, //Base64BinaryDV(), // Base64 know how to deal with spaces NORMALIZE_TRIM, //AnyURIDV(), NORMALIZE_TRIM, //QNameDV(), NORMALIZE_TRIM, //QNameDV(), // notation NORMALIZE_TRIM, //IDDV(), NORMALIZE_TRIM, //IDREFDV(), NORMALIZE_TRIM, //EntityDV(), NORMALIZE_TRIM, //IntegerDV(), NORMALIZE_FULL, //ListDV(), NORMALIZE_NONE, //UnionDV() }; static final short SPECIAL_PATTERN_NONE = 0; static final short SPECIAL_PATTERN_NMTOKEN = 1; static final short SPECIAL_PATTERN_NAME = 2; static final short SPECIAL_PATTERN_NCNAME = 3; static final String[] SPECIAL_PATTERN_STRING = { "NONE", "NMTOKEN", "Name", "NCName" }; static final String[] WS_FACET_STRING = { "preserve", "replace", "collapse" }; static final String URI_SCHEMAFORSCHEMA = "http: static final String ANY_TYPE = "anyType"; static final ValidationContext fEmptyContext = new ValidationContext() { public boolean needFacetChecking() { return true; } public boolean needExtraChecking() { return false; } public boolean needToNormalize() { return true; } public boolean useNamespaces () { return true; } public boolean isEntityDeclared (String name) { return false; } public boolean isEntityUnparsed (String name) { return false; } public boolean isIdDeclared (String name) { return false; } public void addId(String name) { } public void addIdRef(String name) { } public String getSymbol (String symbol) { return null; } public String getURI(String prefix) { return null; } }; // this will be true if this is a static XSSimpleTypeDecl // and hence must remain immutable (i.e., applyFacets // may not be permitted to have any effect). private boolean fIsImmutable = false; private XSSimpleTypeDecl fItemType; private XSSimpleTypeDecl[] fMemberTypes; private String fTypeName; private String fTargetNamespace; private short fFinalSet = 0; private XSSimpleTypeDecl fBase; private short fVariety = -1; private short fValidationDV = -1; private short fFacetsDefined = 0; private short fFixedFacet = 0; //for constraining facets private short fWhiteSpace = 0; private int fLength = -1; private int fMinLength = -1; private int fMaxLength = -1; private int fTotalDigits = -1; private int fFractionDigits = -1; private Vector fPattern; private Vector fPatternStr; private Vector fEnumeration; private StringList fLexicalPattern; private StringList fLexicalEnumeration; private Object fMaxInclusive; private Object fMaxExclusive; private Object fMinExclusive; private Object fMinInclusive; // annotations for constraining facets public XSAnnotation lengthAnnotation; public XSAnnotation minLengthAnnotation; public XSAnnotation maxLengthAnnotation; public XSAnnotation whiteSpaceAnnotation; public XSAnnotation totalDigitsAnnotation; public XSAnnotation fractionDigitsAnnotation; public XSObjectListImpl patternAnnotations; public XSObjectList enumerationAnnotations; public XSAnnotation maxInclusiveAnnotation; public XSAnnotation maxExclusiveAnnotation; public XSAnnotation minInclusiveAnnotation; public XSAnnotation minExclusiveAnnotation; // facets as objects private XSObjectListImpl fFacets; // enumeration and pattern facets private XSObjectListImpl fMultiValueFacets; // simpleType annotations private XSObjectList fAnnotations = null; private short fPatternType = SPECIAL_PATTERN_NONE; // for fundamental facets private short fOrdered; private boolean fFinite; private boolean fBounded; private boolean fNumeric; // default constructor public XSSimpleTypeDecl(){} //Create a new built-in primitive types (and id/idref/entity/integer) protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, short validateDV, short ordered, boolean bounded, boolean finite, boolean numeric, boolean isImmutable) { fIsImmutable = isImmutable; fBase = base; fTypeName = name; fTargetNamespace = URI_SCHEMAFORSCHEMA; // To simplify the code for anySimpleType, we treat it as an atomic type fVariety = VARIETY_ATOMIC; fValidationDV = validateDV; fFacetsDefined = FACET_WHITESPACE; if (validateDV == DV_STRING) { fWhiteSpace = WS_PRESERVE; } else { fWhiteSpace = WS_COLLAPSE; fFixedFacet = FACET_WHITESPACE; } this.fOrdered = ordered; this.fBounded = bounded; this.fFinite = finite; this.fNumeric = numeric; fAnnotations = null; } //Create a new simple type for restriction. protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet, boolean isImmutable, XSObjectList annotations) { fBase = base; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = fBase.fVariety; fValidationDV = fBase.fValidationDV; switch (fVariety) { case VARIETY_ATOMIC: break; case VARIETY_LIST: fItemType = fBase.fItemType; break; case VARIETY_UNION: fMemberTypes = fBase.fMemberTypes; break; } // always inherit facets from the base. // in case a type is created, but applyFacets is not called fLength = fBase.fLength; fMinLength = fBase.fMinLength; fMaxLength = fBase.fMaxLength; fPattern = fBase.fPattern; fPatternStr = fBase.fPatternStr; fEnumeration = fBase.fEnumeration; fWhiteSpace = fBase.fWhiteSpace; fMaxExclusive = fBase.fMaxExclusive; fMaxInclusive = fBase.fMaxInclusive; fMinExclusive = fBase.fMinExclusive; fMinInclusive = fBase.fMinInclusive; fTotalDigits = fBase.fTotalDigits; fFractionDigits = fBase.fFractionDigits; fPatternType = fBase.fPatternType; fFixedFacet = fBase.fFixedFacet; fFacetsDefined = fBase.fFacetsDefined; //we also set fundamental facets information in case applyFacets is not called. caclFundamentalFacets(); fIsImmutable = isImmutable; } //Create a new simple type for list. protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl itemType, boolean isImmutable, XSObjectList annotations) { fBase = fAnySimpleType; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_LIST; fItemType = (XSSimpleTypeDecl)itemType; fValidationDV = DV_LIST; fFacetsDefined = FACET_WHITESPACE; fFixedFacet = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets caclFundamentalFacets(); fIsImmutable = isImmutable; } //Create a new simple type for union. protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes, XSObjectList annotations) { fBase = fAnySimpleType; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_UNION; fMemberTypes = memberTypes; fValidationDV = DV_UNION; // even for union, we set whitespace to something // this will never be used, but we can use fFacetsDefined to check // whether applyFacets() is allwwed: it's not allowed // if fFacetsDefined != 0 fFacetsDefined = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets caclFundamentalFacets(); // none of the schema-defined types are unions, so just set // fIsImmutable to false. fIsImmutable = false; } //set values for restriction. protected XSSimpleTypeDecl setRestrictionValues(XSSimpleTypeDecl base, String name, String uri, short finalSet, XSObjectList annotations) { //decline to do anything if the object is immutable. if(fIsImmutable) return null; fBase = base; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = fBase.fVariety; fValidationDV = fBase.fValidationDV; switch (fVariety) { case VARIETY_ATOMIC: break; case VARIETY_LIST: fItemType = fBase.fItemType; break; case VARIETY_UNION: fMemberTypes = fBase.fMemberTypes; break; } // always inherit facets from the base. // in case a type is created, but applyFacets is not called fLength = fBase.fLength; fMinLength = fBase.fMinLength; fMaxLength = fBase.fMaxLength; fPattern = fBase.fPattern; fPatternStr = fBase.fPatternStr; fEnumeration = fBase.fEnumeration; fWhiteSpace = fBase.fWhiteSpace; fMaxExclusive = fBase.fMaxExclusive; fMaxInclusive = fBase.fMaxInclusive; fMinExclusive = fBase.fMinExclusive; fMinInclusive = fBase.fMinInclusive; fTotalDigits = fBase.fTotalDigits; fFractionDigits = fBase.fFractionDigits; fPatternType = fBase.fPatternType; fFixedFacet = fBase.fFixedFacet; fFacetsDefined = fBase.fFacetsDefined; //we also set fundamental facets information in case applyFacets is not called. caclFundamentalFacets(); return this; } //set values for list. protected XSSimpleTypeDecl setListValues(String name, String uri, short finalSet, XSSimpleTypeDecl itemType, XSObjectList annotations) { //decline to do anything if the object is immutable. if(fIsImmutable) return null; fBase = fAnySimpleType; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_LIST; fItemType = (XSSimpleTypeDecl)itemType; fValidationDV = DV_LIST; fFacetsDefined = FACET_WHITESPACE; fFixedFacet = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets caclFundamentalFacets(); return this; } //set values for union. protected XSSimpleTypeDecl setUnionValues(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes, XSObjectList annotations) { //decline to do anything if the object is immutable. if(fIsImmutable) return null; fBase = fAnySimpleType; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_UNION; fMemberTypes = memberTypes; fValidationDV = DV_UNION; // even for union, we set whitespace to something // this will never be used, but we can use fFacetsDefined to check // whether applyFacets() is allwwed: it's not allowed // if fFacetsDefined != 0 fFacetsDefined = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets caclFundamentalFacets(); return this; } public short getType () { return XSConstants.TYPE_DEFINITION; } public short getTypeCategory () { return SIMPLE_TYPE; } public String getName() { return fTypeName; } public String getNamespace() { return fTargetNamespace; } public short getFinal(){ return fFinalSet; } public boolean isFinal(short derivation) { return (fFinalSet & derivation) != 0; } public XSTypeDefinition getBaseType(){ return fBase; } public boolean getAnonymous() { return fTypeName == null; } public short getVariety(){ // for anySimpleType, return absent variaty return fValidationDV == DV_ANYSIMPLETYPE ? VARIETY_ABSENT : fVariety; } public boolean isIDType(){ switch (fVariety) { case VARIETY_ATOMIC: return fValidationDV == DV_ID; case VARIETY_LIST: return fItemType.isIDType(); case VARIETY_UNION: for (int i = 0; i < fMemberTypes.length; i++) { if (fMemberTypes[i].isIDType()) return true; } } return false; } public short getWhitespace() throws DatatypeException{ if (fVariety == VARIETY_UNION) { throw new DatatypeException("dt-whitespace", new Object[]{fTypeName}); } return fWhiteSpace; } public short getPrimitiveKind() { if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) { if (fValidationDV == DV_ID || fValidationDV == DV_IDREF || fValidationDV == DV_ENTITY) return DV_STRING; else if (fValidationDV == DV_INTEGER) return DV_DECIMAL; else return fValidationDV; } else { // REVISIT: error situation. runtime exception? return (short)0; } } public XSSimpleTypeDefinition getPrimitiveType() { if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) { XSSimpleTypeDecl pri = this; // recursively get base, until we reach anySimpleType while (pri.fBase != fAnySimpleType) pri = pri.fBase; return pri; } else { // REVISIT: error situation. runtime exception? return null; } } public XSSimpleTypeDefinition getItemType() { if (fVariety == VARIETY_LIST) { return fItemType; } else { // REVISIT: error situation. runtime exception? return null; } } public XSObjectList getMemberTypes() { if (fVariety == VARIETY_UNION) { return new XSObjectListImpl(fMemberTypes, fMemberTypes.length); } else { // REVISIT: error situation. runtime exception? return null; } } /** * If <restriction> is chosen */ public void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, ValidationContext context) throws InvalidDatatypeFacetException { applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, context); } /** * built-in derived types by restriction */ void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet) { try { applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, fDummyContext); } catch (InvalidDatatypeFacetException e) { // should never gets here, internel error throw new RuntimeException("internal error"); } // we've now applied facets; so lock this object: fIsImmutable = true; } /** * built-in derived types by restriction */ void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet, short patternType) { try { applyFacets(facets, presentFacet, fixedFacet, patternType, fDummyContext); } catch (InvalidDatatypeFacetException e) { // should never gets here, internel error throw new RuntimeException("internal error"); } // we've now applied facets; so lock this object: fIsImmutable = true; } /** * If <restriction> is chosen, or built-in derived types by restriction */ void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, short patternType, ValidationContext context) throws InvalidDatatypeFacetException { // if the object is immutable, should not apply facets... if(fIsImmutable) return; ValidatedInfo tempInfo = new ValidatedInfo(); // clear facets. because we always inherit facets in the constructor // REVISIT: in fact, we don't need to clear them. // we can convert 5 string values (4 bounds + 1 enum) to actual values, // store them somewhere, then do facet checking at once, instead of // going through the following steps. (lots of checking are redundant: // for example, ((presentFacet & FACET_XXX) != 0)) fFacetsDefined = 0; fFixedFacet = 0; int result = 0 ; // step 1: parse present facets short allowedFacet = fDVs[fValidationDV].getAllowedFacets(); // length if ((presentFacet & FACET_LENGTH) != 0) { if ((allowedFacet & FACET_LENGTH) == 0) { reportError("cos-applicable-facets", new Object[]{"length", fTypeName}); } else { fLength = facets.length; lengthAnnotation = facets.lengthAnnotation; fFacetsDefined |= FACET_LENGTH; if ((fixedFacet & FACET_LENGTH) != 0) fFixedFacet |= FACET_LENGTH; } } // minLength if ((presentFacet & FACET_MINLENGTH) != 0) { if ((allowedFacet & FACET_MINLENGTH) == 0) { reportError("cos-applicable-facets", new Object[]{"minLength", fTypeName}); } else { fMinLength = facets.minLength; minLengthAnnotation = facets.minLengthAnnotation; fFacetsDefined |= FACET_MINLENGTH; if ((fixedFacet & FACET_MINLENGTH) != 0) fFixedFacet |= FACET_MINLENGTH; } } // maxLength if ((presentFacet & FACET_MAXLENGTH) != 0) { if ((allowedFacet & FACET_MAXLENGTH) == 0) { reportError("cos-applicable-facets", new Object[]{"maxLength", fTypeName}); } else { fMaxLength = facets.maxLength; maxLengthAnnotation = facets.maxLengthAnnotation; fFacetsDefined |= FACET_MAXLENGTH; if ((fixedFacet & FACET_MAXLENGTH) != 0) fFixedFacet |= FACET_MAXLENGTH; } } // pattern if ((presentFacet & FACET_PATTERN) != 0) { if ((allowedFacet & FACET_PATTERN) == 0) { reportError("cos-applicable-facets", new Object[]{"pattern", fTypeName}); } else { patternAnnotations = facets.patternAnnotations; RegularExpression regex = null; try { regex = new RegularExpression(facets.pattern, "X"); } catch (Exception e) { reportError("InvalidRegex", new Object[]{facets.pattern, e.getLocalizedMessage()}); } if (regex != null) { fPattern = new Vector(); fPattern.addElement(regex); fPatternStr = new Vector(); fPatternStr.addElement(facets.pattern); fFacetsDefined |= FACET_PATTERN; if ((fixedFacet & FACET_PATTERN) != 0) fFixedFacet |= FACET_PATTERN; } } } // enumeration if ((presentFacet & FACET_ENUMERATION) != 0) { if ((allowedFacet & FACET_ENUMERATION) == 0) { reportError("cos-applicable-facets", new Object[]{"enumeration", fTypeName}); } else { fEnumeration = new Vector(); Vector enumVals = facets.enumeration; Vector enumNSDecls = facets.enumNSDecls; ValidationContextImpl ctx = new ValidationContextImpl(context); enumerationAnnotations = facets.enumAnnotations; for (int i = 0; i < enumVals.size(); i++) { if (enumNSDecls != null) ctx.setNSContext((NamespaceContext)enumNSDecls.elementAt(i)); try { // check 4.3.5.c0 must: enumeration values from the value space of base fEnumeration.addElement(this.fBase.validate((String)enumVals.elementAt(i), ctx, tempInfo)); } catch (InvalidDatatypeValueException ide) { reportError("enumeration-valid-restriction", new Object[]{enumVals.elementAt(i), this.getBaseType().getName()}); } } fFacetsDefined |= FACET_ENUMERATION; if ((fixedFacet & FACET_ENUMERATION) != 0) fFixedFacet |= FACET_ENUMERATION; } } // whiteSpace if ((presentFacet & FACET_WHITESPACE) != 0) { if ((allowedFacet & FACET_WHITESPACE) == 0) { reportError("cos-applicable-facets", new Object[]{"whiteSpace", fTypeName}); } else { fWhiteSpace = facets.whiteSpace; whiteSpaceAnnotation = facets.whiteSpaceAnnotation; fFacetsDefined |= FACET_WHITESPACE; if ((fixedFacet & FACET_WHITESPACE) != 0) fFixedFacet |= FACET_WHITESPACE; } } boolean needCheckBase = true; // maxInclusive if ((presentFacet & FACET_MAXINCLUSIVE) != 0) { if ((allowedFacet & FACET_MAXINCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"maxInclusive", fTypeName}); } else { maxInclusiveAnnotation = facets.maxInclusiveAnnotation; try { fMaxInclusive = getActualValue(facets.maxInclusive, context, tempInfo, true); fFacetsDefined |= FACET_MAXINCLUSIVE; if ((fixedFacet & FACET_MAXINCLUSIVE) != 0) fFixedFacet |= FACET_MAXINCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive, "maxInclusive", fBase.getName()}); } // maxInclusive from base if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive); if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName}); } if (result == 0) { needCheckBase = false; } } if (needCheckBase) { try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive, "maxInclusive", fBase.getName()}); } } } } // maxExclusive needCheckBase = true; if ((presentFacet & FACET_MAXEXCLUSIVE) != 0) { if ((allowedFacet & FACET_MAXEXCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"maxExclusive", fTypeName}); } else { maxExclusiveAnnotation = facets.maxExclusiveAnnotation; try { fMaxExclusive = getActualValue(facets.maxExclusive, context, tempInfo, true); fFacetsDefined |= FACET_MAXEXCLUSIVE; if ((fixedFacet & FACET_MAXEXCLUSIVE) != 0) fFixedFacet |= FACET_MAXEXCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive, "maxExclusive", fBase.getName()}); } // maxExclusive from base if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive); if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"maxExclusive", facets.maxExclusive, fBase.fMaxExclusive, fTypeName}); } if (result == 0) { needCheckBase = false; } } if (needCheckBase) { try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive, "maxExclusive", fBase.getName()}); } } } } // minExclusive needCheckBase = true; if ((presentFacet & FACET_MINEXCLUSIVE) != 0) { if ((allowedFacet & FACET_MINEXCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"minExclusive", fTypeName}); } else { minExclusiveAnnotation = facets.minExclusiveAnnotation; try { fMinExclusive = getActualValue(facets.minExclusive, context, tempInfo, true); fFacetsDefined |= FACET_MINEXCLUSIVE; if ((fixedFacet & FACET_MINEXCLUSIVE) != 0) fFixedFacet |= FACET_MINEXCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive, "minExclusive", fBase.getName()}); } // minExclusive from base if (((fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive); if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"minExclusive", facets.minExclusive, fBase.fMinExclusive, fTypeName}); } if (result == 0) { needCheckBase = false; } } if (needCheckBase) { try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive, "minExclusive", fBase.getName()}); } } } } // minInclusive needCheckBase = true; if ((presentFacet & FACET_MININCLUSIVE) != 0) { if ((allowedFacet & FACET_MININCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"minInclusive", fTypeName}); } else { minInclusiveAnnotation = facets.minInclusiveAnnotation; try { fMinInclusive = getActualValue(facets.minInclusive, context, tempInfo, true); fFacetsDefined |= FACET_MININCLUSIVE; if ((fixedFacet & FACET_MININCLUSIVE) != 0) fFixedFacet |= FACET_MININCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive, "minInclusive", fBase.getName()}); } // minInclusive from base if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive); if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"minInclusive", facets.minInclusive, fBase.fMinInclusive, fTypeName}); } if (result == 0) { needCheckBase = false; } } if (needCheckBase) { try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive, "minInclusive", fBase.getName()}); } } } } // totalDigits if ((presentFacet & FACET_TOTALDIGITS) != 0) { if ((allowedFacet & FACET_TOTALDIGITS) == 0) { reportError("cos-applicable-facets", new Object[]{"totalDigits", fTypeName}); } else { totalDigitsAnnotation = facets.totalDigitsAnnotation; fTotalDigits = facets.totalDigits; fFacetsDefined |= FACET_TOTALDIGITS; if ((fixedFacet & FACET_TOTALDIGITS) != 0) fFixedFacet |= FACET_TOTALDIGITS; } } // fractionDigits if ((presentFacet & FACET_FRACTIONDIGITS) != 0) { if ((allowedFacet & FACET_FRACTIONDIGITS) == 0) { reportError("cos-applicable-facets", new Object[]{"fractionDigits", fTypeName}); } else { fFractionDigits = facets.fractionDigits; fractionDigitsAnnotation = facets.fractionDigitsAnnotation; fFacetsDefined |= FACET_FRACTIONDIGITS; if ((fixedFacet & FACET_FRACTIONDIGITS) != 0) fFixedFacet |= FACET_FRACTIONDIGITS; } } // token type: internal use, so do less checking if (patternType != SPECIAL_PATTERN_NONE) { fPatternType = patternType; } // step 2: check facets against each other: length, bounds if(fFacetsDefined != 0) { // check 4.3.1.c1 error: length & (maxLength | minLength) if((fFacetsDefined & FACET_LENGTH) != 0 ){ if ((fFacetsDefined & FACET_MINLENGTH) != 0) { if ((fFacetsDefined & FACET_MAXLENGTH) != 0) { // length, minLength and maxLength defined reportError("length-minLength-maxLength.a", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fMinLength), Integer.toString(fMaxLength)}); } else { // length and minLength defined reportError("length-minLength-maxLength.b", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fMinLength)}); } } else if ((fFacetsDefined & FACET_MAXLENGTH) != 0) { // length and maxLength defined reportError("length-minLength-maxLength.c", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fMaxLength)}); } } // check 4.3.2.c1 must: minLength <= maxLength if(((fFacetsDefined & FACET_MINLENGTH ) != 0 ) && ((fFacetsDefined & FACET_MAXLENGTH) != 0)) { if(fMinLength > fMaxLength) reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fMaxLength), fTypeName}); } // check 4.3.8.c1 error: maxInclusive + maxExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { reportError( "maxInclusive-maxExclusive", new Object[]{fMaxInclusive, fMaxExclusive, fTypeName}); } // check 4.3.9.c1 error: minInclusive + minExclusive if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { reportError("minInclusive-minExclusive", new Object[]{fMinInclusive, fMinExclusive, fTypeName}); } // check 4.3.7.c1 must: minInclusive <= maxInclusive if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinInclusive, fMaxInclusive); if (result != -1 && result != 0) reportError("minInclusive-less-than-equal-to-maxInclusive", new Object[]{fMinInclusive, fMaxInclusive, fTypeName}); } // check 4.3.8.c2 must: minExclusive <= maxExclusive ??? minExclusive < maxExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinExclusive, fMaxExclusive); if (result != -1 && result != 0) reportError( "minExclusive-less-than-equal-to-maxExclusive", new Object[]{fMinExclusive, fMaxExclusive, fTypeName}); } // check 4.3.9.c2 must: minExclusive < maxInclusive if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { if (fDVs[fValidationDV].compare(fMinExclusive, fMaxInclusive) != -1) reportError( "minExclusive-less-than-maxInclusive", new Object[]{fMinExclusive, fMaxInclusive, fTypeName}); } // check 4.3.10.c1 must: minInclusive < maxExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { if (fDVs[fValidationDV].compare(fMinInclusive, fMaxExclusive) != -1) reportError( "minInclusive-less-than-maxExclusive", new Object[]{fMinInclusive, fMaxExclusive, fTypeName}); } // check 4.3.12.c1 must: fractionDigits <= totalDigits if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) && ((fFacetsDefined & FACET_TOTALDIGITS) != 0)) { if (fFractionDigits > fTotalDigits) reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName}); } // step 3: check facets against base // check 4.3.1.c1 error: length & (fBase.maxLength | fBase.minLength) if((fFacetsDefined & FACET_LENGTH) != 0 ){ if ((fBase.fFacetsDefined & FACET_MINLENGTH) != 0) { if ((fBase.fFacetsDefined & FACET_MAXLENGTH) != 0) { // length, fBase.minLength and fBase.maxLength defined reportError("length-minLength-maxLength.a", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fMinLength), Integer.toString(fMaxLength)}); } else { // length and fBase.minLength defined reportError("length-minLength-maxLength.b", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fMinLength)}); } } else if ((fBase.fFacetsDefined & FACET_MAXLENGTH) != 0) { // length and fBase.maxLength defined reportError("length-minLength-maxLength.c", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fMaxLength)}); } else if ( (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) { // check 4.3.1.c2 error: length != fBase.length if ( fLength != fBase.fLength ) reportError( "length-valid-restriction", new Object[]{Integer.toString(fLength), Integer.toString(fBase.fLength), fTypeName}); } } // check 4.3.1.c1 error: fBase.length & (maxLength | minLength) if((fBase.fFacetsDefined & FACET_LENGTH) != 0 ){ if ((fFacetsDefined & FACET_MINLENGTH) != 0) { if ((fFacetsDefined & FACET_MAXLENGTH) != 0) { // fBase.length, minLength and maxLength defined reportError("length-minLength-maxLength.a", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMinLength), Integer.toString(fMaxLength)}); } else { // fBase.length and minLength defined reportError("length-minLength-maxLength.b", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMinLength)}); } } else if ((fFacetsDefined & FACET_MAXLENGTH) != 0) { // fBase.length and maxLength defined reportError("length-minLength-maxLength.c", new Object[]{this, Integer.toString(fBase.fLength), Integer.toString(fMaxLength)}); } } // check 4.3.2.c1 must: minLength <= fBase.maxLength if ( ((fFacetsDefined & FACET_MINLENGTH ) != 0 ) ) { if ( (fBase.fFacetsDefined & FACET_MAXLENGTH ) != 0 ) { if ( fMinLength > fBase.fMaxLength ) { reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMaxLength), fTypeName}); } } else if ( (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) { if ( (fBase.fFixedFacet & FACET_MINLENGTH) != 0 && fMinLength != fBase.fMinLength ) { reportError( "FixedFacetValue", new Object[]{"minLength", Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName}); } // check 4.3.2.c2 error: minLength < fBase.minLength if ( fMinLength < fBase.fMinLength ) { reportError( "minLength-valid-restriction", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName}); } } } // check 4.3.2.c1 must: maxLength < fBase.minLength if ( ((fFacetsDefined & FACET_MAXLENGTH ) != 0 ) && ((fBase.fFacetsDefined & FACET_MINLENGTH ) != 0 )) { if ( fMaxLength < fBase.fMinLength) { reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fBase.fMinLength), Integer.toString(fMaxLength)}); } } // check 4.3.3.c1 error: maxLength > fBase.maxLength if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) { if ( (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ){ if(( (fBase.fFixedFacet & FACET_MAXLENGTH) != 0 )&& fMaxLength != fBase.fMaxLength ) { reportError( "FixedFacetValue", new Object[]{"maxLength", Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName}); } if ( fMaxLength > fBase.fMaxLength ) { reportError( "maxLength-valid-restriction", new Object[]{Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName}); } } } /* // check 4.3.7.c2 error: // maxInclusive > fBase.maxInclusive // maxInclusive >= fBase.maxExclusive // maxInclusive < fBase.minInclusive // maxInclusive <= fBase.minExclusive if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive); if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName}); } if (result != -1 && result != 0) { reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxInclusive, fTypeName}); } } if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxExclusive) != -1){ reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxExclusive, fTypeName}); } if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinInclusive); if (result != 1 && result != 0) { reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinExclusive ) != 1) reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinExclusive, fTypeName}); } // check 4.3.8.c3 error: // maxExclusive > fBase.maxExclusive // maxExclusive > fBase.maxInclusive // maxExclusive <= fBase.minInclusive // maxExclusive <= fBase.minExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) { if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) { result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive); if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"maxExclusive", fMaxExclusive, fBase.fMaxExclusive, fTypeName}); } if (result != -1 && result != 0) { reportError( "maxExclusive-valid-restriction.1", new Object[]{fMaxExclusive, fBase.fMaxExclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive); if (result != -1 && result != 0) { reportError( "maxExclusive-valid-restriction.2", new Object[]{fMaxExclusive, fBase.fMaxInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinExclusive ) != 1) reportError( "maxExclusive-valid-restriction.3", new Object[]{fMaxExclusive, fBase.fMinExclusive, fTypeName}); if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinInclusive) != 1) reportError( "maxExclusive-valid-restriction.4", new Object[]{fMaxExclusive, fBase.fMinInclusive, fTypeName}); } // check 4.3.9.c3 error: // minExclusive < fBase.minExclusive // minExclusive > fBase.maxInclusive // minExclusive < fBase.minInclusive // minExclusive >= fBase.maxExclusive if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { result= fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive); if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"minExclusive", fMinExclusive, fBase.fMinExclusive, fTypeName}); } if (result != 1 && result != 0) { reportError( "minExclusive-valid-restriction.1", new Object[]{fMinExclusive, fBase.fMinExclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result=fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxInclusive); if (result != -1 && result != 0) { reportError( "minExclusive-valid-restriction.2", new Object[]{fMinExclusive, fBase.fMaxInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive); if (result != 1 && result != 0) { reportError( "minExclusive-valid-restriction.3", new Object[]{fMinExclusive, fBase.fMinInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxExclusive) != -1) reportError( "minExclusive-valid-restriction.4", new Object[]{fMinExclusive, fBase.fMaxExclusive, fTypeName}); } // check 4.3.10.c2 error: // minInclusive < fBase.minInclusive // minInclusive > fBase.maxInclusive // minInclusive <= fBase.minExclusive // minInclusive >= fBase.maxExclusive if (((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive); if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"minInclusive", fMinInclusive, fBase.fMinInclusive, fTypeName}); } if (result != 1 && result != 0) { reportError( "minInclusive-valid-restriction.1", new Object[]{fMinInclusive, fBase.fMinInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result=fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxInclusive); if (result != -1 && result != 0) { reportError( "minInclusive-valid-restriction.2", new Object[]{fMinInclusive, fBase.fMaxInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinExclusive ) != 1) reportError( "minInclusive-valid-restriction.3", new Object[]{fMinInclusive, fBase.fMinExclusive, fTypeName}); if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxExclusive) != -1) reportError( "minInclusive-valid-restriction.4", new Object[]{fMinInclusive, fBase.fMaxExclusive, fTypeName}); } */ // check 4.3.11.c1 error: totalDigits > fBase.totalDigits if (((fFacetsDefined & FACET_TOTALDIGITS) != 0)) { if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0)) { if ((fBase.fFixedFacet & FACET_TOTALDIGITS) != 0 && fTotalDigits != fBase.fTotalDigits) { reportError("FixedFacetValue", new Object[]{"totalDigits", Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName}); } if (fTotalDigits > fBase.fTotalDigits) { reportError( "totalDigits-valid-restriction", new Object[]{Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName}); } } } // check 4.3.12.c1 must: fractionDigits <= base.totalDigits if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) { if ((fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) { if (fFractionDigits > fBase.fTotalDigits) reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName}); } } // check 4.3.12.c2 error: fractionDigits > fBase.fractionDigits // check fixed value for fractionDigits if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) { if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) { if ((fBase.fFixedFacet & FACET_FRACTIONDIGITS) != 0 && fFractionDigits != fBase.fFractionDigits) { reportError("FixedFacetValue", new Object[]{"fractionDigits", Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName}); } if (fFractionDigits > fBase.fFractionDigits) { reportError( "fractionDigits-valid-restriction", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName}); } } } // check 4.3.6.c1 error: // (whiteSpace = preserve || whiteSpace = replace) && fBase.whiteSpace = collapese or // whiteSpace = preserve && fBase.whiteSpace = replace if ( (fFacetsDefined & FACET_WHITESPACE) != 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ){ if ( (fBase.fFixedFacet & FACET_WHITESPACE) != 0 && fWhiteSpace != fBase.fWhiteSpace ) { reportError( "FixedFacetValue", new Object[]{"whiteSpace", whiteSpaceValue(fWhiteSpace), whiteSpaceValue(fBase.fWhiteSpace), fTypeName}); } if ( fWhiteSpace == WS_PRESERVE && fBase.fWhiteSpace == WS_COLLAPSE ){ reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "preserve"}); } if ( fWhiteSpace == WS_REPLACE && fBase.fWhiteSpace == WS_COLLAPSE ){ reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "replace"}); } if ( fWhiteSpace == WS_PRESERVE && fBase.fWhiteSpace == WS_REPLACE ){ reportError( "whiteSpace-valid-restriction.2", new Object[]{fTypeName}); } } }//fFacetsDefined != null // step 4: inherit other facets from base (including fTokeyType) // inherit length if ( (fFacetsDefined & FACET_LENGTH) == 0 && (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) { fFacetsDefined |= FACET_LENGTH; fLength = fBase.fLength; lengthAnnotation = fBase.lengthAnnotation; } // inherit minLength if ( (fFacetsDefined & FACET_MINLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) { fFacetsDefined |= FACET_MINLENGTH; fMinLength = fBase.fMinLength; minLengthAnnotation = fBase.minLengthAnnotation; } // inherit maxLength if ((fFacetsDefined & FACET_MAXLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ) { fFacetsDefined |= FACET_MAXLENGTH; fMaxLength = fBase.fMaxLength; maxLengthAnnotation = fBase.maxLengthAnnotation; } // inherit pattern if ( (fBase.fFacetsDefined & FACET_PATTERN) != 0 ) { if ((fFacetsDefined & FACET_PATTERN) == 0) { fPattern = fBase.fPattern; fPatternStr = fBase.fPatternStr; fFacetsDefined |= FACET_PATTERN; } else { for (int i = fBase.fPattern.size()-1; i >= 0; i fPattern.addElement(fBase.fPattern.elementAt(i)); fPatternStr.addElement(fBase.fPatternStr.elementAt(i)); } if (fBase.patternAnnotations != null){ for (int i = fBase.patternAnnotations.getLength()-1;i>=0;i patternAnnotations.add(fBase.patternAnnotations.item(i)); } } } } // inherit whiteSpace if ( (fFacetsDefined & FACET_WHITESPACE) == 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ) { fFacetsDefined |= FACET_WHITESPACE; fWhiteSpace = fBase.fWhiteSpace; whiteSpaceAnnotation = fBase.whiteSpaceAnnotation; } // inherit enumeration if ((fFacetsDefined & FACET_ENUMERATION) == 0 && (fBase.fFacetsDefined & FACET_ENUMERATION) != 0) { fFacetsDefined |= FACET_ENUMERATION; fEnumeration = fBase.fEnumeration; enumerationAnnotations = fBase.enumerationAnnotations; } // inherit maxExclusive if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { fFacetsDefined |= FACET_MAXEXCLUSIVE; fMaxExclusive = fBase.fMaxExclusive; maxExclusiveAnnotation = fBase.maxExclusiveAnnotation; } // inherit maxInclusive if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { fFacetsDefined |= FACET_MAXINCLUSIVE; fMaxInclusive = fBase.fMaxInclusive; maxInclusiveAnnotation = fBase.maxInclusiveAnnotation; } // inherit minExclusive if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { fFacetsDefined |= FACET_MINEXCLUSIVE; fMinExclusive = fBase.fMinExclusive; minExclusiveAnnotation = fBase.minExclusiveAnnotation; } // inherit minExclusive if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) && !((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { fFacetsDefined |= FACET_MININCLUSIVE; fMinInclusive = fBase.fMinInclusive; minInclusiveAnnotation = fBase.minInclusiveAnnotation; } // inherit totalDigits if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) && !((fFacetsDefined & FACET_TOTALDIGITS) != 0)) { fFacetsDefined |= FACET_TOTALDIGITS; fTotalDigits = fBase.fTotalDigits; totalDigitsAnnotation = fBase.totalDigitsAnnotation; } // inherit fractionDigits if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0) && !((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) { fFacetsDefined |= FACET_FRACTIONDIGITS; fFractionDigits = fBase.fFractionDigits; fractionDigitsAnnotation = fBase.fractionDigitsAnnotation; } //inherit tokeytype if ((fPatternType == SPECIAL_PATTERN_NONE ) && (fBase.fPatternType != SPECIAL_PATTERN_NONE)) { fPatternType = fBase.fPatternType ; } // step 5: mark fixed values fFixedFacet |= fBase.fFixedFacet; //step 6: setting fundamental facets caclFundamentalFacets(); } //applyFacets() /** * validate a value, and return the compiled form */ public Object validate(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { if (context == null) context = fEmptyContext; if (validatedInfo == null) validatedInfo = new ValidatedInfo(); else validatedInfo.memberType = null; // first normalize string value, and convert it to actual value boolean needNormalize = context==null||context.needToNormalize(); Object ob = getActualValue(content, context, validatedInfo, needNormalize); validate(context, validatedInfo); return ob; } /** * validate a value, and return the compiled form */ public Object validate(Object content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { if (context == null) context = fEmptyContext; if (validatedInfo == null) validatedInfo = new ValidatedInfo(); else validatedInfo.memberType = null; // first normalize string value, and convert it to actual value boolean needNormalize = context==null||context.needToNormalize(); Object ob = getActualValue(content, context, validatedInfo, needNormalize); validate(context, validatedInfo); return ob; } /** * validate an actual value against this DV * * @param value the actual value that needs to be validated * @param context the validation context * @param validatedInfo used to provide the actual value and member types */ public void validate(ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { if (context == null) context = fEmptyContext; // then validate the actual value against the facets if (context.needFacetChecking() && (fFacetsDefined != 0 && fFacetsDefined != FACET_WHITESPACE)) { checkFacets(validatedInfo); } // now check extra rules: for ID/IDREF/ENTITY if (context.needExtraChecking()) { checkExtraRules(context, validatedInfo); } } private void checkFacets(ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { Object ob = validatedInfo.actualValue; String content = validatedInfo.normalizedValue; // For QName and NOTATION types, we don't check length facets if (fValidationDV != DV_QNAME && fValidationDV != DV_NOTATION) { int length = fDVs[fValidationDV].getDataLength(ob); // maxLength if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) { if ( length > fMaxLength ) { throw new InvalidDatatypeValueException("cvc-maxLength-valid", new Object[]{content, Integer.toString(length), Integer.toString(fMaxLength), fTypeName}); } } //minLength if ( (fFacetsDefined & FACET_MINLENGTH) != 0 ) { if ( length < fMinLength ) { throw new InvalidDatatypeValueException("cvc-minLength-valid", new Object[]{content, Integer.toString(length), Integer.toString(fMinLength), fTypeName}); } } //length if ( (fFacetsDefined & FACET_LENGTH) != 0 ) { if ( length != fLength ) { throw new InvalidDatatypeValueException("cvc-length-valid", new Object[]{content, Integer.toString(length), Integer.toString(fLength), fTypeName}); } } } //enumeration if ( ((fFacetsDefined & FACET_ENUMERATION) != 0 ) ) { boolean present = false; for (int i = 0; i < fEnumeration.size(); i++) { if (fEnumeration.elementAt(i).equals(ob)) { present = true; break; } } if(!present){ throw new InvalidDatatypeValueException("cvc-enumeration-valid", new Object [] {content, fEnumeration.toString()}); } } //fractionDigits if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) { int scale = fDVs[fValidationDV].getFractionDigits(ob); if (scale > fFractionDigits) { throw new InvalidDatatypeValueException("cvc-fractionDigits-valid", new Object[] {content, Integer.toString(scale), Integer.toString(fFractionDigits)}); } } //totalDigits if ((fFacetsDefined & FACET_TOTALDIGITS)!=0) { int totalDigits = fDVs[fValidationDV].getTotalDigits(ob); if (totalDigits > fTotalDigits) { throw new InvalidDatatypeValueException("cvc-totalDigits-valid", new Object[] {content, Integer.toString(totalDigits), Integer.toString(fTotalDigits)}); } } int compare; //maxinclusive if ( (fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMaxInclusive); if (compare != -1 && compare != 0) { throw new InvalidDatatypeValueException("cvc-maxInclusive-valid", new Object[] {content, fMaxInclusive, fTypeName}); } } //maxExclusive if ( (fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMaxExclusive ); if (compare != -1) { throw new InvalidDatatypeValueException("cvc-maxExclusive-valid", new Object[] {content, fMaxExclusive, fTypeName}); } } //minInclusive if ( (fFacetsDefined & FACET_MININCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMinInclusive); if (compare != 1 && compare != 0) { throw new InvalidDatatypeValueException("cvc-minInclusive-valid", new Object[] {content, fMinInclusive, fTypeName}); } } //minExclusive if ( (fFacetsDefined & FACET_MINEXCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMinExclusive); if (compare != 1) { throw new InvalidDatatypeValueException("cvc-minExclusive-valid", new Object[] {content, fMinExclusive, fTypeName}); } } } private void checkExtraRules(ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { Object ob = validatedInfo.actualValue; if (fVariety == VARIETY_ATOMIC) { fDVs[fValidationDV].checkExtraRules(ob, context); } else if (fVariety == VARIETY_LIST) { ListDV.ListData values = (ListDV.ListData)ob; int len = values.length(); if (fItemType.fVariety == VARIETY_UNION) { XSSimpleTypeDecl[] memberTypes = (XSSimpleTypeDecl[])validatedInfo.memberTypes; XSSimpleType memberType = validatedInfo.memberType; for (int i = len-1; i >= 0; i validatedInfo.actualValue = values.item(i); validatedInfo.memberType = memberTypes[i]; fItemType.checkExtraRules(context, validatedInfo); } validatedInfo.memberType = memberType; } else { // (fVariety == VARIETY_ATOMIC) for (int i = len-1; i >= 0; i validatedInfo.actualValue = values.item(i); fItemType.checkExtraRules(context, validatedInfo); } } validatedInfo.actualValue = values; } else { // (fVariety == VARIETY_UNION) ((XSSimpleTypeDecl)validatedInfo.memberType).checkExtraRules(context, validatedInfo); } }// checkExtraRules() //we can still return object for internal use. private Object getActualValue(Object content, ValidationContext context, ValidatedInfo validatedInfo, boolean needNormalize) throws InvalidDatatypeValueException{ String nvalue; if (needNormalize) { nvalue = normalize(content, fWhiteSpace); } else { nvalue = content.toString(); } if ( (fFacetsDefined & FACET_PATTERN ) != 0 ) { RegularExpression regex; for (int idx = fPattern.size()-1; idx >= 0; idx regex = (RegularExpression)fPattern.elementAt(idx); if (!regex.matches(nvalue)){ throw new InvalidDatatypeValueException("cvc-pattern-valid", new Object[]{content, fPatternStr.elementAt(idx), fTypeName}); } } } if (fVariety == VARIETY_ATOMIC) { // validate special kinds of token, in place of old pattern matching if (fPatternType != SPECIAL_PATTERN_NONE) { boolean seenErr = false; if (fPatternType == SPECIAL_PATTERN_NMTOKEN) { // PATTERN "\\c+" seenErr = !XMLChar.isValidNmtoken(nvalue); } else if (fPatternType == SPECIAL_PATTERN_NAME) { // PATTERN "\\i\\c*" seenErr = !XMLChar.isValidName(nvalue); } else if (fPatternType == SPECIAL_PATTERN_NCNAME) { // PATTERN "[\\i-[:]][\\c-[:]]*" seenErr = !XMLChar.isValidNCName(nvalue); } if (seenErr) { throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{nvalue, SPECIAL_PATTERN_STRING[fPatternType]}); } } validatedInfo.normalizedValue = nvalue; Object avalue = fDVs[fValidationDV].getActualValue(nvalue, context); validatedInfo.actualValue = avalue; return avalue; } else if (fVariety == VARIETY_LIST) { StringTokenizer parsedList = new StringTokenizer(nvalue, " "); int countOfTokens = parsedList.countTokens() ; Object[] avalue = new Object[countOfTokens]; XSSimpleTypeDecl[] memberTypes = new XSSimpleTypeDecl[countOfTokens]; for(int i = 0 ; i < countOfTokens ; i ++){ // we can't call fItemType.validate(), otherwise checkExtraRules() // will be called twice: once in fItemType.validate, once in // validate method of this type. // so we take two steps to get the actual value: // 1. fItemType.getActualValue() // 2. fItemType.chekcFacets() avalue[i] = fItemType.getActualValue(parsedList.nextToken(), context, validatedInfo, false); if (context.needFacetChecking() && (fItemType.fFacetsDefined != 0 && fItemType.fFacetsDefined != FACET_WHITESPACE)) { fItemType.checkFacets(validatedInfo); } memberTypes[i] = (XSSimpleTypeDecl)validatedInfo.memberType; } ListDV.ListData v = new ListDV.ListData(avalue); validatedInfo.actualValue = v; validatedInfo.memberType = null; validatedInfo.memberTypes = memberTypes; validatedInfo.normalizedValue = nvalue; return v; } else { // (fVariety == VARIETY_UNION) for(int i = 0 ; i < fMemberTypes.length; i++) { try { // we can't call fMemberType[i].validate(), otherwise checkExtraRules() // will be called twice: once in fMemberType[i].validate, once in // validate method of this type. // so we take two steps to get the actual value: // 1. fMemberType[i].getActualValue() // 2. fMemberType[i].chekcFacets() Object aValue = fMemberTypes[i].getActualValue(content, context, validatedInfo, true); if (context.needFacetChecking() && (fMemberTypes[i].fFacetsDefined != 0 && fMemberTypes[i].fFacetsDefined != FACET_WHITESPACE)) { fMemberTypes[i].checkFacets(validatedInfo); } validatedInfo.memberType = fMemberTypes[i]; return aValue; } catch(InvalidDatatypeValueException invalidValue) { } } throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.2", new Object[]{content, fTypeName}); } }//getActualValue() public boolean isEqual(Object value1, Object value2) { if (value1 == null) return false; return value1.equals(value2); }//isEqual() // normalize the string according to the whiteSpace facet public static String normalize(String content, short ws) { int len = content == null ? 0 : content.length(); if (len == 0 || ws == WS_PRESERVE) return content; StringBuffer sb = new StringBuffer(); if (ws == WS_REPLACE) { char ch; // when it's replace, just replace #x9, #xa, #xd by #x20 for (int i = 0; i < len; i++) { ch = content.charAt(i); if (ch != 0x9 && ch != 0xa && ch != 0xd) sb.append(ch); else sb.append((char)0x20); } } else { char ch; int i; boolean isLeading = true; // when it's collapse for (i = 0; i < len; i++) { ch = content.charAt(i); // append real characters, so we passed leading ws if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) { sb.append(ch); isLeading = false; } else { // for whitespaces, we skip all following ws for (; i < len-1; i++) { ch = content.charAt(i+1); if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) break; } // if it's not a leading or tailing ws, then append a space if (i < len - 1 && !isLeading) sb.append((char)0x20); } } } return sb.toString(); } // normalize the string according to the whiteSpace facet protected String normalize(Object content, short ws) { if (content == null) return null; // If pattern is not defined, we can skip some of the normalization. // Otherwise we have to normalize the data for correct result of // pattern validation. if ( (fFacetsDefined & FACET_PATTERN ) == 0 ) { short norm_type = fDVNormalizeType[fValidationDV]; if (norm_type == NORMALIZE_NONE) { return content.toString(); } else if (norm_type == NORMALIZE_TRIM) { return content.toString().trim(); } } if (!(content instanceof StringBuffer)) { String strContent = content.toString(); return normalize(strContent, ws); } StringBuffer sb = (StringBuffer)content; int len = sb.length(); if (len == 0) return ""; if (ws == WS_PRESERVE) return sb.toString(); if (ws == WS_REPLACE) { char ch; // when it's replace, just replace #x9, #xa, #xd by #x20 for (int i = 0; i < len; i++) { ch = sb.charAt(i); if (ch == 0x9 || ch == 0xa || ch == 0xd) sb.setCharAt(i, (char)0x20); } } else { char ch; int i, j = 0; boolean isLeading = true; // when it's collapse for (i = 0; i < len; i++) { ch = sb.charAt(i); // append real characters, so we passed leading ws if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) { sb.setCharAt(j++, ch); isLeading = false; } else { // for whitespaces, we skip all following ws for (; i < len-1; i++) { ch = sb.charAt(i+1); if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) break; } // if it's not a leading or tailing ws, then append a space if (i < len - 1 && !isLeading) sb.setCharAt(j++, (char)0x20); } } sb.setLength(j); } return sb.toString(); } void reportError(String key, Object[] args) throws InvalidDatatypeFacetException { throw new InvalidDatatypeFacetException(key, args); } private String whiteSpaceValue(short ws){ return WS_FACET_STRING[ws]; } public short getOrdered() { return fOrdered; } public boolean getBounded(){ return fBounded; } public boolean getFinite(){ return fFinite; } public boolean getNumeric(){ return fNumeric; } public boolean isDefinedFacet(short facetName) { if ((fFacetsDefined & facetName) != 0) return true; if (fPatternType != SPECIAL_PATTERN_NONE) return facetName == FACET_PATTERN; if (fValidationDV == DV_INTEGER) return facetName == FACET_PATTERN || facetName == FACET_FRACTIONDIGITS; return false; } public short getDefinedFacets() { if (fPatternType != SPECIAL_PATTERN_NONE) return (short)(fFacetsDefined | FACET_PATTERN); if (fValidationDV == DV_INTEGER) return (short)(fFacetsDefined | FACET_PATTERN | FACET_FRACTIONDIGITS); return fFacetsDefined; } public boolean isFixedFacet(short facetName) { if ((fFixedFacet & facetName) != 0) return true; if (fValidationDV == DV_INTEGER) return facetName == FACET_FRACTIONDIGITS; return false; } public short getFixedFacets() { if (fValidationDV == DV_INTEGER) return (short)(fFixedFacet | FACET_FRACTIONDIGITS); return fFixedFacet; } public String getLexicalFacetValue(short facetName) { switch (facetName) { case FACET_LENGTH: return (fLength == -1)?null:Integer.toString(fLength); case FACET_MINLENGTH: return (fMinLength == -1)?null:Integer.toString(fMinLength); case FACET_MAXLENGTH: return (fMaxLength == -1)?null:Integer.toString(fMaxLength); case FACET_WHITESPACE: return WS_FACET_STRING[fWhiteSpace]; case FACET_MAXINCLUSIVE: return (fMaxInclusive == null)?null:fMaxInclusive.toString(); case FACET_MAXEXCLUSIVE: return (fMaxExclusive == null)?null:fMaxExclusive.toString(); case FACET_MINEXCLUSIVE: return (fMinExclusive == null)?null:fMinExclusive.toString(); case FACET_MININCLUSIVE: return (fMinInclusive == null)?null:fMinInclusive.toString(); case FACET_TOTALDIGITS: if (fValidationDV == DV_INTEGER) return "0"; return (fTotalDigits == -1)?null:Integer.toString(fTotalDigits); case FACET_FRACTIONDIGITS: return (fFractionDigits == -1)?null:Integer.toString(fFractionDigits); } return null; } public StringList getLexicalEnumeration() { if (fLexicalEnumeration == null){ if (fEnumeration == null) return null; int size = fEnumeration.size(); String[] strs = new String[size]; for (int i = 0; i < size; i++) strs[i] = fEnumeration.elementAt(i).toString(); fLexicalEnumeration = new StringListImpl(strs, size); } return fLexicalEnumeration; } public StringList getLexicalPattern() { if (fPatternType == SPECIAL_PATTERN_NONE && fValidationDV != DV_INTEGER && fPatternStr == null) return null; if (fLexicalPattern == null){ int size = fPatternStr == null ? 0 : fPatternStr.size(); String[] strs; if (fPatternType == SPECIAL_PATTERN_NMTOKEN) { strs = new String[size+1]; strs[size] = "\\c+"; } else if (fPatternType == SPECIAL_PATTERN_NAME) { strs = new String[size+1]; strs[size] = "\\i\\c*"; } else if (fPatternType == SPECIAL_PATTERN_NCNAME) { strs = new String[size+2]; strs[size] = "\\i\\c*"; strs[size+1] = "[\\i-[:]][\\c-[:]]*"; } else if (fValidationDV == DV_INTEGER) { strs = new String[size+1]; strs[size] = "[+\\-]?[0-9]+"; } else { strs = new String[size]; } for (int i = 0; i < size; i++) strs[i] = (String)fPatternStr.elementAt(i); fLexicalPattern = new StringListImpl(strs, size); } return fLexicalPattern; } public XSObjectList getAnnotations() { return fAnnotations; } private void caclFundamentalFacets() { setOrdered(); setNumeric(); setBounded(); setCardinality(); } private void setOrdered(){ // When {variety} is atomic, {value} is inherited from {value} of {base type definition}. For all "primitive" types {value} is as specified in the table in Fundamental Facets (C.1). if(fVariety == VARIETY_ATOMIC){ this.fOrdered = fBase.fOrdered; } // When {variety} is list, {value} is false. else if(fVariety == VARIETY_LIST){ this.fOrdered = ORDERED_FALSE; } // When {variety} is union, the {value} is partial unless one of the following: // 1. If every member of {member type definitions} is derived from a common ancestor other than the simple ur-type, then {value} is the same as that ancestor's ordered facet. // 2. If every member of {member type definitions} has a {value} of false for the ordered facet, then {value} is false. else if(fVariety == VARIETY_UNION){ int length = fMemberTypes.length; // REVISIT: is the length possible to be 0? if (length == 0) { this.fOrdered = ORDERED_PARTIAL; return; } // we need to process the first member type before entering the loop short ancestorId = getPrimitiveDV(fMemberTypes[0].fValidationDV); boolean commonAnc = ancestorId != DV_ANYSIMPLETYPE; boolean allFalse = fMemberTypes[0].fOrdered == ORDERED_FALSE; // for the other member types, check whether the value is false // and whether they have the same ancestor as the first one for (int i = 1; i < fMemberTypes.length && (commonAnc || allFalse); i++) { if (commonAnc) commonAnc = ancestorId == getPrimitiveDV(fMemberTypes[i].fValidationDV); if (allFalse) allFalse = fMemberTypes[i].fOrdered == ORDERED_FALSE; } if (commonAnc) { // REVISIT: all member types should have the same ordered value // just use the first one. Can we assume this? this.fOrdered = fMemberTypes[0].fOrdered; } else if (allFalse) { this.fOrdered = ORDERED_FALSE; } else { this.fOrdered = ORDERED_PARTIAL; } } }//setOrdered private void setNumeric(){ if(fVariety == VARIETY_ATOMIC){ this.fNumeric = fBase.fNumeric; } else if(fVariety == VARIETY_LIST){ this.fNumeric = false; } else if(fVariety == VARIETY_UNION){ XSSimpleType[] memberTypes = fMemberTypes; for(int i = 0 ; i < memberTypes.length ; i++){ if(!memberTypes[i].getNumeric() ){ this.fNumeric = false; return; } } this.fNumeric = true; } }//setNumeric private void setBounded(){ if(fVariety == VARIETY_ATOMIC){ if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) && (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) ){ this.fBounded = true; } else{ this.fBounded = false; } } else if(fVariety == VARIETY_LIST){ if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 ) && ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){ this.fBounded = true; } else{ this.fBounded = false; } } else if(fVariety == VARIETY_UNION){ XSSimpleTypeDecl [] memberTypes = this.fMemberTypes; short ancestorId = 0 ; if(memberTypes.length > 0){ ancestorId = getPrimitiveDV(memberTypes[0].fValidationDV); } for(int i = 0 ; i < memberTypes.length ; i++){ if(!memberTypes[i].getBounded() || (ancestorId != getPrimitiveDV(memberTypes[i].fValidationDV)) ){ this.fBounded = false; return; } } this.fBounded = true; } }//setBounded private boolean specialCardinalityCheck(){ if( (fBase.fValidationDV == XSSimpleTypeDecl.DV_DATE) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEARMONTH) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEAR) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTHDAY) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GDAY) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTH) ){ return true; } return false; } //specialCardinalityCheck() private void setCardinality(){ if(fVariety == VARIETY_ATOMIC){ if(fBase.fFinite){ this.fFinite = true; } else {// (!fBase.fFinite) if ( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 ) || ((this.fFacetsDefined & FACET_TOTALDIGITS) != 0 ) ){ this.fFinite = true; } else if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0 )) && (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 )) ){ if( ((this.fFacetsDefined & FACET_FRACTIONDIGITS) != 0 ) || specialCardinalityCheck()){ this.fFinite = true; } else{ this.fFinite = false; } } else{ this.fFinite = false; } } } else if(fVariety == VARIETY_LIST){ if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 ) && ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){ this.fFinite = true; } else{ this.fFinite = false; } } else if(fVariety == VARIETY_UNION){ XSSimpleType [] memberTypes = fMemberTypes; for(int i = 0 ; i < memberTypes.length ; i++){ if(!(memberTypes[i].getFinite()) ){ this.fFinite = false; return; } } this.fFinite = true; } }//setCardinality private short getPrimitiveDV(short validationDV){ if (validationDV == DV_ID || validationDV == DV_IDREF || validationDV == DV_ENTITY){ return DV_STRING; } else if (validationDV == DV_INTEGER) { return DV_DECIMAL; } else { return validationDV; } }//getPrimitiveDV() public boolean derivedFromType(XSTypeDefinition ancestor, short derivation) { // REVISIT: implement according to derivation // ancestor is null, retur false if (ancestor == null) return false; // ancestor is anyType, return true // anyType is the only type whose base type is itself if (ancestor.getBaseType() == ancestor) return true; // recursively get base, and compare it with ancestor XSTypeDefinition type = this; while (type != ancestor && // compare with ancestor type != fAnySimpleType) { // reached anySimpleType type = type.getBaseType(); } return type == ancestor; } public boolean derivedFrom(String ancestorNS, String ancestorName, short derivation) { // REVISIT: implement according to derivation // ancestor is null, retur false if (ancestorName == null) return false; // ancestor is anyType, return true if (URI_SCHEMAFORSCHEMA.equals(ancestorNS) && ANY_TYPE.equals(ancestorName)) { return true; } // recursively get base, and compare it with ancestor XSTypeDefinition type = this; while (!(ancestorName.equals(type.getName()) && ((ancestorNS == null && type.getNamespace() == null) || (ancestorNS != null && ancestorNS.equals(type.getNamespace())))) && // compare with ancestor type != fAnySimpleType) { // reached anySimpleType type = (XSTypeDefinition)type.getBaseType(); } return type != fAnySimpleType; } static final XSSimpleTypeDecl fAnySimpleType = new XSSimpleTypeDecl(null, "anySimpleType", DV_ANYSIMPLETYPE, ORDERED_FALSE, false, true, false, true); /** * Validation context used to validate facet values. */ static final ValidationContext fDummyContext = new ValidationContext() { public boolean needFacetChecking() { return true; } public boolean needExtraChecking() { return false; } public boolean needToNormalize() { return false; } public boolean useNamespaces() { return true; } public boolean isEntityDeclared(String name) { return false; } public boolean isEntityUnparsed(String name) { return false; } public boolean isIdDeclared(String name) { return false; } public void addId(String name) { } public void addIdRef(String name) { } public String getSymbol (String symbol) { return null; } public String getURI(String prefix) { return null; } }; /** * A wrapper of ValidationContext, to provide a way of switching to a * different Namespace declaration context. */ class ValidationContextImpl implements ValidationContext { ValidationContext fExternal; ValidationContextImpl(ValidationContext external) { fExternal = external; } NamespaceContext fNSContext; void setNSContext(NamespaceContext nsContext) { fNSContext = nsContext; } public boolean needFacetChecking() { return fExternal.needFacetChecking(); } public boolean needExtraChecking() { return fExternal.needExtraChecking(); } public boolean needToNormalize() { return fExternal.needToNormalize(); } // schema validation is predicated upon namespaces public boolean useNamespaces() { return true; } public boolean isEntityDeclared (String name) { return fExternal.isEntityDeclared(name); } public boolean isEntityUnparsed (String name) { return fExternal.isEntityUnparsed(name); } public boolean isIdDeclared (String name) { return fExternal.isIdDeclared(name); } public void addId(String name) { fExternal.addId(name); } public void addIdRef(String name) { fExternal.addIdRef(name); } public String getSymbol (String symbol) { return fExternal.getSymbol(symbol); } public String getURI(String prefix) { if (fNSContext == null) return fExternal.getURI(prefix); else return fNSContext.getURI(prefix); } } public void reset(){ // if it's immutable, can't be reset: if (fIsImmutable) return; fItemType = null; fMemberTypes = null; fTypeName = null; fTargetNamespace = null; fFinalSet = 0; fBase = null; fVariety = -1; fValidationDV = -1; fFacetsDefined = 0; fFixedFacet = 0; //for constraining facets fWhiteSpace = 0; fLength = -1; fMinLength = -1; fMaxLength = -1; fTotalDigits = -1; fFractionDigits = -1; fPattern = null; fPatternStr = null; fEnumeration = null; fLexicalPattern = null; fLexicalEnumeration = null; fMaxInclusive = null; fMaxExclusive = null; fMinExclusive = null; fMinInclusive = null; lengthAnnotation = null; minLengthAnnotation = null; maxLengthAnnotation = null; whiteSpaceAnnotation = null; totalDigitsAnnotation = null; fractionDigitsAnnotation = null; patternAnnotations = null; enumerationAnnotations = null; maxInclusiveAnnotation = null; maxExclusiveAnnotation = null; minInclusiveAnnotation = null; minExclusiveAnnotation = null; fPatternType = SPECIAL_PATTERN_NONE; fAnnotations = null; fFacets = null; // REVISIT: reset for fundamental facets } /** * @see org.apache.xerces.impl.xs.psvi.XSObject#getNamespaceItem() */ public XSNamespaceItem getNamespaceItem() { // REVISIT: implement return null; } /** * @see java.lang.Object#toString() */ public String toString() { return this.fTargetNamespace+"," +this.fTypeName; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSSimpleTypeDefinition#getFacets() */ public XSObjectList getFacets() { if (fFacets == null && (fFacetsDefined != 0 || fValidationDV == DV_INTEGER)) { XSFacetImpl[] facets = new XSFacetImpl[10]; int count = 0; if ((fFacetsDefined & FACET_WHITESPACE) != 0) { facets[count] = new XSFacetImpl( FACET_WHITESPACE, WS_FACET_STRING[fWhiteSpace], (fFixedFacet & FACET_WHITESPACE) != 0, whiteSpaceAnnotation); count++; } if (fLength != -1) { facets[count] = new XSFacetImpl( FACET_LENGTH, Integer.toString(fLength), (fFixedFacet & FACET_LENGTH) != 0, lengthAnnotation); count++; } if (fMinLength != -1) { facets[count] = new XSFacetImpl( FACET_MINLENGTH, Integer.toString(fMinLength), (fFixedFacet & FACET_MINLENGTH) != 0, minLengthAnnotation); count++; } if (fMaxLength != -1) { facets[count] = new XSFacetImpl( FACET_MAXLENGTH, Integer.toString(fMaxLength), (fFixedFacet & FACET_MAXLENGTH) != 0, maxLengthAnnotation); count++; } if (fTotalDigits != -1) { facets[count] = new XSFacetImpl( FACET_TOTALDIGITS, Integer.toString(fTotalDigits), (fFixedFacet & FACET_TOTALDIGITS) != 0, totalDigitsAnnotation); count++; } if (fValidationDV == DV_INTEGER) { facets[count] = new XSFacetImpl( FACET_FRACTIONDIGITS, "0", true, null); count++; } if (fFractionDigits != -1) { facets[count] = new XSFacetImpl( FACET_FRACTIONDIGITS, Integer.toString(fFractionDigits), (fFixedFacet & FACET_FRACTIONDIGITS) != 0, fractionDigitsAnnotation); count++; } if (fMaxInclusive != null) { facets[count] = new XSFacetImpl( FACET_MAXINCLUSIVE, fMaxInclusive.toString(), (fFixedFacet & FACET_MAXINCLUSIVE) != 0, maxInclusiveAnnotation); count++; } if (fMaxExclusive != null) { facets[count] = new XSFacetImpl( FACET_MAXEXCLUSIVE, fMaxExclusive.toString(), (fFixedFacet & FACET_MAXEXCLUSIVE) != 0, maxExclusiveAnnotation); count++; } if (fMinExclusive != null) { facets[count] = new XSFacetImpl( FACET_MINEXCLUSIVE, fMinExclusive.toString(), (fFixedFacet & FACET_MINEXCLUSIVE) != 0, minExclusiveAnnotation); count++; } if (fMinInclusive != null) { facets[count] = new XSFacetImpl( FACET_MININCLUSIVE, fMinInclusive.toString(), (fFixedFacet & FACET_MININCLUSIVE) != 0, minInclusiveAnnotation); count++; } fFacets = new XSObjectListImpl(facets, count); } return fFacets; } public XSObjectList getMultiValueFacets(){ if (fMultiValueFacets == null && ((fFacetsDefined & FACET_ENUMERATION) != 0 || (fFacetsDefined & FACET_PATTERN) != 0 || fPatternType != SPECIAL_PATTERN_NONE || fValidationDV == DV_INTEGER)) { XSMVFacetImpl[] facets = new XSMVFacetImpl[2]; int count = 0; if ((fFacetsDefined & FACET_PATTERN) != 0 || fPatternType != SPECIAL_PATTERN_NONE || fValidationDV == DV_INTEGER) { facets[count] = new XSMVFacetImpl( FACET_PATTERN, this.getLexicalPattern(), patternAnnotations); count++; } if (fEnumeration != null) { facets[count] = new XSMVFacetImpl( FACET_ENUMERATION, this.getLexicalEnumeration(), enumerationAnnotations); count++; } fMultiValueFacets = new XSObjectListImpl(facets, count); } return fMultiValueFacets; } private static final class XSFacetImpl implements XSFacet { final short kind; final String value; final boolean fixed; final XSAnnotation annotation; public XSFacetImpl(short kind, String value, boolean fixed, XSAnnotation annotation) { this.kind = kind; this.value = value; this.fixed = fixed; this.annotation = annotation; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSFacet#getAnnotation() */ public XSAnnotation getAnnotation() { return annotation; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSFacet#getFacetKind() */ public short getFacetKind() { return kind; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSFacet#getLexicalFacetValue() */ public String getLexicalFacetValue() { return value; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSFacet#isFixed() */ public boolean isFixed() { return fixed; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getName() */ public String getName() { return null; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getNamespace() */ public String getNamespace() { return null; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getNamespaceItem() */ public XSNamespaceItem getNamespaceItem() { // REVISIT: implement return null; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getType() */ public short getType() { return XSConstants.FACET; } } private static final class XSMVFacetImpl implements XSMultiValueFacet { final short kind; XSObjectList annotations; StringList values; public XSMVFacetImpl(short kind, StringList values, XSObjectList annotations) { this.kind = kind; this.values = values; this.annotations = annotations; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSFacet#getFacetKind() */ public short getFacetKind() { return kind; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSMultiValueFacet#getAnnotations() */ public XSObjectList getAnnotations() { return annotations; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSMultiValueFacet#getLexicalFacetValues() */ public StringList getLexicalFacetValues() { return values; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getName() */ public String getName() { return null; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getNamespace() */ public String getNamespace() { return null; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getNamespaceItem() */ public XSNamespaceItem getNamespaceItem() { // REVISIT: implement return null; } /* (non-Javadoc) * @see org.apache.xerces.impl.xs.psvi.XSObject#getType() */ public short getType() { return XSConstants.MULTIVALUE_FACET; } } } // class XSSimpleTypeDecl
package hudson.plugins.report.jck.main.cmdline; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Arguments { private final String[] base; private final List<String> mainArgs; private boolean argsAreDirs; private String jenkinsDir; private File jobsDir; private String[] possibleJobs; public Arguments(String[] args) { this.mainArgs = new ArrayList<>(args.length); if (args.length == 0) { printHelp(System.out); throw new RuntimeException("At least one param expected"); } this.base = new String[args.length]; //clean dashes for (int i = 0; i < args.length; i++) { base[i] = args[i].replaceAll("^-+", "-"); } //verify single output int outputs = 0; for (String base1 : base) { if (base1.startsWith(output + "=")) { outputs++; } } if (outputs > 1) { throw new RuntimeException("none or one " + output + " expected. you have " + outputs); } for (String base1 : base) { String opt = base1.split("=")[0]; if (!isNumber(opt)) { //not u number.. is known? if (opt.startsWith("-") && !arrayContains(switches, opt)) { System.err.println("WARNING unknown param " + opt); } } } } private void printHelp(PrintStream p) { p.println(" options DIR1 DIR2 DIR3 ... DIRn"); p.println(" or "); p.println(" options JOB_NAME-1 buildPointer1.1 buildPointer1.2 ... jobPointer1.N JOB_NAME-2 buildPointer2.1 buildPointer2.2 ... jobPointer2.N ... JOB_NAME-N ...jobPointerN.N"); p.println(" options: "); p.println(" " + output + "=" + argsToHelp(knownOutputs)); p.println(" default output is 'plain text'. 0-1 of " + output + " is allowed."); p.println(" " + view + "=" + argsToHelp(knownViews)); p.println(" default view is 'all'. 0-N of " + view + " is allowed."); p.println(" job pointers are numbers. If zero or negative, then it is 0 for last one, -1 for one beofre last ..."); p.println(" When using even number of build pointers, you can use " + fillSwitch + " switch to consider them as rows"); p.println(" Another strange argument is " + keepFailedSwitch + " which will include failed/aborted/not-existing builds/dirs during listing."); } private static final String output = "-output"; private static final String view = "-view"; private static final String fillSwitch = "-fill"; private static final String keepFailedSwitch = "-keep-failed"; private static final String[] switches = {output, view, fillSwitch, keepFailedSwitch}; static final String output_html = "html"; static final String output_color = "color"; private static final String[] knownOutputs = new String[]{output_color, output_html}; static final String view_info_summary = "info-summary"; static final String view_info_summary_suites = "info-summary-suites"; static final String view_info_problems = "info-problems"; static final String view_info = "info"; static final String view_info_hidevalues = "info-hide-details"; static final String view_diff_summary = "diff-summary"; static final String view_diff_summary_suites = "diff-summary-suites"; static final String view_diff_details = "diff-details"; static final String view_diff_list = "diff-list"; static final String view_diff = "diff"; static final String view_hide_positives = "hide-positives"; static final String view_hide_negatives = "hide-negatives"; static final String view_hide_misses = "hide-misses"; static final String view_hide_totals = "hide-totals"; private static final String[] knownViews = new String[]{ view_info_summary, view_info_summary_suites, view_info_problems, view_info_hidevalues, view_diff_summary, view_diff_summary_suites, view_diff_details, view_diff_list, view_hide_positives, view_hide_negatives, view_hide_misses, view_hide_totals, view_diff, view_info }; public Options parse() { Options result = new Options(); for (String arg : base) { if (arg.startsWith(output + "=")) { String output_type = arg.split("=")[1]; if (!arrayContains(knownOutputs, output_type)) { System.err.println(argsToHelp(knownOutputs)); throw new RuntimeException("unknown arg for " + output + " - " + output_type); } result.setOutputType(output_type); } else if (arg.startsWith(view + "=")) { String nextView = arg.split("=")[1]; if (!arrayContains(knownViews, nextView)) { System.err.println(argsToHelp(knownViews)); throw new RuntimeException("unknown arg for " + view + " - " + nextView); } result.addView(nextView); } else if (arg.equals(fillSwitch)) { result.setFill(true); } else if (arg.equals(keepFailedSwitch)) { result.setSkipFailed(false); } else { mainArgs.add(arg); } } if (mainArgs.isEmpty()) { throw new RuntimeException("No main argument. At elast one Directory is expected"); } if (result.isFill() && mainArgs.size() <= 2) { throw new RuntimeException(fillSwitch + " can be used only for two or more job pointers. You have " + (mainArgs.size() - 1)); } Boolean allSameKind = null; for (String string : mainArgs) { if (allSameKind == null) { allSameKind = new File(string).isDirectory(); } else if (!new File(string).isDirectory() == allSameKind) { mainArgs.stream().forEach((badArg) -> { System.err.println(badArg + " - " + new File(string).isDirectory()); }); throw new RuntimeException("Sorry, all main arguments must be directories or all must not be an directories. You have mix"); } } argsAreDirs = allSameKind; jenkinsDir = System.getProperty("jenkins_home"); if (jenkinsDir == null) { jenkinsDir = System.getenv("JENKINS_HOME"); } if (!argsAreDirs) { if (jenkinsDir == null) { throw new RuntimeException("You are working in jenkins jobs mode, but non -Djenkins_home nor $JENKINS_HOME is specified"); } jobsDir = new File(jenkinsDir, "jobs"); possibleJobs = jobsDir.list(); Arrays.sort(possibleJobs); String jobName = null; File jobDir; File buildsDir = null; Integer latestBuild = null; if (result.isFill()) { int i = -1; while (true) { i++; if (i >= mainArgs.size()) { break; } String arg = mainArgs.get(i); if (!isNumber(arg)) { jobName = arg; checkJob(jobName); jobDir = new File(jobsDir, jobName); buildsDir = new File(jobDir, "builds"); latestBuild = getLatestBuildId(buildsDir); System.err.println("latest build for "+jobName+" is "+latestBuild); continue; } if (jobName == null) { throw new RuntimeException("You are tying to specify build " + arg + " but not have no job specified ahead."); } int from = Integer.valueOf(arg); i++; arg = mainArgs.get(i); if (!isNumber(arg)) { throw new RuntimeException("You have " + fillSwitch + " set, but when reading " + arg + " it looks like odd number of arguments. Even expected"); } int to = Integer.valueOf(arg); if (from <= 0) { from = latestBuild + from; } if (to <= 0) { to = latestBuild + to; } from = sanitize(from); to = sanitize(to); if (from > to) { for (int x = from; x >= to; x result.add(new File(buildsDir, String.valueOf(x))); } } else { for (int x = from; x <= to; x++) { result.add(new File(buildsDir, String.valueOf(x))); } } } } else { for (int i = 0; i < mainArgs.size(); i++) { String arg = mainArgs.get(i); if (!isNumber(arg)) { jobName = arg; checkJob(jobName); jobDir = new File(jobsDir, jobName); buildsDir = new File(jobDir, "builds"); latestBuild = getLatestBuildId(buildsDir); System.err.println("latest build for "+jobName+" is "+latestBuild); continue; } if (jobName == null) { throw new RuntimeException("You are tying to specify build " + arg + " but not have no job specified ahead."); } int origJobId = Integer.valueOf(mainArgs.get(i)); int jobId = origJobId; if (jobId <= 0) { jobId = latestBuild + jobId; } jobId = sanitize(jobId); if (result.isSkipFailed()) { while (true) { //iterating untill we find an passing build boolean added = result.add(new File(buildsDir, String.valueOf(jobId))); if (added) { break; } if (origJobId < 0) { jobId } else { jobId++; } if ((jobId < 1) || (jobId > latestBuild)) { break; } } } else { result.add(new File(buildsDir, String.valueOf(jobId))); } } } } else { //no jenkins mode mainArgs.stream().forEach((string) -> { result.add(new File(string)); }); } if (result.getDirsToWork().isEmpty()) { throw new RuntimeException("No directories to work on at the end!"); } return result; } private String argsToHelp(String[] outputs) { StringBuilder sb = new StringBuilder(); for (String o : outputs) { sb.append(o).append("|"); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } private boolean arrayContains(String[] as, String s) { for (String a : as) { if (a.equals(s)) { return true; } } return false; } private static int getLatestBuildId(File jobDir) { if (jobDir.exists() && jobDir.isDirectory()) { String[] files = jobDir.list(); List<Integer> results = new ArrayList<>(files.length); for (String file : files) { try { Integer i = Integer.valueOf(file); results.add(i); } catch (Exception ex) { System.err.println(jobDir + "/" + file + " is not number."); } } Collections.sort(results); return results.get(results.size() - 1); } else { throw new RuntimeException(jobDir + " do not exists or is not directory"); } } private int sanitize(int jobId) { if (jobId <= 0) { return 1; } return jobId; } public boolean isNumber(String s) { try { Integer.valueOf(s); return true; } catch (Exception ex) { return false; } } private boolean isJob(String jobName) { return arrayContains(possibleJobs, jobName); } private void checkJob(String jobName) { if (!isJob(jobName)) { System.out.println("Possible jobs"); for (String jobs : possibleJobs) { System.out.println(jobs); } throw new RuntimeException("Unknown job `" + jobName + "`"); } } }
package info.faceland.strife.tasks; import info.faceland.strife.managers.DarknessManager; import java.util.ArrayList; import org.bukkit.Particle; import org.bukkit.entity.LivingEntity; import org.bukkit.scheduler.BukkitRunnable; public class DarknessReductionTask extends BukkitRunnable { private ArrayList<LivingEntity> toBeRemoved = new ArrayList<>(); @Override public void run() { for (LivingEntity le : DarknessManager.getDarkMap().keySet()) { int particleAmount = 1 + Math.max((int) (DarknessManager.getEntity(le) / 3), 25); le.getWorld().spawnParticle(Particle.SMOKE_NORMAL, le.getEyeLocation(), particleAmount,0.3, 0.3, 0.4, 0.01); DarknessManager.updateEntity(le, -0.5f); if (!DarknessManager.isValidEntity(le) || !DarknessManager.isCorrupted(le)) { toBeRemoved.add(le); } } for (LivingEntity le : toBeRemoved) { DarknessManager.removeEntity(le); } toBeRemoved.clear(); } }
package info.u_team.u_team_core.container; import java.util.List; import java.util.stream.Collectors; import com.google.common.collect.Lists; import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable; import info.u_team.u_team_core.intern.init.UCoreNetwork; import info.u_team.u_team_core.intern.network.*; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.inventory.container.*; import net.minecraft.item.ItemStack; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SSetSlotPacket; import net.minecraft.util.NonNullList; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.fluids.*; import net.minecraftforge.fluids.capability.IFluidHandler.FluidAction; import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fml.network.PacketDistributor; import net.minecraftforge.items.ItemHandlerHelper; public abstract class FluidContainer extends Container { private final NonNullList<FluidStack> fluidStacks = NonNullList.create(); public final List<FluidSlot> fluidSlots = Lists.newArrayList(); public FluidContainer(ContainerType<?> type, int id) { super(type, id); } protected FluidSlot addFluidSlot(FluidSlot slot) { slot.slotNumber = fluidSlots.size(); fluidSlots.add(slot); fluidStacks.add(FluidStack.EMPTY); return slot; } public FluidSlot getFluidSlot(int slot) { return fluidSlots.get(slot); } public NonNullList<FluidStack> getFluids() { final NonNullList<FluidStack> list = NonNullList.create(); for (int index = 0; index < fluidSlots.size(); index++) { list.add(fluidSlots.get(index).getStack()); } return list; } // Called when a client clicks on a fluid slot public void fluidSlotClick(ServerPlayerEntity player, int index, boolean shift, ItemStack clientClickStack) { final ItemStack serverClickStack = player.inventory.getItemStack(); // Check if an item is in the hand if (serverClickStack.isEmpty()) { return; } // Check if the client item is the same as the server item stack if (!ItemStack.areItemStacksEqual(clientClickStack, serverClickStack)) { return; } // Check if the slot index is in range to prevent server crashes with malicious packets if (index < 0 && index >= fluidSlots.size()) { return; } final LazyOptional<IFluidHandlerItem> containedFluidHandlerOptional = FluidUtil.getFluidHandler(ItemHandlerHelper.copyStackWithSize(serverClickStack, 1)); // Check if the item stack has a fluid capability attached if (!containedFluidHandlerOptional.isPresent()) { return; } final IFluidHandlerItem containedFluidHandler = containedFluidHandlerOptional.orElseThrow(AssertionError::new); final FluidStack containedFluidStack = containedFluidHandler.drain(Integer.MAX_VALUE, FluidAction.SIMULATE); final FluidSlot fluidSlot = getFluidSlot(index); if (!containedFluidStack.isEmpty()) { // Called when filled to the fluid slot } else { // Called when drained from the fluid slot } player.connection.sendPacket(new SSetSlotPacket(-1, -1, player.inventory.getItemStack())); } // Used for sync with the client public void setFluidStackInSlot(int slot, FluidStack stack) { getFluidSlot(slot).putStack(stack); } public void setAllFluidSlots(List<FluidStack> list) { for (int index = 0; index < list.size(); index++) { getFluidSlot(index).putStack(list.get(index)); } } // Send packets for client sync @Override public void addListener(IContainerListener listener) { super.addListener(listener); if (listener instanceof ServerPlayerEntity) { UCoreNetwork.NETWORK.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) listener), new FluidSetAllContainerMessage(windowId, getFluids())); } } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); for (int index = 0; index < fluidSlots.size(); index++) { final FluidStack stackSlot = fluidSlots.get(index).getStack(); final FluidStack stackSynced = fluidStacks.get(index); if (!stackSynced.isFluidStackIdentical(stackSlot)) { final FluidStack stackNewSynced = stackSlot.copy(); fluidStacks.set(index, stackNewSynced); final List<NetworkManager> networkManagers = listeners.stream() .filter(listener -> listener instanceof ServerPlayerEntity) .map(listener -> ((ServerPlayerEntity) listener).connection.getNetworkManager()) .collect(Collectors.toList()); UCoreNetwork.NETWORK.send(PacketDistributor.NMLIST.with(() -> networkManagers), new FluidSetSlotContainerMessage(windowId, index, stackNewSynced)); } } } /** * This methods can add any {@link IFluidHandlerModifiable} to the container. You can specialize the inventory height * (slot rows) and width (slot columns). * * @param handler Some fluid handler * @param inventoryHeight Slot rows * @param inventoryWidth Slot columns * @param x Start x * @param y Start y */ protected void appendFluidInventory(IFluidHandlerModifiable handler, int inventoryHeight, int inventoryWidth, int x, int y) { appendFluidInventory(handler, FluidSlot::new, inventoryHeight, inventoryWidth, x, y); } /** * This methods can add any {@link IFluidHandlerModifiable} to the container. You can specialize the inventory height * (slot rows) and width (slot columns). You must supplier a function that create a fluid slot. With this you can set * your own slot. implementations. * * @param handler Some fluid handler * @param function Function to create a fluid slot. * @param inventoryHeight Slot rows * @param inventoryWidth Slot columns * @param x Start x * @param y Start y */ protected void appendFluidInventory(IFluidHandlerModifiable handler, FluidSlotHandlerFunction function, int inventoryHeight, int inventoryWidth, int x, int y) { for (int height = 0; height < inventoryHeight; height++) { for (int width = 0; width < inventoryWidth; width++) { addFluidSlot(function.getSlot(handler, width + height * inventoryWidth, width * 18 + x, height * 18 + y)); } } } /** * Used as a function to customize fluid slots with the append methods * * @author HyCraftHD */ @FunctionalInterface public static interface FluidSlotHandlerFunction { /** * Should return a slot with the applied parameters. * * @param fluidHandler A fluid handler * @param index Index for this fluid handler * @param xPosition x coordinate * @param yPosition y coordinate * @return A Slot instance */ FluidSlot getSlot(IFluidHandlerModifiable fluidHandler, int index, int xPosition, int yPosition); } }
package io.github.repir.tools.Content; import io.github.repir.tools.ByteRegex.ByteRegex; import io.github.repir.tools.ByteRegex.ByteRegex.Pos; import io.github.repir.tools.DataTypes.ArrayMap; import io.github.repir.tools.Lib.Log; import java.io.DataInput; import java.io.DataOutput; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.TreeSet; import io.github.repir.tools.Lib.ByteTools; /** * This is a general class to read and write binary data to an in memory buffer * that can optionally be connected to an input stream. * <p/> * @author jbpvuurens */ public class BufferReaderWriter implements StructureData, StructureReader, StructureWriter { public static Log log = new Log(BufferReaderWriter.class); public EOFException eof; public byte[] buffer; public boolean[] whitespace = io.github.repir.tools.Lib.ByteTools.whitespace; public byte[] sametext = io.github.repir.tools.Lib.ByteTools.sametext; public long offset = 0; public long ceiling = Long.MAX_VALUE; public boolean hasmore = true; public int bufferpos = 0; public int end; public DataIn datain = null; public DataOut dataout = null; public BufferReaderWriter() { buffer = new byte[1000]; } public BufferReaderWriter(byte buffer[]) { setBuffer(buffer); } public BufferReaderWriter(DataInput in) { readBuffer(in); } @Override public void writeBuffer(DataOutput out) { try { byte b[] = new byte[bufferpos]; System.arraycopy(buffer, 0, b, 0, bufferpos); out.writeInt(b.length); out.write(b); } catch (IOException ex) { log.exception(ex, "writeBuffer( %s ) when writing bytes", out); } } public void setEnd( int end ) { this.end = end; } public void readBuffer(DataInput in) { try { int buffersize = in.readInt(); byte b[] = new byte[buffersize]; in.readFully(b); setBuffer(b); } catch (IOException ex) { log.exception(ex, "readBuffer( %s ) when reading bytes", in); } } public BufferReaderWriter(DataIn in) { this(); setDataIn(in); resetOffset(); } public BufferReaderWriter(DataOut out) { this(); dataout = out; out.setBuffer(this); } @Override public final void setDataIn(DataIn in) { //log.info("setDataIn %s %s", this, in); datain = in; in.setBuffer(this); } public final void setDataOut(DataOut out) { dataout = out; if (out != null) { out.setBuffer(this); } bufferpos = 0; setEnd(0); } public final void setBuffer(byte buffer[]) { this.buffer = buffer; bufferpos = 0; offset = 0; setEnd(buffer.length); } public final void setBuffer(byte buffer[], int pos, int end) { //log.info("setBuffer() pos %d end %d", pos, end); this.buffer = buffer; bufferpos = pos; setEnd(end); } public final void resetOffset() { ceiling = Long.MAX_VALUE; offset = bufferpos = 0; setEnd(0); eof = null; hasmore = true; } public void checkFlush(int size) { if (size > buffer.length) { setBufferSize(size); } else if (bufferpos + size > buffer.length) { flushBuffer(); } } public void checkIn(int size) throws EOFException { //log.info("checkIn( %d ) bufferlegth %d", size, buffer.length); if (size > buffer.length) { resize(size); } if (end - bufferpos < size) { fillBuffer(); if (end - bufferpos < size) { throw new EOFException("EOF reached"); } } } @Override public void fillBuffer() throws EOFException { if (datain != null) { shift(); if (hasmore) { try { //log.info("fillBuffer %s %s", this, datain); datain.fillBuffer(this); } catch (EOFException ex) { hasmore = false; this.eof = ex; throw ex; } } else { throw eof; } } else { hasmore = false; throw new EOFException(); } } public void flushBuffer() { dataout.flushBuffer(this); } public void setAppendOffset(long offset) { this.offset = offset; this.bufferpos = 0; setEnd(0); } @Override public void reset() { setOffset(offset); hasmore = true; } @Override public void setOffset(long offset) { //log.info("setOffset off %d end %d pos %d newoff %d", this.offset, end, bufferpos, offset); if (offset >= this.offset && offset < this.offset + end) { bufferpos = (int) (offset - this.offset); if (datain != null) { //shift(); } } else { if (offset < this.offset && datain != null) { datain.mustMoveBack(); } this.offset = offset; this.bufferpos = 0; setEnd(0); } //log.info("new off %d end %d pos %d", this.offset, end, bufferpos); hasmore = true; eof = null; } @Override public void skip(int bytes) { if (this.bufferpos + bytes <= this.end) { bufferpos += bytes; } else if (bufferpos == end) { offset += bytes; } else { offset += (bytes - (end - bufferpos)); bufferpos = end; } } public void discard() { bufferpos = 0; setEnd(0); } public void setBufferSize(int buffersize) { //log.info("setBufferSize( %d ) currentlength %d dataout %s", buffersize, buffer.length, dataout); if (buffer != null && buffersize != buffer.length && bufferpos > 0 && dataout != null) { flushBuffer(); } resize(buffersize); } public int getBufferSize() { return buffer.length; } public void closeWrite() { //log.info("closeWrite()"); if (dataout != null) { //log.info("close offset %d bufferpos %d bufferend %d", offset, bufferpos, end); flushBuffer(); setBuffer(new byte[0]); dataout.close(); } } @Override public void closeRead() { if (datain != null) { datain.close(); } setBuffer(new byte[0]); } @Override public boolean hasMore() { //log.info("hasMore() hasmore %b offset %d bufferpos %d end %d ceiling %d", hasmore, offset, bufferpos, end, ceiling); return (hasmore && (bufferpos < end || offset + bufferpos < ceiling)); } public int readBytes(long offset, byte b[], int pos, int length) { if (offset == this.offset + this.bufferpos) { if (offset + length <= this.offset + this.end) { System.arraycopy(buffer, bufferpos, b, pos, length); return length; } else { int read = datain.readBytes(offset, b, pos, length); if (read == 0) { //log.info("EOF reached (%d)", offset); setCeiling(getOffset()); } this.offset = offset + read; bufferpos = 0; setEnd(read); return read; } } else if (offset > this.offset && offset + length <= this.offset + this.end) { System.arraycopy(buffer, (int) (offset - this.offset), b, pos, length); return length; } return datain.readBytes(offset, b, pos, length); } public long getOffset() { return this.offset + this.bufferpos; } public long getCeiling() { return ceiling; } public void setCeiling(long ceiling) { this.ceiling = ceiling; if (end > ceiling - offset && ceiling - offset >= 0) { setEnd((int) (ceiling - offset)); } if (end > buffer.length - bufferpos) { setEnd(buffer.length - bufferpos); } //log.info("end %d", end); } public long getLength() { return datain.getLength(); } public int resize(int size) { //log.info("resize( %d )", size); if (buffer == null) { buffer = new byte[size]; } else if (size > buffer.length) { int shift = bufferpos; byte newbuffer[] = new byte[size]; for (int i = bufferpos; i < end; i++) { newbuffer[ i - bufferpos] = buffer[i]; } setEnd(end - bufferpos); bufferpos = 0; buffer = newbuffer; //log.info("resize() size %d end %d", buffer.length, end); this.offset += shift; return shift; } return 0; } public int expand(int size) { //log.info("expand( %d )", size); if (size > buffer.length) { return resize(size); } return 0; } public int shift() { //log.info("shift()"); int shift = bufferpos; for (int i = shift; i < end; i++) { buffer[ i - shift] = buffer[i]; } setEnd(end-bufferpos); //log.info("shift() end %d", end); bufferpos = 0; offset += shift; return shift; } public void print(String s) { if (s != null) { byte b[] = s.getBytes(); write(b); } } public void write0(String s) { if (s != null) { write(s.getBytes()); } write((byte) 0); } public int readInt() throws EOFException { //log.info("readInt() bufferpos %d", bufferpos); checkIn(4); int ch1 = buffer[bufferpos++] & 0xFF; int ch2 = buffer[bufferpos++] & 0xFF; int ch3 = buffer[bufferpos++] & 0xFF; int ch4 = buffer[bufferpos++] & 0xFF; int result = ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4)); return result; } public int readInt2() throws EOFException { //log.info("readInt() bufferpos %d", bufferpos); checkIn(2); int ch1 = buffer[bufferpos++] & 0xFF; int ch2 = buffer[bufferpos++] & 0xFF; int result = (ch1 << 8) + ch2; return result; } public int readInt3() throws EOFException { //log.info("readInt() bufferpos %d", bufferpos); checkIn(3); int ch1 = buffer[bufferpos++] & 0xFF; int ch2 = buffer[bufferpos++] & 0xFF; int ch3 = buffer[bufferpos++] & 0xFF; int result = ((ch1 << 16) + (ch2 << 8) + (ch3)); return result; } public void skipInt() { skip(4); } public int readShort() throws EOFException { checkIn(2); int ch1 = buffer[bufferpos++] & 0xFF; int ch2 = buffer[bufferpos++] & 0xFF; int result = ((ch1 << 8) + (ch2)); return result; } public void skipShort() { skip(2); } public int readUShort() throws EOFException { checkIn(2); int ch1 = buffer[bufferpos++] & 0xFF; int ch2 = buffer[bufferpos++] & 0xFF; int result = (int) ((ch1 << 8) + (ch2)); return result; } public void skipUShort() { skip(2); } public double readDouble() throws EOFException { long l = readLong(); return Double.longBitsToDouble(l); } public void skipDouble() { skip(8); } public long readLong() throws EOFException { checkIn(8); long ch1 = buffer[bufferpos++] & 0xFF; long ch2 = buffer[bufferpos++] & 0xFF; long ch3 = buffer[bufferpos++] & 0xFF; long ch4 = buffer[bufferpos++] & 0xFF; long ch5 = buffer[bufferpos++] & 0xFF; long ch6 = buffer[bufferpos++] & 0xFF; long ch7 = buffer[bufferpos++] & 0xFF; long ch8 = buffer[bufferpos++] & 0xFF; long result = ((ch1 << 56) + (ch2 << 48) + (ch3 << 40) + (ch4 << 32) + (ch5 << 24) + (ch6 << 16) + (ch7 << 8) + (ch8)); return result; } public void skipLong() { skip(8); } public int readByte() throws EOFException { checkIn(1); return (buffer[bufferpos++] & 0xFF); } public boolean readBoolean() throws EOFException { checkIn(1); return (buffer[bufferpos++] == 0) ? false : true; } public void skipByte() { skip(1); } public String readString() throws EOFException { int length = readInt(); return readString(length); } public StringBuilder readStringBuilder() throws EOFException { int length = readInt(); if (length == -1) { return null; } return new StringBuilder(readString(length)); } public void skipString() throws EOFException { int length = readInt(); skip(length); } public void skipStringBuilder() throws EOFException { skipString(); } public byte[] readBytes(int length) throws EOFException { if (length > 1000000) { log.info("very long data length=%d offset=%d", length, this.getOffset()); } if (length < 0) { return null; } byte b[] = new byte[length]; readBytes(b, 0, length); return b; } public byte[] readByteBlock() throws EOFException { int length = readInt(); return readBytes(length); } public void skipByteBlock() throws EOFException { int length = readInt(); skip(length); } public void readBytes(byte b[], int offset, int length) throws EOFException { if (length > buffer.length) { for (; bufferpos < end; bufferpos++, length b[offset++] = buffer[bufferpos]; } int read = datain.readBytes(this.offset + this.bufferpos, b, offset, length); if (read != length) { log.info("readBytes(%d %d): EOF reached when reading fixed number of bytes", offset, length); if (datain instanceof HDFSIn) { log.info("in file %s", ((HDFSIn) datain).path.toString()); } log.crash(); } this.offset += bufferpos + length; bufferpos = 0; setEnd(0); } else { checkIn(length); if (bufferpos <= end - length) { length += offset; while (offset < length) { b[offset++] = buffer[bufferpos++]; } } } } public String readString(int length) throws EOFException { if (length > -1) { return ByteTools.toString(readBytes(length)); } return null; } public String readString0() throws EOFException { checkIn(1); int strend = bufferpos - 1; StringBuilder sb = new StringBuilder(); do { if (++strend >= end) { sb.append(ByteTools.toString(buffer, bufferpos, strend - bufferpos)); bufferpos = strend; fillBuffer(); strend = 0; } } while (buffer[strend] != 0); String s = ByteTools.toString(buffer, bufferpos, strend - bufferpos); bufferpos = strend + 1; if (sb.length() > 0) { return sb.append(s).toString(); } return s; } public void skipString0() throws EOFException { bufferpos -= 1; do { if (++bufferpos >= end) { fillBuffer(); } } while (buffer[bufferpos] != 0); bufferpos++; } public String readUntil(ByteRegex regex) throws EOFException { Pos first = find(regex); String s = new String(buffer, bufferpos, first.start - bufferpos); bufferpos = first.end; return s; } public String read(ByteRegex regex) throws EOFException { Pos first = find(regex); String s = new String(buffer, first.start, first.end - first.start); bufferpos = first.end; return s; } public void skipAfter(ByteRegex regex) throws EOFException { Pos first = find(regex); bufferpos = first.end; } public void skipBefore(ByteRegex regex) throws EOFException { Pos first = find(regex); bufferpos = first.start; } public Pos find(ByteRegex regex) throws EOFException { if (!hasMore()) throw this.eof; Pos first = regex.find(buffer, bufferpos, end); if (first.endreached && hasMore()) { fillBuffer(); first = regex.find(buffer, bufferpos, end); } //log.info("%d %d %d", first.start, bufferpos, end); if (first.found()) { return first; } else { throw new EOFException(); } } public String[] readStringArray() throws EOFException { int length = readInt(); if (length == -1) { return null; } String array[] = new String[length]; for (int i = 0; i < length; i++) { array[i] = readString(); } return array; } public void skipStringArray() throws EOFException { int length = readInt(); if (length == -1) { return; } for (int i = 0; i < length; i++) { skipString(); } } public long[] readLongArray() throws EOFException { int length = readInt(); if (length == -1) { return null; } long array[] = new long[length]; for (int i = 0; i < length; i++) { array[i] = readLong(); } return array; } public void skipLongArray() throws EOFException { int length = readInt(); if (length == -1) { return; } skip(8 * length); } public double[] readDoubleArray() throws EOFException { int length = readInt(); if (length == -1) { return null; } double array[] = new double[length]; for (int i = 0; i < length; i++) { array[i] = readDouble(); } return array; } public void skipDoubleArray() throws EOFException { skipLongArray(); } public long[][] readCLongArray2() throws EOFException { int length = readCInt(); if (length == -1) { return null; } if (length == 0) { return new long[0][]; } long array[][] = new long[length][]; for (int i = 0; i < length; i++) { array[i] = readCLongArray(); } return array; } public void skipCLongArray2() throws EOFException { int length = readInt(); if (length < 1) { return; } for (int i = 0; i < length; i++) { skipCLongArray(); } } public int[] readIntArray() throws EOFException { int length = readInt(); if (length == -1) { return null; } int array[] = new int[length]; for (int i = 0; i < length; i++) { array[i] = readInt(); } return array; } public void skipIntArray() throws EOFException { int length = readInt(); if (length == -1) { return; } skip(4 * length); } public int[][] readSquaredIntArray2() throws EOFException { int length = readCInt(); if (length == -1) { return null; } if (length == 0) { return new int[0][]; } int length2 = readCInt(); int array[][] = new int[length][length2]; int input[] = readCIntArray(); int p = 0; for (int i = 0; i < length; i++) { for (int j = 0; j < length2; j++) { array[i][j] = input[p++]; } } return array; } public int[][][] readSquaredIntArray3() throws EOFException { int length = readCInt(); if (length == -1) { return null; } if (length == 0) { return new int[0][][]; } int length2 = readCInt(); int length3 = readCInt(); int array[][][] = new int[length][length2][length3]; int input[] = readCIntArray(); int p = 0; for (int d1 = 0; d1 < length; d1++) { for (int d2 = 0; d2 < length2; d2++) { for (int d3 = 0; d3 < length3; d3++) { array[ d1][ d2][ d3] = input[p++]; } } } return array; } public int[][][] readCIntArray3() throws EOFException { int length = readCInt(); if (length == -1) { return null; } int array[][][] = new int[length][][]; for (int i = 0; i < length; i++) { array[i] = readCIntArray2(); } return array; } public int[][] readCIntArray2() throws EOFException { int length = readCInt(); if (length == -1) { return null; } int array[][] = new int[length][]; for (int i = 0; i < length; i++) { array[i] = readCIntArray(); } return array; } public void skipCIntArray2() throws EOFException { int length = readCInt(); for (int i = 0; i < length; i++) { skipCIntArray(); } } public void skipCIntArray3() throws EOFException { int length = readCInt(); for (int i = 0; i < length; i++) { skipSquaredIntArray2(); } } public void skipSquaredIntArray2() throws EOFException { int length = this.readCInt(); if (length < 1) { return; } skipCInt(); skipCIntArray(); } public void skipSquaredIntArray3() throws EOFException { int length = this.readCInt(); if (length < 1) { return; } skipCInt(); skipCInt(); skipCIntArray(); } public void write(int i) { checkFlush(4); buffer[bufferpos++] = (byte) ((i >>> 24) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 16) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 8) & 0xFF); buffer[bufferpos++] = (byte) ((i) & 0xFF); } public void write2(int i) { checkFlush(2); buffer[bufferpos++] = (byte) ((i >>> 8) & 0xFF); buffer[bufferpos++] = (byte) ((i) & 0xFF); } public void write3(int i) { checkFlush(3); buffer[bufferpos++] = (byte) ((i >>> 16) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 8) & 0xFF); buffer[bufferpos++] = (byte) ((i) & 0xFF); } public void write(short i) { checkFlush(2); buffer[bufferpos++] = (byte) ((i >>> 8) & 0xFF); buffer[bufferpos++] = (byte) ((i) & 0xFF); } public void write(double d) { checkFlush(8); write(Double.doubleToLongBits(d)); } public void write(long i) { checkFlush(8); buffer[bufferpos++] = (byte) ((i >>> 56) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 48) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 40) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 32) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 24) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 16) & 0xFF); buffer[bufferpos++] = (byte) ((i >>> 8) & 0xFF); buffer[bufferpos++] = (byte) ((i) & 0xFF); } public void write(long i[]) { if (i == null) { write(-1); } else { write(i.length); for (long l : i) { write(l); } } } public void write(double i[]) { if (i == null) { write(-1); } else { write(i.length); for (double l : i) { write(l); } } } public void write(int i[]) { if (i == null) { write(-1); } else { write(i.length); for (int l : i) { write(l); } } } public void write(Collection<Integer> i) { if (i == null) { write(-1); } else { write(i.size()); for (int l : i) { write(l); } } } public void writeStr(Collection<String> i) { if (i == null) { write(-1); } else { write(i.size()); for (String l : i) { write(l); } } } /** * Compresses a squared 2-dim array. Note: all rows in the array must have * equal lengths! * * @param array */ public void writeSquared(int array[][]) { if (array == null) { writeC(-1); } if (array.length == 0) { writeC(0); } else { writeC(array.length); writeC(array[0].length); int flat[] = io.github.repir.tools.Lib.ArrayTools.flatten(array); if (array.length * array[0].length != flat.length) { log.fatal("Can only use writeSquared on squared arrays"); } writeC(flat); } } public void writeSquared(int array[][][]) { if (array == null) { writeC(-1); } else if (array.length == 0) { writeC(0); } else { writeC(array.length); writeC(array[0].length); writeC(array[0][0].length); int flat[] = io.github.repir.tools.Lib.ArrayTools.flatten(array); if (array.length * array[0].length * array[0][0].length != flat.length) { log.fatal("Can only use writeSquared on squared arrays"); } writeC(flat); } } public void writeC(int array[][]) { if (array == null) { writeC(-1); } else { writeC(array.length); for (int a[] : array) { writeC(a); } } } public void writeC(int array[][][]) { if (array == null) { writeC(-1); } else { writeC(array.length); for (int a[][] : array) { writeC(a); } } } public void writeSparse(int array[][][]) { if (array == null) { writeC(-1); } else if (array.length == 0) { writeC(0); } else { writeC(array.length); writeC(array[0].length); writeC(array[0][0].length); writeSparse(io.github.repir.tools.Lib.ArrayTools.flatten(array)); } } public void writeSparse(int array[][]) { if (array == null) { writeC(-1); } else if (array.length == 0) { writeC(0); } else { writeC(array.length); writeC(array[0].length); writeSparse(io.github.repir.tools.Lib.ArrayTools.flatten(array)); } } public void writeSparse(long array[][]) { if (array == null) { writeC(-1); } else if (array.length == 0) { writeC(0); } else { writeC(array.length); writeC(array[0].length); writeSparse(io.github.repir.tools.Lib.ArrayTools.flatten(array)); } } public void skipIntSparse3() throws EOFException { int length = readCInt(); if (length < 1) { return; } skipCInt(); skipCInt(); skipIntSparse(); } public void skipIntSparse2() throws EOFException { int length = readCInt(); if (length < 1) { return; } skipCInt(); skipIntSparse(); } public void skipLongSparse2() throws EOFException { int length = readCInt(); if (length < 1) { return; } skipCInt(); skipLongSparse(); } public int[][] readIntSparse2() throws EOFException { int length = readCInt(); if (length == -1) { return null; } else if (length == 0) { return new int[0][]; } else { int length2 = readCInt(); int array[][] = new int[length][length2]; int input[] = readIntSparse(); int pos = 0; for (int i = 0; i < length; i++) { for (int j = 0; j < length2; j++) { array[i][j] = input[pos++]; } } return array; } } public long[][] readLongSparse2() throws EOFException { int length = readCInt(); if (length == -1) { return null; } else if (length == 0) { return new long[0][]; } else { int length2 = readCInt(); long array[][] = new long[length][length2]; long input[] = readLongSparse(); int pos = 0; for (int i = 0; i < length; i++) { for (int j = 0; j < length2; j++) { array[i][j] = input[pos++]; } } return array; } } public int[][][] readIntSparse3() throws EOFException { int length = readCInt(); if (length == -1) { return null; } else if (length == 0) { return new int[0][][]; } else { int length2 = readCInt(); int length3 = readCInt(); int array[][][] = new int[length][length2][length3]; int input[] = readIntSparse(); int pos = 0; for (int i = 0; i < length; i++) { for (int j = 0; j < length2; j++) { for (int k = 0; k < length3; k++) { array[i][j][k] = input[pos++]; } } } return array; } } @Override public void writeC(long array[][]) { if (array == null) { writeC(-1); } else { writeC(array.length); for (long a[] : array) { writeC(a); } } } public void write(String i[]) { if (i == null) { write(-1); } else { write(i.length); for (String l : i) { write(l); } } } public void write(byte b[]) { for (byte i : b) { if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = i; } } public void writeByteBlock(byte b[]) { write(b.length); write(b); } public void write(byte b[], byte escape) { for (int i = 0; i < b.length; i++) { if (b[i] == escape) { if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = escape; } if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = b[i]; } } public void write(byte b[], byte eof[], byte escape) { if (eof.length == 0) { write(b, escape); return; } for (int i = 0; i < b.length; i++) { if (b[i] == escape || io.github.repir.tools.Lib.ByteTools.matchString(b, eof, i)) { if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = escape; } if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = b[i]; } } public void write(byte b[], byte end[], byte end2[], byte escape) { if (end2.length == 0) { write(b, end, escape); } else if (end.length == 0) { write(b, end2, escape); } else { for (int i = 0; i < b.length; i++) { if (b[i] == escape || io.github.repir.tools.Lib.ByteTools.matchString(b, end, i) || io.github.repir.tools.Lib.ByteTools.matchString(b, end2, i)) { if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = escape; } if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = b[i]; } } } public void writeWS(byte b[], byte eof[], byte escape) { for (int i = 0; i < b.length; i++) { if (bufferpos >= buffer.length) { this.flushBuffer(); } if (io.github.repir.tools.Lib.ByteTools.matchStringWS(b, eof, i)) { buffer[bufferpos++] = escape; if (bufferpos >= buffer.length) { this.flushBuffer(); } } buffer[bufferpos++] = b[i]; } } public void write(byte b[], int offset, int length) { length = offset + length; while (offset < length) { if (bufferpos >= buffer.length) { this.flushBuffer(); } buffer[bufferpos++] = b[offset++]; } } public void write(byte i) { checkFlush(1); buffer[bufferpos++] = i; } public void write(boolean i) { checkFlush(1); buffer[bufferpos++] = (byte) (i ? -1 : 0); } public void writeUB(int i) { checkFlush(1); buffer[bufferpos++] = (byte) (i & 0xFF); } public void writeChar(int c) { checkFlush(2); buffer[ bufferpos++] = (byte) ((c >>> 8) & 0xFF); buffer[ bufferpos++] = (byte) ((c >>> 0) & 0xFF); } public void write(String s) { if (s == null) { write(-1); } else { byte b[] = s.getBytes(); write(b.length); write(b); } } public void write(StringBuilder s) { if (s == null) { write(-1); } else { write(s.toString()); } } public long readCLong() throws EOFException { checkIn(1); byte firstByte = buffer[bufferpos++]; int len = decodeVIntSize(firstByte); if (len == 1) { return firstByte; } checkIn(len - 1); long i = 0; for (int idx = 0; idx < len - 1; idx++) { i = i << 8; i = i | (buffer[bufferpos++] & 0xFF); } return (isNegativeVInt(firstByte) ? (i ^ -1L) : i); } public void skipCLong() throws EOFException { checkIn(1); byte firstByte = buffer[bufferpos++]; int len = decodeVIntSize(firstByte); skip(len - 1); } public void writeC(int i) { writeC((long) i); } public int readCInt() throws EOFException { return (int) readCLong(); } public void skipCInt() throws EOFException { skipCLong(); } public void writeC(long i) { if (i >= -112 && i <= 127) { write((byte) i); return; } int len = -112; if (i < 0) { i ^= -1L; // take one's complement' len = -120; } long tmp = i; while (tmp != 0) { tmp = tmp >> 8; len } write((byte) len); len = (len < -120) ? -(len + 120) : -(len + 112); checkFlush(len); for (int idx = len; idx != 0; idx int shiftbits = (idx - 1) * 8; long mask = 0xFFL << shiftbits; buffer[bufferpos++] = (byte) ((i & mask) >> shiftbits); } } public static int decodeVIntSize(byte value) { if (value >= -112) { return 1; } else if (value < -120) { return -119 - value; } return -111 - value; } public static boolean isNegativeVInt(byte value) { return value < -120 || (value >= -112 && value < 0); } public byte longmask(long l) { if ((l & 0xFFFFFFFFFF000000l) != 0) { return 3; } if ((l & 0xFF0000) != 0) { return 2; } if ((l & 0xFF00) != 0) { return 1; } else { return 0; } } public long[] readCLongArray() throws EOFException { int length = readCInt(); if (length == -1) { return null; } long l[] = new long[length]; int mainlength = (length / 4) * 4; for (int i = 0; i < mainlength; i += 4) { checkIn(1); int mask = buffer[bufferpos++]; for (int s = i; s < i + 4; s++) { int m = (mask >> ((s - i) * 2)) & 3; if (m < 3) { checkIn(m + 1); } switch (m) { case 3: l[s] = readCLong(); break; case 2: l[s] |= ((buffer[bufferpos++] & 0xFF) << 16); case 1: l[s] |= ((buffer[bufferpos++] & 0xFF) << 8); case 0: l[s] |= (buffer[bufferpos++] & 0xFF); } } } for (int i = mainlength; i < l.length; i++) { l[i] = readCLong(); } return l; } public void skipCLongArray() throws EOFException { int length = readCInt(); if (length == -1) { return; } int mainlength = (length / 4) * 4; for (int i = 0; i < mainlength; i += 4) { checkIn(1); int mask = buffer[bufferpos++]; for (int s = i; s < i + 4; s++) { int m = (mask >> ((s - i) * 2)) & 3; if (m == 3) { skipCLong(); } else { skip(m + 1); } } } for (int i = mainlength; i < length; i++) { skipCLong(); } } public void writeC(long[] l) { if (l == null) { writeC(-1); return; } writeC(l.length); byte m[] = new byte[4]; int mainlength = (l.length / 4) * 4; for (int i = 0; i < mainlength; i += 4) { byte mask = 0; for (int s = i; s < i + 4; s++) { m[s - i] = longmask(l[s]); mask |= (m[s - i] << ((s - i) * 2)); } checkFlush(1); buffer[bufferpos++] = mask; for (int s = i; s < i + 4; s++) { if (m[s - i] < 3) { checkFlush(m[s - i] + 1); } switch (m[s - i]) { case 3: writeC(l[s]); break; case 2: buffer[bufferpos++] = (byte) ((l[s] >> 16) & 0xFF); case 1: buffer[bufferpos++] = (byte) ((l[s] >> 8) & 0xFF); case 0: buffer[bufferpos++] = (byte) (l[s] & 0xFF); } } } for (int i = mainlength; i < l.length; i++) { writeC(l[i]); } } public void writeSparse(long l[]) { writeSparse(l, 0, (l != null) ? l.length : 0); } public void writeSparse(long l[], int offset, int length) { if (l == null) { writeC(-1); return; } writeC(length); int end = offset + length; int mainlength = 0; for (int i = offset; i < end; i++) { if (l[i] != 0) { mainlength++; } } int leap[] = new int[mainlength]; long ltf[] = new long[mainlength]; int last = 0, pos = 0; for (int i = offset; i < end; i++) { if (l[i] > 0) { leap[pos] = i - last; ltf[pos++] = l[i]; last = i + 1; } } writeC(leap); writeC(ltf); } public void writeSparse(int l[]) { writeSparse(l, 0, (l != null) ? l.length : 0); } public void writeSparse(int l[], int offset, int length) { if (l == null) { writeC(-1); return; } writeC(length); int end = offset + length; int mainlength = 0; for (int i = offset; i < end; i++) { if (l[i] != 0) { mainlength++; } } int leap[] = new int[mainlength]; int ltf[] = new int[mainlength]; int last = 0, pos = 0; for (int i = offset; i < end; i++) { if (l[i] > 0) { leap[pos] = i - last; ltf[pos++] = l[i]; last = i + 1; } } writeC(leap); writeC(ltf); } public void writeSparse(double l[]) { writeSparse(l, 0, (l != null) ? l.length : 0); } public void writeSparse(double l[], int offset, int length) { if (l == null) { writeC(-1); return; } writeC(length); int end = offset + length; int mainlength = 0; for (int i = offset; i < end; i++) { if (l[i] != 0) { mainlength++; } } int leap[] = new int[mainlength]; double ltf[] = new double[mainlength]; int last = 0, pos = 0; for (int i = offset; i < end; i++) { if (l[i] > 0) { leap[pos] = i - last; ltf[pos++] = l[i]; last = i + 1; } } writeC(leap); write(ltf); } public void writeSparseLong(Map<Integer, Long> table) { if (table == null) { writeC(-1); return; } TreeSet<Integer> keys = new TreeSet<Integer>(table.keySet()); if (keys.size() > 0) { writeC(keys.last() + 1); int mainlength = 0; for (long value : table.values()) { if (value > 0) { mainlength++; } } int leap[] = new int[mainlength]; long ltf[] = new long[mainlength]; int last = 0, pos = 0; for (int key : keys) { long value = table.get(key); if (value > 0) { leap[pos] = key - last; ltf[pos++] = value; last = key + 1; } } writeC(leap); writeC(ltf); } else { writeC(0); writeC(0); writeC(0); } } public void writeSparseInt(Map<Integer, Integer> table) { if (table == null) { writeC(-1); return; } TreeSet<Integer> keys = new TreeSet<Integer>(table.keySet()); if (keys.size() > 0) { writeC(keys.last() + 1); int mainlength = 0; for (int value : table.values()) { if (value > 0) { mainlength++; } } int leap[] = new int[mainlength]; int ltf[] = new int[mainlength]; int last = 0, pos = 0; for (int key : keys) { int value = table.get(key); if (value > 0) { leap[pos] = key - last; ltf[pos++] = value; last = key + 1; } } writeC(leap); writeC(ltf); } else { writeC(0); writeC(0); writeC(0); } } public long[] readLongSparse() throws EOFException { int length = readCInt(); if (length == -1) { return null; } int leap[] = readCIntArray(); long value[] = readCLongArray(); long l[] = new long[length]; int last = 0; for (int i = 0; i < leap.length; i++) { //log.info("%d", value[i]); last += leap[i]; l[last++] = value[i]; } return l; } public void skipLongSparse() throws EOFException { int length = readCInt(); if (length == -1) { return; } skipCIntArray(); skipCLongArray(); } public double[] readDoubleSparse() throws EOFException { int length = readCInt(); if (length == -1) { return null; } int leap[] = readCIntArray(); double value[] = readDoubleArray(); double l[] = new double[length]; int last = 0; for (int i = 0; i < leap.length; i++) { //log.info("%d", value[i]); last += leap[i]; l[last++] = value[i]; } return l; } public void skipDoubleSparse() throws EOFException { int length = readCInt(); if (length == -1) { return; } skipCIntArray(); skipDoubleArray(); } public int[] readIntSparse() throws EOFException { int length = readCInt(); if (length == -1) { return null; } int leap[] = readCIntArray(); int value[] = readCIntArray(); int l[] = new int[length]; int last = 0; for (int i = 0; i < leap.length; i++) { //log.info("%d", value[i]); last += leap[i]; l[last++] = value[i]; } return l; } public void skipIntSparse() throws EOFException { int length = readCInt(); if (length == -1) { return; } skipCIntArray(); skipCIntArray(); } public HashMap<Integer, Long> readSparseLongMap() throws EOFException { int length = readCInt(); if (length == -1) { return null; } HashMap<Integer, Long> table = new HashMap<Integer, Long>(length); int leap[] = readCIntArray(); long value[] = readCLongArray(); int last = 0; for (int i = 0; i < leap.length; i++) { last += leap[i]; table.put(last++, value[i]); } return table; } public HashMap<Integer, Integer> readSparseIntMap() throws EOFException { int length = readCInt(); if (length == -1) { return null; } HashMap<Integer, Integer> table = new HashMap<Integer, Integer>(length); int leap[] = readCIntArray(); int value[] = readCIntArray(); int last = 0; for (int i = 0; i < leap.length; i++) { last += leap[i]; table.put(last++, value[i]); } return table; } public void writeIncr(int[] array) { for (int i = array.length - 1; i > 0; i array[i] -= array[i - 1]; } writeC(array); } public void writeIncr(ArrayList<Integer> list) { Integer arrayI[] = list.toArray(new Integer[list.size()]); int arrayi[] = new int[arrayI.length]; for (int i = arrayI.length - 1; i > 0; i arrayi[i] = arrayI[i] - arrayI[i - 1]; } arrayi[0] = arrayI[0]; writeC(arrayi); } public void writeC(int[] l) { if (l == null) { writeC(-1); return; } writeC(l.length); int length = (l.length / 4) * 4; byte m[] = new byte[4]; for (int i = 0; i < length; i += 4) { byte mask = 0; for (int s = i; s < i + 4; s++) { m[s - i] = longmask(l[s]); mask |= (m[s - i] << ((s - i) * 2)); //if (l[s] == 2554) { // log.info("m[%d]=%d mask %d bufferpos %d", s-i, m[s-i], mask, i); } checkFlush(1); buffer[bufferpos++] = mask; for (int s = i; s < i + 4; s++) { checkFlush(m[s - i] + 1); switch (m[ s - i]) { case 3: buffer[bufferpos++] = (byte) ((l[s] >>> 24) & 0xFF); case 2: buffer[bufferpos++] = (byte) ((l[s] >>> 16) & 0xFF); case 1: buffer[bufferpos++] = (byte) ((l[s] >>> 8) & 0xFF); case 0: buffer[bufferpos++] = (byte) (l[s] & 0xFF); } } } for (int i = length; i < l.length; i++) { writeC(l[i]); } } public void writeC(ArrayList<Integer> l) { if (l == null) { writeC(-1); return; } writeC(l.size()); int length = (l.size() / 4) * 4; byte m[] = new byte[4]; int v[] = new int[4]; for (int i = 0; i < length; i += 4) { byte mask = 0; v[0] = l.get(i); v[1] = l.get(i + 1); v[2] = l.get(i + 2); v[3] = l.get(i + 3); m[0] = longmask(v[0]); m[1] = longmask(v[1]); m[2] = longmask(v[2]); m[3] = longmask(v[3]); mask = (byte) (m[0] | (m[1] << 2) | (m[2] << 4) | (m[3] << 6)); checkFlush(1); buffer[bufferpos++] = mask; for (int s = 0; s < 4; s++) { checkFlush(m[s] + 1); switch (m[s]) { case 3: buffer[bufferpos++] = (byte) ((v[s] >>> 24) & 0xFF); case 2: buffer[bufferpos++] = (byte) ((v[s] >>> 16) & 0xFF); case 1: buffer[bufferpos++] = (byte) ((v[s] >>> 8) & 0xFF); case 0: buffer[bufferpos++] = (byte) (v[s] & 0xFF); } } } for (int i = length; i < l.size(); i++) { writeC(l.get(i)); } } public int[] readCIntArray() throws EOFException { int length = readCInt(); if (length == -1) { return null; } int l[] = new int[length]; int mainlength = (length / 4) * 4; //log.info("mainlength %d length %d", mainlength, length); for (int i = 0; i < mainlength; i += 4) { checkIn(1); int mask = buffer[bufferpos++]; for (int s = i; s < i + 4; s++) { int m = (mask >> ((s - i) * 2)) & 3; checkIn(m + 1); switch (m) { case 3: l[s] = ((buffer[bufferpos++] & 0xFF) << 24); case 2: l[s] |= ((buffer[bufferpos++] & 0xFF) << 16); case 1: l[s] |= ((buffer[bufferpos++] & 0xFF) << 8); case 0: l[s] |= (buffer[bufferpos++] & 0xFF); } } } for (int i = mainlength; i < l.length; i++) { l[i] = readCInt(); } return l; } public ArrayList<Integer> readCIntArrayList() throws EOFException { int length = readCInt(); if (length == -1) { return null; } ArrayList<Integer> l = new ArrayList<Integer>(); int mainlength = (length / 4) * 4; //log.info("mainlength %d length %d", mainlength, length); for (int i = 0; i < mainlength; i += 4) { checkIn(1); int mask = buffer[bufferpos++]; for (int s = i; s < i + 4; s++) { int m = (mask >> ((s - i) * 2)) & 3; checkIn(m + 1); int value = 0; switch (m) { case 3: value = ((buffer[bufferpos++] & 0xFF) << 24); case 2: value |= ((buffer[bufferpos++] & 0xFF) << 16); case 1: value |= ((buffer[bufferpos++] & 0xFF) << 8); case 0: value |= (buffer[bufferpos++] & 0xFF); } l.add(value); } } for (int i = mainlength; i < length; i++) { l.add(readCInt()); } return l; } public ArrayList<Integer> readIntArrayList() throws EOFException { int length = readInt(); if (length == -1) { return null; } ArrayList<Integer> l = new ArrayList<Integer>(); for (int i = 0; i < length; i++) { l.add(this.readInt()); } return l; } public ArrayList<String> readStrArrayList() throws EOFException { int length = readInt(); if (length == -1) { return null; } ArrayList<String> l = new ArrayList<String>(); for (int i = 0; i < length; i++) { l.add(this.readString()); } return l; } static final int CIntArrayLength[] = initClongArrayLength(); public static int[] initClongArrayLength() { int a[] = new int[256]; for (int i = 0; i < 256; i++) { int total = 4; for (int s = 0; s < 4; s++) { int m = (i >> ((s) * 2)) & 3; total += m; } a[i] = total; } return a; } public void skipCIntArray() throws EOFException { int length = readCInt(); if (length == -1) { return; } int mainlength = (length / 4) * 4; for (int i = 0; i < mainlength; i += 4) { checkIn(1); int mask = buffer[bufferpos++]; skip(CIntArrayLength[ mask]); } for (int i = mainlength; i < length; i++) { skipCInt(); } //log.info("%d", this.getOffset()); } public void writeC(double d) { writeC(Double.doubleToLongBits(d)); } public double readCDouble() throws EOFException { long l = readCLong(); return Double.longBitsToDouble(l); } public void skipCDouble() throws EOFException { skipCLong(); } public void openRead() { datain.openRead(); hasmore = true; eof = null; } public void openWrite() { dataout.openWrite(); } public void openAppend() { dataout.openAppend(); } public void write(Map<String, String> map) { write(map.size()); for (Map.Entry<String, String> e : map.entrySet()) { write(e.getKey()); write(e.getValue()); } } public Map<String, String> readStringPairMap() throws EOFException { int size = readInt(); ArrayMap<String, String> map = new ArrayMap<String, String>(); for (int i = 0; i < size; i++) { String key = readString(); String value = readString(); map.put(key, value); } return map; } public void skipStringPairMap() throws EOFException { int size = readInt(); for (int i = 0; i < size; i++) { skipString(); skipString(); } } /** * Reads the buffer until end-of-field is found. * <p/> * @param eof end-of-field sequence * @param escape escape character that must not precede eof * @return the String up till the point of the end-of-field * @throws EOFException */ public String readString(byte[] eof, byte escape) throws EOFException { //log.info("readString( %s )", new String(eof)); int current2 = bufferpos; int match = 0; pos p = new pos(bufferpos); while (match < eof.length && p.endoffile == null) { current2 = p.pos; for (match = 0; match < eof.length && hasMore();) { if (current2 >= end) { current2 -= fillBuffer(p); } if (buffer[current2] == escape) { p.pos = current2 + 1; break; } else if (buffer[current2] == eof[match]) { match++; current2++; } else { break; } } if (match < eof.length && p.endoffile == null) { ++p.pos; } } if (p.endoffile != null && match < eof.length) { throw p.endoffile; } if (p.pos > bufferpos) { p.s.append(ByteTools.toString(buffer, bufferpos, p.pos - bufferpos)); } bufferpos = current2; //log.info("end readString( %s )", new String(eof)); return p.s.toString(); } public String readString(byte[] eof, byte peekend[], byte escape) throws EOFException { if (eof.length == 0) { return readStringPeekEnd(peekend, escape); } //log.info("readString( '%s', '%s' )", new String(eof), new String(peekend)); int current2 = bufferpos; int match = 0; pos p = new pos(bufferpos); while (match < eof.length && p.endoffile == null) { if (!peekStringNotExists(peekend, p)) { current2 = p.pos; break; } if (buffer[p.pos] == escape) { p.pos++; fillBuffer(p); ++p.pos; } else { current2 = p.pos; for (match = 0; match < eof.length && this.hasMore();) { if (current2 >= end) { current2 -= fillBuffer(p); } else if (buffer[current2] == eof[match]) { match++; current2++; } else { break; } } if (match < eof.length && p.endoffile == null) { ++p.pos; } } } if (p.endoffile != null && match < eof.length) { throw p.endoffile; } if (p.pos > bufferpos) { p.s.append(ByteTools.toString(buffer, bufferpos, p.pos - bufferpos)); } //log.info("end"); bufferpos = current2; return p.s.toString(); } public String readStringPeekEnd(byte peekend[], byte escape) throws EOFException { pos p = new pos(bufferpos); while (p.endoffile == null || p.pos < end) { if (!peekStringNotExists(peekend, p)) { if (p.pos > bufferpos) { p.s.append(ByteTools.toString(buffer, bufferpos, p.pos - bufferpos)); } bufferpos = p.pos; return p.s.toString(); } if (buffer[p.pos] == escape) { p.pos++; fillBuffer(p); ++p.pos; } else { ++p.pos; } } throw p.endoffile; } public String readStringPeekEndWS(byte peekend[], byte escape) throws EOFException { pos p = new pos(bufferpos); while (p.endoffile == null || p.pos < end) { if (!peekStringNotExistsWS(peekend, p)) { if (p.pos > bufferpos) { p.s.append(ByteTools.toString(buffer, bufferpos, p.pos - bufferpos)); } bufferpos = p.pos; return p.s.toString(); } if (buffer[p.pos] == escape) { p.pos++; fillBuffer(p); ++p.pos; } else { ++p.pos; } } throw p.endoffile; } /** * Reads the buffer until end-of-field is found. Spaces in the eof sequence, * matchWS zero or more whitespace characters. * <p/> * @param eof end-of-field sequence * @return the String up till the point of the end-of-field * @throws EOFException */ public String readStringWS(byte[] eof, byte escape) throws EOFException { //log.info("start readStringWS '%s'", new String(eof)); int current2 = bufferpos; int match = 0; pos p = new pos(bufferpos); //log.info("readStringWS %s %d %d %b %s", new String(eof), matchWS, eof.length, matchWS < eof.length, new String(buffer, bufferpos, 10)); while (match < eof.length && p.endoffile == null) { current2 = p.pos; //log.info("readString %s bufferpos %d end %d current %d matchWS %d", new String(eof), bufferpos, end, p.pos, match); for (match = 0; match < eof.length;) { if (current2 >= end) { //log.info("readStringWS fillBuffer"); current2 -= fillBuffer(p); //log.info("after fillbuffer %d %d '%s'", bufferpos, current2, new String(buffer, 0, 50)); } //log.info("matchWS %d %d %d '%s' %d", match, current2, buffer[current2], DataTypes.ByteTools.listBytesAsString(buffer[current2]), eof[match]); if (current2 >= end) { for (; match < eof.length && whitespace[eof[match]]; match++); break; } else if (buffer[current2] == escape) { p.pos = current2 + 1; break; } else if (whitespace[eof[match]]) { if (buffer[current2] >= 0 && whitespace[buffer[current2]]) { current2++; } else if (whitespace[eof[match]]) { match++; } } else if (sametext(buffer[current2], eof[match])) { match++; current2++; } else { break; } } if (match < eof.length && p.endoffile == null) { ++p.pos; } } if (p.endoffile != null && match < eof.length) { throw p.endoffile; } if (p.pos > bufferpos) { p.s.append(ByteTools.toString(buffer, bufferpos, p.pos - bufferpos)); } bufferpos = current2; //log.info("return"); return p.s.toString(); } /** * Reads the buffer until end-of-field is found. Spaces in the eof sequence, * matchWS zero or more whitespace characters. * <p/> * @param eof end-of-field sequence * @return the String up till the point of the end-of-field * @throws EOFException */ public String readString(ByteRegex eof) throws EOFException { pos p = new pos(bufferpos); //log.info("endos start %d found %b endreached %b", endpos.start, endpos.found(), endpos.endreached); while (p.endoffile == null) { if (p.pos < end && buffer[p.pos] == '\\') { if (++p.pos >= end) { fillBuffer(p); } p.pos++; continue; } Pos endpos = eof.find(buffer, p.pos, end); if (endpos.endreached) { p.pos = endpos.start; fillBuffer(p); if (p.pos < end) { continue; } if (!endpos.found()) { throw new EOFException(); } } if (endpos.found()) { p.s.append(ByteTools.toString(buffer, bufferpos, endpos.start - bufferpos)); bufferpos = endpos.end; return p.s.toString(); } p.pos++; } throw p.endoffile; } /** * Peek in the buffer if regex is found next * <p/> * @param regex * @param p * @return * @throws EOFException */ public Pos peekStringExists(ByteRegex regex, pos p) throws EOFException { //log.info("peekString( %s )", new String(sof)); //regex.print(); Pos endpos = regex.findFirst(buffer, p.pos, end); if (!endpos.found() && endpos.endreached) { fillBuffer(p); endpos = regex.findFirst(buffer, p.pos, end); } //log.info("end peekString() start %d end %d found %b", endpos.start, endpos.end, endpos.found()); return endpos; } @Override public void skipString(ByteRegex regex) throws EOFException { readString(regex); } @Override public boolean peekStringExists(ByteRegex sof) throws EOFException { return sof.isEmpty() || peekStringExists(sof, new pos(bufferpos)).found(); } public void skipFirst(ByteRegex sof) throws EOFException { if (!sof.isEmpty()) { Pos peekStringExists = peekStringExists(sof, new pos(bufferpos)); if (peekStringExists.found()) { bufferpos = peekStringExists.end; } } } @Override public boolean peekStringNotExists(ByteRegex sof) throws EOFException { return sof.isEmpty() || !peekStringExists(sof, new pos(bufferpos)).found(); } public boolean peekStringNotExists(ByteRegex sof, pos p) throws EOFException { return sof.isEmpty() || !peekStringExists(sof, p).found(); } public boolean sametext(byte a, byte b) { return (a == b || (a >= 0 && b >= 0 && sametext[a] == sametext[b])); } public String readStringWS(byte[] eof, byte peekend[], byte escape) throws EOFException { if (eof.length == 0) { return readStringPeekEndWS(peekend, escape); } //log.info("start readStringWS '%s' '%s'", new String(eof), new String(peekend)); int current2 = bufferpos; int match = 0; pos p = new pos(bufferpos); //log.info("readStringWS %s %d %d %b %s", new String(eof), match, eof.length, match < eof.length, new String(buffer, bufferpos, 10)); while (match < eof.length && p.endoffile == null) { if (!peekStringNotExistsWS(peekend, p)) { current2 = p.pos; break; } current2 = p.pos; for (match = 0; match < eof.length;) { if (current2 >= end) { //log.info("readStringWS fillBuffer"); current2 -= fillBuffer(p); //log.info("after fillbuffer %d %d '%s'", bufferpos, current2, new String(buffer, 0, 50)); } //log.info("matchWS %d %d %d %d '%s' %d buffer '%s'", match, p.pos, current2, buffer[current2], DataTypes.ByteTools.listBytesAsString(buffer[current2]), eof[match], // new String( buffer, p.pos, Math.min(40, end-p.pos))); if (current2 >= end) { for (; match < eof.length && whitespace[eof[match]]; match++); } else if (buffer[current2] == escape) { p.pos = current2 + 1; break; } else if (whitespace[eof[match]]) { if (buffer[current2] >= 0 && whitespace[buffer[current2]]) { current2++; } else { match++; } } else if (sametext(buffer[current2], eof[match])) { match++; current2++; } else { break; } } if (match < eof.length && p.endoffile == null) { ++p.pos; } } if (p.endoffile != null && match < eof.length) { throw p.endoffile; } if (p.pos > bufferpos) { //log.info("store '%s' bufferpos %d pos %d next %d", new String(buffer, bufferpos, current2 - bufferpos), bufferpos, p.pos, current2); p.s.append(ByteTools.toString(buffer, bufferpos, p.pos - bufferpos)); } bufferpos = current2; //log.info("return"); return p.s.toString(); } public int fillBuffer(pos p) { //log.info("fillBuffer offset %d bufferpos %d pos %d end %d", this.offset, bufferpos, p.pos, end); if (p.pos > bufferpos) { p.s.append(ByteTools.toString(buffer, bufferpos, p.pos - bufferpos)); } int shift = p.pos; bufferpos = p.pos; p.pos = 0; try { if (this.hasmore) { fillBuffer(); } } catch (EOFException ex) { } if (!hasmore) { //log.info("set EOF %s", eof); p.endoffile = eof; } //log.info("fillBuffer end offset %d bufferpos %d pos %d", offset, bufferpos, p.pos); return shift; } public int[] readCIntIncr() throws EOFException { int value[] = readCIntArray(); for (int i = 1; i < value.length; i++) { value[i] += value[i - 1]; } return value; } class pos { int pos; StringBuilder s = new StringBuilder(); EOFException endoffile; public pos(int pos) { this.pos = pos; if (!hasMore()) { endoffile = eof; } } } /** * Checks if next in the buffer the start-of-field is found. Spaces in the * sof sequence, matchWS zero or more whitespace characters. * <p/> * @param sof start-of-field sequence * @return true if the at the current position the buffer matches * start-of-field */ public boolean peekStringExists(byte[] sof, pos p) throws EOFException { //log.info("peekString( %s )", new String(sof)); int match = 0; int pos = p.pos; for (match = 0; match < sof.length;) { if (pos >= end) { pos -= fillBuffer(p); } if (buffer[pos] == sof[match]) { match++; pos++; } else { break; } } //log.info("end peekString( %s ) end %b", new String(sof), match >= sof.length); return (match >= sof.length); } public boolean peekStringExists(byte[] sof) throws EOFException { return sof.length == 0 || peekStringExists(sof, new pos(bufferpos)); } public boolean peekStringNotExists(byte[] sof) throws EOFException { return sof.length == 0 || !peekStringExists(sof, new pos(bufferpos)); } public boolean peekStringNotExists(byte[] sof, pos p) throws EOFException { return sof.length == 0 || !peekStringExists(sof, p); } /** * Checks if next in the buffer the start-of-field is found. Spaces in the * sof sequence, matchWS zero or more whitespace characters. * <p/> * @param sof start-of-field sequence * @return true if the at the current position the buffer matches * start-of-field */ public boolean peekStringExistsWS(byte[] sof, pos p) throws EOFException { //log.info("peekStringWS( %s )", new String(sof)); int match = 0; int pos = p.pos; for (match = 0; match < sof.length;) { if (pos >= end) { //log.info("filling buffer"); pos -= fillBuffer(p); //log.info("after fillbuffer %d '%s'", bufferpos, new String(buffer, 0, 50)); } //log.info("peekStringExists %d '%s' buffer %d '%s' '%s'", match, new String(sof, match, 1), pos, new String(buffer, pos, 1), // new String(buffer, p.pos, Math.min(40, end -p.pos))); if (whitespace[sof[match]]) { if (buffer[pos] >= 0 && whitespace[buffer[pos]]) { pos++; } else { match++; } } else if (sametext(buffer[pos], sof[match])) { match++; pos++; } else { break; } } for (; match < sof.length && whitespace[sof[match]]; match++); //log.info("peekStringWS( %s ) return %b", new String(sof), match >= sof.length); return (match >= sof.length); } public boolean peekStringExistsWS(byte[] sof) throws EOFException { return sof.length == 0 || peekStringExistsWS(sof, new pos(bufferpos)); } public boolean peekStringNotExistsWS(byte[] sof) throws EOFException { return sof.length == 0 || !peekStringExistsWS(sof, new pos(bufferpos)); } public boolean peekStringNotExistsWS(byte[] sof, pos p) throws EOFException { return sof.length == 0 || !peekStringExistsWS(sof, p); } /** * reads past the first occurrence of end-of-field. Whitespaces in the eof * sequence, matchWS zero or more whitespace characters. * <p/> * @param eof end-of-field sequence * @throws EOFException */ public void skipString(byte[] eof, byte escape) throws EOFException { //log.info("skipString()"); int match = 0; int current = bufferpos; pos p = new pos(bufferpos); while (match < eof.length) { if (current >= end) { current -= fillBuffer(p); } if (buffer[current] == eof[match]) { current++; if (++match == eof.length) { break; } } else if (buffer[current] == escape) { p.pos++; fillBuffer(p); current = ++p.pos; match = 0; } else { match = 0; current = ++p.pos; } } bufferpos = current + match; //log.info("end skipString()"); } /** * reads past the first occurrence of end-of-field. Whitespaces in the eof * sequence, matchWS zero or more whitespace characters. * <p/> * @param eof end-of-field sequence * @throws EOFException */ public void skipString(byte[] eof, byte peekend[], byte escape) throws EOFException { //log.info("skipString(eof peekend, escape)"); int match = 0; int current = bufferpos; pos p = new pos(bufferpos); while (match < eof.length) { if (!peekStringNotExistsWS(peekend, p)) { current = p.pos; break; } current = p.pos + match; if (buffer[current] == eof[match]) { current++; if (++match == eof.length) { break; } } else if (buffer[current] == escape) { p.pos++; fillBuffer(p); current = ++p.pos; match = 0; } else { match = 0; current = ++p.pos; } } bufferpos = current; //log.info("end skipString(eof peekend, escape)"); } /** * reads past the first occurrence of end-of-field. Whitespaces in the eof * sequence, matchWS zero or more whitespace characters. * <p/> * @param eof end-of-field sequence * @throws EOFException */ public void skipStringWS(byte[] eof, byte escape) throws EOFException { //log.info("skipStringWS( %s )", new String(eof)); int match = 0; int current2 = bufferpos; pos p = new pos(bufferpos); while (match < eof.length) { // log.info("match eof %d '%s' buffer %d '%s'", match, new String(eof, match, 1), current2, new String(buffer, current2, 1)); if (current2 >= end) { bufferpos = p.pos; current2 -= fillBuffer(p); } if (buffer[current2] == escape) { ++p.pos; fillBuffer(p); current2 = ++p.pos; match = 0; } else if (whitespace[eof[match]]) { if (buffer[current2] >= 0 && whitespace[buffer[current2]]) { current2++; } else { match++; } } else if (sametext(buffer[current2], eof[match])) { match++; current2++; } else { current2 = ++p.pos; match = 0; } } bufferpos = current2; //log.info("end skipStringWS( %s )", new String(eof)); } /** * reads past the first occurrence of end-of-field. Whitespaces in the eof * sequence, matchWS zero or more whitespace characters. * <p/> * @param eof end-of-field sequence * @throws EOFException */ public void skipStringWS(byte[] eof, byte peekend[], byte escape) throws EOFException { //log.info("skipStringWS( eof, peekend, escape )"); if (peekend.length == 0) { skipStringWS(eof, escape); } else { int match = 0; int current2 = bufferpos; pos p = new pos(bufferpos); while (match < eof.length && peekStringNotExistsWS(peekend, p)) { // log.info("match eof %d '%s' buffer %d '%s'", match, new String(eof, match, 1), current2, new String(buffer, current2, 1)); if (current2 >= end) { bufferpos = p.pos; current2 -= fillBuffer(p); } if (buffer[current2] == escape) { ++p.pos; fillBuffer(p); current2 = ++p.pos; match = 0; } else if (whitespace[eof[match]]) { if (buffer[current2] >= 0 && whitespace[buffer[current2]]) { current2++; } else { match++; } } else if (sametext(buffer[current2], eof[match])) { match++; current2++; } else { current2 = ++p.pos; match = 0; } } bufferpos = current2; } //log.info("end skipStringWS( %s )", new String(eof)); } }
package org.appwork.utils.swing.dialog; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.awt.event.WindowListener; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.List; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import net.miginfocom.swing.MigLayout; import org.appwork.exceptions.WTFException; import org.appwork.resources.AWUTheme; import org.appwork.storage.JSonStorage; import org.appwork.swing.MigPanel; import org.appwork.uio.UIOManager; import org.appwork.uio.UserIODefinition; import org.appwork.utils.Application; import org.appwork.utils.BinaryLogic; import org.appwork.utils.formatter.TimeFormatter; import org.appwork.utils.images.IconIO; import org.appwork.utils.locale._AWU; import org.appwork.utils.logging.Log; import org.appwork.utils.net.Base64OutputStream; import org.appwork.utils.swing.EDTHelper; import org.appwork.utils.swing.EDTRunner; import org.appwork.utils.swing.WindowManager; import org.appwork.utils.swing.WindowManager.FrameState; import org.appwork.utils.swing.dialog.dimensor.DialogDimensor; import org.appwork.utils.swing.dialog.locator.CenterOfScreenDialogLocator; import org.appwork.utils.swing.dialog.locator.DialogLocator; public abstract class AbstractDialog<T> implements ActionListener, WindowListener, OKCancelCloseUserIODefinition { private static int BUTTON_HEIGHT = -1; public static DialogLocator DEFAULT_LOCATOR = null; public static final DialogLocator LOCATE_CENTER_OF_SCREEN = new CenterOfScreenDialogLocator(); private static final HashMap<String, Integer> SESSION_DONTSHOW_AGAIN = new HashMap<String, Integer>(); protected static final WindowStack WINDOW_STACK = new WindowStack(); public static FrameState WINDOW_STATE_ON_VISIBLE = FrameState.TO_FRONT_FOCUSED; public static int getButtonHeight() { return AbstractDialog.BUTTON_HEIGHT; } public static DialogLocator getDefaultLocator() { return AbstractDialog.DEFAULT_LOCATOR; } /** * @return */ public static Window getRootFrame() { return WINDOW_STACK.size() == 0 ? null : WINDOW_STACK.get(0); } public static Integer getSessionDontShowAgainValue(final String key) { final Integer ret = AbstractDialog.SESSION_DONTSHOW_AGAIN.get(key); if (ret == null) { return -1; } return ret; } public static void resetDialogInformations() { try { AbstractDialog.SESSION_DONTSHOW_AGAIN.clear(); JSonStorage.getPlainStorage("Dialogs").clear(); } catch (final Exception e) { Log.exception(e); } } /** * @param i */ public static void setButtonHeight(final int height) { AbstractDialog.BUTTON_HEIGHT = height; } public static void setDefaultLocator(final DialogLocator dEFAULT_LOCATOR) { AbstractDialog.DEFAULT_LOCATOR = dEFAULT_LOCATOR; } /** * @param frame */ public static void setRootFrame(final Window frame) { new EDTRunner() { @Override protected void runInEDT() { if (WINDOW_STACK.size() > 0) { if (WINDOW_STACK.get(0) == frame) { return; } } WINDOW_STACK.reset(frame); } }.waitForEDT(); } protected AbstractAction[] actions = null; protected JButton cancelButton; private final String cancelOption; private boolean countdownPausable = true; /** * Current timer value */ protected long counter; private FocusListener defaultButtonFocusListener; private DefaultButtonPanel defaultButtons; protected InternDialog<T> dialog; private DialogDimensor dimensor; protected boolean disposed = false; protected boolean doNotShowAgainSelected = false; protected JCheckBox dontshowagain; private boolean dummyInit = false; protected int flagMask; private ImageIcon icon; private JLabel iconLabel; private boolean initialized = false; private DialogLocator locator; protected JButton okButton; private final String okOption; private Point orgLocationOnScreen; protected JComponent panel; protected Dimension preferredSize; protected int returnBitMask = 0; private int timeout = 0; /** * Timer Thread to count down the {@link #counter} */ protected Thread timer; /** * Label to display the timervalue */ protected JLabel timerLbl; private String title; public AbstractDialog(final int flag, final String title, final ImageIcon icon, final String okOption, final String cancelOption) { super(); this.title = title; this.flagMask = flag; this.icon = BinaryLogic.containsAll(flag, Dialog.STYLE_HIDE_ICON) ? null : icon; this.okOption = okOption == null ? _AWU.T.ABSTRACTDIALOG_BUTTON_OK() : okOption; this.cancelOption = cancelOption == null ? _AWU.T.ABSTRACTDIALOG_BUTTON_CANCEL() : cancelOption; } /** * this function will init and show the dialog */ protected void _init() { layoutDialog(); if (BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_COUNTDOWN)) { timerLbl.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { AbstractDialog.this.cancel(); AbstractDialog.this.timerLbl.removeMouseListener(this); } }); timerLbl.setToolTipText(_AWU.T.TIMERDIALOG_TOOLTIP_TIMERLABEL()); timerLbl.setIcon(AWUTheme.I().getIcon("dialog/cancel", 16)); } try { this.setTitle(this.title); if (this.evaluateDontShowAgainFlag()) { return; } final Container parent = getDialog().getParent(); if (parent == null || !parent.isShowing()) { // final Window main = getRootFrame(); // if (main != null) { // main.addWindowFocusListener(new WindowFocusListener() { // @Override // public void windowGainedFocus(final WindowEvent e) { // SwingUtils.toFront(getDialog()); // main.removeWindowFocusListener(this); // @Override // public void windowLostFocus(final WindowEvent e) { // // getDialog().setAlwaysOnTop(true); } // Layout manager // Dispose dialog on close getDialog().setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); getDialog().addWindowListener(this); this.defaultButtonFocusListener = new FocusListener() { @Override public void focusGained(final FocusEvent e) { System.out.println(" final JRootPane root = SwingUtilities.getRootPane(e.getComponent()); if (root != null && e.getComponent() instanceof JButton) { root.setDefaultButton((JButton) e.getComponent()); } } @Override public void focusLost(final FocusEvent e) { System.out.println(" final JRootPane root = SwingUtilities.getRootPane(e.getComponent()); if (root != null) { root.setDefaultButton(null); } } }; // create panel for the dialog's buttons this.okButton = new JButton(this.okOption); this.cancelButton = new JButton(this.cancelOption); this.cancelButton.addFocusListener(this.defaultButtonFocusListener); this.okButton.addFocusListener(this.defaultButtonFocusListener); this.defaultButtons = this.getDefaultButtonPanel(); /* * We set the focus on the ok button. if no ok button is shown, we * set the focus on cancel button */ JButton focus = null; // add listeners here this.okButton.addActionListener(this); this.cancelButton.addActionListener(this); // add icon if available if (this.icon != null) { getDialog().setLayout(new MigLayout("ins 5,wrap 2", "[][grow,fill]", "[grow,fill][]")); getDialog().add(this.getIconComponent(), this.getIconConstraints()); } else { getDialog().setLayout(new MigLayout("ins 5,wrap 1", "[grow,fill]", "[grow,fill][]")); } // Layout the dialog content and add it to the contentpane this.panel = this.layoutDialogContent(); getDialog().add(this.panel, ""); // add the countdown timer final MigPanel bottom = this.createBottomPanel(); bottom.setOpaque(false); bottom.add(timerLbl); if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) { this.dontshowagain = new JCheckBox(this.getDontShowAgainLabelText()); this.dontshowagain.setHorizontalAlignment(SwingConstants.TRAILING); this.dontshowagain.setHorizontalTextPosition(SwingConstants.LEADING); this.dontshowagain.setSelected(this.doNotShowAgainSelected); bottom.add(this.dontshowagain, "alignx right"); } else { bottom.add(Box.createHorizontalGlue()); } bottom.add(this.defaultButtons); if ((this.flagMask & UIOManager.BUTTONS_HIDE_OK) == 0) { // Set OK as defaultbutton getDialog().getRootPane().setDefaultButton(this.okButton); this.okButton.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(final HierarchyEvent e) { if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { final JButton defaultButton = (JButton) e.getComponent(); final JRootPane root = SwingUtilities.getRootPane(defaultButton); if (root != null) { root.setDefaultButton(defaultButton); } } } }); focus = this.okButton; this.defaultButtons.addOKButton(this.okButton); } if (!BinaryLogic.containsAll(this.flagMask, UIOManager.BUTTONS_HIDE_CANCEL)) { this.defaultButtons.addCancelButton(this.cancelButton); if (BinaryLogic.containsAll(this.flagMask, UIOManager.BUTTONS_HIDE_OK)) { getDialog().getRootPane().setDefaultButton(this.cancelButton); // focus is on cancel if OK is hidden focus = this.cancelButton; } } this.addButtons(this.defaultButtons); if (BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_COUNTDOWN)) { // show timer initTimer(getCountdown()); } else { timerLbl.setText(null); } getDialog().add(bottom, "spanx,growx,pushx"); // pack dialog getDialog().invalidate(); // this.setMinimumSize(this.getPreferredSize()); getDialog().setResizable(this.isResizable()); // minimum size foir a dialog // // Dimension screenDim = // Toolkit.getDefaultToolkit().getScreenSize(); // this.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize()); // if (this.getDesiredSize() != null) { // this.setSize(this.getDesiredSize()); pack(); if (this.dimensor != null) { final Dimension ret = this.dimensor.getDimension(AbstractDialog.this); if (ret != null) { getDialog().setSize(ret); } }// register an escape listener to cancel the dialog this.registerEscape(focus); this.packed(); Point loc = null; try { loc = this.getLocator().getLocationOnScreen(this); } catch (final Exception e) { e.printStackTrace(); } if (loc != null) { getDialog().setLocation(loc); } else { try { getDialog().setLocation(AbstractDialog.LOCATE_CENTER_OF_SCREEN.getLocationOnScreen(this)); } catch (final Exception e) { e.printStackTrace(); } } /* * workaround a javabug that forces the parentframe to stay always * on top */ // Disabled on 14.06.2013: // This peace of code causes the parent to come on top even if we do // not want or need it // In our case, we do not want the captcha dialogs causing the // mainframe to get on top. // i think that this piece of code is a workaround for always on top // bugs we had years ago. // if (getDialog().getParent() != null && !CrossSystem.isMac()) { // ((Window) getDialog().getParent()).setAlwaysOnTop(true); // ((Window) getDialog().getParent()).setAlwaysOnTop(false); getDialog().addComponentListener(new ComponentListener() { @Override public void componentHidden(final ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentMoved(final ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentResized(final ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentShown(final ComponentEvent e) { AbstractDialog.this.orgLocationOnScreen = AbstractDialog.this.getDialog().getLocationOnScreen(); System.out.println(AbstractDialog.this.orgLocationOnScreen); } }); final InternDialog<T> d = getDialog(); WINDOW_STACK.add(d); System.out.println("Window Stack Before " + WINDOW_STACK.size()); for (final Window w : WINDOW_STACK) { if(w==null){ System.out.println("Window null"); }else{ System.out.println(w.getName() + " - " + w); } } try { setVisible(true); } finally { final int i = WINDOW_STACK.lastIndexOf(d); if (i >= 0) { WINDOW_STACK.remove(i); System.out.println("Window Stack After " + WINDOW_STACK.size()); for (final Window w : WINDOW_STACK) { System.out.println(w.getName() + " - " + w); } } } // if the dt has been interrupted,s setVisible will return even for // modal dialogs // however the dialog will stay open. Make sure to close it here if (getDialog().getModalityType() != ModalityType.MODELESS) { this.dispose(); } // dialog gets closed // 17.11.2011 I did not comment this - may be debug code while // finding the problem with dialogs with closed parent...s // this code causes a dialog which gets disposed without setting // return mask to appear again. // System.out.println("Unlocked " + // this.getDialog().isDisplayable()); // if (this.returnBitMask == 0) { // this.setVisible(true); // Log.L.fine("Answer: Parent Closed "); // this.returnBitMask |= Dialog.RETURN_CLOSED; // this.setVisible(false); // this.dispose(); } finally { // System.out.println("SET OLD"); } /* * workaround a javabug that forces the parentframe to stay always on * top */ // Disabled on 14.06.2013: // This peace of code causes the parent to come on top even if we do not // want or need it // In our case, we do not want the captcha dialogs causing the mainframe // to get on top. // i think that this piece of code is a workaround for always on top // bugs we had years ago. // if (getDialog().getParent() != null && !CrossSystem.isMac()) { // ((Window) getDialog().getParent()).setAlwaysOnTop(true); // ((Window) getDialog().getParent()).setAlwaysOnTop(false); } public void actionPerformed(final ActionEvent e) { if (e.getSource() == this.okButton) { Log.L.fine("Answer: Button<OK:" + this.okButton.getText() + ">"); this.setReturnmask(true); } else if (e.getSource() == this.cancelButton) { Log.L.fine("Answer: Button<CANCEL:" + this.cancelButton.getText() + ">"); this.setReturnmask(false); } this.dispose(); } /** * Overwrite this method to add additional buttons */ protected void addButtons(final JPanel buttonBar) { } /** * interrupts the timer countdown */ public void cancel() { if (!isCountdownPausable()) { return; } if (timer != null) { timer.interrupt(); timer = null; timerLbl.setEnabled(false); } } /** * called when user closes the window * * @return <code>true</code>, if and only if the dialog should be closeable **/ public boolean closeAllowed() { return true; } /** * @return */ protected DefaultButtonPanel createBottomButtonPanel() { // TODO Auto-generated method stub if (AbstractDialog.BUTTON_HEIGHT <= 0) { return new DefaultButtonPanel("ins 0", "[]", "0[grow,fill]0"); } else { return new DefaultButtonPanel("ins 0", "[]", "0[grow,fill," + AbstractDialog.BUTTON_HEIGHT + "!]0"); } } /** * @return */ protected MigPanel createBottomPanel() { // TODO Auto-generated method stub return new MigPanel("ins 0", "[]20[grow,fill][]", "[]"); } protected abstract T createReturnValue(); /** * This method has to be called to display the dialog. make sure that all * settings have beens et before, becvause this call very likly display a * dialog that blocks the rest of the gui until it is closed */ public void displayDialog() { if (this.initialized) { return; } this.initialized = true; this._init(); } public void dispose() { if (this.dummyInit && dialog == null) { return; } if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); } new EDTRunner() { @Override protected void runInEDT() { if (isDisposed()) { return; } setDisposed(true); if (AbstractDialog.this.getDialog().isVisible()) { try { AbstractDialog.this.getLocator().onClose(AbstractDialog.this); } catch (final Exception e) { e.printStackTrace(); } try { if (AbstractDialog.this.dimensor != null) { AbstractDialog.this.dimensor.onClose(AbstractDialog.this); } } catch (final Exception e) { e.printStackTrace(); } } setDisposed(true); getDialog().realDispose(); if (AbstractDialog.this.timer != null) { AbstractDialog.this.timer.interrupt(); AbstractDialog.this.timer = null; } } }; } /** * @return */ public boolean evaluateDontShowAgainFlag() { if (this.isDontShowAgainFlagEabled()) { final String key = this.getDontShowAgainKey(); if (key != null) { // bypass if key is null. this enables us to show don't show // again checkboxes, but handle the result extern. try { final int i = BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT) ? AbstractDialog.getSessionDontShowAgainValue(key) : JSonStorage.getPlainStorage("Dialogs").get(key, -1); if (i >= 0) { // filter saved return value int ret = i & (Dialog.RETURN_OK | Dialog.RETURN_CANCEL); // add flags ret |= Dialog.RETURN_DONT_SHOW_AGAIN | Dialog.RETURN_SKIPPED_BY_DONT_SHOW; /* * if LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL or * LOGIC_DONT_SHOW_AGAIN_IGNORES_OK are used, we check * here if we should handle the dont show again feature */ if (BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL) && BinaryLogic.containsAll(ret, Dialog.RETURN_CANCEL)) { return false; } if (BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_DONT_SHOW_AGAIN_IGNORES_OK) && BinaryLogic.containsAll(ret, Dialog.RETURN_OK)) { return false; } if (isDeveloperMode() && isDisposed() && returnBitMask != ret) { throw new IllegalStateException("Dialog already disposed"); } this.returnBitMask = ret; return true; } } catch (final Exception e) { Log.exception(e); } } } return false; } /** * Fakes an init of the dialog. we need this if we want to work with the * model only. */ public void forceDummyInit() { this.initialized = true; this.dummyInit = true; } /** * @return */ protected Color getBackground() { // TODO Auto-generated method stub return getDialog().getBackground(); } @Override public CloseReason getCloseReason() { if (this.getReturnmask() == 0) { throw new IllegalStateException("Dialog has not been closed yet"); } if (BinaryLogic.containsSome(this.getReturnmask(), Dialog.RETURN_TIMEOUT)) { return CloseReason.TIMEOUT; } if (BinaryLogic.containsSome(this.getReturnmask(), Dialog.RETURN_CLOSED)) { return CloseReason.CLOSE; } if (BinaryLogic.containsSome(this.getReturnmask(), Dialog.RETURN_CANCEL)) { return CloseReason.CANCEL; } if (BinaryLogic.containsSome(this.getReturnmask(), Dialog.RETURN_OK)) { return CloseReason.OK; } throw new WTFException(); } /** * @return the timeout a dialog actually should display */ public long getCountdown() { return getTimeout() > 0 ? getTimeout() : Dialog.getInstance().getDefaultTimeout(); } /** * @return */ protected DefaultButtonPanel getDefaultButtonPanel() { final DefaultButtonPanel ret = this.createBottomButtonPanel(); if (this.actions != null) { for (final AbstractAction a : this.actions) { ret.addAction(a).addFocusListener(this.defaultButtonFocusListener); } } return ret; } public InternDialog<T> getDialog() { if (dialog == null) { throw new NullPointerException("Call #org.appwork.utils.swing.dialog.AbstractDialog.displayDialog() first"); } return dialog; } public DialogDimensor getDimensor() { return this.dimensor; } /** * Create the key to save the don't showmagain state in database. should be * overwritten in same dialogs. by default, the dialogs get differed by * their title and their classname * * @return */ public String getDontShowAgainKey() { return "ABSTRACTDIALOG_DONT_SHOW_AGAIN_" + this.getClass().getSimpleName() + "_" + this.toString(); } /** * @return */ protected String getDontShowAgainLabelText() { return _AWU.T.ABSTRACTDIALOG_STYLE_SHOW_DO_NOT_DISPLAY_AGAIN(); } public int getFlags() { return this.flagMask; } public ImageIcon getIcon() { return this.icon; } // /** // * should be overwritten and return a Dimension of the dialog should have // a // * special size // * // * @return // */ // protected Dimension getDesiredSize() { // return null; /** * @return */ protected JComponent getIconComponent() { this.iconLabel = new JLabel(this.icon); // iconLabel.setVerticalAlignment(JLabel.TOP); return this.iconLabel; } /** * @return */ protected String getIconConstraints() { // TODO Auto-generated method stub return "gapright 10,gaptop 2"; } public String getIconDataUrl() { if (this.getIcon() == null) { return null; } Base64OutputStream b64os = null; ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); b64os = new Base64OutputStream(bos); ImageIO.write(IconIO.toBufferedImage(this.getIcon().getImage()), "png", b64os); b64os.flush(true); final String ret = "png;base64," + bos.toString("UTF-8"); return ret; } catch (final Exception e) { e.printStackTrace(); return null; } finally { try { b64os.close(); } catch (final Throwable e) { } try { bos.close(); } catch (final Throwable e) { } } } /** * @return */ public List<? extends Image> getIconList() { // TODO Auto-generated method stub return null; } public DialogLocator getLocator() { if (this.locator == null) { if (AbstractDialog.DEFAULT_LOCATOR != null) { return AbstractDialog.DEFAULT_LOCATOR; } return AbstractDialog.LOCATE_CENTER_OF_SCREEN; } return this.locator; } /** * @return */ public ModalityType getModalityType() { // TODO Auto-generated method stub return ModalityType.TOOLKIT_MODAL; } /** * @return */ public Window getOwner() { return WINDOW_STACK.size() == 0 ? null : WINDOW_STACK.get(WINDOW_STACK.size() - 1); } /** * override this if you want to set a special height * * @return */ protected int getPreferredHeight() { // TODO Auto-generated method stub return -1; } /** * @return */ public Dimension getPreferredSize() { final Dimension pref = getRawPreferredSize(); int w = getPreferredWidth(); int h = getPreferredHeight(); if (w <= 0) { w = pref.width; } if (h <= 0) { h = pref.height; } try { final Dimension ret = new Dimension(Math.min(Toolkit.getDefaultToolkit().getScreenSize().width, w), Math.min(Toolkit.getDefaultToolkit().getScreenSize().height, h)); return ret; } catch (final Throwable e) { return pref; } } /** * overwride this to set a special width * * @return */ protected int getPreferredWidth() { // TODO Auto-generated method stub return -1; } /** * @return */ public Dimension getRawPreferredSize() { return getDialog().getRawPreferredSize(); } /** * Return the returnbitmask * * @return */ public int getReturnmask() { if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); } return this.returnBitMask; } public T getReturnValue() { if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); } return this.createReturnValue(); } public int getTimeout() { return timeout; } /** * @return */ public String getTitle() { try { return getDialog().getTitle(); } catch (final NullPointerException e) { // not initialized yet return this.title; } } /** * * @return if the dialog has been moved by the user */ public boolean hasBeenMoved() { return this.orgLocationOnScreen != null && !getDialog().getLocationOnScreen().equals(this.orgLocationOnScreen); } /** * @param focus */ protected void initFocus(final JComponent focus) { getDialog().addWindowFocusListener(new WindowFocusListener() { @Override public void windowLostFocus(final WindowEvent windowevent) { // TODO Auto-generated method stub } @Override public void windowGainedFocus(final WindowEvent windowevent) { System.out.println("Focus rquest!"); final Component focusOwner = getDialog().getFocusOwner(); if (focusOwner != null) { // dialog component has already focus... return; } final boolean success = focus.requestFocusInWindow(); } }); } protected void initTimer(final long time) { counter = time / 1000; timer = new Thread() { @Override public void run() { try { // sleep while dialog is invisible while (!AbstractDialog.this.isVisible()) { try { Thread.sleep(200); } catch (final InterruptedException e) { break; } } long count = counter; while (--count >= 0) { if (!AbstractDialog.this.isVisible()) { return; } if (timer == null) { return; } final String left = TimeFormatter.formatSeconds(count, 0); new EDTHelper<Object>() { @Override public Object edtRun() { timerLbl.setText(left); return null; } }.start(); Thread.sleep(1000); if (counter < 0) { return; } if (!AbstractDialog.this.isVisible()) { return; } } if (counter < 0) { return; } if (!isInterrupted()) { AbstractDialog.this.onTimeout(); } } catch (final InterruptedException e) { return; } } }; timer.start(); } /** * Closes the thread. Causes a cancel and setting the interrupted flag */ public void interrupt() { new EDTRunner() { @Override protected void runInEDT() { if (!isInitialized()) { return; } if (isDisposed() && returnBitMask != (Dialog.RETURN_CLOSED | Dialog.RETURN_INTERRUPT) && isDeveloperMode()) { throw new IllegalStateException("Dialog already disposed"); } AbstractDialog.this.dispose(); AbstractDialog.this.returnBitMask = Dialog.RETURN_CLOSED | Dialog.RETURN_INTERRUPT; } }; } /** * @return * */ public boolean isCountdownFlagEnabled() { return BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_COUNTDOWN); } public boolean isCountdownPausable() { return countdownPausable; } /** * @return */ protected boolean isDeveloperMode() { // dev mode in IDE return !Application.isJared(AbstractDialog.class); } public boolean isDisposed() { return disposed; } /** * @return */ public boolean isDontShowAgainFlagEabled() { return BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN); } public boolean isDontShowAgainSelected() { if (this.isHiddenByDontShowAgain() || this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()) { return true; } return false; } public boolean isHiddenByDontShowAgain() { if (this.dontshowagain != null && this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()) { return false; } final String key = this.getDontShowAgainKey(); if (key == null) { return false; } final int i = BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT) ? AbstractDialog.getSessionDontShowAgainValue(this.getDontShowAgainKey()) : JSonStorage.getPlainStorage("Dialogs").get(this.getDontShowAgainKey(), -1); return i >= 0; } /** * @return the initialized */ public boolean isInitialized() { return this.initialized; } /** * override to change default resizable flag * * @return */ protected boolean isResizable() { // by default dialogs should be resizeble - at least for windows. // size calculation is almost impossible for nonresizable dialogs. they // are always a bit bigger than getDimension tells us return true; } /** * @return */ protected boolean isVisible() { // TODO Auto-generated method stub return getDialog().isVisible(); } protected void layoutDialog() { Dialog.getInstance().initLaf(); dialog = new InternDialog<T>(this); if (preferredSize != null) { dialog.setPreferredSize(preferredSize); } timerLbl = new JLabel(TimeFormatter.formatSeconds(getCountdown(), 0)); timerLbl.setEnabled(isCountdownPausable()); } /** * This method has to be overwritten to implement custom content * * @return musst return a JComponent */ abstract public JComponent layoutDialogContent(); public void onSetVisible(final boolean b) { if (!b && getDialog().isVisible()) { try { this.getLocator().onClose(AbstractDialog.this); } catch (final Exception e) { e.printStackTrace(); } if (this.dimensor != null) { try { this.dimensor.onClose(AbstractDialog.this); } catch (final Exception e) { e.printStackTrace(); } } } } /** * Handle timeout */ public void onTimeout() { this.setReturnmask(false); if (isDeveloperMode() && isDisposed()) { throw new IllegalStateException("Dialog is already Disposed"); } this.returnBitMask |= Dialog.RETURN_TIMEOUT; this.dispose(); } public void pack() { getDialog().pack(); if (!getDialog().isMinimumSizeSet()) { getDialog().setMinimumSize(getDialog().getPreferredSize()); } } /** * may be overwritten to set focus to special components etc. */ protected void packed() { } protected void registerEscape(final JComponent focus) { if (focus != null) { final KeyStroke ks = KeyStroke.getKeyStroke("ESCAPE"); focus.getInputMap().put(ks, "ESCAPE"); focus.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "ESCAPE"); focus.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "ESCAPE"); focus.getActionMap().put("ESCAPE", new AbstractAction() { private static final long serialVersionUID = -6666144330707394562L; public void actionPerformed(final ActionEvent e) { if (isDisposed()) { return; } Log.L.fine("Answer: Key<ESCAPE>"); AbstractDialog.this.setReturnmask(false); AbstractDialog.this.returnBitMask |= Dialog.RETURN_ESC; AbstractDialog.this.dispose(); } }); this.initFocus(focus); } } public void requestFocus() { WindowManager.getInstance().setZState(getDialog(), FrameState.TO_FRONT_FOCUSED); } /** * resets the dummyinit to continue working with the dialog instance after * using {@link #forceDummyInit()} */ public void resetDummyInit() { this.initialized = false; this.dummyInit = false; } protected void setAlwaysOnTop(final boolean b) { getDialog().setAlwaysOnTop(b); } public void setCountdownPausable(final boolean b) { countdownPausable = b; new EDTRunner() { @Override protected void runInEDT() { if (timer != null && timer.isAlive()) { timerLbl.setEnabled(b); } } }; } /** * @deprecated use #setTimeout instead * @param countdownTime */ @Deprecated public void setCountdownTime(final int countdownTimeInSeconds) { timeout = countdownTimeInSeconds * 1000; } protected void setDefaultCloseOperation(final int doNothingOnClose) { getDialog().setDefaultCloseOperation(doNothingOnClose); } public void setDimensor(final DialogDimensor dimensor) { this.dimensor = dimensor; } /** * @param b */ protected void setDisposed(final boolean b) { disposed = b; } /** * @param b */ public void setDoNotShowAgainSelected(final boolean b) { if (!BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) { throw new IllegalStateException("You have to set the Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN flag to use this method"); } this.doNotShowAgainSelected = b; } public void setIcon(final ImageIcon icon) { this.icon = icon; if (this.iconLabel != null) { new EDTRunner() { @Override protected void runInEDT() { AbstractDialog.this.iconLabel.setIcon(AbstractDialog.this.icon); } }; } } public void setInterrupted() { if (isDeveloperMode() && isDisposed()) { throw new IllegalStateException("Dialog already disposed"); } this.returnBitMask |= Dialog.RETURN_INTERRUPT; } /** * Add Additional BUttons on the left side of ok and cancel button. You can * add a "tag" property to the action in ordner to help the layouter, * * <pre> * abstractActions[0].putValue(&quot;tag&quot;, &quot;ok&quot;) * </pre> * * @param abstractActions * list */ public void setLeftActions(final AbstractAction... abstractActions) { this.actions = abstractActions; } /** * @param locateCenterOfScreen */ public void setLocator(final DialogLocator locator) { this.locator = locator; } protected void setMinimumSize(final Dimension dimension) { getDialog().setMinimumSize(dimension); } /** * @param dimension */ public void setPreferredSize(final Dimension dimension) { try { getDialog().setPreferredSize(dimension); } catch (final NullPointerException e) { preferredSize = dimension; } } protected void setResizable(final boolean b) { getDialog().setResizable(b); } /** * Sets the returnvalue and saves the don't show again states to the * database * * @param b */ protected void setReturnmask(final boolean b) { int ret = b ? Dialog.RETURN_OK : Dialog.RETURN_CANCEL; if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) { if (this.dontshowagain != null && this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()) { ret |= Dialog.RETURN_DONT_SHOW_AGAIN; try { final String key = this.getDontShowAgainKey(); if (key != null) { if (BinaryLogic.containsAll(this.flagMask, UIOManager.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT)) { AbstractDialog.SESSION_DONTSHOW_AGAIN.put(this.getDontShowAgainKey(), ret); } else { JSonStorage.getPlainStorage("Dialogs").put(this.getDontShowAgainKey(), ret); JSonStorage.getPlainStorage("Dialogs").save(); } } } catch (final Exception e) { Log.exception(e); } } } if (ret == returnBitMask) { return; } if (isDeveloperMode() && isDisposed()) { throw new IllegalStateException("Dialog already disposed"); } this.returnBitMask = ret; } /** * Set countdown time on Milliseconds! * * @param countdownTimeInMs */ public void setTimeout(final int countdownTimeInMs) { timeout = countdownTimeInMs; } /** * @param title2 */ public void setTitle(final String title2) { try { getDialog().setTitle(title2); } catch (final NullPointerException e) { this.title = title2; } } /** * @param b */ public void setVisible(final boolean b) { onSetVisible(b); new EDTRunner() { @Override protected void runInEDT() { WindowManager.getInstance().setVisible(getDialog(), b, getWindowStateOnVisible()); } }; } /** * @return */ protected FrameState getWindowStateOnVisible() { return WINDOW_STATE_ON_VISIBLE; } public UserIODefinition show() { final UserIODefinition ret = UIOManager.I().show(UserIODefinition.class, this); return ret; } /** * @throws DialogClosedException * @throws DialogCanceledException * */ public void throwCloseExceptions() throws DialogClosedException, DialogCanceledException { final int mask = this.getReturnmask(); if (BinaryLogic.containsSome(mask, Dialog.RETURN_CLOSED)) { throw new DialogClosedException(mask); } if (BinaryLogic.containsSome(mask, Dialog.RETURN_CANCEL)) { throw new DialogCanceledException(mask); } } /** * Returns an id of the dialog based on it's title; */ @Override public String toString() { return ("dialog-" + this.getTitle()).replaceAll("\\W", "_"); } public void windowActivated(final WindowEvent arg0) { } public void windowClosed(final WindowEvent arg0) { } public void windowClosing(final WindowEvent arg0) { if (this.closeAllowed()) { Log.L.fine("Answer: Button<[X]>"); if (isDeveloperMode() && isDisposed()) { throw new IllegalStateException("Dialog already disposed"); } this.returnBitMask |= Dialog.RETURN_CLOSED; this.dispose(); } else { Log.L.fine("(Answer: Tried [X] bot not allowed)"); } } public void windowDeactivated(final WindowEvent arg0) { } public void windowDeiconified(final WindowEvent arg0) { } public void windowIconified(final WindowEvent arg0) { } public void windowOpened(final WindowEvent arg0) { } }
package it.polito.tellmefirst.apimanager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class NYTimesSearcher { static Log LOG = LogFactory.getLog(NYTimesSearcher.class); final static String NYT_API = "http://api.nytimes.com/svc/semantic/v2/concept/search"; final static String API_KEY = "8eb6657c2a9c0793224fb4e27652cc51:1:63640734"; public String getSearchApiQuery(String uri, String dbpediaLabel){ LOG.debug("[getSearchApiQuery] - BEGIN"); String result = ""; String uriId = uri.split("http://data.nytimes.com/")[1]; String query = "query="+dbpediaLabel+"&concept_uri="+uriId; result = NYT_API+".json?fields=article_list&"+query+"&api-key="+API_KEY; LOG.debug("[getSearchApiQuery] - END"); return result; } // just for testing public static void main(String[] args){ NYTimesSearcher nyTimesSearcher = new NYTimesSearcher(); String s = nyTimesSearcher.getSearchApiQuery("http://data.nytimes.com/86043020378633512412", "Facebook"); System.out.println("Search Query: " + s); } }
package org.callimachusproject.management; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.management.ManagementFactory; import java.net.URL; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.mail.MessagingException; import org.apache.http.HttpHost; import org.apache.http.client.utils.URIUtils; import org.callimachusproject.Version; import org.callimachusproject.auth.AuthorizationService; import org.callimachusproject.client.HTTPObjectClient; import org.callimachusproject.io.FileUtil; import org.callimachusproject.logging.LoggingProperties; import org.callimachusproject.repository.CalliRepository; import org.callimachusproject.server.WebServer; import org.callimachusproject.setup.SetupOrigin; import org.callimachusproject.setup.SetupTool; import org.callimachusproject.util.CallimachusConf; import org.callimachusproject.util.ConfigTemplate; import org.callimachusproject.util.MailProperties; import org.openrdf.OpenRDFException; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.model.vocabulary.RDF; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.config.RepositoryConfig; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.manager.LocalRepositoryManager; import org.openrdf.repository.manager.SystemRepository; import org.openrdf.repository.object.ObjectRepository; import org.openrdf.store.blob.BlobStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CalliServer implements CalliServerMXBean { private static final String CHANGES_PATH = "../changes/"; private static final String ERROR_XPL_PATH = "pipelines/error.xpl"; private static final String SCHEMA_GRAPH = "types/SchemaGraph"; private static final String INDIRECT_PATH = "/diverted;"; private static final String ORIGIN = "http://callimachusproject.org/rdf/2009/framework#Origin"; private static final String REPOSITORY_TYPES = "META-INF/templates/repository-types.properties"; private static final ThreadFactory THREADFACTORY = new ThreadFactory() { public Thread newThread(Runnable r) { String name = CalliServer.class.getSimpleName() + "-" + Integer.toHexString(r.hashCode()); Thread t = new Thread(r, name); t.setDaemon(true); return t; } }; public static interface ServerListener { void repositoryInitialized(String repositoryID, CalliRepository repository); void repositoryShutDown(String repositoryID); void webServiceStarted(WebServer server); void webServiceStopping(WebServer server); } private final Logger logger = LoggerFactory.getLogger(CalliServer.class); private final ExecutorService executor = Executors .newSingleThreadScheduledExecutor(THREADFACTORY); private final CallimachusConf conf; private final ServerListener listener; private final File serverCacheDir; private volatile int starting; private volatile boolean running; private volatile boolean stopping; private int processing; private Exception exception; WebServer server; private final LocalRepositoryManager manager; private final Map<String, CalliRepository> repositories = new LinkedHashMap<String, CalliRepository>(); public CalliServer(CallimachusConf conf, LocalRepositoryManager manager, ServerListener listener) throws OpenRDFException, IOException { this.conf = conf; this.listener = listener; this.manager = manager; String tmpDirStr = System.getProperty("java.io.tmpdir"); if (tmpDirStr == null) { tmpDirStr = "tmp"; } File tmpDir = new File(tmpDirStr); if (!tmpDir.exists()) { tmpDir.mkdirs(); } File cacheDir = File.createTempFile("cache", "", tmpDir); cacheDir.delete(); cacheDir.mkdirs(); FileUtil.deleteOnExit(cacheDir); File in = new File(cacheDir, "client"); HTTPObjectClient.setCacheDirectory(in); serverCacheDir = new File(cacheDir, "server"); } public String toString() { return manager.getBaseDir().toString(); } public boolean isRunning() { return running; } public synchronized void init() throws OpenRDFException, IOException { if (isWebServiceRunning()) { stopWebServiceNow(); } try { if (isThereAnOriginSetup()) { server = createServer(); } else { logger.warn("No Web origin is setup on this server"); } } catch (IOException e) { logger.error(e.toString(), e); } catch (OpenRDFException e) { logger.error(e.toString(), e); } catch (GeneralSecurityException e) { logger.error(e.toString(), e); } finally { if (server == null) { shutDownRepositories(); } } } public synchronized void start() throws IOException, OpenRDFException { running = true; notifyAll(); if (server != null) { try { logger.info("Callimachus is binding to {}", toString()); for (SetupOrigin origin : getOrigins()) { HttpHost host = URIUtils.extractHost(java.net.URI.create(origin.getRoot())); HTTPObjectClient.getInstance().setProxy(host, server); } for (CalliRepository repository : repositories.values()) { repository.setCompileRepository(true); } server.start(); System.gc(); Thread.yield(); long uptime = ManagementFactory.getRuntimeMXBean().getUptime(); logger.info("Callimachus started after {} seconds", uptime / 1000.0); if (listener != null) { listener.webServiceStarted(server); } } catch (IOException e) { logger.error(e.toString(), e); } catch (OpenRDFException e) { logger.error(e.toString(), e); } } } public synchronized void stop() throws IOException, OpenRDFException { running = false; if (isWebServiceRunning()) { stopWebServiceNow(); } notifyAll(); } public synchronized void destroy() throws IOException, OpenRDFException { stop(); shutDownRepositories(); manager.shutDown(); notifyAll(); } @Override public String getServerName() throws IOException { String name = conf.getServerName(); if (name == null || name.length() == 0) return Version.getInstance().getVersion(); return name; } @Override public void setServerName(String name) throws IOException { if (name == null || name.length() == 0 || name.equals(Version.getInstance().getVersion())) { conf.setServerName(null); } else { conf.setServerName(name); } if (server != null) { server.setName(getServerName()); } } public String getPorts() throws IOException { int[] ports = getPortArray(); StringBuilder sb = new StringBuilder(); for (int i=0; i<ports.length; i++) { sb.append(ports[i]); if (i <ports.length - 1) { sb.append(' '); } } return sb.toString(); } public void setPorts(String portStr) throws IOException { int[] ports = new int[0]; if (portStr != null && portStr.trim().length() > 0) { String[] values = portStr.trim().split("\\s+"); ports = new int[values.length]; for (int i = 0; i < values.length; i++) { ports[i] = Integer.parseInt(values[i]); } } conf.setPorts(ports); if (server != null) { server.listen(getPortArray(), getSSLPortArray()); } } public String getSSLPorts() throws IOException { int[] ports = getSSLPortArray(); StringBuilder sb = new StringBuilder(); for (int i=0; i<ports.length; i++) { sb.append(ports[i]); if (i <ports.length - 1) { sb.append(' '); } } return sb.toString(); } public void setSSLPorts(String portStr) throws IOException { int[] ports = new int[0]; if (portStr != null && portStr.trim().length() > 0) { String[] values = portStr.trim().split("\\s+"); ports = new int[values.length]; for (int i = 0; i < values.length; i++) { ports[i] = Integer.parseInt(values[i]); } } conf.setSslPorts(ports); if (server != null) { server.listen(getPortArray(), getSSLPortArray()); } } public boolean isStartingInProgress() { return starting > 0; } public boolean isStoppingInProgress() { return stopping; } public boolean isWebServiceRunning() { return server != null && server.isRunning(); } public synchronized void startWebService() throws Exception { if (isWebServiceRunning()) return; final int start = ++starting; submit(new Callable<Void>() { public Void call() throws Exception { startWebServiceNow(start); return null; } }); } public void restartWebService() throws Exception { final int start = ++starting; submit(new Callable<Void>() { public Void call() throws Exception { stopWebServiceNow(); startWebServiceNow(start); return null; } }); } public void stopWebService() throws Exception { if (stopping || !isWebServiceRunning()) return; submit(new Callable<Void>() { public Void call() throws Exception { stopWebServiceNow(); return null; } }); } @Override public Map<String, String> getMailProperties() throws IOException { return MailProperties.getInstance().getMailProperties(); } @Override public void setMailProperties(Map<String, String> lines) throws IOException, MessagingException { MailProperties.getInstance().setMailProperties(lines); } @Override public Map<String, String> getLoggingProperties() throws IOException { return LoggingProperties.getInstance().getLoggingProperties(); } @Override public void setLoggingProperties(Map<String, String> lines) throws IOException, MessagingException { LoggingProperties.getInstance().setLoggingProperties(lines); } @Override public String[] getRepositoryIDs() throws OpenRDFException { Set<String> set = manager.getRepositoryIDs(); set = new LinkedHashSet<String>(set); set.remove(SystemRepository.ID); return set.toArray(new String[0]); } public Map<String,String> getRepositoryProperties() throws IOException, OpenRDFException { Map<String, String> map = getAllRepositoryProperties(); map = new LinkedHashMap<String, String>(map); Iterator<String> iter = map.keySet().iterator(); while (iter.hasNext()) { if (iter.next().contains("password")) { iter.remove(); } } return map; } public String[] getAvailableRepositoryTypes() throws IOException { List<String> list = new ArrayList<String>(); ClassLoader cl = this.getClass().getClassLoader(); Enumeration<URL> types = cl.getResources(REPOSITORY_TYPES); while (types.hasMoreElements()) { Properties properties = new Properties(); InputStream in = types.nextElement().openStream(); try { properties.load(in); } finally { in.close(); } Enumeration<?> names = properties.propertyNames(); while (names.hasMoreElements()) { list.add((String) names.nextElement()); } } return list.toArray(new String[list.size()]); } public synchronized void setRepositoryProperties(Map<String,String> parameters) throws IOException, OpenRDFException { Map<String, Map<String, String>> params; Map<String, String> combined; combined = getAllRepositoryProperties(); combined = new LinkedHashMap<String, String>(combined); combined.putAll(parameters); params = groupBeforePeriod(combined); Set<String> removed = new LinkedHashSet<String>(params.keySet()); removed.removeAll(groupBeforePeriod(parameters).keySet()); for (String repositoryID : removed) { if (manager.removeRepository(repositoryID)) { logger.warn("Removed repository {}", repositoryID); } } combined = getAllRepositoryProperties(); combined = new LinkedHashMap<String, String>(combined); combined.putAll(parameters); params = groupBeforePeriod(combined); for (String repositoryID : params.keySet()) { Map<String, String> pmap = params.get(repositoryID); String type = pmap.get(null); ClassLoader cl = this.getClass().getClassLoader(); Enumeration<URL> types = cl.getResources(REPOSITORY_TYPES); while (types.hasMoreElements()) { Properties properties = new Properties(); InputStream in = types.nextElement().openStream(); try { properties.load(in); } finally { in.close(); } if (!properties.containsKey(type)) continue; String path = properties.getProperty(type); Enumeration<URL> configs = cl.getResources(path); while (configs.hasMoreElements()) { URL url = configs.nextElement(); ConfigTemplate temp = new ConfigTemplate(url); RepositoryConfig config = temp.render(pmap); if (config == null) throw new RepositoryConfigException("Missing parameters for " + repositoryID); if (manager.hasRepositoryConfig(repositoryID)) { RepositoryConfig oldConfig = manager.getRepositoryConfig(repositoryID); if (temp.getParameters(config).equals(temp.getParameters(oldConfig))) continue; config.validate(); logger.info("Replacing repository configuration {}", repositoryID); manager.addRepositoryConfig(config); } else { config.validate(); logger.info("Creating repository {}", repositoryID); manager.addRepositoryConfig(config); } if (manager.getInitializedRepositoryIDs().contains(repositoryID)) { manager.getRepository(repositoryID).shutDown(); } try { Repository repo = manager.getRepository(repositoryID); RepositoryConnection conn = repo.getConnection(); try { // just check that we can access the repository conn.hasStatement(null, null, null, false); } finally { conn.close(); } } catch (OpenRDFException e) { logger.error(e.toString(), e); throw new RepositoryConfigException(e.toString()); } } } } } public synchronized void checkForErrors() throws Exception { try { if (exception != null) throw exception; } finally { exception = null; } } public synchronized boolean isSetupInProgress() { return processing > 0; } public String[] getWebappOrigins() throws IOException { return conf.getWebappOrigins(); } @Override public void setupWebappOrigin(final String webappOrigin, final String repositoryID) throws Exception { submit(new Callable<Void>() { public Void call() throws Exception { CalliRepository repository = getInitializedRepository(repositoryID); Repository repo = manager.getRepository(repositoryID); File dataDir = manager.getRepositoryDir(repositoryID); if (repository == null) { repository = new CalliRepository(repo, dataDir); } else { BlobStore blobs = repository.getBlobStore(); String changes = repository.getChangeFolder(); repository = new CalliRepository(repo, dataDir); if (changes != null) { repository.setChangeFolder(changes); } if (blobs != null) { repository.setBlobStore(blobs); } } SetupTool tool = new SetupTool(repositoryID, repository, conf); tool.setupWebappOrigin(webappOrigin); refreshRepository(repositoryID); if (isWebServiceRunning()) { server.addOrigin(webappOrigin, getRepository(repositoryID)); server.setIndirectIdentificationPrefix(getIndirectPrefixes()); HttpHost host = URIUtils.extractHost(java.net.URI.create(webappOrigin + "/")); HTTPObjectClient.getInstance().setProxy(host, server); } return null; } }); } @Override public void ignoreWebappOrigin(String webappOrigin) throws Exception { List<String> list = new ArrayList<String>(Arrays.asList(conf.getWebappOrigins())); list.remove(webappOrigin); for (SetupOrigin origin : getOrigins()) { if (webappOrigin.equals(origin.getWebappOrigin())) { list.remove(origin.getRoot().replaceAll("/$", "")); } } conf.setWebappOrigins(list.toArray(new String[list.size()])); } public SetupOrigin[] getOrigins() throws IOException, OpenRDFException { List<SetupOrigin> list = new ArrayList<SetupOrigin>(); Set<String> webapps = new LinkedHashSet<String>(Arrays.asList(getWebappOrigins())); Map<String, String> map = conf.getOriginRepositoryIDs(); for (String repositoryID : new LinkedHashSet<String>(map.values())) { CalliRepository repository = getRepository(repositoryID); SetupTool tool = new SetupTool(repositoryID, repository, conf); SetupOrigin[] origins = tool.getOrigins(); for (SetupOrigin origin : origins) { webapps.remove(origin.getWebappOrigin()); } list.addAll(Arrays.asList(origins)); } for (String webappOrigin : webapps) { // this webapp are not yet setup in the store String id = map.get(webappOrigin); list.add(new SetupOrigin(webappOrigin, id)); } return list.toArray(new SetupOrigin[list.size()]); } public void setupResolvableOrigin(final String origin, final String webappOrigin) throws Exception { submit(new Callable<Void>() { public Void call() throws Exception { SetupTool tool = getSetupTool(webappOrigin); tool.setupResolvableOrigin(origin, webappOrigin); if (isWebServiceRunning()) { server.addOrigin(origin, getRepository(tool.getRepositoryID())); server.setIndirectIdentificationPrefix(getIndirectPrefixes()); HttpHost host = URIUtils.extractHost(java.net.URI.create(origin + "/")); HTTPObjectClient.getInstance().setProxy(host, server); } return null; } }); } public void setupRootRealm(final String realm, final String webappOrigin) throws Exception { submit(new Callable<Void>() { public Void call() throws Exception { getSetupTool(webappOrigin).setupRootRealm(realm, webappOrigin); return null; } }); } public String[] getDigestEmailAddresses(String webappOrigin) throws OpenRDFException, IOException { return getSetupTool(webappOrigin).getDigestEmailAddresses(webappOrigin); } public void inviteAdminUser(final String email, final String username, final String label, final String comment, final String subject, final String body, final String webappOrigin) throws Exception { submit(new Callable<Void>() { public Void call() throws Exception { SetupTool tool = getSetupTool(webappOrigin); tool.inviteAdminUser(email, username, label, comment, subject, body, webappOrigin); String repositoryID = tool.getRepositoryID(); CalliRepository repository = getRepository(repositoryID); ObjectRepository object = repository.getDelegate(); AuthorizationService.getInstance().get(object).resetCache(); return null; } }); } public boolean changeDigestUserPassword(String email, String password, String webappOrigin) throws OpenRDFException, IOException { return getSetupTool(webappOrigin).changeDigestUserPassword(email, password, webappOrigin); } synchronized void saveError(Exception exc) { exception = exc; } synchronized void begin() { processing++; } synchronized void end() { processing notifyAll(); } protected void submit(final Callable<Void> task) throws Exception { checkForErrors(); executor.submit(new Runnable() { public void run() { begin(); try { task.call(); } catch (Exception exc) { saveError(exc); } finally { end(); } } }); Thread.yield(); } SetupTool getSetupTool(String webappOrigin) throws OpenRDFException, IOException { String repositoryID = conf.getOriginRepositoryIDs().get(webappOrigin); if (repositoryID == null) throw new IllegalArgumentException("Unknown Callimachus origin: " + webappOrigin); CalliRepository repository = getRepository(repositoryID); return new SetupTool(repositoryID, repository, conf); } private Map<String, String> getAllRepositoryProperties() throws IOException, OpenRDFException { Map<String, String> map = new LinkedHashMap<String, String>(); ClassLoader cl = this.getClass().getClassLoader(); Enumeration<URL> types = cl.getResources(REPOSITORY_TYPES); while (types.hasMoreElements()) { Properties properties = new Properties(); InputStream in = types.nextElement().openStream(); try { properties.load(in); } finally { in.close(); } Enumeration<?> names = properties.propertyNames(); while (names.hasMoreElements()) { String type = (String) names.nextElement(); String path = properties.getProperty(type); Enumeration<URL> configs = cl.getResources(path); while (configs.hasMoreElements()) { URL url = configs.nextElement(); ConfigTemplate temp = new ConfigTemplate(url); for (String id : manager.getRepositoryIDs()) { if (id.equals(SystemRepository.ID)) continue; RepositoryConfig cfg = manager.getRepositoryConfig(id); Map<String, String> params = temp.getParameters(cfg); if (params == null || id.indexOf('.') >= 0) continue; for (Map.Entry<String, String> e : params.entrySet()) { map.put(id + '.' + e.getKey(), e.getValue()); } map.put(id, type); } } } } return map; } private Map<String, Map<String, String>> groupBeforePeriod( Map<String, String> parameters) { Map<String, Map<String, String>> params = new LinkedHashMap<String, Map<String,String>>(); for (Map.Entry<String, String> e : parameters.entrySet()) { String id, key; int idx = e.getKey().indexOf('.'); if (idx < 0) { id = e.getKey(); key = null; } else { id = e.getKey().substring(0, idx); key = e.getKey().substring(idx + 1); } String value = e.getValue(); Map<String, String> map = params.get(id); if (map == null) { params.put(id, map = new LinkedHashMap<String, String>()); } map.put(key, value); } return params; } synchronized void startWebServiceNow(int start) { if (start != starting) return; try { if (isWebServiceRunning()) { stopWebServiceNow(); } try { if (getPortArray().length == 0 && getSSLPortArray().length == 0) throw new IllegalStateException("No TCP port defined for server"); if (!isThereAnOriginSetup()) throw new IllegalStateException("Repository origin is not setup"); if (server == null) { server = createServer(); } } finally { if (server == null) { shutDownRepositories(); } } server.start(); if (listener != null) { listener.webServiceStarted(server); } } catch (IOException e) { logger.error(e.toString(), e); } catch (OpenRDFException e) { logger.error(e.toString(), e); } catch (GeneralSecurityException e) { logger.error(e.toString(), e); } finally { starting = 0; notifyAll(); } } synchronized boolean stopWebServiceNow() throws OpenRDFException { stopping = true; try { if (server == null) { shutDownRepositories(); return false; } else { if (listener != null) { listener.webServiceStopping(server); } server.stop(); shutDownRepositories(); server.destroy(); for (SetupOrigin origin : getOrigins()) { HttpHost host = URIUtils.extractHost(java.net.URI.create(origin.getRoot())); HTTPObjectClient.getInstance().removeProxy(host, server); } return true; } } catch (IOException e) { logger.error(e.toString(), e); return false; } finally { stopping = false; notifyAll(); server = null; shutDownRepositories(); } } private boolean isThereAnOriginSetup() throws RepositoryException, RepositoryConfigException, IOException { Map<String, String> map = conf.getOriginRepositoryIDs(); for (String repositoryID : new LinkedHashSet<String>(map.values())) { if (!manager.hasRepositoryConfig(repositoryID)) continue; Repository repository = manager.getRepository(repositoryID); RepositoryConnection conn = repository.getConnection(); try { ValueFactory vf = conn.getValueFactory(); URI Origin = vf.createURI(ORIGIN); for (String origin : map.keySet()) { if (!repositoryID.equals(map.get(origin))) continue; URI subj = vf.createURI(origin + "/"); if (conn.hasStatement(subj, RDF.TYPE, Origin, false)) return true; // at least one origin is setup } return getPortArray().length > 0 || getSSLPortArray().length > 0; } finally { conn.close(); } } return false; } private synchronized WebServer createServer() throws OpenRDFException, IOException, NoSuchAlgorithmException { WebServer server = new WebServer(serverCacheDir); for (SetupOrigin so : getOrigins()) { boolean first = repositories.isEmpty(); if (so.isResolvable()) { String origin = so.getRoot().replaceAll("/$", ""); server.addOrigin(origin, getRepository(so.getRepositoryID())); HttpHost host = URIUtils.extractHost(java.net.URI.create(so.getRoot())); HTTPObjectClient.getInstance().setProxy(host, server); if (first) { CalliRepository repo = getRepository(so.getRepositoryID()); String pipe = repo.getCallimachusUrl(so.getWebappOrigin(), ERROR_XPL_PATH); if (pipe == null) throw new IllegalArgumentException( "Callimachus webapp not setup on: " + so.getWebappOrigin()); server.setErrorPipe(pipe); } } } server.setName(getServerName()); server.setIndirectIdentificationPrefix(getIndirectPrefixes()); server.listen(getPortArray(), getSSLPortArray()); return server; } CalliRepository getRepository(String repositoryID) throws IOException, OpenRDFException { Map<String, String> map = conf.getOriginRepositoryIDs(); List<String> origins = new ArrayList<String>(map.size()); for (Map.Entry<String, String> e : map.entrySet()) { if (repositoryID.equals(e.getValue())) { origins.add(e.getKey()); } } CalliRepository repository = repositories.get(repositoryID); if (repository != null && repository.isInitialized()) return repository; if (origins.isEmpty()) return null; Repository repo = manager.getRepository(repositoryID); File dataDir = manager.getRepositoryDir(repositoryID); repository = new CalliRepository(repo, dataDir); String changes = repository.getCallimachusUrl(origins.get(0), CHANGES_PATH); if (changes != null) { repository.setChangeFolder(changes); } for (String origin : origins) { String schema = repository.getCallimachusUrl(origin, SCHEMA_GRAPH); if (schema != null) { repository.addSchemaGraphType(schema); } } repository.setCompileRepository(true); if (listener != null && repositories.containsKey(repositoryID)) { listener.repositoryShutDown(repositoryID); } repositories.put(repositoryID, repository); if (listener != null) { listener.repositoryInitialized(repositoryID, repository); } return repository; } synchronized CalliRepository getInitializedRepository(String repositoryID) { CalliRepository repository = repositories.get(repositoryID); if (repository == null || !repository.isInitialized()) return null; return repository; } synchronized void refreshRepository(String repositoryID) { repositories.remove(repositoryID); } private synchronized void shutDownRepositories() throws OpenRDFException { for (Map.Entry<String, CalliRepository> e : repositories.entrySet()) { e.getValue().shutDown(); if (listener != null) { listener.repositoryShutDown(e.getKey()); } } repositories.clear(); if (!manager.getInitializedRepositoryIDs().isEmpty()) { manager.refresh(); } } private int[] getPortArray() throws IOException { return conf.getPorts(); } private int[] getSSLPortArray() throws IOException { return conf.getSslPorts(); } private String[] getIndirectPrefixes() throws IOException, OpenRDFException { Map<String, String> map = new LinkedHashMap<String, String>(); for (SetupOrigin origin : getOrigins()) { String key = origin.getRepositoryID(); if (origin.isResolvable() && map.containsKey(key)) { map.put(key, null); } else if (origin.isResolvable()) { map.put(key, origin.getWebappOrigin()); } } List<String> identities = new ArrayList<String>(map.size()); for (String origin : map.values()) { if (origin != null) { identities.add(origin + INDIRECT_PATH); } } return identities.toArray(new String[identities.size()]); } }
package net.atos.entng.forum.events; import com.mongodb.DBObject; import com.mongodb.QueryBuilder; import fr.wseduc.mongodb.MongoDb; import fr.wseduc.mongodb.MongoQueryBuilder; import fr.wseduc.webutils.Either; import fr.wseduc.webutils.Either.Right; import fr.wseduc.webutils.I18n; import net.atos.entng.forum.Forum; import org.entcore.common.search.SearchingEvents; import org.entcore.common.service.VisibilityFilter; import org.entcore.common.service.impl.MongoDbSearchService; import org.entcore.common.utils.StringUtils; import org.vertx.java.core.Handler; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; import java.util.*; import java.util.regex.Pattern; import static org.entcore.common.mongodb.MongoDbResult.validResults; import static org.entcore.common.mongodb.MongoDbResult.validResultsHandler; public class ForumSearchingEvents implements SearchingEvents { private static final Logger log = LoggerFactory.getLogger(ForumSearchingEvents.class); private final MongoDb mongo; private static final I18n i18n = I18n.getInstance(); public ForumSearchingEvents() { this.mongo = MongoDb.getInstance(); } @Override public void searchResource(List<String> appFilters, String userId, JsonArray groupIds, final JsonArray searchWords, final Integer page, final Integer limit, final JsonArray columnsHeader, final String locale, final Handler<Either<String, JsonArray>> handler) { if (appFilters.contains(ForumSearchingEvents.class.getSimpleName())) { final List<String> groupIdsLst = groupIds.toList(); final List<DBObject> groups = new ArrayList<DBObject>(); groups.add(QueryBuilder.start("userId").is(userId).get()); for (String gpId: groupIdsLst) { groups.add(QueryBuilder.start("groupId").is(gpId).get()); } final QueryBuilder rightsQuery = new QueryBuilder().or( QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(), QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(), QueryBuilder.start("owner.userId").is(userId).get(), QueryBuilder.start("shared").elemMatch( new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get() ).get()); JsonObject sort = new JsonObject().putNumber("modified", -1); final JsonObject projection = new JsonObject(); projection.putNumber("name", 1); //search all category of user mongo.find(Forum.CATEGORY_COLLECTION, MongoQueryBuilder.build(rightsQuery), sort, projection, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { final Either<String, JsonArray> ei = validResults(event); if (ei.isRight()) { final JsonArray categoryResult = ei.right().getValue(); final Map<String, String> mapIdName = new HashMap<String, String>(); for (int i=0;i<categoryResult.size();i++) { final JsonObject j = categoryResult.get(i); mapIdName.put(j.getString("_id"), j.getString("name")); } //search subject for the catagories found searchSubject(page, limit, searchWords.toList(), mapIdName, new Handler<Either<String, JsonArray>>() { @Override public void handle(Either<String, JsonArray> event) { if (event.isRight()) { if (log.isDebugEnabled()) { log.debug("[ForumSearchingEvents][searchResource] The resources searched by user are finded"); } final JsonArray res = formatSearchResult(event.right().getValue(), columnsHeader, searchWords.toList(), mapIdName, locale); handler.handle(new Right<String, JsonArray>(res)); } else { handler.handle(new Either.Left<String, JsonArray>(event.left().getValue())); } } }); } else { handler.handle(new Either.Left<String, JsonArray>(ei.left().getValue())); } } }); } else { handler.handle(new Right<String, JsonArray>(new JsonArray())); } } private void searchSubject(int page, int limit, List<String> searchWords, final Map<String,String> mapIdName, Handler<Either<String, JsonArray>> handler) { final int skip = (0 == page) ? -1 : page * limit; final QueryBuilder worldsQuery = new QueryBuilder(); worldsQuery.text(MongoDbSearchService.textSearchedComposition(searchWords)); final QueryBuilder categoryQuery = new QueryBuilder().start("category").in(mapIdName.keySet()); final QueryBuilder query = new QueryBuilder().and(worldsQuery.get(), categoryQuery.get()); JsonObject sort = new JsonObject().putNumber("modified", -1); final JsonObject projection = new JsonObject(); projection.putNumber("title", 1); projection.putNumber("messages", 1); projection.putNumber("category", 1); projection.putNumber("modified", 1); projection.putNumber("owner.userId", 1); projection.putNumber("owner.displayName", 1); mongo.find(Forum.SUBJECT_COLLECTION, MongoQueryBuilder.build(query), sort, projection, skip, limit, Integer.MAX_VALUE, validResultsHandler(handler)); } private JsonArray formatSearchResult(final JsonArray results, final JsonArray columnsHeader, final List<String> words, final Map<String,String> mapIdName, final String locale) { final List<String> aHeader = columnsHeader.toList(); final JsonArray traity = new JsonArray(); for (int i=0;i<results.size();i++) { final JsonObject j = results.get(i); final JsonObject jr = new JsonObject(); if (j != null) { final String categoryId = j.getString("category"); final Map<String, Object> map = formatDescription(j.getArray("messages", new JsonArray()), words, j.getObject("modified"), categoryId, j.getString("_id"), j.getString("title"), locale); jr.putString(aHeader.get(0), mapIdName.get(categoryId)); jr.putString(aHeader.get(1), map.get("description").toString()); jr.putObject(aHeader.get(2), (JsonObject) map.get("modified")); jr.putString(aHeader.get(3), j.getObject("owner").getString("displayName")); jr.putString(aHeader.get(4), j.getObject("owner").getString("userId")); jr.putString(aHeader.get(5), "/forum#/view/" + categoryId); traity.add(jr); } } return traity; } private Map<String, Object> formatDescription(JsonArray ja, final List<String> words, JsonObject defaultDate, String categoryId, String subjectId, String subjectTitle, String locale) { final Map<String, Object> map = new HashMap<String, Object>(); Integer countMatchMessages = 0; String titleRes = "<a href=\"/forum#/view/" + categoryId + "/" + subjectId + "\">" + subjectTitle + "</a>"; JsonObject modifiedRes = null; Date modifiedMarker = null; final List<String> unaccentWords = new ArrayList<String>(); for (final String word : words) { unaccentWords.add(StringUtils.stripAccentsToLowerCase(word)); } //get the last modified page that match with searched words for create the description for(int i=0;i<ja.size();i++) { final JsonObject jO = ja.get(i); final String content = jO.getString("content" ,""); final Date currentDate = MongoDb.parseIsoDate(jO.getObject("modified")); int match = unaccentWords.size(); for (final String word : unaccentWords) { if (StringUtils.stripAccentsToLowerCase(content).contains(word)) { match } } if (countMatchMessages == 0 && match == 0) { modifiedRes = jO.getObject("modified"); } else if (countMatchMessages > 0 && modifiedMarker.before(currentDate)) { modifiedMarker = currentDate; modifiedRes = jO.getObject("modified"); } if (match == 0) { modifiedMarker = currentDate; countMatchMessages++; } } if (countMatchMessages == 0) { map.put("modified", defaultDate); map.put("description", i18n.translate("forum.search.description.none", locale, titleRes)); } else if (countMatchMessages == 1) { map.put("modified", modifiedRes); map.put("description", i18n.translate("forum.search.description.one", locale, titleRes)); } else { map.put("modified", modifiedRes); map.put("description", i18n.translate("forum.search.description.several", locale, titleRes, countMatchMessages.toString())); } return map; } }
package org.ensembl.healthcheck.eg_gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.Box; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportLine; import org.ensembl.healthcheck.Reporter; import org.ensembl.healthcheck.eg_gui.Constants; import org.ensembl.healthcheck.eg_gui.JPopupTextArea; import org.ensembl.healthcheck.eg_gui.ReportPanel; import org.ensembl.healthcheck.testcase.EnsTestCase; public class GuiReporterTab extends JPanel implements Reporter { final protected TestClassList testList; final protected JScrollPane testListScrollPane; final protected TestClassListModel listModel; final protected ReportPanel reportPanel; final protected TestCaseColoredCellRenderer testCaseCellRenderer; protected boolean userClickedOnList = false; final protected Map<Class<? extends EnsTestCase>,GuiReportPanelData> reportData; public void selectDefaultListItem() { if (!userClickedOnList) { selectLastListItem(); } } /** * Selects the last item in the list and scrolls to that position. */ public void selectLastListItem() { if (listModel.getSize()>0) { int indexOfLastComponentInList =listModel.getSize()-1; testList.setSelectedIndex(indexOfLastComponentInList); testList.ensureIndexIsVisible(indexOfLastComponentInList); } } public GuiReporterTab() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); reportData = new HashMap<Class<? extends EnsTestCase>,GuiReportPanelData>(); testList = new TestClassList(TestClassList.TestClassListToolTipType.CLASS); listModel = new TestClassListModel(); reportPanel = new ReportPanel(); testList.setModel(listModel); testCaseCellRenderer = new TestCaseColoredCellRenderer(); testList.setCellRenderer(testCaseCellRenderer); testList.addMouseListener(new MouseListener() { // We want to know, when as soon as the user clicks somewhere on // the list so we can stop selecting the last item in the list. @Override public void mouseClicked(MouseEvent arg0) { userClickedOnList = true; } @Override public void mouseEntered (MouseEvent arg0) {} @Override public void mouseExited (MouseEvent arg0) {} @Override public void mousePressed (MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); // Setting the preferred size causes the scrollbars to not be adapted // to the list changing size when items are added later on, so // commented out. // testList.setPreferredSize( // new Dimension( // Constants.INITIAL_APPLICATION_WINDOW_WIDTH / 3, // Constants.INITIAL_APPLICATION_WINDOW_HEIGHT / 3 * 2 setLayout(new BorderLayout()); testListScrollPane = new JScrollPane(testList); add( new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, testListScrollPane, //new JScrollPane(reportPanel) reportPanel ), BorderLayout.CENTER ); testList.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { if (!arg0.getValueIsAdjusting()) { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } } ); } @Override public void message(final ReportLine reportLine) { final Class<? extends EnsTestCase> currentKey = reportLine.getTestCase().getClass(); if (!reportData.containsKey(currentKey)) { reportData.put(currentKey, new GuiReportPanelData(reportLine)); testCaseCellRenderer.setOutcome(currentKey, null); // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. SwingUtilities.invokeLater( new Runnable() { @Override public void run() { listModel.addTest(currentKey); // If nothing has been selected, then select // something so the user is not staring at an // empty report. //if (testList.isSelectionEmpty()) { if (!userClickedOnList) { selectDefaultListItem(); } } } ); } else { reportData.get(currentKey).addReportLine(reportLine); } // If anything was reported as a problem, the outcome is false. if (reportLine.getLevel()==ReportLine.PROBLEM) { testCaseCellRenderer.setOutcome(currentKey, false); } // If a testcase has been selected, then display the new data in the // GUI so the user can see the new line in real time. if (!testList.isSelectionEmpty()) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } ); } } @Override public void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) {} @Override public void finishTestCase( final EnsTestCase testCase, final boolean result, DatabaseRegistryEntry dbre ) { // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. SwingUtilities.invokeLater( new Runnable() { @Override public void run() { testCaseCellRenderer.setOutcome(testCase.getClass(), result); } } ); } } class ReportPanel extends JPanel implements ActionListener { final protected JTextField testName; final protected JPopupTextArea description; final protected JTextField teamResponsible; final protected JTextField speciesName; final protected JPopupTextArea message; final String copy_selected_text_action = "copy_selected_text_action"; protected Component createVerticalSpacing() { return Box.createVerticalStrut(Constants.DEFAULT_VERTICAL_COMPONENT_SPACING); } public ReportPanel() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); Box singleLineInfo = Box.createVerticalBox(); testName = new JPopupTextField("Name"); description = new JPopupTextArea(3, 0); teamResponsible = new JPopupTextField("Team Responsible"); speciesName = new JPopupTextField("Species Name"); message = new JPopupTextArea (); description.setLineWrap(true); description.setWrapStyleWord(true); GuiTestRunnerFrameComponentBuilder g = null; singleLineInfo.add(g.createLeftJustifiedText("Test class:")); singleLineInfo.add(testName); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Description:")); singleLineInfo.add(description); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Team responsible:")); singleLineInfo.add(teamResponsible); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Species name:")); singleLineInfo.add(speciesName); singleLineInfo.add(createVerticalSpacing()); setLayout(new BorderLayout()); final JPopupMenu popup = new JPopupMenu(); message.add(GuiTestRunnerFrameComponentBuilder.makeMenuItem("Copy selected text", this, copy_selected_text_action)); message.setComponentPopupMenu(popup); Font currentFont = message.getFont(); Font newFont = new Font( "Courier", currentFont.getStyle(), currentFont.getSize() ); message.setFont(newFont); message.setLineWrap(true); message.setWrapStyleWord(true); singleLineInfo.add(g.createLeftJustifiedText("Output from test:")); add(singleLineInfo, BorderLayout.NORTH); add(new JScrollPane(message), BorderLayout.CENTER); // This has to be set to something small otherwise we will get problems when // wrapping this in a JSplitPane: // "When the user is resizing the Components the minimum size of the // Components is used to determine the maximum/minimum position the // Components can be set to. If the minimum size of the two // components is greater than the size of the split pane the divider // will not allow you to resize it." this.setMinimumSize(new Dimension(200,300)); this.addComponentListener(this); } public void setData(GuiReportPanelData reportData) { testName .setText (reportData.getTestName()); description .setText (reportData.getDescription()); speciesName .setText (reportData.getSpeciesName()); teamResponsible .setText (reportData.getTeamResponsible()); message .setText (reportData.getMessage()); } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.paramString().equals(copy_selected_text_action)) { String selection = message.getSelectedText(); StringSelection data = new StringSelection(selection); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(data, data); } } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.event.WindowEvent; import org.gridlab.gridsphere.event.impl.WindowEventImpl; import org.gridlab.gridsphere.layout.event.PortletComponentEvent; import org.gridlab.gridsphere.layout.event.PortletTitleBarEvent; import org.gridlab.gridsphere.layout.event.PortletTitleBarListener; import org.gridlab.gridsphere.layout.event.impl.PortletTitleBarEventImpl; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.SportletProperties; import org.gridlab.gridsphere.portletcontainer.*; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.io.File; import java.util.*; /** * A <code>PortletTitleBar</code> represents the visual display of the portlet title bar * within a portlet frame and is contained by {@link PortletFrame}. * The title bar contains portlet mode and window state as well as a title. */ public class PortletTitleBar extends BasePortletComponent implements Serializable, Cloneable { private String title = "unknown title"; private String portletClass = null; private transient PortletWindow.State windowState = PortletWindow.State.NORMAL; private List supportedModes = new Vector(); private transient Portlet.Mode portletMode = Portlet.Mode.VIEW; private transient Portlet.Mode previousMode = null; private transient PortletSettings settings = null; private List allowedWindowStates = new Vector(); private String errorMessage = ""; private boolean hasError = false; private boolean isActive = false; /** * Link is an abstract representation of a hyperlink with an href, image and * alt tags. */ abstract class Link { protected String href = ""; protected String imageSrc = ""; protected String altTag = ""; /** * Returns the image source attribute in the link * * @return the image source attribute in the link */ public String getImageSrc() { return imageSrc; } /** * Sets the href attribute in the link * * @param href the href attribute in the link */ public void setHref(String href) { this.href = href; } /** * Returns the href attribute in the link * * @return the href attribute in the link */ public String getHref() { return href; } /** * Returns the alt tag attribute in the link * * @return the alt tag attribute in the link */ public String getAltTag() { return altTag; } /** * Returns a string containing the image src, href and alt tag attributes * Used primarily for debugging purposes */ public String toString() { StringBuffer sb = new StringBuffer("\n"); sb.append("image src: " + imageSrc + "\n"); sb.append("href: " + href + "\n"); sb.append("alt tag: " + altTag + "\n"); return sb.toString(); } } /** * PortletModeLink is a concrete instance of a Link used for creating * portlet mode hyperlinks */ class PortletModeLink extends Link { public static final String configImage = "images/window_configure.gif"; public static final String editImage = "images/window_edit.gif"; public static final String helpImage = "images/window_help.gif"; public static final String viewImage = "images/window_view.gif"; /** * Constructs an instance of PortletModeLink with the supplied portlet mode * * @param mode the portlet mode */ public PortletModeLink(Portlet.Mode mode, Locale locale) throws IllegalArgumentException { if (mode == null) return; altTag = mode.getText(locale); // Set the image src if (mode.equals(Portlet.Mode.CONFIGURE)) { imageSrc = configImage; } else if (mode.equals(Portlet.Mode.EDIT)) { imageSrc = editImage; } else if (mode.equals(Portlet.Mode.HELP)) { imageSrc = helpImage; } else if (mode.equals(Portlet.Mode.VIEW)) { imageSrc = viewImage; } else { throw new IllegalArgumentException("No matching Portlet.Mode found for received portlet mode: " + mode); } } } /** * PortletStateLink is a concrete instance of a Link used for creating * portlet window state hyperlinks */ class PortletStateLink extends Link { public static final String minimizeImage = "images/window_minimize.gif"; public static final String maximizeImage = "images/window_maximize.gif"; public static final String resizeImage = "images/window_resize.gif"; /** * Constructs an instance of PortletStateLink with the supplied window state * * @param state the window state */ public PortletStateLink(PortletWindow.State state, Locale locale) throws IllegalArgumentException { if (state == null) return; altTag = state.getText(locale); // Set the image src if (state.equals(PortletWindow.State.MINIMIZED)) { imageSrc = minimizeImage; } else if (state.equals(PortletWindow.State.MAXIMIZED)) { imageSrc = maximizeImage; } else if (state.equals(PortletWindow.State.RESIZING)) { imageSrc = resizeImage; } else { throw new IllegalArgumentException("No matching PortletWindow.State found for received window mode: " + state); } } } /** * Constructs an instance of PortletTitleBar */ public PortletTitleBar() { } /** * Sets the portlet class used to render the title bar * * @param portletClass the concrete portlet class */ public void setPortletClass(String portletClass) { this.portletClass = portletClass; } /** * Returns the portlet class used in rendering the title bar * * @return the concrete portlet class */ public String getPortletClass() { return portletClass; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } /** * Returns the title of the portlet title bar * * @return the portlet title bar */ public String getTitle() { return title; } /** * Sets the title of the portlet title bar * * @param title the portlet title bar */ public void setTitle(String title) { this.title = title; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string * @see PortletWindow.State */ public void setWindowState(PortletWindow.State state) { if (state != null) this.windowState = state; } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string * @see PortletWindow.State */ public PortletWindow.State getWindowState() { return windowState; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string * @see PortletWindow.State */ public void setWindowStateAsString(String state) { if (state != null) { try { this.windowState = PortletWindow.State.toState(state); } catch (IllegalArgumentException e) { // do nothing } } } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string * @see PortletWindow.State */ public String getWindowStateAsString() { return windowState.toString(); } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string * @see Portlet.Mode */ public void setPortletMode(Portlet.Mode mode) { if (mode != null) this.portletMode = mode; } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string * @see Portlet.Mode */ public Portlet.Mode getPortletMode() { return portletMode; } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string * @see Portlet.Mode */ public void setPortletModeAsString(String mode) { if (mode == null) return; try { this.portletMode = Portlet.Mode.toMode(mode); } catch (IllegalArgumentException e) { // do nothing } } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string * @see Portlet.Mode */ public String getPortletModeAsString() { return portletMode.toString(); } /** * Adds a title bar listener to be notified of title bar events * * @param listener a title bar listener * @see PortletTitleBarEvent */ public void addTitleBarListener(PortletTitleBarListener listener) { listeners.add(listener); } /** * Indicates an error ocurred suring the processing of this title bar * * @return <code>true</code> if an error occured during rendering, * <code>false</code> otherwise */ public boolean hasRenderError() { return hasError; } /** * Returns any errors associated with the functioning of this title bar * * @return any title bar errors that occured */ public String getErrorMessage() { return errorMessage; } /** * Initializes the portlet title bar. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List init(PortletRequest req, List list) { list = super.init(req, list); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setPortletClass(portletClass); compId.setComponentID(list.size()); compId.setComponentLabel(label); compId.setClassName(this.getClass().getName()); list.add(compId); doConfig(); return list; } /** * Sets configuration information about the supported portlet modes, * allowed window states and title bar and web app name obtained from {@link PortletSettings}. * Information is queried from the {@link PortletRegistry} */ protected void doConfig() { PortletRegistry registryManager = PortletRegistry.getInstance(); String appID = registryManager.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = registryManager.getApplicationPortlet(appID); if (appPortlet != null) { ApplicationPortletConfig appConfig = appPortlet.getApplicationPortletConfig(); if (appConfig != null) { // get supported modes from application portlet config supportedModes = sort(appConfig.getSupportedModes()); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(portletClass); if (concPortlet != null) { settings = concPortlet.getPortletSettings(); } // get window states from application portlet config allowedWindowStates = sort(appConfig.getAllowedWindowStates()); } } } /** * Simple sorting algoritm that sorts in increasing order a <code>List</code> * containing objects that implement <code>Comparator</code> * @param list a <code>List</code> to be sorted * @return the sorted list */ private List sort(List list) { int n = list.size(); for (int i=0; i < n-1; i++) { for (int j=0; j < n-1-i; j++) { Comparator c = (Comparator)list.get(j); Comparator d = (Comparator)list.get(j+1); if (c.compare(c, d) == 1) { Object tmp = list.get(j); list.set(j, d); list.set(j+1, tmp); } } } return list; } /** * Creates the portlet window state hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of window state hyperlinks */ protected List createWindowLinks(GridSphereEvent event) { PortletURI portletURI; PortletResponse res = event.getPortletResponse(); PortletWindow.State tmp; if (allowedWindowStates.isEmpty()) return null; //String[] windowStates = new String[allowedWindowStates.size()]; List windowStates = new ArrayList(); for (int i = 0; i < allowedWindowStates.size(); i++) { tmp = (PortletWindow.State)allowedWindowStates.get(i); windowStates.add(tmp); // remove current state from list if (tmp.equals(windowState)) { windowStates.remove(i); } } // get rid of resized if window state is normal if (windowState.equals(PortletWindow.State.NORMAL)) { windowStates.remove(PortletWindow.State.RESIZING); } // Localize the window state names PortletRequest req = event.getPortletRequest(); String locStr = (String)req.getPortletSession(true).getAttribute(User.LOCALE); Locale locale = new Locale(locStr, "", ""); // create a URI for each of the window states PortletStateLink stateLink; List stateLinks = new Vector(); for (int i = 0; i < windowStates.size(); i++) { tmp = (PortletWindow.State)windowStates.get(i); portletURI = res.createURI(); portletURI.addParameter(SportletProperties.COMPONENT_ID, this.componentIDStr); //portletURI.addParameter(SportletProperties.PORTLETID, portletClass); try { stateLink = new PortletStateLink(tmp, locale); portletURI.addParameter(SportletProperties.PORTLET_WINDOW, tmp.toString()); stateLink.setHref(portletURI.toString()); stateLinks.add(stateLink); } catch (IllegalArgumentException e) { // do nothing } } return stateLinks; } /** * Creates the portlet mode hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of portlet mode hyperlinks */ public List createModeLinks(GridSphereEvent event) { int i; PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); // make modes from supported modes if (supportedModes.isEmpty()) return null; // Unless user is a super they should not see configure mode boolean hasConfigurePermission = false; PortletRole role = req.getRole(); if (role.isAdmin() || role.isSuper()) { hasConfigurePermission = true; } List smodes = new ArrayList(); Portlet.Mode mode; for (i = 0; i < supportedModes.size(); i++) { mode = (Portlet.Mode)supportedModes.get(i); if (mode.equals(Portlet.Mode.CONFIGURE)) { if (hasConfigurePermission) { smodes.add(mode); } } else { smodes.add(mode); } // remove current mode from list smodes.remove(portletMode); } // Localize the portlet mode names String locStr = (String)req.getPortletSession(true).getAttribute(User.LOCALE); Locale locale = null; if (locStr != null) { locale = new Locale(locStr, "", ""); } else { locale = req.getLocale(); } List portletLinks = new ArrayList(); for (i = 0; i < smodes.size(); i++) { // create a URI for each of the portlet modes PortletURI portletURI; PortletModeLink modeLink; mode = (Portlet.Mode)smodes.get(i); portletURI = res.createURI(); portletURI.addParameter(SportletProperties.COMPONENT_ID, this.componentIDStr); //portletURI.addParameter(SportletProperties.PORTLETID, portletClass); try { modeLink = new PortletModeLink(mode, locale); portletURI.addParameter(SportletProperties.PORTLET_MODE, mode.toString()); modeLink.setHref(portletURI.toString()); portletLinks.add(modeLink); } catch (IllegalArgumentException e) { //log.debug("Unable to get mode for : " + mode.toString()); } } return portletLinks; } /** * Performs an action on this portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void actionPerformed(GridSphereEvent event) throws PortletLayoutException, IOException { super.actionPerformed(event); isActive = true; PortletRequest req = event.getPortletRequest(); req.setAttribute(SportletProperties.PORTLETID, portletClass); PortletComponentEvent lastEvent = event.getLastRenderEvent(); PortletTitleBarEvent titleBarEvent = new PortletTitleBarEventImpl(this, event, COMPONENT_ID); User user = req.getUser(); if (!(user instanceof GuestUser)) { if (titleBarEvent.hasAction()) { if (titleBarEvent.getAction().getID() == PortletTitleBarEvent.TitleBarAction.WINDOW_MODIFY.getID()) { PortletResponse res = event.getPortletResponse(); windowState = titleBarEvent.getState(); WindowEvent winEvent = null; if (windowState == PortletWindow.State.MAXIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MAXIMIZED); } else if (windowState == PortletWindow.State.MINIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MINIMIZED); } else if (windowState == PortletWindow.State.RESIZING) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_RESTORED); } if (winEvent != null) { try { PortletInvoker.windowEvent(portletClass, winEvent, req, res); } catch (PortletException e) { hasError = true; errorMessage += "Failed to invoke window event method of portlet: " + portletClass; } } } else if (titleBarEvent.getAction().getID() == PortletTitleBarEvent.TitleBarAction.MODE_MODIFY.getID()) { previousMode = portletMode; portletMode = titleBarEvent.getMode(); } } } req.setAttribute(SportletProperties.PORTLET_WINDOW, windowState); req.setMode(portletMode); req.setAttribute(SportletProperties.PREVIOUS_MODE, previousMode); Iterator it = listeners.iterator(); PortletComponent comp; while (it.hasNext()) { comp = (PortletComponent) it.next(); event.addNewRenderEvent(titleBarEvent); comp.actionPerformed(event); } //if (evt != null) fireTitleBarEvent(evt); } /** * Fires a title bar event notification * * @param event a portlet title bar event * @throws PortletLayoutException if a layout error occurs */ protected void fireTitleBarEvent(PortletTitleBarEvent event) throws PortletLayoutException { Iterator it = listeners.iterator(); PortletTitleBarListener l; while (it.hasNext()) { l = (PortletTitleBarListener) it.next(); l.handleTitleBarEvent(event); } } /** * Renders the portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void doRender(GridSphereEvent event) throws PortletLayoutException, IOException { hasError = false; // title bar: configure, edit, help, title, min, max PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); // get the appropriate title for this client Client client = req.getClient(); Locale locale = null; String locStr = (String)req.getPortletSession(true).getAttribute(User.LOCALE); if (locStr != null) { locale = new Locale(locStr, "", ""); } if (settings != null) { title = settings.getTitle(locale, client); } List modeLinks = null, windowLinks = null; User user = req.getUser(); if (!(user instanceof GuestUser)) { if (portletClass != null) { modeLinks = createModeLinks(event); windowLinks = createWindowLinks(event); } } req.setMode(portletMode); req.setAttribute(SportletProperties.PREVIOUS_MODE, previousMode); req.setAttribute(SportletProperties.PORTLET_WINDOW, windowState); PrintWriter out = res.getWriter(); if (isActive) { out.println("<tr><td class=\"window-title-active\">"); } else { out.println("<tr><td class=\"window-title-inactive\">"); } isActive = false; out.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>"); // Output portlet mode icons if (modeLinks != null) { Iterator modesIt = modeLinks.iterator(); out.println("<td class=\"window-icon-left\">"); PortletModeLink mode; while (modesIt.hasNext()) { mode = (PortletModeLink) modesIt.next(); out.println("<a href=\"" + mode.getHref() + "\"><img border=\"0\" src=\"themes" + File.separator + theme + File.separator + mode.getImageSrc() + "\" title=\"" + mode.getAltTag() + "\"/></a>"); } out.println("</td>"); } // Invoke doTitle of portlet whose action was perfomed //String actionStr = req.getParameter(SportletProperties.DEFAULT_PORTLET_ACTION); out.println("<td class=\"window-title-name\">"); //if (actionStr != null) { try { //System.err.println("invoking doTitle:" + title); PortletInvoker.doTitle(portletClass, req, res); //out.println(" (" + portletMode.toString() + ") "); } catch (PortletException e) { String pname = portletClass.substring(0, portletClass.length() - 1); pname = pname.substring(0, pname.lastIndexOf(".")); pname = pname.substring(pname.lastIndexOf(".")+1); ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale); String value = bundle.getString("PORTLET_UNAVAILABLE"); title = value + " : " + pname; out.println(title); errorMessage = portletClass + " is currently unavailable!\n"; hasError = true; } //} else { // out.println(title); out.println("</td>"); // Output window state icons if (windowLinks != null) { Iterator windowsIt = windowLinks.iterator(); PortletStateLink state; out.println("<td class=\"window-icon-right\">"); while (windowsIt.hasNext()) { state = (PortletStateLink) windowsIt.next(); out.println("<a href=\"" + state.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + File.separator + state.getImageSrc() + "\" title=\"" + state.getAltTag() + "\"/></a>"); } out.println("</td>"); } out.println("</tr></table>"); out.println("</td></tr>"); } public Object clone() throws CloneNotSupportedException { PortletTitleBar t = (PortletTitleBar)super.clone(); t.title = this.title; t.portletClass = this.portletClass; t.portletMode = Portlet.Mode.toMode(this.portletMode.toString()); t.windowState = PortletWindow.State.toState(this.windowState.toString()); t.previousMode = this.previousMode; t.errorMessage = this.errorMessage; t.hasError = this.hasError; // don't clone settings for now //t.settings = this.settings; t.supportedModes = new ArrayList(this.supportedModes.size()); for (int i = 0; i < this.supportedModes.size(); i++) { Portlet.Mode mode = (Portlet.Mode)supportedModes.get(i); t.supportedModes.add(mode.clone()); } t.allowedWindowStates = new ArrayList(this.allowedWindowStates.size()); for (int i = 0; i < this.allowedWindowStates.size(); i++) { PortletWindow.State state = (PortletWindow.State)allowedWindowStates.get(i); t.allowedWindowStates.add(state.clone()); } return t; } }
package net.floodlightcontroller.connmonitor; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Vector; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.io.InputStream; import java.io.InputStreamReader; import org.openflow.protocol.OFFlowMod; import org.openflow.protocol.OFFlowRemoved; import org.openflow.protocol.OFMatch; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPacketOut; import org.openflow.protocol.OFPort; import org.openflow.protocol.OFSetConfig; import org.openflow.protocol.OFStatisticsRequest; import org.openflow.protocol.OFType; import org.openflow.protocol.Wildcards; import org.openflow.protocol.action.OFAction; import org.openflow.protocol.action.OFActionDataLayerDestination; import org.openflow.protocol.action.OFActionDataLayerSource; import org.openflow.protocol.action.OFActionNetworkLayerDestination; import org.openflow.protocol.action.OFActionNetworkLayerSource; import org.openflow.protocol.action.OFActionOutput; import org.openflow.protocol.action.OFActionTransportLayerDestination; import org.openflow.protocol.action.OFActionTransportLayerSource; import org.openflow.protocol.statistics.OFFlowStatisticsReply; import org.openflow.protocol.statistics.OFFlowStatisticsRequest; import org.openflow.protocol.statistics.OFStatistics; import org.openflow.protocol.statistics.OFStatisticsType; import org.openflow.util.HexString; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IListener.Command; import net.floodlightcontroller.core.IOFSwitch.PortChangeType; import net.floodlightcontroller.core.IOFSwitchListener; import net.floodlightcontroller.core.ImmutablePort; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPacket; import net.floodlightcontroller.packet.IPv4; import net.floodlightcontroller.packet.TCP; import net.floodlightcontroller.packet.UDP; import net.floodlightcontroller.restserver.IRestApiService; import net.floodlightcontroller.routing.ForwardingBase; import net.floodlightcontroller.routing.IRoutingDecision; import net.floodlightcontroller.routing.IRoutingDecision.RoutingAction; public class ConnMonitor extends ForwardingBase implements IFloodlightModule,IOFMessageListener, IOFSwitchListener, IConnMonitorService { //FIXME: move these to configure file static short HARD_TIMEOUT = 0; static short IDLE_TIMEOUT = 300; static short HIH_HARD_TIMEOUT = 300; static short HIH_IDLE_TIMEOUT = 60; static short DELTA = 50; static long CONN_TIMEOUT = 300000; //static short HIGH_PRIORITY = 100; static short DEFAULT_PRIORITY = 30; static short CONTROLLER_PRIORITY = 20; static short NORMAL_PRIORITY = 10; static short DROP_PRIORITY = 1; //static short HIGH_DROP_PRIORITY = 100; //static short HIGH_DROP_TIMEOUT = 300; //static long NW_SW = 130650748906319L; static long EC2_SW = 266281717810249L; static int CONN_MAX_SIZE = 100000; static String hih_manager_url = "http://localhost:55551/inform"; static String honeypotConfigFileName = "honeypots.config"; static String PortsConfigFileName = "ports.config"; static byte[] switchPrivateIP = {(byte)10,(byte)0,(byte)1,(byte)60}; static byte[] switchPrivateMac = {(byte)0x02,(byte)0x1b,(byte)0xb2,(byte)0x19,(byte)0xf2,(byte)0xa7}; static byte[] switchPublicIP = {(byte)10,(byte)0,(byte)0,(byte)103}; static byte[] switchPublicMac = {(byte)0x02,(byte)0xe6,(byte)0xc7,(byte)0x4b,(byte)0xa8,(byte)0xae}; static byte[] ec2PublicNetGWMac = {(byte)0x02,(byte)0xc6,(byte)0xee,(byte)0x16,(byte)0xa2e,(byte)0x4c}; static byte[] ec2PrivateNetGWMac = {(byte)0x02,(byte)0xa7,(byte)0x5a,(byte)0xf4,(byte)0x8c,(byte)0xe5}; static byte[] honeypotNet = {(byte)10,(byte)0,(byte)1, (byte)0}; static int honeypotNetMask = 8; /*Change this*/ static byte[] sriNet = {(byte)129, (byte)105, (byte)44, (byte)102}; static int sriNetMask = 0; /*For test */ static byte[] nwIP = {(byte)129,(byte)105,(byte)44, (byte)102}; Random randomGen; boolean testFlag; /* * These five tables' sizes are fixed. * no worry about memory leak... */ protected Hashtable<String,HoneyPot> honeypots; private Hashtable<String,Long> switches; protected Hashtable<Short, Vector<HoneyPot>> ports; protected Hashtable<Short, Vector<HoneyPot>> portsForHIH; protected Hashtable<String,Boolean> HIHAvailabilityMap; protected Hashtable<Long, String > HIHNameMap; protected Hashtable<String, Integer> HIHFlowCount; /* * These tables's sizes will get increased * Make sure they will NOT increase infinitely... */ protected Hashtable<Long,Connection> connMap; protected Hashtable<String, Connection> connToPot; protected Hashtable<String, HashSet<Integer> > HIHClientMap; protected IFloodlightProviderService floodlightProvider; protected IRestApiService restApi; private ExecutorService executor; protected MyLogger logger; static Date currentTime = new Date(); private long lastClearConnMapTime; private long lastClearConnToPotTime; private long lastTime; private long packetCounter; private long droppedCounter; private long droppedHIHCounter; @Override public String getName() { return ConnMonitor.class.getSimpleName(); } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { return false; } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { return false; } /* * DownloadIP: 130.107.1XXXXXXX.1XXXXXX1 * OpenIP: 130.107.1XXXXXXX.1XXXXXX0 => 13 valid bits * srcIP/13 => one OpenIP */ static public int getOpenAddress(int srcIP){ /* get first 13 bits 0x00 00 1F FF */ int net = (srcIP>>19)&(0x00001FFF); int first7 = (net>>6)&(0x0000007F); int last6 = (net)&(0x0000003F); int c = first7 | 128; //1 first7 int d = (last6<<1) | 128; //1 last6 0 int dstIP = ((130<<24) | (107<<16) | (c<<8) | d); return dstIP; } private byte extractStateFromEthernet(Ethernet eth){ IPacket pkt = eth.getPayload(); if(pkt instanceof IPv4){ IPv4 ip_pkt = (IPv4)pkt; byte dscp = ip_pkt.getDiffServ(); return dscp; } else{ return (byte)0x00; } } private short extractIDFromEthernet(Ethernet eth){ IPacket pkt = eth.getPayload(); if(pkt instanceof IPv4){ IPv4 ip_pkt = (IPv4)pkt; short id = ip_pkt.getIdentification(); return id; } else{ return (short)0x00; } } static public String bytesToHexString(byte[] contents){ StringBuilder hexcontents = new StringBuilder(); for (byte b:contents) { hexcontents.append(String.format("%02X ", b)); } return hexcontents.toString(); } private net.floodlightcontroller.core.IListener.Command PacketInMsgHandler( IOFSwitch sw, OFMessage msg, FloodlightContext cntx){ packetCounter++; //System.err.println("switch id is: "+sw.getId()); if(msg.getType()!=OFType.PACKET_IN) return Command.CONTINUE; if(sw.getId() == EC2_SW){ Ethernet eth = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); Connection conn = new Connection(eth); if(conn.srcIP==0 || conn.type==Connection.INVALID){ droppedCounter++; System.err.println("give up beacause of not effective connection:"+conn); return Command.CONTINUE; } //only deal with udp and tcp if((conn.getProtocol()!= 0x11) && (conn.getProtocol()!= 0x06)){ System.err.println("give up because of not ip:"+conn); return Command.CONTINUE; } HoneyPot pot = getHoneypotFromConnection(conn); if(pot == null){ droppedCounter++; System.err.println("give up because of no appropriate pot:"+conn); return Command.CONTINUE; } conn.setHoneyPot(pot); Long key = conn.getConnectionSimplifiedKey(); Connection e2IFlow = null; byte[] srcIP = null; boolean forward_packet = false; boolean install_rules = false; if(connMap.containsKey(key)){ e2IFlow = connMap.get(key); srcIP = IPv4.toIPv4AddressBytes(e2IFlow.getSrcIP()); System.err.println("Contains Key:" + conn.getConnectionSimplifiedKeyString()); if(conn.type==Connection.EXTERNAL_TO_INTERNAL){ System.err.println("FIXME. currently replace exiting item"); forward_packet = true; install_rules = true; /* byte conn_state = e2IFlow.getState(); byte state = extractStateFromEthernet(eth); short id = extractIDFromEthernet(eth); if((conn_state==0x0C) && (state==0x00) ){ System.err.println("Regular packet, and the path is ready"); install_rules = true; forward_packet = true; } else if(conn_state==0x0C){ System.err.println("Constructor packet, but the path is ready, ignore!"); install_rules = false; forward_packet = false; } else if(state == 0x00){ install_rules = false; forward_packet = false; byte missing_state = (byte)((byte)0x0c - conn_state); boolean test = (((OFPacketIn)msg).getBufferId()==OFPacketOut.BUFFER_ID_NONE); System.err.println("Regular packet, but the path is not ready. sending out setup requesting packet "+ String.valueOf(missing_state)+" "+test); forwardPacketForLosingPkt(sw,(OFPacketIn)msg,nw_gw_mac_address, IPv4.toIPv4AddressBytes(e2IFlow.dstIP), IPv4.toIPv4AddressBytes(e2IFlow.srcIP), e2IFlow.dstPort, e2IFlow.srcPort, outside_port, missing_state,eth); } else if(conn_state == state){ System.err.println("repeated Constructor packet and path is not ready"); install_rules = false; forward_packet = false; } else{ if(state == 0x04){ System.err.println("Useful constructor packet up "); e2IFlow.setState((byte)(state|conn_state)); int tmp_ip = ((id&0x0000ffff)<<16) |e2IFlow.getOriginalIP() ; e2IFlow.setOriginalIP(tmp_ip); } else if(state == 0x08){ System.err.println("Useful constructor packet down"); e2IFlow.setState((byte)(state|conn_state)); int tmp_ip = id&0x0000ffff |e2IFlow.getOriginalIP(); e2IFlow.setOriginalIP(tmp_ip); } else{ System.err.println("Error state packet"+state); } forward_packet = false; if(e2IFlow.getState()==0x0C){ String real_src = IPv4.fromIPv4Address(e2IFlow.getOriginalIP()); String real_dst = IPv4.fromIPv4Address(e2IFlow.getDstIP()); System.err.println("path is ready:"+real_src+":"+e2IFlow.srcPort+"=>"+real_dst+":"+real_dst); install_rules = true; } } */ } else if(conn.type==Connection.INTERNAL_TO_EXTERNAL){ System.err.println("[old]Ignore I2E connections temporarily"); } }/* has found such connection */ else{ /* no such connection */ System.err.println("New connection: src:" + IPv4.fromIPv4Address(conn.srcIP)+ ":"+ " dst:"+IPv4.fromIPv4Address(conn.dstIP)); install_rules = true; forward_packet = true; System.err.println("FIXME: Src port mapping"); /* if(conn.type==Connection.EXTERNAL_TO_INTERNAL){ connMap.put(key, conn); byte state = extractStateFromEthernet(eth); short id = extractIDFromEthernet(eth); if(state==0x00){ System.err.println(conn+" first packet, non-constructor packet, sending setup requesting packet"); forwardPacketForLosingPkt(sw,(OFPacketIn)msg,nw_gw_mac_address, IPv4.toIPv4AddressBytes(conn.dstIP), IPv4.toIPv4AddressBytes(conn.srcIP), conn.dstPort, conn.srcPort, outside_port, (byte)0x0c,eth); } else if(state==0x04){ conn.setState(state); System.err.println(conn+" first packet, set state "+state+" "); int tmp_ip = id<<16; conn.setOriginalIP(tmp_ip); } else if(state == 0x08){ conn.setState(state); System.err.println(conn+" first packet, set state "+state); int tmp_ip = id&0x0000ffff; conn.setOriginalIP(tmp_ip); } else{ System.err.println("new "+conn+" error state "+state); } install_rules = false; forward_packet = false; clearMaps(); } else if(conn.type==Connection.INTERNAL_TO_EXTERNAL){ System.err.println("[new]Ignore I2E connections temporarily"); install_rules = false; forward_packet = false; } else{ logger.LogError("shouldn't come here 2 "+conn); System.err.println("5:"+conn); return Command.CONTINUE; } */ }/*No such connections*/ /*Not installing rules implies not installing forwarding packet*/ if(install_rules==false) return Command.CONTINUE; OFPacketIn pktInMsg = (OFPacketIn)msg; OFMatch match = null; byte[] newDstMAC = null; byte[] newSrcMAC = null; byte[] newDstIP = null; byte[] newSrcIP = null; short outPort = 0; boolean result1 = true; if(conn.type == Connection.EXTERNAL_TO_INTERNAL){ //set rule forward traffic out System.err.println("FIXME: set two rules for e2i conns, remember src transformation"); match = new OFMatch(); match.setDataLayerType((short)0x0800); //10.0.1.60 match.setNetworkDestination(IPv4.toIPv4Address(switchPrivateIP)); //10.0.1.61 match.setNetworkSource(conn.getHoneyPot().getIpAddrInt()); match.setTransportSource(conn.dstPort); match.setTransportDestination(conn.srcPort); match.setNetworkProtocol(conn.getProtocol()); match.setWildcards( OFMatch.OFPFW_IN_PORT| OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_NW_TOS | OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP ); newSrcMAC = switchPublicMac; //seems it doesn't matter newDstMAC = ec2PublicNetGWMac; outPort = OFPort.OFPP_LOCAL.getValue(); newSrcIP = IPv4.toIPv4AddressBytes(conn.dstIP); newDstIP = IPv4.toIPv4AddressBytes(conn.srcIP); result1 = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0, newSrcMAC,newDstMAC,newSrcIP,newDstIP,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,DEFAULT_PRIORITY); match = new OFMatch(); match.setDataLayerType((short)0x0800); match.setNetworkDestination(conn.dstIP); match.setNetworkSource(conn.srcIP); match.setTransportSource(conn.srcPort); match.setTransportDestination(conn.dstPort); //match.setInputPort(pktInMsg.getInPort()); match.setNetworkProtocol(conn.getProtocol()); match.setWildcards(OFMatch.OFPFW_IN_PORT | OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_NW_TOS | OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP); newDstMAC = ec2PrivateNetGWMac; newSrcMAC = switchPrivateMac; newDstIP = conn.getHoneyPot().getIpAddress(); newSrcIP = switchPrivateIP; outPort = conn.getHoneyPot().getOutPort(); boolean result2 = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0,newSrcMAC, newDstMAC,newSrcIP,newDstIP,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,DEFAULT_PRIORITY); result1 &= result2; } else if(conn.type == Connection.INTERNAL_TO_EXTERNAL){ System.err.println("ignoring installing rules ofr I2E flows"); } else{ logger.LogError("shouldn't come here 3 "+conn); return Command.CONTINUE; } boolean result2 = true; if(forward_packet) result2 = forwardPacket(sw,pktInMsg,newSrcMAC,newDstMAC,newDstIP,srcIP,outPort); if(!result1 || !result2){ logger.LogError("fail to install rule for "+conn); } } else{ logger.LogDebug("Unknown switch: "+sw.getStringId()); } return Command.CONTINUE; } private net.floodlightcontroller.core.IListener.Command FlowRemovedMsgHandler( IOFSwitch sw, OFMessage msg, FloodlightContext cntx){ return Command.CONTINUE; } @Override public net.floodlightcontroller.core.IListener.Command receive( IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { if (msg.getType() == OFType.PACKET_IN) { //System.err.println("packet in msg"); PacketInMsgHandler(sw,msg,cntx); return Command.CONTINUE; } return Command.CONTINUE; } private HoneyPot getHoneypotFromConnection(Connection conn){ if(conn.type==Connection.EXTERNAL_TO_INTERNAL){ short dport = conn.getDstPort(); //int dstIP = conn.getDstIP(); int srcIP = conn.getSrcIP(); int flag = (srcIP>>8)&0x000000e0; /* if we have records for this connection, use existing honeypot */ String key = Connection.createConnKeyString(conn.getSrcIP(), conn.getSrcPort(), conn.getDstIP(), conn.getDstPort()); if(connToPot.containsKey(key)){ if(!(connToPot.get(key).isConnExpire(CONN_TIMEOUT))){ connToPot.get(key).updateTime(); return connToPot.get(key).getHoneyPot(); } } /* if not, find a LIH to address the port */ if(ports.containsKey(dport)){ Vector<HoneyPot> pots = ports.get(dport); for(HoneyPot pot : pots){ if(pot.getMask().containsKey(dport) && pot.getMask().get(dport).inSubnet(srcIP)){ return pot; } } logger.LogError("can't address srcIP "+IPv4.fromIPv4Address(srcIP)+ dport+" "); for(HoneyPot pot : pots){ logger.LogError(pot.getName()+" containsKey:"+pot.getMask().containsKey(dport)); if(pot.getMask().containsKey(dport)) logger.LogError(pot.getName()+" :"+pot.getMask().get(dport)+" "+pot.getMask().get(dport).inSubnet(srcIP)); } return null; } else{ logger.LogDebug("can't address port "+dport); //for(short p : ports.keySet()){ // System.err.println("debug: port:"+p); return null; } } else if(conn.type == Connection.INTERNAL_TO_EXTERNAL){ for (HoneyPot pot: honeypots.values()) { if(pot.getIpAddrInt() == conn.getSrcIP()){ return pot; } } } return null; } private boolean initEC2Switch(long switchId){ IOFSwitch sw = floodlightProvider.getSwitch(switchId); OFSetConfig config = new OFSetConfig(); config.setMissSendLength((short)0xffff); try{ sw.write(config, null); sw.flush(); System.out.println("Done writing config to sw"); } catch(Exception e){ System.err.println("Write config to sw: "+e); } //e2i to controller OFMatch match = new OFMatch(); match.setDataLayerType((short)0x0800); match.setNetworkDestination(IPv4.toIPv4Address(switchPublicIP)); match.setNetworkSource(IPv4.toIPv4Address(sriNet)); match.setWildcards( OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP| OFMatch.OFPFW_NW_DST_ALL | sriNetMask<<OFMatch.OFPFW_NW_SRC_SHIFT| OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS | OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST | OFMatch.OFPFW_IN_PORT); byte[] newSrcMAC = null; byte[] newDstMAC = null; byte[] newSrcIP = null; byte[] newDstIP = null; short outPort = OFPort.OFPP_CONTROLLER.getValue(); boolean result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0,newSrcMAC, newDstMAC,newSrcIP,newDstIP,outPort,(short)0, (short)0,CONTROLLER_PRIORITY); if(!result){ logger.LogError("fail to create default rule1 for ec2"); System.exit(1); return false; } // i2e to controller match = new OFMatch(); match.setDataLayerType((short)0x0800); match.setNetworkSource(IPv4.toIPv4Address(honeypotNet)); match.setNetworkDestination(IPv4.toIPv4Address(switchPrivateIP)); match.setWildcards( OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP| OFMatch.OFPFW_NW_DST_ALL | honeypotNetMask<<OFMatch.OFPFW_NW_SRC_SHIFT| OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS | OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST | OFMatch.OFPFW_IN_PORT); outPort = OFPort.OFPP_CONTROLLER.getValue(); result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0, newSrcMAC,newDstMAC,newSrcIP,newDstIP,outPort,(short)0, (short)0,CONTROLLER_PRIORITY); if(!result){ logger.LogError("fail to create default rule2 for ec2"); System.exit(1); return false; } //arp match = new OFMatch(); match.setDataLayerType((short)0x0806); match.setWildcards( OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP| OFMatch.OFPFW_NW_DST_ALL | OFMatch.OFPFW_NW_SRC_ALL| OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS | OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST | OFMatch.OFPFW_IN_PORT); outPort = OFPort.OFPP_NORMAL.getValue(); result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0, newSrcMAC,newDstMAC,newSrcIP,newDstIP,outPort,(short)0, (short)0,NORMAL_PRIORITY); if(!result){ logger.LogError("fail to create default rule5 for ec2"); System.exit(1); return false; } match = new OFMatch(); match.setDataLayerType((short)0x8035); match.setWildcards( OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP| OFMatch.OFPFW_NW_DST_ALL | OFMatch.OFPFW_NW_SRC_ALL| OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS | OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST | OFMatch.OFPFW_IN_PORT); outPort = OFPort.OFPP_NORMAL.getValue(); result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0, newSrcMAC,newDstMAC,newSrcIP,newDstIP,outPort,(short)0, (short)0,NORMAL_PRIORITY); if(!result){ logger.LogError("fail to create default rule6 for ec2"); System.exit(1); return false; } match = new OFMatch(); match.setWildcards( OFMatch.OFPFW_DL_TYPE | OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP| OFMatch.OFPFW_NW_DST_ALL | OFMatch.OFPFW_NW_SRC_ALL| OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS | OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST | OFMatch.OFPFW_IN_PORT); return installDropRule(sw.getId(),match,(short)0,(short)0, DROP_PRIORITY); } public boolean forwardPacketForLosingPkt(IOFSwitch sw, OFPacketIn pktInMsg, byte[] dstMAC, byte[] srcIP, byte[] dstIP,short srcPort, short dstPort, short outSwPort, short dscp, Ethernet eth) { OFPacketOut pktOut = new OFPacketOut(); pktOut.setInPort(pktInMsg.getInPort()); pktOut.setBufferId(pktInMsg.getBufferId()); List<OFAction> actions = new ArrayList<OFAction>(); int actionLen = 0; if(dstMAC != null){ OFActionDataLayerDestination action_mod_dst_mac = new OFActionDataLayerDestination(dstMAC); actions.add(action_mod_dst_mac); actionLen += OFActionDataLayerDestination.MINIMUM_LENGTH; } if(dstIP != null){ OFActionNetworkLayerDestination action_mod_dst_ip = new OFActionNetworkLayerDestination(IPv4.toIPv4Address(dstIP)); actions.add(action_mod_dst_ip); actionLen += OFActionNetworkLayerDestination.MINIMUM_LENGTH; } if(srcIP != null){ OFActionNetworkLayerSource action_mod_src_ip = new OFActionNetworkLayerSource(IPv4.toIPv4Address(srcIP)); actions.add(action_mod_src_ip); actionLen += OFActionNetworkLayerSource.MINIMUM_LENGTH; } if(srcPort != 0){ OFActionTransportLayerSource action_mod_src_port = new OFActionTransportLayerSource(srcPort); actions.add(action_mod_src_port); actionLen += OFActionTransportLayerSource.MINIMUM_LENGTH; } if(dstPort != 0){ OFActionTransportLayerDestination action_mod_dst_port = new OFActionTransportLayerDestination(dstPort); actions.add(action_mod_dst_port); actionLen += OFActionTransportLayerDestination.MINIMUM_LENGTH; } System.err.println("from:"+IPv4.fromIPv4Address(IPv4.toIPv4Address(srcIP))+":"+srcPort+" to: "+ IPv4.fromIPv4Address(IPv4.toIPv4Address(dstIP))+":"+dstPort ); OFActionOutput action_out_port; actionLen += OFActionOutput.MINIMUM_LENGTH; if(pktInMsg.getInPort() == outSwPort) action_out_port = new OFActionOutput(OFPort.OFPP_IN_PORT.getValue()); else action_out_port = new OFActionOutput(outSwPort); actions.add(action_out_port); pktOut.setActions(actions); pktOut.setActionsLength((short)actionLen); // Set data if it is included in the packet in but buffer id is NONE if (pktOut.getBufferId() == OFPacketOut.BUFFER_ID_NONE) { byte[] packetData = pktInMsg.getPacketData(); pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH + pktOut.getActionsLength() + packetData.length)); int packetLen = packetData.length; int msgLen = pktInMsg.getLength(); IPacket pkt = eth.getPayload(); if(pkt instanceof IPv4){ IPv4 ipPkt = (IPv4)pkt; int ipLen = ipPkt.getTotalLength(); int ipHeaderLen = (ipPkt.getHeaderLength() & 0x000000ff) * 4; byte[] ipPktData = Arrays.copyOfRange(packetData, ChecksumCalc.ETHERNET_HEADER_LEN,ChecksumCalc.ETHERNET_HEADER_LEN + ipLen); /*FIXME it turns out dscp will be striped from NW to SRI, we use ecn instead */ byte ecn = (byte)(dscp >>> 2); ipPktData[1] = ecn; if(ChecksumCalc.reCalcAndUpdateIPPacketChecksum(ipPktData, ipHeaderLen)==false){ System.err.println("error calculating ip pkt checksum"); } byte[] newEtherData = new byte[packetLen]; for(int i=0; i<ChecksumCalc.ETHERNET_HEADER_LEN; i++) newEtherData[i] = packetData[i]; for(int i=ChecksumCalc.ETHERNET_HEADER_LEN,j=0; i<packetLen; i++,j++){ if(j < ipLen) newEtherData[i] = ipPktData[j]; else newEtherData[i] = 0x00; } System.err.println("Having configured setup packet "+newEtherData[15]+":"+bytesToHexString(ipPktData)); pktOut.setPacketData(newEtherData); } else{ short eth_type = eth.getEtherType(); String eth_type_str = Integer.toHexString(eth_type & 0xffff); System.err.println("msglen:"+msgLen+" packetlen:"+packetLen+" iplen: no ipv4 pkt :"+eth_type_str); pktOut.setPacketData(packetData); } } else { pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH + pktOut.getActionsLength())); System.err.println("Attention: packet stored in SW"); } /*For test byte[] packetData = pktInMsg.getPacketData(); pktOut.setPacketData(packetData); pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH + pktOut.getActionsLength() + packetData.length)); */ // Send the packet to the switch try { System.err.println("sent out requesting setup packet!\n"); sw.write(pktOut, null); sw.flush(); //logger.info("forwarded packet "); } catch (IOException e) { logger.LogError("failed forward packet"); return false; } return true; } public boolean forwardPacket(IOFSwitch sw, OFPacketIn pktInMsg, byte srcMac[], byte[] dstMac, byte[] destIP, byte[] srcIP, short outSwPort) { OFPacketOut pktOut = new OFPacketOut(); pktOut.setInPort(pktInMsg.getInPort()); pktOut.setBufferId(pktInMsg.getBufferId()); List<OFAction> actions = new ArrayList<OFAction>(); int actionLen = 0; if(srcMac != null){ OFActionDataLayerSource action_mod_src_mac = new OFActionDataLayerSource(srcMac); actions.add(action_mod_src_mac); actionLen += OFActionDataLayerSource.MINIMUM_LENGTH; } if(dstMac != null){ OFActionDataLayerDestination action_mod_dst_mac = new OFActionDataLayerDestination(dstMac); actions.add(action_mod_dst_mac); actionLen += OFActionDataLayerDestination.MINIMUM_LENGTH; } if(destIP != null){ OFActionNetworkLayerDestination action_mod_dst_ip = new OFActionNetworkLayerDestination(IPv4.toIPv4Address(destIP)); actions.add(action_mod_dst_ip); actionLen += OFActionNetworkLayerDestination.MINIMUM_LENGTH; } if(srcIP != null){ OFActionNetworkLayerSource action_mod_src_ip = new OFActionNetworkLayerSource(IPv4.toIPv4Address(srcIP)); actions.add(action_mod_src_ip); actionLen += OFActionNetworkLayerSource.MINIMUM_LENGTH; } OFActionOutput action_out_port; actionLen += OFActionOutput.MINIMUM_LENGTH; if(pktInMsg.getInPort() == outSwPort){ action_out_port = new OFActionOutput(OFPort.OFPP_IN_PORT.getValue()); } else{ action_out_port = new OFActionOutput(outSwPort); } actions.add(action_out_port); pktOut.setActions(actions); pktOut.setActionsLength((short)actionLen); // Set data if it is included in the packet in but buffer id is NONE if (pktOut.getBufferId() == OFPacketOut.BUFFER_ID_NONE) { byte[] packetData = pktInMsg.getPacketData(); pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH + pktOut.getActionsLength() + packetData.length)); pktOut.setPacketData(packetData); } else { pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH + pktOut.getActionsLength())); } // Send the packet to the switch try { sw.write(pktOut, null); sw.flush(); //logger.info("forwarded packet "); } catch (IOException e) { logger.LogError("failed forward packet"); return false; } return true; } private boolean installPathForFlow(long swID,short inPort,OFMatch match, short flowFlag, long flowCookie, byte[] newSrcMAC, byte[] newDstMAC, byte[] newSrcIP, byte[] newDstIP, short outPort, short idleTimeout, short hardTimeout,short priority) { IOFSwitch sw = floodlightProvider.getSwitch(swID); if(sw == null){ logger.LogError("deleteFlows fail getting switch [installPathForFlow]"); return false; } OFFlowMod rule = new OFFlowMod(); if (flowFlag != (short) 0) { rule.setFlags(flowFlag); } if (flowCookie != (long) 0) rule.setCookie(flowCookie); rule.setHardTimeout(hardTimeout); rule.setIdleTimeout(idleTimeout); rule.setPriority(priority); rule.setCommand(OFFlowMod.OFPFC_MODIFY_STRICT); rule.setBufferId(OFPacketOut.BUFFER_ID_NONE); rule.setMatch(match.clone()); List<OFAction> actions = new ArrayList<OFAction>(); int actionLen = 0; if (newSrcMAC != null) { OFActionDataLayerSource action_mod_src_mac = new OFActionDataLayerSource( newSrcMAC); actions.add(action_mod_src_mac); actionLen += OFActionDataLayerSource.MINIMUM_LENGTH; } if (newDstMAC != null) { OFActionDataLayerDestination action_mod_dst_mac = new OFActionDataLayerDestination( newDstMAC); actions.add(action_mod_dst_mac); actionLen += OFActionDataLayerDestination.MINIMUM_LENGTH; } if (newDstIP != null) { OFActionNetworkLayerDestination action_mod_dst_ip = new OFActionNetworkLayerDestination( IPv4.toIPv4Address(newDstIP)); actions.add(action_mod_dst_ip); actionLen += OFActionNetworkLayerDestination.MINIMUM_LENGTH; } if (newSrcIP != null) { OFActionNetworkLayerSource action_mod_src_ip = new OFActionNetworkLayerSource( IPv4.toIPv4Address(newSrcIP)); actions.add(action_mod_src_ip); actionLen += OFActionNetworkLayerSource.MINIMUM_LENGTH; } OFActionOutput action_out_port; actionLen += OFActionOutput.MINIMUM_LENGTH; if (outPort == inPort) { action_out_port = new OFActionOutput(OFPort.OFPP_IN_PORT.getValue()); } else { action_out_port = new OFActionOutput(outPort); } actions.add(action_out_port); rule.setActions(actions); rule.setLength((short) (OFFlowMod.MINIMUM_LENGTH + actionLen)); try { sw.write(rule, null); sw.flush(); } catch (IOException e) { logger.LogError("fail to install rule: " + rule); return false; } return true; } private void clearMaps(){ if((connMap.size()<CONN_MAX_SIZE) && (connToPot.size()<CONN_MAX_SIZE)){ return ; } if(connToPot.size()>= CONN_MAX_SIZE){ connToPot = new Hashtable<String,Connection>(); long currTime = System.currentTimeMillis(); currTime -= lastClearConnToPotTime; logger.LogError("Clear connToPot after "+currTime/1000+" seconds"); lastClearConnToPotTime = System.currentTimeMillis(); } if(connMap.size() >= CONN_MAX_SIZE){ connMap = new Hashtable<Long, Connection>(); long currTime = System.currentTimeMillis(); currTime -= lastClearConnMapTime; logger.LogError("Clear connMap after "+currTime/1000+" seconds"); lastClearConnMapTime = System.currentTimeMillis(); } } private void forceClearMaps(){ connToPot = new Hashtable<String,Connection>(); long currTime = System.currentTimeMillis(); currTime -= lastClearConnToPotTime; logger.LogError("Clear connToPot after "+currTime/1000+" seconds"); lastClearConnToPotTime = System.currentTimeMillis(); connMap = new Hashtable<Long, Connection>(); currTime = System.currentTimeMillis(); currTime -= lastClearConnMapTime; logger.LogError("Clear connMap after "+currTime/1000+" seconds"); lastClearConnMapTime = System.currentTimeMillis(); System.gc(); } private boolean installDropRule(long swID, OFMatch match,short idleTimeout, short hardTimeout, short priority){ IOFSwitch sw = floodlightProvider.getSwitch(swID); if(sw == null){ logger.LogError("deleteFlows fail getting switch [installDropRule]"); return false; } OFFlowMod rule = new OFFlowMod(); rule.setHardTimeout(hardTimeout); rule.setIdleTimeout(idleTimeout); rule.setPriority(priority); rule.setCommand(OFFlowMod.OFPFC_ADD); rule.setBufferId(OFPacketOut.BUFFER_ID_NONE); rule.setMatch(match.clone()); /* Empty action list means drop! */ List<OFAction> actions = new ArrayList<OFAction>(); rule.setActions(actions); rule.setLength((short)(OFFlowMod.MINIMUM_LENGTH)); try { sw.write(rule, null); sw.flush(); logger.LogDebug("succ installed drop rule: "+rule); } catch (IOException e) { logger.LogError("fail installing rule: "+rule); return false; } return true; } private boolean deleteFlowsForHoneypot(String honeypotName){ if(!(honeypots.containsKey(honeypotName)) ){ logger.LogError("fail finding honeypot "+honeypotName); return false; } short outPort = honeypots.get(honeypotName).getOutPort(); long swID = 0; try{ swID = switches.get(honeypots.get(honeypotName).getSwName()); } catch(Exception e){ logger.LogError("switches"+e); return false; } IOFSwitch sw = floodlightProvider.getSwitch(swID); if(sw == null){ logger.LogError("fail getting switch deleteFlowsForHoneypot"); return false; } OFFlowMod ruleIncoming = new OFFlowMod(); ruleIncoming.setOutPort(outPort); ruleIncoming.setCommand(OFFlowMod.OFPFC_DELETE); ruleIncoming.setBufferId(OFPacketOut.BUFFER_ID_NONE); OFMatch match = new OFMatch(); match.setWildcards(~0); ruleIncoming.setMatch(match.clone()); OFFlowMod ruleOutgoing = new OFFlowMod(); ruleOutgoing.setOutPort(OFPort.OFPP_NONE); ruleOutgoing.setCommand(OFFlowMod.OFPFC_DELETE); ruleOutgoing.setBufferId(OFPacketOut.BUFFER_ID_NONE); match = new OFMatch(); match.setInputPort(outPort); match.setWildcards(~(OFMatch.OFPFW_IN_PORT)); ruleOutgoing.setMatch(match.clone()); try{ sw.write(ruleIncoming, null); sw.write(ruleOutgoing, null); sw.flush(); } catch (IOException e){ logger.LogError("fail delete flows for: "+honeypotName+" "+ruleIncoming+" "+ruleOutgoing); return false; } return true; } private boolean deleteFlows(OFMatch match, long swID){ IOFSwitch sw = floodlightProvider.getSwitch(swID); if(sw == null){ logger.LogError("deleteFlows fail getting switch "); return false; } OFFlowMod rule = new OFFlowMod(); rule.setOutPort(OFPort.OFPP_NONE); rule.setCommand(OFFlowMod.OFPFC_DELETE); rule.setBufferId(OFPacketOut.BUFFER_ID_NONE); rule.setMatch(match.clone()); try{ sw.write(rule, null); sw.flush(); logger.LogDebug("succ delete flow "+rule); } catch (IOException e) { logger.LogError("fail delete flows for: "+rule); return false; } return true; } @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(IConnMonitorService.class); return l; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(); m.put(IConnMonitorService.class, this); return m; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(IFloodlightProviderService.class); l.add(IRestApiService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); restApi = context.getServiceImpl(IRestApiService.class); connMap = new Hashtable<Long,Connection>(); honeypots = new Hashtable<String, HoneyPot>(); ports = new Hashtable<Short, Vector<HoneyPot>>(); portsForHIH = new Hashtable<Short, Vector<HoneyPot>>(); connToPot = new Hashtable<String,Connection>(); HIHAvailabilityMap = new Hashtable<String,Boolean>(); HIHClientMap = new Hashtable<String, HashSet<Integer> >(); HIHNameMap = new Hashtable<Long, String>(); HIHFlowCount = new Hashtable<String, Integer>(); executor = Executors.newFixedThreadPool(1); logger = new MyLogger(); /* Init Switches */ switches = new Hashtable<String,Long>(); switches.put("ec2", EC2_SW); /* Init Honeypots */ initHoneypots(); //initPorts(); lastClearConnMapTime = System.currentTimeMillis(); lastClearConnToPotTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis(); droppedCounter = 0; packetCounter = 1; /*For test*/ randomGen = new Random(); testFlag = false; } @Override public void startUp(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); floodlightProvider.addOFMessageListener(OFType.FLOW_REMOVED, this); floodlightProvider.addOFSwitchListener(this); restApi.addRestletRoutable(new ConnMonitorWebRoutable()); } @Override public net.floodlightcontroller.core.IListener.Command processPacketInMessage( IOFSwitch sw, OFPacketIn pi, IRoutingDecision decision, FloodlightContext cntx) { return null; } @Override public void switchAdded(long switchId) { } @Override public void switchRemoved(long switchId) { } @Override public void switchActivated(long switchId) { if(switchId == EC2_SW){ initEC2Switch(switchId); } else System.err.println("unknown switch gets activated "+switchId); } @Override public void switchPortChanged(long switchId, ImmutablePort port, PortChangeType type) { } @Override public void switchChanged(long switchId) { } private void initHoneypots(){ BufferedReader br = null; try { InputStream ins = this.getClass().getClassLoader().getResourceAsStream(honeypotConfigFileName); br = new BufferedReader(new InputStreamReader(ins)); String line = null; byte[] mac = new byte[6]; /* id name ip mac out_port down_ip type switch */ while ((line = br.readLine()) != null) { logger.LogInfo(line); if(line.startsWith(" continue; String[] elems = line.split("\t"); int len = elems.length; int id = Integer.parseInt(elems[0]); String name = elems[1].trim(); byte[] ip = IPv4.toIPv4AddressBytes(elems[2]); String[] rawMAC = elems[3].split(":"); for(int i=0; i<6; i++) mac[i] = (byte)Integer.parseInt(rawMAC[i],16); short outPort = (short)Integer.parseInt(elems[4]); byte[] downIP = IPv4.toIPv4AddressBytes(elems[5]); byte type = HoneyPot.LOW_INTERACTION; if(elems[6].trim().equals("H") ){ type = HoneyPot.HIGH_INTERACTION; } String swName = elems[7].trim().toLowerCase(); honeypots.put(name, new HoneyPot(name,id,ip,mac,downIP,outPort,type,swName)); } ins.close(); ins = this.getClass().getClassLoader().getResourceAsStream(PortsConfigFileName); br = new BufferedReader(new InputStreamReader(ins)); /* Port Name Netmask */ while ((line = br.readLine()) != null) { if(line.startsWith("#") || line.trim().length()==0) continue; String[] elems = line.split("\t"); short port = (short)Integer.parseInt(elems[0]); String name = elems[1].trim(); IPv4Netmask mask = new IPv4Netmask(elems[2]); HoneyPot pot = honeypots.get(name); if(pot == null){ logger.LogError("can't find pot:"+name); continue; } pot.getMask().put(port, mask); if(ports.containsKey(port)){ Vector<HoneyPot> pots = ports.get(port); pots.add(pot); ports.put(port, pots); } else{ System.err.println("debug:"+port+" "+pot.getName()); Vector<HoneyPot> pots = new Vector<HoneyPot>(); pots.add(pot); ports.put(port, pots); } } Iterator<Map.Entry<Short, Vector<HoneyPot>>> it = ports.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Short, Vector<HoneyPot>> entry = it.next(); Vector<HoneyPot> pots = ports.get(entry.getKey()); for(HoneyPot pot : pots){ System.err.println("test:"+entry.getKey()+" : "+pot.getName()); } } }catch(Exception e){ logger.LogError("failed to read honeypot_config_path"); e.printStackTrace(); } } @Override public boolean ReceiveInterestingSrcMsg(String content) { logger.LogInfo("TODO: received information: "+content); return false; } @Override public boolean ReceiveHIHStatus(String pot_name, String status){ return false; } @Override public List<Connection> getConnections() { return null; } private boolean SendUDPData(String data,String dstIP, short dstPort){ try{ DatagramSocket socket = new DatagramSocket(); byte[] buf = new byte[256]; buf = data.getBytes(); InetAddress dst = InetAddress.getByName(dstIP); DatagramPacket packet = new DatagramPacket(buf, buf.length, dst, dstPort); socket.send(packet); socket.close(); } catch(Exception e){ logger.LogError("error sending udp: "+e+" "+data); return false; } logger.LogDebug("Sent out data "+data); return true; } /* This function is only for demonstration */ @Override public boolean WhetherMigrate(String src_ip, String src_port, String lih_ip,String dst_port) { return false; } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.event.WindowEvent; import org.gridlab.gridsphere.event.impl.WindowEventImpl; import org.gridlab.gridsphere.layout.event.PortletTitleBarEvent; import org.gridlab.gridsphere.layout.event.PortletTitleBarListener; import org.gridlab.gridsphere.layout.event.impl.PortletTitleBarEventImpl; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portletcontainer.*; import java.io.IOException; import java.io.PrintWriter; import java.util.*; /** * A <code>PortletTitleBar</code> represents the visual display of the portlet title bar * within a portlet frame and is contained by {@link PortletFrame}. * The title bar contains portlet mode and window state as well as a title. */ public class PortletTitleBar extends BasePortletComponent { private String title = "Portlet Unavailable"; private String portletClass = null; private PortletWindow.State windowState = PortletWindow.State.NORMAL; private List supportedModes = new ArrayList(); private Portlet.Mode portletMode = Portlet.Mode.VIEW; private Portlet.Mode previousMode = null; private List listeners = new ArrayList(); private PortletSettings settings; private List allowedWindowStates = new ArrayList(); private String errorMessage = ""; private boolean hasError = false; /** * Link is an abstract representation of a hyperlink with an href, image and * alt tags. */ abstract class Link { protected String href = ""; protected String imageSrc = ""; protected String altTag = ""; /** * Returns the image source attribute in the link * * @return the image source attribute in the link */ public String getImageSrc() { return imageSrc; } /** * Sets the href attribute in the link * * @param href the href attribute in the link */ public void setHref(String href) { this.href = href; } /** * Returns the href attribute in the link * * @return the href attribute in the link */ public String getHref() { return href; } /** * Returns the alt tag attribute in the link * * @return the alt tag attribute in the link */ public String getAltTag() { return altTag; } /** * Returns a string containing the image src, href and alt tag attributes * Used primarily for debugging purposes */ public String toString() { StringBuffer sb = new StringBuffer("\n"); sb.append("image src: " + imageSrc + "\n"); sb.append("href: " + href + "\n"); sb.append("alt tag: " + altTag + "\n"); return sb.toString(); } } /** * PortletModeLink is a concrete instance of a Link used for creating * portlet mode hyperlinks */ class PortletModeLink extends Link { public static final String configImage = "images/window_configure.gif"; public static final String editImage = "images/window_edit.gif"; public static final String helpImage = "images/window_help.gif"; public static final String configAlt = "Configure"; public static final String editAlt = "Edit"; public static final String helpAlt = "Help"; /** * Constructs an instance of PortletModeLink with the supplied portlet mode * * @param mode the portlet mode */ public PortletModeLink(String mode) throws IllegalArgumentException { // Set the image src if (mode.equalsIgnoreCase(Portlet.Mode.CONFIGURE.toString())) { imageSrc = configImage; altTag = configAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.EDIT.toString())) { imageSrc = editImage; altTag = editAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.HELP.toString())) { imageSrc = helpImage; altTag = helpAlt; } else { throw new IllegalArgumentException("No matching Portlet.Mode found for received portlet mode: " + mode); } } } /** * PortletStateLink is a concrete instance of a Link used for creating * portlet window state hyperlinks */ class PortletStateLink extends Link { public static final String minimizeImage = "images/window_minimize.gif"; public static final String maximizeImage = "images/window_maximize.gif"; public static final String resizeImage = "images/window_resize.gif"; public static final String minimizeAlt = "Minimize"; public static final String maximizeAlt = "Maximize"; public static final String resizeAlt = "Resize"; /** * Constructs an instance of PortletStateLink with the supplied window state * * @param state the window state */ public PortletStateLink(String state) throws IllegalArgumentException { // Set the image src if (state.equalsIgnoreCase(PortletWindow.State.MINIMIZED.toString())) { imageSrc = minimizeImage; altTag = minimizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.MAXIMIZED.toString())) { imageSrc = maximizeImage; altTag = maximizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { imageSrc = resizeImage; altTag = resizeAlt; } else { throw new IllegalArgumentException("No matching PortletWindow.State found for received window mode: " + state); } } } /** * Constructs an instance of PortletTitleBar */ public PortletTitleBar() { } /** * Sets the portlet class used to render the title bar * * @param portletClass the concrete portlet class */ public void setPortletClass(String portletClass) { this.portletClass = portletClass; } /** * Returns the portlet class used in rendering the title bar * * @return the concrete portlet class */ public String getPortletClass() { return portletClass; } /** * Returns the title of the portlet title bar * * @return the portlet title bar */ public String getTitle() { return title; } /** * Sets the title of the portlet title bar * * @param title the portlet title bar */ public void setTitle(String title) { this.title = title; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string * @see PortletWindow.State */ public void setWindowState(String state) { if (state != null) { try { this.windowState = PortletWindow.State.toState(state); } catch (IllegalArgumentException e) { // do nothing } } } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string * @see PortletWindow.State */ public String getWindowState() { return windowState.toString(); } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string * @see Portlet.Mode */ public void setPortletMode(String mode) { try { this.portletMode = Portlet.Mode.toMode(mode); } catch (IllegalArgumentException e) { // do nothing } } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string * @see Portlet.Mode */ public String getPortletMode() { return portletMode.toString(); } /** * Adds a title bar listener to be notified of title bar events * * @param listener a title bar listener * @see PortletTitleBarEvent */ public void addTitleBarListener(PortletTitleBarListener listener) { listeners.add(listener); } /** * Indicates an error ocurred suring the processing of this title bar * * @return <code>true</code> if an error occured during rendering, * <code>false</code> otherwise */ public boolean hasRenderError() { return hasError; } /** * Returns any errors associated with the functioning of this title bar * * @return any title bar errors that occured */ public String getErrorMessage() { return errorMessage; } /** * Initializes the portlet title bar. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List init(List list) { list = super.init(list); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setPortletClass(portletClass); compId.setComponentID(list.size()); compId.setClassName(this.getClass().getName()); list.add(compId); doConfig(); return list; } /** * Sets configuration information about the supported portlet modes, * allowed window states and title bar obtained from {@link PortletSettings}. * Information is queried from the {@link PortletRegistry} */ protected void doConfig() { PortletRegistry registryManager = PortletRegistry.getInstance(); String appID = registryManager.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = registryManager.getApplicationPortlet(appID); if (appPortlet != null) { ApplicationPortletConfig appConfig = appPortlet.getApplicationPortletConfig(); // get supported modes from application portlet config supportedModes = sort(appConfig.getSupportedModes()); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(portletClass); settings = concPortlet.getPortletSettings(); // get window states from application portlet config allowedWindowStates = sort(appConfig.getAllowedWindowStates()); } } public List sort(List list) { int n = list.size(); for (int i=0; i < n-1; i++) { for (int j=0; j < n-1-i; j++) { Comparator c = (Comparator)list.get(j); Comparator d = (Comparator)list.get(j+1); if (c.compare(c, d) == 1) { Object tmp = list.get(j); /* swap a[j] and a[j+1] */ list.set(j, d); list.set(j+1, tmp); } } } return list; } /** private boolean greaterThan(Comparator c, Object left, Object right) { return c.compare(left, right) == 1; } **/ /** * Creates the portlet window state hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of window state hyperlinks */ protected List createWindowLinks(GridSphereEvent event) { PortletURI portletURI; PortletResponse res = event.getPortletResponse(); if (allowedWindowStates.isEmpty()) return null; String[] windowStates = new String[allowedWindowStates.size()]; for (int i = 0; i < allowedWindowStates.size(); i++) { PortletWindow.State state = (PortletWindow.State)allowedWindowStates.get(i); windowStates[i] = state.toString(); } for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // get rid of resized if window state is normal if (windowState == PortletWindow.State.NORMAL) { for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { windowStates[i] = ""; } } } for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // create a URI for each of the window states PortletStateLink stateLink; List stateLinks = new Vector(); for (int i = 0; i < windowStates.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { stateLink = new PortletStateLink(windowStates[i]); portletURI.addParameter(GridSphereProperties.PORTLETWINDOW, windowStates[i]); stateLink.setHref(portletURI.toString()); stateLinks.add(stateLink); } catch (IllegalArgumentException e) { // do nothing } } return stateLinks; } /** * Creates the portlet mode hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of portlet mode hyperlinks */ public List createModeLinks(GridSphereEvent event) { int i; PortletResponse res = event.getPortletResponse(); // make modes from supported modes if (supportedModes.isEmpty()) return null; String[] portletModes = new String[supportedModes.size()]; for (i = 0; i < supportedModes.size(); i++) { Portlet.Mode mode = (Portlet.Mode)supportedModes.get(i); portletModes[i] = mode.toString(); } // create a URI for each of the portlet modes PortletURI portletURI; PortletModeLink modeLink; List portletLinks = new ArrayList(); for (i = 0; i < portletModes.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { modeLink = new PortletModeLink(portletModes[i]); portletURI.addParameter(GridSphereProperties.PORTLETMODE, portletModes[i]); modeLink.setHref(portletURI.toString()); portletLinks.add(modeLink); } catch (IllegalArgumentException e) { } } return portletLinks; } /** * Performs an action on this portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void actionPerformed(GridSphereEvent event) throws PortletLayoutException, IOException { PortletTitleBarEvent evt = new PortletTitleBarEventImpl(event, COMPONENT_ID); PortletRequest req = event.getPortletRequest(); if (evt.getAction() == PortletTitleBarEvent.Action.WINDOW_MODIFY) { PortletResponse res = event.getPortletResponse(); windowState = evt.getState(); WindowEvent winEvent = null; if (windowState == PortletWindow.State.MAXIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MAXIMIZED); } else if (windowState == PortletWindow.State.MINIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MINIMIZED); } else if (windowState == PortletWindow.State.RESIZING) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_RESTORED); } if (winEvent != null) { try { //userManager.windowEvent(portletClass, winEvent, req, res); PortletInvoker.windowEvent(portletClass, winEvent, req, res); } catch (PortletException e) { hasError = true; errorMessage += "Failed to invoke window event method of portlet: " + portletClass; } } } else if (evt.getAction() == PortletTitleBarEvent.Action.MODE_MODIFY) { previousMode = portletMode; portletMode = evt.getMode(); req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, portletMode); } if (evt != null) fireTitleBarEvent(evt); } /** * Fires a title bar event notification * * @param event a portlet title bar event * @throws PortletLayoutException if a layout error occurs */ protected void fireTitleBarEvent(PortletTitleBarEvent event) throws PortletLayoutException { Iterator it = listeners.iterator(); PortletTitleBarListener l; while (it.hasNext()) { l = (PortletTitleBarListener) it.next(); l.handleTitleBarEvent(event); } } /** * Renders the portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void doRender(GridSphereEvent event) throws PortletLayoutException, IOException { // title bar: configure, edit, help, title, min, max PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); // get the appropriate title for this client Client client = req.getClient(); if (settings == null) { doConfig(); } else { title = settings.getTitle(req.getLocale(), client); } List modeLinks = null, windowLinks = null; User user = req.getUser(); if (user instanceof GuestUser) { } else { if (portletClass != null) { modeLinks = createModeLinks(event); windowLinks = createWindowLinks(event); } } req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, previousMode); PrintWriter out = res.getWriter(); out.println("<tr><td class=\"window-title\">"); out.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>"); // Output portlet mode icons if (modeLinks != null) { Iterator modesIt = modeLinks.iterator(); out.println("<td class=\"window-icon-left\">"); PortletModeLink mode; while (modesIt.hasNext()) { mode = (PortletModeLink) modesIt.next(); out.println("<a href=\"" + mode.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + mode.getImageSrc() + "\" title=\"" + mode.getAltTag() + "\"/></a>"); } out.println("</td>"); } // Invoke doTitle of portlet whose action was perfomed String actionStr = req.getParameter(GridSphereProperties.ACTION); out.println("<td class=\"window-title-name\">"); if (actionStr != null) { try { PortletInvoker.doTitle(portletClass, req, res); //out.println(" (" + portletMode.toString() + ") "); } catch (PortletException e) { errorMessage += "Unable to invoke doTitle on active portlet\n"; hasError = true; } } else { out.println(title); } out.println("</td>"); // Output window state icons if (windowLinks != null) { Iterator windowsIt = windowLinks.iterator(); PortletStateLink state; out.println("<td class=\"window-icon-right\">"); while (windowsIt.hasNext()) { state = (PortletStateLink) windowsIt.next(); out.println("<a href=\"" + state.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + state.getImageSrc() + "\" title=\"" + state.getAltTag() + "\"/></a>"); } out.println("</td>"); } out.println("</tr></table>"); out.println("</td></tr>"); } }
package net.gtaun.shoebill.common; import net.gtaun.util.event.EventManager; public class ShoebillContextManager extends AbstractShoebillContext { public ShoebillContextManager(EventManager parentEventManager) { super(parentEventManager); } @Override protected void onInit() { } @Override protected void onDestroy() { } public <ContextType extends AbstractShoebillContext> ContextType manage(ContextType context) { addDestroyable(context); context.init(); return context; } public void destroy(AbstractShoebillContext context) { context.destroy(); removeDestroyable(context); } }
/* * * Adafruit16CServoDriver * * TODO - test with Steppers & Motors - switches on board - interface accepts motor control * */ package org.myrobotlab.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.I2CControl; import org.myrobotlab.service.interfaces.I2CController; import org.myrobotlab.service.interfaces.MotorControl; import org.myrobotlab.service.interfaces.MotorController; import org.myrobotlab.service.interfaces.PinDefinition; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.ServoController; import org.slf4j.Logger; public class Adafruit16CServoDriver extends Service implements I2CControl, ServoController, MotorController { /** * SpeedControl, calculates the next position at regular intervals to make * the servo move at the desired speed * */ public class SpeedControl extends Thread { volatile ServoData servoData; String name; long now; long lastExecution; long deltaTime; public SpeedControl(String name) { super(String.format("%s.SpeedControl", name)); servoData = servoMap.get(name); servoData.isMoving = true; this.name = name; } @Override public void run() { log.info(String.format("Speed control started for %s", name)); servoData = servoMap.get(name); log.debug(String.format("Moving from %s to %s at %s degrees/second", servoData.currentOutput, servoData.targetOutput, servoData.velocity)); try { lastExecution = System.currentTimeMillis(); double _velocity; if (servoData.acceleration == -1) { _velocity = servoData.velocity; } else { _velocity = 0; } while (servoData.isMoving && servoData.isEnergized) { now = System.currentTimeMillis(); deltaTime = now - lastExecution; if (servoData.acceleration != -1) { _velocity = _velocity + (servoData.acceleration * deltaTime * 0.001); if (_velocity > servoData.velocity) { _velocity = servoData.velocity; } } if (servoData.currentOutput < servoData.targetOutput) { // Move // positive // direction servoData.currentOutput += (_velocity * deltaTime) * 0.001; if (servoData.currentOutput >= servoData.targetOutput) { servoData.currentOutput = servoData.targetOutput; servoData.isMoving = false; } } else if (servoData.currentOutput > servoData.targetOutput) { // Move // negative // direction servoData.currentOutput -= (_velocity * deltaTime * 0.001); if (servoData.currentOutput <= servoData.targetOutput) { servoData.currentOutput = servoData.targetOutput; servoData.isMoving = false; } } else { // We have reached the position so shutdown the thread servoData.isMoving = false; log.debug("This line should not repeat"); } int pulseWidthOff = SERVOMIN + (int) (servoData.currentOutput * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180)); setServo(servoData.pin, pulseWidthOff); // Sleep 100ms before sending next position lastExecution = now; log.info(String.format("Sent %s using a %s tick at velocity %s", servoData.currentOutput, deltaTime, _velocity)); Thread.sleep(50); } log.info("Shuting down SpeedControl"); } catch (Exception e) { servoData.isMoving = false; if (e instanceof InterruptedException) { log.debug("Shuting down SpeedControl"); } else { log.error("speed control threw", e); } } } } /** version of the library */ static public final String VERSION = "0.9"; private static final long serialVersionUID = 1L; // Depending on your servo make, the pulse width min and max may vary, you // want these to be as small/large as possible without hitting the hard stop // for max range. You'll have to tweak them as necessary to match the servos // you have! public final static int SERVOMIN = 150; // this // the // 'minimum' // pulse // length count (out of 4096) public final static int SERVOMAX = 600; // this // the // 'maximum' // pulse // length count (out of 4096) transient public I2CController controller; // Constant for default PWM freqency private static int defaultPwmFreq = 60; final static int minPwmFreq = 24; final static int maxPwmFreq = 1526; int pwmFreq; boolean pwmFreqSet = false; // List of possible addresses. Used by the GUI. public List<String> deviceAddressList = Arrays.asList("0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F"); // Default address public String deviceAddress = "0x40"; /** * This address is to address all Adafruit16CServoDrivers on the i2c bus * Don't use this address for any other device on the i2c bus since it will * cause collisions. */ public String broadcastAddress = "0x70"; public List<String> deviceBusList = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7"); public String deviceBus = "1"; public transient final static Logger log = LoggerFactory.getLogger(Adafruit16CServoDriver.class.getCanonicalName()); public static final int PCA9685_MODE1 = 0x00; // Mod // register public static final byte PCA9685_SLEEP = 0x10; // Set // sleep // mode, // before // changing // prescale // value public static final byte PCA9685_AUTOINCREMENT = 0x20; // Set // autoincrement // able // write // more // than // one // byte // sequence public static final byte PCA9685_PRESCALE = (byte) 0xFE; // PreScale // register // Pin PWM addresses 4 bytes repeats for each pin so I only define pin 0 // The rest of the addresses are calculated based on pin numbers public static final int PCA9685_LED0_ON_L = 0x06; // First // LED // address // Low public static final int PCA9685_LED0_ON_H = 0x07; // First // LED // address // High public static final int PCA9685_LED0_OFF_L = 0x08; // First // LED // address // Low public static final int PCA9685_LED0_OFF_H = 0x08; // First // LED // addressHigh // public static final int PWM_FREQ = 60; // default frequency for servos public static final float osc_clock = 25000000; // clock // frequency // the // internal // clock public static final float precision = 4096; // pwm_precision // i2c controller public List<String> controllers; public String controllerName; public boolean isControllerSet = false; /** * @Mats - added by GroG - was wondering if this would help, probably you * need a reverse index too ? * @GroG - I only need servoNameToPin yet. To be able to move at a set speed * a few extra values are needed */ class ServoData { int pin; SpeedControl speedcontrol; double velocity = -1; double acceleration = -1; boolean isMoving = false; double targetOutput; double currentOutput; boolean isEnergized = false; } transient HashMap<String, ServoData> servoMap = new HashMap<String, ServoData>(); // Motor related constants public static final int MOTOR_FORWARD = 1; public static final int MOTOR_BACKWARD = 0; public static final int defaultMotorPwmFreq = 1000; /** * pin named map of all the pins on the board */ Map<String, PinDefinition> pinMap = null; /** * the definitive sequence of pins - "true address" */ Map<Integer, PinDefinition> pinIndex = null; public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.DEBUG); Adafruit16CServoDriver driver = (Adafruit16CServoDriver) Runtime.start("pwm", "Adafruit16CServoDriver"); log.info("Driver {}", driver); } public Adafruit16CServoDriver(String n) { super(n); createPinList(); refreshControllers(); subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered"); } public void onRegistered(ServiceInterface s) { refreshControllers(); broadcastState(); } /* * Refresh the list of running services that can be selected in the GUI */ public List<String> refreshControllers() { controllers = Runtime.getServiceNamesFromInterface(I2CController.class); return controllers; } // TODO // Implement MotorController /** * This set of methods is used to set i2c parameters * * @param controllerName * = The name of the i2c controller * @param deviceBus * = i2c bus Should be "1" for Arduino and RasPi "0"-"7" for * I2CMux * @param deviceAddress * = The i2c address of the PCA9685 ( "0x40" - "0x5F") * @return */ // @Override public boolean setController(String controllerName, String deviceBus, String deviceAddress) { return setController((I2CController) Runtime.getService(controllerName), deviceBus, deviceAddress); } public boolean setController(String controllerName) { return setController((I2CController) Runtime.getService(controllerName), this.deviceBus, this.deviceAddress); } @Override public boolean setController(I2CController controller) { return setController(controller, this.deviceBus, this.deviceAddress); } public boolean setController(I2CController controller, String deviceBus, String deviceAddress) { if (controller == null) { error("setting null as controller"); return false; } controllerName = controller.getName(); log.info(String.format("%s setController %s", getName(), controllerName)); controllerName = controller.getName(); this.controller = controller; this.deviceBus = deviceBus; this.deviceAddress = deviceAddress; createDevice(); isControllerSet = true; broadcastState(); return true; } @Override public void setDeviceBus(String deviceBus) { this.deviceBus = deviceBus; broadcastState(); } @Override public void setDeviceAddress(String deviceAddress) { if (controller != null) { if (this.deviceAddress != deviceAddress) { controller.releaseI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress)); controller.i2cAttach(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress)); } } log.info(String.format("Setting device address to %s", deviceAddress)); this.deviceAddress = deviceAddress; } /** * This method creates the i2c device */ boolean createDevice() { if (controller != null) { // controller.releaseI2cDevice(this, Integer.parseInt(deviceBus), // Integer.decode(deviceAddress)); controller.i2cAttach(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress)); } else { log.error("Can't create device until the controller has been set"); return false; } log.info(String.format("Creating device on bus: %s address %s", deviceBus, deviceAddress)); return true; } // @Override // boolean DeviceControl.isAttached() public boolean isAttached() { return controller != null; } /** * Set the PWM pulsewidth * * @param pin * @param pulseWidthOn * @param pulseWidthOff */ public void setPWM(Integer pin, Integer pulseWidthOn, Integer pulseWidthOff) { byte[] buffer = { (byte) (PCA9685_LED0_ON_L + (pin * 4)), (byte) (pulseWidthOn & 0xff), (byte) (pulseWidthOn >> 8), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) }; log.info(String.format("Writing pin %s, pulesWidthOn %s, pulseWidthOff %s", pin, pulseWidthOn, pulseWidthOff)); controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length); } /** * Set the PWM frequency i.e. the frequency between positive pulses. * * @param hz */ public void setPWMFreq(int pin, Integer hz) { // Analog servos run at ~60 Hz float prescale_value; if (hz < minPwmFreq) { log.error(String.format("Minimum PWMFreq is %s Hz, requested freqency is %s Hz, clamping to minimum", minPwmFreq, hz)); hz = minPwmFreq; prescale_value = 255; } else if (hz > maxPwmFreq) { log.error(String.format("Maximum PWMFreq is %s Hz, requested frequency is %s Hz, clamping to maximum", maxPwmFreq, hz)); hz = maxPwmFreq; prescale_value = 3; } else { // Multiplying with factor 0.9 to correct the frequency prescale_value = Math.round(0.9 * osc_clock / precision / hz) - 1; } log.info(String.format("PWMFreq %s hz, prescale_value calculated to %s", hz, prescale_value)); // Set sleep mode before changing PWM freqency byte[] writeBuffer = { PCA9685_MODE1, PCA9685_SLEEP }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), writeBuffer, writeBuffer.length); // Wait 1 millisecond until the oscillator has stabilized try { Thread.sleep(1); } catch (InterruptedException e) { if (Thread.interrupted()) { // Clears interrupted status! } } // Write the PWM frequency value byte[] buffer2 = { PCA9685_PRESCALE, (byte) prescale_value }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer2, buffer2.length); // Leave sleep mode, set autoincrement to be able to write several // bytes // in sequence byte[] buffer3 = { PCA9685_MODE1, PCA9685_AUTOINCREMENT }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer3, buffer3.length); // Wait 1 millisecond until the oscillator has stabilized try { Thread.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block if (Thread.interrupted()) { // Clears interrupted status! } } pwmFreq = hz; pwmFreqSet = true; } public void setServo(Integer pin, Integer pulseWidthOff) { // since pulseWidthOff can be larger than > 256 it needs to be // sent as 2 bytes /* * log.debug( * String.format("setServo %s deviceAddress %s pin %s pulse %s", pin, * deviceAddress, pin, pulseWidthOff)); byte[] buffer = { (byte) * (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), * (byte) (pulseWidthOff >> 8) }; controller.i2cWrite(this, * Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, * buffer.length); */ setPWM(pin, 0, pulseWidthOff); } /** * this would have been nice to have Java 8 and a default implementation in * this interface which does Servo sweeping in the Servo (already * implemented) and only if the controller can does it do sweeping on the * "controller" * * For example MrlComm can sweep internally (or it used to be implemented) */ @Override public void servoSweepStart(ServoControl servo) { log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl"); } @Override public void servoSweepStop(ServoControl servo) { log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl"); } @Override public void servoMoveTo(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); if (!pwmFreqSet) { setPWMFreq(servoData.pin, defaultPwmFreq); } if (servoData.isEnergized) { // Move at max speed if (servoData.velocity == -1) { log.debug("Ada move at max speed"); servoData.currentOutput = servo.getTargetOutput(); servoData.targetOutput = servo.getTargetOutput(); log.debug(String.format("servoWrite %s deviceAddress %s targetOutput %f", servo.getName(), deviceAddress, servo.getTargetOutput())); int pulseWidthOff = SERVOMIN + (int) (servo.getTargetOutput() * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180)); setServo(servo.getPin(), pulseWidthOff); } else { log.debug(String.format("Ada move at velocity %s degrees/s", servoData.velocity)); servoData.targetOutput = servo.getTargetOutput(); // Start a thread to handle the speed for this servo if (servoData.isMoving == false) { servoData.speedcontrol = new SpeedControl(servo.getName()); servoData.speedcontrol.start(); } } } } @Override public void servoWriteMicroseconds(ServoControl servo, int uS) { ServoData servoData = servoMap.get(servo.getName()); if (!pwmFreqSet) { setPWMFreq(servoData.pin, defaultPwmFreq); } int pin = servo.getPin(); // 1000 ms => 150, 2000 ms => 600 int pulseWidthOff = (int) (uS * 0.45) - 300; // since pulseWidthOff can be larger than > 256 it needs to be // sent as 2 bytes log.debug(String.format("servoWriteMicroseconds %s deviceAddress x%02X pin %s pulse %d", servo.getName(), deviceAddress, pin, pulseWidthOff)); byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length); } /* @Override public DeviceController getController() { return controller; } */ /** * Device attach - this should be creating the I2C bus on MRLComm for the * "first" servo if not already created - Since this does not use the * Arduino <Servo.h> servos - it DOES NOT need to create "Servo" devices in * MRLComm. It will need to keep track of the "pin" to I2C address, and * whenever a ServoControl.moveTo(pos) - the Servo will tell this controller * its name & location to move. Mats says. The board has a single i2c * address that doesn't change. The Arduino only needs to keep track of the * i2c bus, not all devices that can communicate thru it. I.e. This service * should keep track of servos, not the Arduino or the Raspi. * * * This service will translate the name & location to an I2C address & value * write request to the MRLComm device. * * Mats comments on the above. MRLComm should not know anything about the * servos in this case. This service keeps track of the servos. MRLComm * should not know anything about what addresses are used on the i2c bus * MRLComm should initiate the i2c bus when it receives the first i2c write * or read This service knows nothing about other i2c devices that can be on * the same bus. And most important. This service knows nothing about * MRLComm at all. I.e except for this bunch of comments :-) * * It implements the methods defined in the ServoController and translates * the servo requests to i2c writes defined in the I2CControl interface * */ /** * if your device controller can provided several {Type}Controller * interfaces, there might be commonality between all of them. e.g. * initialization of data structures, preparing communication, sending * control and motor messages, etc.. - if there is commonality, it could be * handled here - where Type specific methods call this method * * This is a software representation of a board that uses the i2c protocol. * It uses the methods defined in the I2CController interface to write * servo-commands. The I2CController interface defines the common methods * for all devices that use the i2c protocol. In most services I will define * addition <device>Control methods, but this service is a "middle man" so * it implements the ServoController methods and should not have any "own" * methods. * * After our explanation of the roles of <device>Control and * <device>Controller it's clear to me that any device that uses the i2c * protocol needs to implement to <device>Control methods: I2CControl that * is the generic interface for any i2c device <device>Control, that defines * the specific methods for that device. For example the MPU6050 should * implement both I2CControl and MPU6050Control or perhaps a AccGyroControl * interface that would define the common methods that a * Gyro/Accelerometer/Magnetometer device should implement. */ @Deprecated // use attach(ServoControl servo) void servoAttach(ServoControl device, Object... conf) { ServoControl servo = (ServoControl) device; // should initial pos be a requirement ? // This will fail because the pin data has not yet been set in Servo // servoNameToPin.put(servo.getName(), servo.getPin()); String servoName = servo.getName(); ServoData servoData = new ServoData(); servoData.pin = (int) conf[0]; servoMap.put(servoName, servoData); invoke("publishAttachedDevice", servoName); } public void attachServoControl(ServoControl servo) throws Exception { if (isAttachedServoControl(servo)) { log.info("servo {} already attached", servo.getName()); return; } ServoData servoData = new ServoData(); servoData.pin = servo.getPin(); servoData.targetOutput = servo.getTargetOutput(); servoData.velocity = servo.getVelocity(); servoData.isEnergized = true; servoMap.put(servo.getName(), servoData); servo.attachServoController(this); } public boolean isAttachedServoControl(Attachable device) { return servoMap.containsKey(device.getName()); } public void motorAttach(MotorControl device) { /* * This is where motor data could be initialized. So far all motor data * this service needs can be requested from the motors motor */ MotorControl motor = (MotorControl) device; invoke("publishAttachedDevice", motor.getName()); } public void detach(Attachable servo) { servoDetachPin((ServoControl) servo); servoMap.remove(servo.getName()); } public String publishAttachedDevice(String deviceName) { return deviceName; } /** * Start sending pulses to the servo * */ @Override public void servoAttachPin(ServoControl servo, int pin) { ServoData servoData = servoMap.get(servo.getName()); servoData.pin = pin; // servoData.isEnergized = true; // servoMoveTo(servo); } /** * Stop sending pulses to the servo, relax */ @Override public void servoDetachPin(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); setPWM(servoData.pin, 4096, 0); servoData.isEnergized = false; } public void servoSetMaxVelocity(ServoControl servo) { // TODO Auto-generated method stub. // perhaps cannot do this with Adafruit16CServoDriver // Mats says: It can be done in this service. But not by the board. log.warn("servoSetMaxVelocity not implemented in Adafruit16CServoDriver"); } @Override public void motorMove(MotorControl mc) { Class<?> type = mc.getClass(); double powerOutput = mc.getPowerOutput(); if (Motor.class == type) { Motor motor = (Motor) mc; if (motor.getPwmFreq() == null) { motor.setPwmFreq(defaultMotorPwmFreq); setPWMFreq(motor.getPwrPin(), motor.getPwmFreq()); } setPinValue(motor.getDirPin(), (powerOutput < 0) ? MOTOR_BACKWARD : MOTOR_FORWARD); setPinValue(motor.getPwrPin(), powerOutput); } else if (MotorDualPwm.class == type) { MotorDualPwm motor = (MotorDualPwm) mc; log.info(String.format("Adafrutit16C Motor DualPwm motorMove, powerOutput = %s", powerOutput)); if (motor.getPwmFreq() == null) { motor.setPwmFreq(defaultMotorPwmFreq); setPWMFreq(motor.getLeftPwmPin(), motor.getPwmFreq()); setPWMFreq(motor.getRightPwmPin(), motor.getPwmFreq()); } if (powerOutput < 0) { setPinValue(motor.getLeftPwmPin(), 0); setPinValue(motor.getRightPwmPin(), Math.abs(powerOutput / 255)); } else if (powerOutput > 0) { setPinValue(motor.getRightPwmPin(), 0); setPinValue(motor.getLeftPwmPin(), Math.abs(powerOutput / 255)); } else { setPinValue(motor.getRightPwmPin(), 0); setPinValue(motor.getLeftPwmPin(), 0); } } else { error("motorMove for motor type %s not supported", type); } } @Override public void motorMoveTo(MotorControl mc) { // speed parameter? // modulo - if < 1 // speed = 1 else log.info("motorMoveTo targetPos {} powerLevel {}", mc.getTargetPos(), mc.getPowerLevel()); Class<?> type = mc.getClass(); // if pulser (with or without fake encoder // send a series of pulses ! // with current direction if (Motor.class == type) { Motor motor = (Motor) mc; // check motor direction // send motor direction // TODO powerLevel = 100 * powerlevel // FIXME !!! - this will have to send a Long for targetPos at some // point !!!! double target = Math.abs(motor.getTargetPos()); int b0 = (int) target & 0xff; int b1 = ((int) target >> 8) & 0xff; int b2 = ((int) target >> 16) & 0xff; int b3 = ((int) target >> 24) & 0xff; // TODO FIXME // sendMsg(PULSE, deviceList.get(motor.getName()).id, b3, b2, b1, // b0, (int) motor.getPowerLevel(), feedbackRate); } } @Override public void motorStop(MotorControl mc) { Class<?> type = mc.getClass(); if (Motor.class == type) { Motor motor = (Motor) mc; if (motor.getPwmFreq() == null) { motor.setPwmFreq(defaultMotorPwmFreq); setPWMFreq(motor.getPwrPin(), motor.getPwmFreq()); } setPinValue(motor.getPwrPin(), 0); } else if (MotorDualPwm.class == type) { MotorDualPwm motor = (MotorDualPwm) mc; setPinValue(motor.getLeftPwmPin(), 0); setPinValue(motor.getRightPwmPin(), 0); } } @Override public void motorReset(MotorControl motor) { // perhaps this should be in the motor control // motor.reset(); // opportunity to reset variables on the controller // sendMsg(MOTOR_RESET, motor.getind); } public void setPinValue(int pin, double powerOutput) { log.info(String.format("Adafruit16C setPinValue, pin = %s, powerOutput = %s", pin, powerOutput)); if (powerOutput < 0) { log.error(String.format("Adafruit16CServoDriver setPinValue. Value below zero (%s). Defaulting to 0.", powerOutput)); powerOutput = 0; } else if (powerOutput > 1) { log.error(String.format("Adafruit16CServoDriver setPinValue. Value > 1 (%s). Defaulting to 1", powerOutput)); powerOutput = 1; } int powerOn; int powerOff; // No phase shift. Simple calculation if (powerOutput == 0) { powerOn = 4096; powerOff = 0; } else if (powerOutput == 1) { powerOn = 0; powerOff = 1; } else { powerOn = (int) (powerOutput * 4096); powerOff = 4095; } log.info(String.format("powerOutput = %s, powerOn = %s, powerOff = %s", powerOutput, powerOn, powerOff)); setPWM(pin, powerOn, powerOff); } public Map<String, PinDefinition> createPinList() { pinIndex = new HashMap<Integer, PinDefinition>(); for (int i = 0; i < 16; ++i) { PinDefinition pindef = new PinDefinition(); String name = null; name = String.format("D%d", i); pindef.setDigital(true); pindef.setName(name); pindef.setAddress(i); pinIndex.put(i, pindef); } return pinMap; } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Adafruit16CServoDriver.class.getCanonicalName()); meta.addDescription("Adafruit 16-Channel PWM/Servo Driver"); meta.addCategory("shield", "servo & pwm"); meta.setSponsor("Mats"); /* * meta.addPeer("arduino", "Arduino", "our Arduino"); * meta.addPeer("raspi", "RasPi", "our RasPi"); */ return meta; } @Override public void servoSetVelocity(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); servoData.velocity = servo.getVelocity(); } @Override public void attach(ServoControl servo, int pin) throws Exception { servo.setPin(pin); attachServoControl(servo); } /** * we can only have one controller for this control - so it's easy - just * detach */ // TODO - this could be Java 8 default interface implementation @Override public void detach(String controllerName) { if (controller == null || !controllerName.equals(controller.getName())) { return; } controller.detach(this); controller = null; this.deviceBus = null; this.deviceAddress = null; isControllerSet = false; broadcastState(); } @Override public Set<String> getAttached() { HashSet<String> ret = new HashSet<String>(); if (controller != null) { ret.add(controller.getName()); } ret.addAll(servoMap.keySet()); return ret; } @Override public void servoSetAcceleration(ServoControl servo) { ServoData servoData = servoMap.get(servo.getName()); servoData.acceleration = servo.getAcceleration(); } public List<PinDefinition> getPinList() { List<PinDefinition> list = new ArrayList<PinDefinition>(pinIndex.values()); pinMap = new TreeMap<String, PinDefinition>(); pinIndex = new TreeMap<Integer, PinDefinition>(); List<PinDefinition> pinList = new ArrayList<PinDefinition>(); for (int i = 0; i < 15; ++i) { PinDefinition pindef = new PinDefinition(); // begin wacky pin def logic String pinName = String.format("D%d", i); pindef.setName(pinName); pindef.setRx(false); pindef.setDigital(true); pindef.setAnalog(true); pindef.setDigital(true); pindef.canWrite(true); pindef.setPwm(true); pindef.setAddress(i); pinIndex.put(i, pindef); pinMap.put(pinName, pindef); pinList.add(pindef); } return list; } /* @Override public boolean isAttached(String name) { return (controller != null && controller.getName().equals(name) || servoMap.containsKey(name)); } */ @Override public boolean isAttached(Attachable instance) { return (controller != null && controller.getName().equals(instance.getName())); } @Override public void attach(Attachable service) throws Exception { if (ServoControl.class.isAssignableFrom(service.getClass())) { attachServoControl((ServoControl) service); return; } } }
package net.imagej.ops.filter.fft; import net.imagej.ops.Ops; import net.imagej.ops.special.function.AbstractBinaryFunctionOp; import net.imagej.ops.special.function.BinaryFunctionOp; import net.imagej.ops.special.function.Functions; import net.imglib2.Dimensions; import net.imglib2.img.Img; import net.imglib2.type.NativeType; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Function that creates an output for FFTMethods FFT * * @author Brian Northan * @param <T> */ @Plugin(type = Ops.Filter.CreateFFTOutput.class) public class CreateOutputFFTMethods<T> extends AbstractBinaryFunctionOp<Dimensions, T, Img<T>> implements Ops.Filter.CreateFFTOutput { @Parameter(required = false) private boolean fast = true; private BinaryFunctionOp<Dimensions, T, Img<T>> create; @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void initialize() { super.initialize(); create = (BinaryFunctionOp) Functions.unary(ops(), Ops.Create.Img.class, Img.class, Dimensions.class, NativeType.class); } @Override public Img<T> compute2(Dimensions paddedDimensions, T outType) { Dimensions paddedFFTMethodsFFTDimensions = FFTMethodsUtility .getFFTDimensionsRealToComplex(fast, paddedDimensions); return create.compute2(paddedFFTMethodsFFTDimensions, outType); } }
package net.ja731j.twitter.autoreply.command; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import net.ja731j.twitter.autoreply.MyStreamAdapter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.UserMentionEntity; public class FoodCommand extends BaseCommand { private final Pattern commandPattern = Pattern.compile("^@ja731j coop_food$"); private final Pattern englishPattern = Pattern.compile("[(][\\p{Alnum}\\p{Space},.'-()]+[)]"); @Override public boolean verifySyntax(Status status) { boolean result = false; ArrayList<UserMentionEntity> mentionList = new ArrayList<>(Arrays.asList(status.getUserMentionEntities())); for (UserMentionEntity e : mentionList) { if (e.getScreenName().equalsIgnoreCase("ja731j")) { result = commandPattern.matcher(status.getText()).matches(); } } return result; } @Override public StatusUpdate execute(Status status) { try { String result = "@" + status.getUser().getScreenName() + " \n\n"; List<Map.Entry<String, Integer>> items = fetchMenu(); int total = 0; for (Map.Entry<String, Integer> item : items) { result = result.concat(String.format("%s(%d)\n", item.getKey(), item.getValue())); total += item.getValue(); } result = result.concat(String.format("%d", total)); return new StatusUpdate(result).inReplyToStatusId(status.getId()); } catch (IOException ex) { Logger.getLogger(MyStreamAdapter.class.getName()).log(Level.SEVERE, null, ex); } return createReply(status, ""); } protected List<Map.Entry<String, Integer>> fetchMenu() throws IOException { List<Map.Entry<String, Integer>> result = new ArrayList<>(); Document doc = Jsoup.connect("http://gakushoku.coop/setmenu.php?feeling=C&price=500").get(); Element list = doc.getElementById("setList"); //Get name and price for each item for (Element item : list.select(":root > li")) { //Get name Elements e = item.getElementsByClass("menuphoto").first().getElementsByAttribute("alt"); String name = englishPattern.matcher(e.last().attr("alt")).replaceAll(""); //Get price int price = Integer.parseInt(item.getElementsByClass("tt-prices").first().text().replace("", "")); result.add(new AbstractMap.SimpleEntry<>(name, price)); } return result; } }
package org.pentaho.ui.xul.swing.tags; import java.awt.GridBagLayout; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JPanel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.components.XulRadioGroup; import org.pentaho.ui.xul.swing.SwingElement; import org.pentaho.ui.xul.util.Orient; /** * @author aphillips * */ public class SwingRadioGroup extends SwingElement implements XulRadioGroup { private static final Log logger = LogFactory.getLog(SwingRadioGroup.class); private ButtonGroup buttonGroup = new ButtonGroup(); public SwingRadioGroup(XulComponent parent, XulDomContainer domContainer, String tagName) { super("radiogroup"); container = new JPanel(new GridBagLayout()); managedObject = container; resetContainer(); } @Override public void addComponent(XulComponent c) { addComponentToButtonGroup(c); super.addComponent(c); } protected void addComponentToButtonGroup(XulComponent c) { for(XulComponent child : c.getChildNodes()) { addComponentToButtonGroup(child); } if(AbstractButton.class.isAssignableFrom(c.getManagedObject().getClass())) { this.buttonGroup.add((AbstractButton)c.getManagedObject()); } } @Override public Orient getOrientation() { return Orient.VERTICAL; } }
package net.nickac.lithium.frontend.mod.ui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.*; import net.nickac.lithium.backend.controls.LControl; import net.nickac.lithium.backend.controls.impl.*; import net.nickac.lithium.backend.other.objects.Point; import net.nickac.lithium.frontend.mod.LithiumMod; import net.nickac.lithium.frontend.mod.network.LithiumMessage; import net.nickac.lithium.frontend.mod.ui.renders.ProgressBarRender; import net.nickac.lithium.frontend.mod.utils.NickHashMap; import java.io.IOException; import java.util.*; import static net.nickac.lithium.backend.other.LithiumConstants.*; public class NewLithiumGUI extends GuiScreen { private static ProgressBarRender progressBarRender = new ProgressBarRender(); //The base window private LWindow baseWindow; private Map<UUID, GuiTextField> textBoxes = new HashMap<>(); private Map<Integer, UUID> textBoxesReverse = new HashMap<>(); private Map<UUID, LTextBox> textBoxesLReverse = new HashMap<>(); private Map<UUID, LProgressBar> progressBars = new NickHashMap<>(); //Button stuff //We take a global count number and give a Lithium button private Map<Integer, LButton> buttonsCounter = new HashMap<>(); //We take an UUID (of a control) and we get the global count button private Map<UUID, Integer> reverseLButtonsCounter = new HashMap<>(); //We take a global count button and give a GuiButton id private Map<Integer, Integer> reverseButtonsCounter = new HashMap<>(); //Labels to be rendered! private List<LTextLabel> labelsToRender = new ArrayList<>(); private int globalCounter = 0; private int BUTTON_HEIGHT = 20; public NewLithiumGUI(LWindow base) { this.baseWindow = base; } public LWindow getBaseWindow() { return baseWindow; } /** * Get the center location of control.<br> * Width and height are taken in account. * * @param s - scaled size * @param w - size * @param x - original coordinate * @param centered Is the control centered * @return the corrdinate on the screen */ private int centerLoc(LControl c, int s, int w, int x, boolean centered, boolean atX) { /* int parentLeft = c.getParent() != null && c.getParent() instanceof LControl ? ((LControl) c.getParent()).getLeft() : 0; int parentTop = c.getParent() != null && c.getParent() instanceof LControl ? ((LControl) c.getParent()).getTop() : 0; */ if (centered) { return (s / 2) - (w / 2); } return x; } /** * Goes thru all controls and adds them to the gui * * @param ctrls The collection of Lithium controls to be added. */ private void allControls(Collection<LControl> ctrls) { for (LControl c : ctrls) { addControlToGUI(c); } } private Point centerControl(LControl c) { Point parentLoc = (c.getParent() != null) && (c.getParent() instanceof LControl) && !(c.getParent() instanceof LWindow) ? centerControl((LControl) c.getParent()) : Point.EMPTY; if (c.getCentered() == LControl.CenterOptions.NONE) { return new Point(parentLoc.getX() + c.getLeft(), parentLoc.getY() + c.getTop()); } ScaledResolution sr = getScaledResolution(); int parentWidth = sr.getScaledWidth(); int parentHeight = sr.getScaledHeight(); /*if ((c.getParent() != null) && (c.getParent() instanceof LControl) && !(c.getParent() instanceof LWindow)) { parentWidth = c.getParent() instanceof LPanel ? ((LPanel) c.getParent()).getTotalWidth() : ((LControl) c.getParent()).getSize().getWidth(); parentHeight = c.getParent() instanceof LPanel ? ((LPanel) c.getParent()).getTotalHeight() : ((LControl) c.getParent()).getSize().getWidth(); }*/ int newX = parentLoc.getX() + c.getLocation().getX(); int newY = parentLoc.getY() + c.getLocation().getY(); int sizeW = c instanceof LPanel ? ((LPanel) c).getTotalWidth() : c.getSize().getWidth(); int sizeH = c instanceof LPanel ? ((LPanel) c).getTotalHeight() : c.getSize().getHeight(); boolean centeredX = c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.VERTICAL; boolean centeredY = c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.HORIZONTAL; if (centeredX) newX = parentLoc.getX() + (parentWidth / 2) - (sizeW / 2); if (centeredX) newY = parentLoc.getY() + (parentHeight / 2) - (sizeH / 2); return new Point(newX, newY); } Point addOffset = Point.EMPTY; /** * Adds a Lithium control to the GUI.<br> * This is the method that does the heavy lifting.. * * @param c Control to be added * @SuppressWarnings("ConstantConditions") */ public void addControlToGUI(LControl c) { //Get scaled resolutin //ScaledResolution sr = getScaledResolution(); //Here we check if control is a panel, and if it is, check if it's centered on x or y axis. boolean centeredX = c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.VERTICAL; boolean centeredY = c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.HORIZONTAL; //Then we finally calculate the location of the control. //Minecraft has some limitations regarding button height, so it's always equal to the constant Point newLoc = centerControl(c); int controlX = newLoc.getX();/*centerLoc(c, c.getParent() instanceof LWindow ? sr.getScaledWidth() : (c.getParent() instanceof LControl ? ((LControl) c.getParent()).getSize().getWidth() : sr.getScaledWidth()), c.getClass().equals(LPanel.class) ? ((LPanel) c).getTotalWidth() : c.getSize().getWidth(), c.getLeft(), centeredX, true);*/ int controlY = newLoc.getY();/*centerLoc(c, sr.getScaledHeight(), ((c.getClass().equals(LButton.class)) ? BUTTON_HEIGHT : (c.getClass().equals(LPanel.class) ? ((LPanel) c).getTotalHeight() : c.getSize().getHeight())), c.getTop(), centeredY, false);*/ if (centeredX || centeredY) { //c.setLocation(new Point(controlX, controlY)); } //The cool part! //Adding the control if (c.getClass().equals(LPanel.class)) { LPanel pnl = (LPanel) c; /*Point original = c.getLocation(); pnl.setLocation(new Point(controlX, controlY));*/ for (LControl lControl : pnl.getControls()) { addControlToGUI(lControl); } // pnl.setLocation(original); } else if (c.getClass().equals(LButton.class)) { LButton b = (LButton) c; GuiButton bb = generateGuiButton(b); addButton(bb); buttonsCounter.put(globalCounter, b); reverseLButtonsCounter.put(b.getUUID(), bb.id); reverseButtonsCounter.put(bb.id, globalCounter); } else if (c.getClass().equals(LTextLabel.class)) { LTextLabel lbl = (LTextLabel) c; if (!labelsToRender.contains(lbl)) { labelsToRender.add(lbl); } } else if (c.getClass().equals(LTextBox.class)) { GuiTextField txt = new GuiTextField(globalCounter, Minecraft.getMinecraft().fontRenderer, controlX, c.getTop(), c.getSize().getWidth(), c.getSize().getHeight()); txt.setText(c.getText() != null ? c.getText() : ""); textBoxes.put(c.getUUID(), txt); textBoxesReverse.put(txt.getId(), c.getUUID()); textBoxesLReverse.put(c.getUUID(), (LTextBox) c); } else if (c.getClass().equals(LProgressBar.class)) { progressBars.put(c.getUUID(), (LProgressBar) c); } if (c.getParent() == null || (c.getParent() != null && c.getParent().equals(baseWindow))) { baseWindow.addControl(c); } globalCounter++; } @Override public void updateScreen() { super.updateScreen(); textBoxes.values().forEach(GuiTextField::updateCursorCounter); } @Override protected void keyTyped(char typedChar, int keyCode) throws IOException { super.keyTyped(typedChar, keyCode); textBoxes.values().forEach(t -> { if (t.isFocused()) { if (t.textboxKeyTyped(typedChar, keyCode)) { LTextBox lTextBox = textBoxesLReverse.get(textBoxesReverse.get(t.getId())); if (lTextBox != null) { LithiumMod.getSimpleNetworkWrapper().sendToServer(new LithiumMessage(LITHIUM_TEXTBOX_TEXT_CHANGED + lTextBox.getUUID() + "|" + t.getText())); } } } }); } private boolean isCenteredX(LControl c) { return c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.VERTICAL; } private boolean isCenteredY(LControl c) { return c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.HORIZONTAL; } public void removeControl(LControl g) { baseWindow.removeControl(g); softRemoveControl(g); } private GuiButton generateGuiButton(LButton b) { ScaledResolution sr = getScaledResolution(); /* int parentOffsetX = (b.getParent() instanceof LControl) ? ((LControl) b.getParent()).getLeft() : 0; int parentOffsetY = (b.getParent() instanceof LControl) ? ((LControl) b.getParent()).getTop() : 0; */ int controlX = centerLoc(b, sr.getScaledWidth(), b.getSize().getWidth(), b.getLeft(), isCenteredX(b), true); int controlY = centerLoc(b, sr.getScaledHeight(), BUTTON_HEIGHT, b.getTop(), isCenteredY(b), false); return new GuiButton(globalCounter, controlX, controlY, b.getSize().getWidth(), BUTTON_HEIGHT, b.getText()); } @Override public void initGui() { //We need to clear the button list //buttonList.clear(); baseWindow.getControls().forEach(this::softRemoveControl); //Then we need to initialize the gui super.initGui(); //Then we need to register the window LithiumMod.getWindowManager().registerWindow(baseWindow); //Then we set the current Lithium GUI to this. LithiumMod.setCurrentLithium(this); //Then we add all controls to gui allControls(baseWindow.getControls()); } /** * Removes a Lithium control from the GUI * * @param g The control that will be removed */ private void softRemoveControl(LControl g) { if (g.getClass().equals(LTextBox.class)) { for (GuiTextField gg : textBoxes.values()) { UUID txtUUID = textBoxesReverse.getOrDefault(gg.getId(), null); if (txtUUID != null && g.getUUID().equals(txtUUID)) { textBoxesReverse.remove(gg.getId()); textBoxesLReverse.remove(txtUUID); textBoxes.remove(txtUUID); } } } else if (g.getClass().equals(LButton.class)) { for (GuiButton guiButton : buttonList) { if (guiButton.id == reverseLButtonsCounter.get(g.getUUID())) { Integer id = reverseButtonsCounter.get(guiButton.id); buttonsCounter.remove(id); reverseLButtonsCounter.remove(g.getUUID()); reverseButtonsCounter.remove(guiButton.id); buttonList.remove(guiButton); break; } } } else if (g.getClass().equals(LTextLabel.class)) { for (LTextLabel lTextLabel : labelsToRender) { if (lTextLabel.getUUID().equals(g.getUUID())) { labelsToRender.remove(lTextLabel); break; } } } else if (g.getClass().equals(LPanel.class)) { LPanel p = (LPanel) g; p.getControls().forEach(this::softRemoveControl); } else if (g.getClass().equals(LProgressBar.class)) { progressBars.remove(g.getUUID()); } } @Override public void onGuiClosed() { super.onGuiClosed(); //We can unregister the window, because everything has an UUID, and it wouldn't make sense to reuse a window or its controls. LithiumMod.getWindowManager().unregisterWindow(baseWindow); //Then we need to the server that the window was closed (event) LithiumMod.getSimpleNetworkWrapper().sendToServer(new LithiumMessage(LITHIUM_WINDOW_CLOSE + baseWindow.getUUID())); //Then, we can "safely" set the current LithiumGUI to null. LithiumMod.setCurrentLithium(null); } @Override public boolean doesGuiPauseGame() { return true; } @Override protected void actionPerformed(GuiButton button) throws IOException { super.actionPerformed(button); //Get the id of the button. It's safer to use and store the button's own id(integer) instead of the instance itself. int buttonId = reverseButtonsCounter.getOrDefault(button.id, -1); //If we have a button, we send an event to the server with the UUID of the LButton instance. //Later, it will invoke an event on the spigot side. if (buttonId != -1) { LithiumMod.getSimpleNetworkWrapper().sendToServer(new LithiumMessage(LITHIUM_BUTTON_ACTION + buttonsCounter.get(buttonId).getUUID())); } } /** * Returns a new scaled resolution from Minecraft.<br> * This method exists to easier backport of the mod.<br> * Between versions, the constructor was changed and * * @return A new scaled resolution object */ private ScaledResolution getScaledResolution() { return new ScaledResolution(Minecraft.getMinecraft()); } private FontRenderer getFontRenderer() { return Minecraft.getMinecraft().fontRenderer; } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { super.mouseClicked(mouseX, mouseY, mouseButton); textBoxes.values().forEach(t -> t.mouseClicked(mouseX, mouseY, mouseButton)); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { //Just get a scaled resolution ScaledResolution sr = getScaledResolution(); //Then we draw a background to make it easier to see this.drawDefaultBackground(); /* for (Object lControl : baseWindow.getControls().stream().filter(cc -> cc instanceof LPanel).toArray()) { LPanel p = (LPanel) lControl; drawRect(p.getLeft(), p.getTop(), p.getLeft() + p.getTotalWidth(), p.getTop() + p.getTotalHeight(), (int) Color.WHITE.getHexColor()); for (Object l2 : p.getControls().stream().filter(cc -> cc instanceof LPanel).toArray()) { LPanel p2 = (LPanel) l2; drawRect(p2.getLeft(), p2.getTop(), p2.getLeft() + p2.getTotalWidth(), p2.getTop() + p2.getTotalHeight(), (int) Color.GRAY.getHexColor()); } }*/ //Then, we render all textboxes textBoxes.values().forEach(GuiTextField::drawTextBox); //Then we render the labels for (LTextLabel l : labelsToRender) { //Since the labels aren't a real GUI control on forge, we must calculate the location independently. int width = getFontRenderer().getStringWidth(l.getText()); int height = getFontRenderer().FONT_HEIGHT; drawString(getFontRenderer(), l.getText(), centerLoc(l, sr.getScaledWidth(), width, l.getLeft(), isCenteredX(l), true), centerLoc(l, sr.getScaledWidth(), height, l.getTop(), isCenteredY(l), false), (int) l.getColor().getHexColor()); } progressBars.values().forEach(l -> progressBarRender.renderLithiumControl(l, this)); super.drawScreen(mouseX, mouseY, partialTicks); } }
package org.shaman.terrain.polygonal; import Jama.Matrix; import com.jme3.app.Application; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Spatial; import com.jme3.scene.VertexBuffer; import com.jme3.texture.FrameBuffer; import com.jme3.texture.Image; import com.jme3.util.BufferUtils; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.*; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import org.apache.commons.lang3.ArrayUtils; import org.shaman.terrain.AbstractTerrainStep; import org.shaman.terrain.Heightmap; import org.shaman.terrain.Vectorfield; import org.shaman.terrain.heightmap.Noise; import org.shaman.terrain.sketch.SketchTerrain; /** * Converts the graph to a heightmap.<br> * Input: a {@link Graph} with all the informations of elevation, temperature, * moisture, biomes.<br> * Output: a {@link Map} object with the heightmap, temperature and moisture * stored in {@link Heightmap} instances, using the keys from * {@link AbstractTerrainStep}. * * @author Sebastian Weiss */ public class GraphToHeightmap { private static final Logger LOG = Logger.getLogger(GraphToHeightmap.class.getName()); /** * Maps the biomes to noise amplitude (0), noise roughness (1), * voronoi amplitude (2) and the factor of the height on the voronoi amplitude(3) */ private static final EnumMap<Biome, double[]> BIOME_PROPERTIES = new EnumMap<>(Biome.class); static { BIOME_PROPERTIES.put(Biome.SNOW, new double[]{0.5, 0.7, 0.7, 0.5}); BIOME_PROPERTIES.put(Biome.TUNDRA, new double[]{0.5, 0.5, 0.5, 0.5}); BIOME_PROPERTIES.put(Biome.BARE, new double[]{0.4, 0.4, 0.5, 0.5}); BIOME_PROPERTIES.put(Biome.SCORCHED, new double[]{0.7, 0.3, 0, 0}); BIOME_PROPERTIES.put(Biome.TAIGA, new double[]{0.4, 0.3, 0, 0}); BIOME_PROPERTIES.put(Biome.SHRUBLAND, new double[]{0.5, 0.2, 0, 0}); BIOME_PROPERTIES.put(Biome.TEMPERATE_DESERT, new double[]{0.1, 0.1, 0.3, 0}); BIOME_PROPERTIES.put(Biome.TEMPERATE_RAIN_FOREST, new double[]{0.3, 0.2, 0, 0}); BIOME_PROPERTIES.put(Biome.TEMPERATE_DECIDUOUS_FOREST, new double[]{0.3, 0.4, 0, 0}); BIOME_PROPERTIES.put(Biome.GRASSLAND, new double[]{0.4, 0.5, 0, 0}); BIOME_PROPERTIES.put(Biome.TROPICAL_RAIN_FOREST, new double[]{0.3, 0.2, 0.05, 0}); BIOME_PROPERTIES.put(Biome.TROPICAL_SEASONAL_FOREST, new double[]{0.3, 0.2, 0, 0}); BIOME_PROPERTIES.put(Biome.SUBTROPICAL_DESERT, new double[]{0.3, 0.6, 0.3, 0}); BIOME_PROPERTIES.put(Biome.BEACH, new double[]{0.3, 0.5, 0.1, 0}); BIOME_PROPERTIES.put(Biome.LAKE, new double[]{0.2, 0.2, 0, 0}); BIOME_PROPERTIES.put(Biome.OCEAN, new double[]{0.2, 0.1, 0, 0}); } private static final int NOISE_OCTAVES = 6; private static final float NOISE_OCTAVE_FACTOR = 2; private static final float BASE_FREQUENCY = 1/32f; private static final float PERLIN_NOISE_SCALE = 0.2f; private static final float DISTORTION_FREQUENCY = 32; private static final float DISTORTION_AMPLITUDE = 0.01f; private static final float SMOOTHING_STEPS = 10; private static final int[][] NEIGHBORS = new int[][]{ {1, -1}, {1, 0}, {1, 1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {0, -1} }; private static final int VORONOI_CELL_COUNT = 32; private static final int VORONOI_POINTS_PER_CELL = 3; private static final float VORONOI_DISTORTION_FREQUENCY = 32; private static final float VORONOI_DISTORTION_AMPLITUDE = 0;//0.01f; private static final float VORONOI_SCALE = 1.5f; private static final float BIOMES_DISTORTION_FREQUENCY = 32; private static final float BIOMES_DISTORTION_AMPLITUDE = 0.005f; private static final double HEIGHT_SCALING = 1.5; //Input private final Graph graph; private final int size; private final Application app; private final Random rand; //Output private final Heightmap heightmap; private final Heightmap temperature; private final Heightmap moisture; private final Vectorfield biomes; private final Map<Object, Object> properties; //temporal values private float[][][] noise; public GraphToHeightmap(Graph graph, int size, Application app, long seed) { this.graph = graph; this.size = size; this.app = app; this.rand = new Random(seed); heightmap = new Heightmap(size); temperature = new Heightmap(size); moisture = new Heightmap(size); biomes = new Vectorfield(size, Biome.values().length); properties = new HashMap<>(); properties.put(AbstractTerrainStep.KEY_HEIGHTMAP, heightmap); properties.put(AbstractTerrainStep.KEY_TEMPERATURE, temperature); properties.put(AbstractTerrainStep.KEY_MOISTURE, moisture); properties.put(AbstractTerrainStep.KEY_BIOMES, biomes); // properties.put("PolygonalGraph", graph); //for backup calculate(); } public Map<Object, Object> getResult() { return properties; } private void calculate() { calculateTemperatureAndMoisture(); calculateElevation(); calculateBiomeVectorfield(); // saveMaps(); } private void calculateElevation() { calculateBaseElevation(); //get noise parameters Geometry geom = createNoiseGeometry(); noise = new float[size][size][4]; renderColor(noise, geom, ColorRGBA.Black, 0, 1); LOG.info("noise properties calculated"); addPerlinNoise(); // addVoronoiNoise(); } private void addPerlinNoise() { float[] perlinFactors = new float[NOISE_OCTAVES]; Noise[] noiseGenerators = new Noise[NOISE_OCTAVES]; for (int i=0; i<NOISE_OCTAVES; ++i) { noiseGenerators[i] = new Noise(rand.nextLong()); perlinFactors[i] = (float) (BASE_FREQUENCY * Math.pow(NOISE_OCTAVE_FACTOR, i)); } Heightmap values = new Heightmap(size); float min = Float.POSITIVE_INFINITY; float max = Float.NEGATIVE_INFINITY; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float roughness = noise[x][y][1]; //multi-fractal perlin noise double perlin = 0; for (int i=0; i<NOISE_OCTAVES; ++i) { perlin += noiseGenerators[i].noise(perlinFactors[i]*x, perlinFactors[i]*y) / Math.pow(NOISE_OCTAVE_FACTOR, i*(1-roughness)); } values.setHeightAt(x, y, (float) perlin); min = (float) Math.min(perlin, min); max = (float) Math.max(perlin, max); } } float factor = 1f / (max-min); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float amplitude = noise[x][y][0]; float perlin = (values.getHeightAt(x, y) - min) * factor; perlin *= amplitude * PERLIN_NOISE_SCALE; heightmap.adjustHeightAt(x, y, perlin); } } LOG.info("perlin noise added"); } private void addVoronoiNoise() { float cellSize = (float) size / (float) VORONOI_CELL_COUNT; List<Vector3f> pointList = new ArrayList<>(); for (int x=0; x<VORONOI_CELL_COUNT; ++x) { for (int y=0; y<VORONOI_CELL_COUNT; ++y) { float nx = x*cellSize; float ny = y*cellSize; for (int i=0; i<VORONOI_POINTS_PER_CELL; ++i) { pointList.add(new Vector3f( nx + rand.nextFloat()*cellSize, ny + rand.nextFloat()*cellSize, rand.nextFloat())); } } } Vector3f[] points = pointList.toArray(new Vector3f[pointList.size()]); LOG.info("voronoi point created"); //now cycle through cells and find influencing hills Heightmap tmp = new Heightmap(size); Vector3f first = new Vector3f(); Vector3f second = new Vector3f(); float min = Float.POSITIVE_INFINITY; float max = Float.NEGATIVE_INFINITY; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { //sort points by distance to (x,y) final float px = x; final float py = y; findClosestTwoPoints(points, px, py, first, second); assert (dist(first, px, py) <= dist(second, px, py)); //calc height float v = -1*dist(first, px, py) + 1*dist(second, px, py); tmp.setHeightAt(x, y, v); min = Math.min(v, min); max = Math.max(v, max); } } //normalize float factor = 1f / (max-min); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float h = tmp.getHeightAt(x, y); tmp.setHeightAt(x, y, (h-min) * factor); } } LOG.info("voronoi cells calculated"); //distort Noise distortionNoise = new Noise(rand.nextLong()); Heightmap tmp2 = new Heightmap(size); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float s = x/(float)size; float t = y/(float)size; float ss = (float) (s + VORONOI_DISTORTION_AMPLITUDE * 2*distortionNoise.noise(s*VORONOI_DISTORTION_FREQUENCY, t*VORONOI_DISTORTION_FREQUENCY, 0)); float tt = (float) (t + VORONOI_DISTORTION_AMPLITUDE * 2*distortionNoise.noise(s*VORONOI_DISTORTION_FREQUENCY, t*VORONOI_DISTORTION_FREQUENCY, 3.4)); float v = tmp.getHeightInterpolating(ss*size, tt*size); tmp2.setHeightAt(x, y, v); } } LOG.info("voronoi cells distorted"); //apply for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float amplitude = noise[x][y][2]; heightmap.adjustHeightAt(x, y, amplitude * tmp.getHeightAt(x, y) * VORONOI_SCALE); } } LOG.info("voronoi noise added"); } private static void findClosestTwoPoints(Vector3f[] points, float px, float py, Vector3f first, Vector3f second) { float dist1 = Float.POSITIVE_INFINITY; float dist2 = Float.POSITIVE_INFINITY; for (Vector3f p : points) { float d = dist(p, px, py); if (d<dist1) { dist2 = dist1; second.set(first); dist1 = d; first.set(p); } else if (d<dist2) { dist2 = d; second.set(p); } } } private static float dist(Vector3f hillCenter, float px, float py) { return FastMath.sqrt((hillCenter.x-px)*(hillCenter.x-px) + (hillCenter.y-py)*(hillCenter.y-py))*hillCenter.z; //return ((hillCenter.x-px)*(hillCenter.x-px) + (hillCenter.y-py)*(hillCenter.y-py))*hillCenter.z; } private void calculateBaseElevation() { //assign elevation to oceans for (Graph.Corner c : graph.corners) { if (c.ocean) { c.elevation = -1; } } Queue<Graph.Corner> q = new ArrayDeque<>(); for (Graph.Corner c : graph.corners) { if (c.coast) { q.add(c); } } while (!q.isEmpty()) { Graph.Corner c = q.poll(); for (Graph.Corner r : c.adjacent) { float h = Math.max(-1, c.elevation - 0.2f); if (r.ocean && r.elevation<h) { r.elevation = h; q.add(r); } } } assignCenterElevations(); //render Geometry geom = createElevationGeometry(); Heightmap tmp = new Heightmap(size); render(tmp.getRawData(), geom, ColorRGBA.Black, -1, 1); //scale for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float h = tmp.getHeightAt(x, y); h = (float) (Math.signum(h) * Math.pow(Math.abs(h), HEIGHT_SCALING)); tmp.setHeightAt(x, y, h); } } //distort Noise distortionNoise = new Noise(rand.nextLong()); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float s = x/(float)size; float t = y/(float)size; float ss = (float) (s + DISTORTION_AMPLITUDE * 2*distortionNoise.noise(s*DISTORTION_FREQUENCY, t*DISTORTION_FREQUENCY, 0)); float tt = (float) (t + DISTORTION_AMPLITUDE * 2*distortionNoise.noise(s*DISTORTION_FREQUENCY, t*DISTORTION_FREQUENCY, 3.4)); float v = tmp.getHeightInterpolating(ss*size, tt*size); heightmap.setHeightAt(x, y, v); } } //smooth for (int i=0; i<SMOOTHING_STEPS; ++i) { smooth(heightmap); } //reset height for (Graph.Corner c : graph.corners) { if (c.ocean) { c.elevation = 0; } } assignCenterElevations(); LOG.info("base elevation assigned"); } private void smooth_old(Heightmap map) { Heightmap m = map.clone(); float t = 2 / map.getSize(); for (int x=0; x<map.getSize(); ++x) { for (int y=0; y<map.getSize(); ++y) { float h = map.getHeightAt(x, y); float[] hi = new float[NEIGHBORS.length]; float[] di = new float[NEIGHBORS.length]; float dmax = 0; float dtotal = 0; //compute slopes for (int i=0; i<NEIGHBORS.length; ++i) { hi[i] = m.getHeightAtClamping(x + NEIGHBORS[i][0], y + NEIGHBORS[i][1]); di[i] = h-hi[i]; dmax = Math.max(dmax, di[i]); if (di[i] > t) { dtotal+=di[i]; } } //move terrain float vsum = 0; for (int i=0; i<NEIGHBORS.length; ++i) { if (di[i] > t) { float v = 0.25f*(dmax-t)*di[i]/dtotal; map.adjustHeightAt(x + NEIGHBORS[i][0], y + NEIGHBORS[i][1], v); vsum+=v; } } map.adjustHeightAt(x, y, -vsum); } } } private void smooth(Heightmap map) { Heightmap m = map.clone(); float t = 2 / map.getSize(); for (int x=0; x<map.getSize(); ++x) { for (int y=0; y<map.getSize(); ++y) { float h = map.getHeightAt(x, y); float nh = 0; //compute average for (int i=0; i<NEIGHBORS.length; ++i) { nh += m.getHeightAtClamping(x + NEIGHBORS[i][0], y + NEIGHBORS[i][1]); } nh /= NEIGHBORS.length; float diff = nh - h; diff *= 0.2f; map.adjustHeightAt(x, y, diff); } } } private void assignCenterElevations() { //assign elevation to centers for (Graph.Center c : graph.centers) { float elevation = 0; for (Graph.Corner corner : c.corners) { elevation += corner.elevation; } elevation /= c.corners.size(); c.elevation = elevation; } } private void calculateTemperatureAndMoisture() { Geometry geom = createTemperatureGeometry(); render(temperature.getRawData(), geom, ColorRGBA.White, 0, 1); LOG.info("temperature map created"); geom = createMoistureGeometry(); render(moisture.getRawData(), geom, ColorRGBA.Black, 0, 1); LOG.info("moisture map created"); } private void calculateBiomeVectorfield() { float[][] tmp = new float[size][size]; Vectorfield tmpBiomes = new Vectorfield(size, Biome.values().length); for (int i=0; i<Biome.values().length; ++i) { Biome b = Biome.values()[i]; Geometry geom = createBiomesGeometry(b); //render(tmp, geom, b==Biome.OCEAN ? ColorRGBA.White : ColorRGBA.Black, 0, 1); render(tmp, geom, ColorRGBA.Black, 0, 1); tmpBiomes.setLayer(i, tmp); } LOG.info("biome vectorfield rendered"); //disturb Noise distortionNoise = new Noise(rand.nextLong()); float[] v = new float[Biome.values().length]; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { float s = x/(float)size; float t = y/(float)size; float ss = (float) (s + BIOMES_DISTORTION_AMPLITUDE * 2*distortionNoise.noise(s*BIOMES_DISTORTION_FREQUENCY, t*BIOMES_DISTORTION_FREQUENCY, 0)); float tt = (float) (t + BIOMES_DISTORTION_AMPLITUDE * 2*distortionNoise.noise(s*BIOMES_DISTORTION_FREQUENCY, t*BIOMES_DISTORTION_FREQUENCY, 3.4)); v = tmpBiomes.getVectorInterpolating(ss*size, tt*size, v); for (int i=0; i<Biome.values().length; ++i) { biomes.setVectorAt(x, y, v); } } } //TODO: maybe add smoothing } private Geometry createElevationGeometry() { ArrayList<Vector3f> posList = new ArrayList<>(); ArrayList<Integer> indexList = new ArrayList<>(); ArrayList<ColorRGBA> colorList = new ArrayList<>(); Map<Graph.Corner, Integer> cornerIndices = new HashMap<>(); for (Graph.Center c : graph.centers) { int i = posList.size(); posList.add(new Vector3f(c.location.x, c.location.y, 1)); colorList.add(new ColorRGBA(c.elevation/2 + 0.5f, c.elevation/2 + 0.5f, c.elevation/2 + 0.5f, 1)); cornerIndices.clear(); for (Graph.Corner q : c.corners) { cornerIndices.put(q, posList.size()); posList.add(new Vector3f(q.point.x, q.point.y, 1)); colorList.add(new ColorRGBA(q.elevation/2 + 0.5f, q.elevation/2 + 0.5f, q.elevation/2 + 0.5f, 1)); } for (Graph.Edge edge : c.borders) { indexList.add(i); indexList.add(cornerIndices.get(edge.v0)); indexList.add(cornerIndices.get(edge.v1)); } } Mesh mesh = new Mesh(); mesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(posList.toArray(new Vector3f[posList.size()]))); mesh.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(colorList.toArray(new ColorRGBA[colorList.size()]))); mesh.setBuffer(VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer(ArrayUtils.toPrimitive(indexList.toArray(new Integer[indexList.size()])))); mesh.setMode(Mesh.Mode.Triangles); mesh.updateCounts(); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setBoolean("VertexColor", true); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); Geometry geom = new Geometry("elevationGeom", mesh); geom.setMaterial(mat); geom.setLocalScale(size); geom.setQueueBucket(RenderQueue.Bucket.Gui); geom.setCullHint(Spatial.CullHint.Never); return geom; } private Geometry createNoiseGeometry() { ArrayList<Vector3f> posList = new ArrayList<>(graph.centers.size()); ArrayList<Integer> indexList = new ArrayList<>(); ArrayList<ColorRGBA> colorList = new ArrayList<>(graph.centers.size()); for (Graph.Center c : graph.centers) { double[] settings = BIOME_PROPERTIES.get(c.biome); float r = (float) settings[0]; float g = (float) settings[1]; float b = (float) (settings[2] + settings[3]*Math.max(0, c.elevation)*Math.max(0, c.elevation)); //float b = Math.max(0, c.elevation); b*=b; ColorRGBA col = new ColorRGBA(r, g, b, 1); colorList.add(col); posList.add(new Vector3f(c.location.x, c.location.y, 0)); } for (Graph.Corner c : graph.corners) { if (c.touches.size() != 3) { //LOG.log(Level.INFO, "corner {0} does not touch 3 centers but {1}", new Object[]{c, c.touches.size()}); continue; //border } else { for (Graph.Center c2 : c.touches) { indexList.add(c2.index); } } } Mesh mesh = new Mesh(); mesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(posList.toArray(new Vector3f[posList.size()]))); mesh.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(colorList.toArray(new ColorRGBA[colorList.size()]))); mesh.setBuffer(VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer(ArrayUtils.toPrimitive(indexList.toArray(new Integer[indexList.size()])))); mesh.setMode(Mesh.Mode.Triangles); mesh.updateCounts(); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setBoolean("VertexColor", true); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); Geometry geom = new Geometry("elevationGeom", mesh); geom.setMaterial(mat); geom.setLocalScale(size); geom.setQueueBucket(RenderQueue.Bucket.Gui); geom.setCullHint(Spatial.CullHint.Never); return geom; } private Geometry createTemperatureGeometry() { ArrayList<Vector3f> posList = new ArrayList<>(); ArrayList<Integer> indexList = new ArrayList<>(); ArrayList<ColorRGBA> colorList = new ArrayList<>(); Map<Graph.Corner, Integer> cornerIndices = new HashMap<>(); for (Graph.Center c : graph.centers) { int i = posList.size(); posList.add(new Vector3f(c.location.x, c.location.y, 1)); colorList.add(new ColorRGBA(c.temperature, c.temperature, c.temperature, 1)); cornerIndices.clear(); for (Graph.Corner q : c.corners) { cornerIndices.put(q, posList.size()); posList.add(new Vector3f(q.point.x, q.point.y, 1)); colorList.add(new ColorRGBA(q.temperature, q.temperature, q.temperature, 1)); } for (Graph.Edge edge : c.borders) { indexList.add(i); indexList.add(cornerIndices.get(edge.v0)); indexList.add(cornerIndices.get(edge.v1)); } } Mesh mesh = new Mesh(); mesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(posList.toArray(new Vector3f[posList.size()]))); mesh.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(colorList.toArray(new ColorRGBA[colorList.size()]))); mesh.setBuffer(VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer(ArrayUtils.toPrimitive(indexList.toArray(new Integer[indexList.size()])))); mesh.setMode(Mesh.Mode.Triangles); mesh.updateCounts(); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setBoolean("VertexColor", true); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); Geometry geom = new Geometry("biomesGeom", mesh); geom.setMaterial(mat); geom.setLocalScale(size); geom.setQueueBucket(RenderQueue.Bucket.Gui); geom.setCullHint(Spatial.CullHint.Never); return geom; } private Geometry createMoistureGeometry() { //moisture ArrayList<Vector3f> posList = new ArrayList<>(); ArrayList<Integer> indexList = new ArrayList<>(); ArrayList<ColorRGBA> colorList = new ArrayList<>(); Map<Graph.Corner, Integer> cornerIndices = new HashMap<>(); ColorRGBA waterMoisture = new ColorRGBA(1, 1, 1, 1); ColorRGBA oceanMoisture = new ColorRGBA(0, 0, 0, 1); for (Graph.Center c : graph.centers) { int i = posList.size(); posList.add(new Vector3f(c.location.x, c.location.y, 1)); if (c.ocean) { colorList.add(oceanMoisture); } else if (c.water) { colorList.add(waterMoisture); } else { colorList.add(new ColorRGBA(1-c.moisture, 1-c.moisture, 1-c.moisture, 1)); } cornerIndices.clear(); for (Graph.Corner q : c.corners) { cornerIndices.put(q, posList.size()); posList.add(new Vector3f(q.point.x, q.point.y, 1)); if (c.ocean) { colorList.add(oceanMoisture); } else if (c.water) { colorList.add(waterMoisture); } else { colorList.add(new ColorRGBA(1-q.moisture, 1-q.moisture, 1-q.moisture, 1)); } } for (Graph.Edge edge : c.borders) { indexList.add(i); indexList.add(cornerIndices.get(edge.v0)); indexList.add(cornerIndices.get(edge.v1)); } } Mesh mesh = new Mesh(); mesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(posList.toArray(new Vector3f[posList.size()]))); mesh.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(colorList.toArray(new ColorRGBA[colorList.size()]))); mesh.setBuffer(VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer(ArrayUtils.toPrimitive(indexList.toArray(new Integer[indexList.size()])))); mesh.setMode(Mesh.Mode.Triangles); mesh.updateCounts(); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setBoolean("VertexColor", true); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); Geometry geom = new Geometry("biomesGeom", mesh); geom.setMaterial(mat); geom.setLocalScale(size); geom.setQueueBucket(RenderQueue.Bucket.Gui); geom.setCullHint(Spatial.CullHint.Never); return geom; } private Geometry createBiomesGeometry(Biome slot) { //biomes ArrayList<Vector3f> posList = new ArrayList<>(); ArrayList<Integer> indexList = new ArrayList<>(); Map<Graph.Corner, Integer> cornerIndices = new HashMap<>(); for (Graph.Center c : graph.centers) { if (c.biome != slot) { continue; } int i = posList.size(); posList.add(new Vector3f(c.location.x, c.location.y, 1)); cornerIndices.clear(); for (Graph.Corner corner : c.corners) { cornerIndices.put(corner, posList.size()); posList.add(new Vector3f(corner.point.x, corner.point.y, 1)); } for (Graph.Edge edge : c.borders) { indexList.add(i); indexList.add(cornerIndices.get(edge.v0)); indexList.add(cornerIndices.get(edge.v1)); } } Mesh biomesMesh = new Mesh(); biomesMesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(posList.toArray(new Vector3f[posList.size()]))); biomesMesh.setBuffer(VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer(ArrayUtils.toPrimitive(indexList.toArray(new Integer[indexList.size()])))); biomesMesh.setMode(Mesh.Mode.Triangles); biomesMesh.updateCounts(); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", ColorRGBA.White); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); Geometry geom = new Geometry("biomesGeom", biomesMesh); geom.setMaterial(mat); geom.setLocalScale(size); geom.setQueueBucket(RenderQueue.Bucket.Gui); geom.setCullHint(Spatial.CullHint.Never); return geom; } /** * Renders the given scene in a top-down manner in the given matrix * * @param matrix * @param scene */ private void render(float[][] matrix, final Spatial scene, final ColorRGBA background, float min, float max) { final ByteBuffer data = BufferUtils.createByteBuffer(size * size * 4 * 4); try { app.enqueue(new Callable<Object>() { @Override public Object call() throws Exception { //init Camera cam = new Camera(size, size); cam.setParallelProjection(true); final ViewPort view = new ViewPort("Off", cam); view.setBackgroundColor(background); view.setClearFlags(true, true, true); final FrameBuffer buffer = new FrameBuffer(size, size, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorBuffer(Image.Format.RGBA32F); view.setOutputFrameBuffer(buffer); view.attachScene(scene); //render scene.setCullHint(Spatial.CullHint.Never); scene.updateGeometricState(); view.setEnabled(true); app.getRenderManager().renderViewPort(view, 0); app.getRenderer().readFrameBufferWithFormat(buffer, data, Image.Format.RGBA32F); return new Object(); } }).get(); } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(GraphToHeightmap.class.getName()).log(Level.SEVERE, "unable to render", ex); return; } data.rewind(); for (int y = 0; y < size; ++y) { for (int x = 0; x < size; ++x) { float v = data.getFloat(); v *= (max-min); v += min; matrix[x][y] = v; data.getFloat(); data.getFloat(); data.getFloat(); } } } /** * Renders the given scene in a top-down manner in the given matrix * * @param matrix * @param scene */ private void renderColor(float[][][] matrix, final Spatial scene, final ColorRGBA background, float min, float max) { final ByteBuffer data = BufferUtils.createByteBuffer(size * size * 4 * 4); try { app.enqueue(new Callable<Object>() { @Override public Object call() throws Exception { //init Camera cam = new Camera(size, size); cam.setParallelProjection(true); final ViewPort view = new ViewPort("Off", cam); view.setBackgroundColor(background); view.setClearFlags(true, true, true); final FrameBuffer buffer = new FrameBuffer(size, size, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorBuffer(Image.Format.RGBA32F); view.setOutputFrameBuffer(buffer); view.attachScene(scene); //render scene.setCullHint(Spatial.CullHint.Never); scene.updateGeometricState(); view.setEnabled(true); app.getRenderManager().renderViewPort(view, 0); app.getRenderer().readFrameBufferWithFormat(buffer, data, Image.Format.RGBA32F); return new Object(); } }).get(); } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(GraphToHeightmap.class.getName()).log(Level.SEVERE, "unable to render", ex); return; } data.rewind(); for (int y = 0; y < size; ++y) { for (int x = 0; x < size; ++x) { float v; v = data.getFloat(); v *= (max-min); v += min; matrix[x][y][0] = v; v = data.getFloat(); v *= (max-min); v += min; matrix[x][y][1] = v; v = data.getFloat(); v *= (max-min); v += min; matrix[x][y][2] = v; v = data.getFloat(); v *= (max-min); v += min; matrix[x][y][3] = v; } } } private void saveMaps() { saveMatrix(temperature.getRawData(), "temperature.png", 0, 1); saveMatrix(moisture.getRawData(), "moisture.png", 0, 1); saveMatrix(heightmap.getRawData(), "elevation.png", -1.5f, 1.5f); saveColorMatrix(noise, "noise.png", 0, 1); float[][] tmp = new float[size][size]; for (int i=0; i<Biome.values().length; ++i) { tmp = biomes.getLayer(i, tmp); saveMatrix(tmp, "Biome"+Biome.values()[i]+".png", 0, 1); } } private void saveMatrix(float[][] matrix, String filename, float min, float max) { byte[] buffer = new byte[size*size]; int i=0; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { buffer[i] = (byte) ((matrix[x][y]-min) * 255 / (max-min)); i++; } } ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); int[] nBits = { 8 }; ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); SampleModel sm = cm.createCompatibleSampleModel(size, size); DataBufferByte db = new DataBufferByte(buffer, size * size); WritableRaster raster = Raster.createWritableRaster(sm, db, null); BufferedImage result = new BufferedImage(cm, raster, false, null); try { ImageIO.write(result, "png", new File(filename)); } catch (IOException ex) { Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex); } } private void saveColorMatrix(float[][][] matrix, String filename, float min, float max) { byte[] buffer = new byte[size*size*3]; int i=0; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { buffer[i] = (byte) ((matrix[x][y][0]-min) * 255 / (max-min)); i++; buffer[i] = (byte) ((matrix[x][y][1]-min) * 255 / (max-min)); i++; buffer[i] = (byte) ((matrix[x][y][2]-min) * 255 / (max-min)); i++; } } ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB); int[] nBits = { 8, 8, 8 }; ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); SampleModel sm = cm.createCompatibleSampleModel(size, size); DataBufferByte db = new DataBufferByte(buffer, size * size * 3); WritableRaster raster = Raster.createWritableRaster(sm, db, null); BufferedImage result = new BufferedImage(cm, raster, false, null); try { ImageIO.write(result, "png", new File(filename)); } catch (IOException ex) { Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex); } } }
package net.ripe.db.whois.common.rpsl; import net.ripe.db.whois.common.Message; import net.ripe.db.whois.common.Messages; public final class ValidationMessages { private ValidationMessages() { } public static Message missingMandatoryAttribute(final AttributeType type) { return new Message(Messages.Type.ERROR, "Mandatory attribute \"%s\" is missing", type.getName()); } public static Message missingConditionalRequiredAttribute(final AttributeType type) { return new Message(Messages.Type.ERROR, "Missing required \"%s\" attribute", type.getName()); } public static Message tooManyAttributesOfType(final AttributeType type) { return new Message(Messages.Type.ERROR, "Attribute \"%s\" appears more than once", type.getName()); } public static Message unknownAttribute(final CharSequence key) { return new Message(Messages.Type.ERROR, "\"%s\" is not a known RPSL attribute", key); } public static Message invalidAttributeForObject(final AttributeType attributeType) { return new Message(Messages.Type.ERROR, "\"%s\" is not valid for this object type", attributeType.getName()); } public static Message syntaxError(final CharSequence value) { return new Message(Messages.Type.ERROR, "Syntax error in %s", value); } public static Message syntaxError(final CharSequence value, final CharSequence reason) { return new Message(Messages.Type.ERROR, "Syntax error in %s (%s)", value, reason); } public static Message suppliedAttributeReplacedWithGeneratedValue(final AttributeType type) { return new Message(Messages.Type.WARNING, "Supplied attribute '%s' has been replaced with a generated value", type.getName()); } public static Message attributeValueConverted(final CharSequence original, final CharSequence converted) { return new Message(Messages.Type.INFO, "Value %s converted to %s", original, converted); } public static Message continuationLinesRemoved() { return new Message(Messages.Type.INFO, "Continuation lines are not allowed here and have been removed"); } public static Message remarksReformatted() { return new Message(Messages.Type.INFO, "Please use the \"remarks:\" attribute instead of end of line comment on primary key"); } //TODO get someone to specify the info message public static Message attributeValueSticky(final AttributeType attributeType, final String stuck) { return new Message(Messages.Type.INFO, "Attribute '%s' has been put back with value '%s'", attributeType.getName(), stuck); } }
package pl.pwr.hiervis.ui; import java.awt.Adjustable; import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.Arrays; import java.util.function.Consumer; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JViewport; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.plaf.basic.BasicLabelUI; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import basic_hierarchy.interfaces.Hierarchy; import basic_hierarchy.interfaces.Node; import pl.pwr.hiervis.core.HVConfig; import pl.pwr.hiervis.core.HVConstants; import pl.pwr.hiervis.core.HVContext; import pl.pwr.hiervis.ui.components.MouseWheelEventBubbler; import pl.pwr.hiervis.ui.components.VerticalLabelUI; import pl.pwr.hiervis.ui.control.PanControl; import pl.pwr.hiervis.ui.control.ZoomScrollControl; import pl.pwr.hiervis.util.GridBagConstraintsBuilder; import pl.pwr.hiervis.util.Utils; import pl.pwr.hiervis.visualisation.HierarchyProcessor; import prefuse.Display; import prefuse.Visualization; import prefuse.controls.ToolTipControl; @SuppressWarnings("serial") public class InstanceVisualizationsFrame extends JFrame { private static final Logger log = LogManager.getLogger( InstanceVisualizationsFrame.class ); private static final int defaultFrameWidth = 800; private static final int defaultFrameHeight = 800; private static final int defaultLabelHeight = new JLabel( " " ).getPreferredSize().height; private static final int visWidthMin = 100; private static final int visWidthMax = 1000; private static final int visHeightMin = 100; private static final int visHeightMax = 1000; private static final Insets displayInsets = new Insets( 5, 5, 5, 5 ); private HVContext context; private int visZoomIncrement = 5; private int visWidth = 200; private int visHeight = 200; private JCheckBox[] cboxesHorizontal; private JCheckBox[] cboxesVertical; private JPanel cDimsH; private JPanel cDimsV; private JPanel cCols; private JPanel cRows; private JScrollPane scrollPane; private JPanel cViewport; private JScrollPane scrollPaneH; private JScrollPane scrollPaneV; private JCheckBox cboxAllH; private JCheckBox cboxAllV; public InstanceVisualizationsFrame( HVContext context, Frame owner ) { super( "Instance Visualizations" ); this.context = context; setDefaultCloseOperation( HIDE_ON_CLOSE ); setSize( defaultFrameWidth, defaultFrameHeight ); createGUI(); context.hierarchyChanging.addListener( this::onHierarchyChanging ); context.hierarchyChanged.addListener( this::onHierarchyChanged ); context.nodeSelectionChanged.addListener( this::onNodeSelectionChanged ); context.configChanged.addListener( this::onConfigChanged ); if ( context.isHierarchyDataLoaded() ) { recreateUI(); } } // GUI creation methods private void createGUI() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 0, 0 }; gridBagLayout.rowHeights = new int[] { 0, 0 }; gridBagLayout.columnWeights = new double[] { 0.0, 1.0 }; gridBagLayout.rowWeights = new double[] { 0.0, 1.0 }; getContentPane().setLayout( gridBagLayout ); createCheckboxHolders(); createVisualizationHolder(); } private void createCheckboxHolders() { GridBagConstraintsBuilder builder = new GridBagConstraintsBuilder(); // Horizontal JPanel cHorizontal = new JPanel(); GridBagLayout layout = new GridBagLayout(); layout.columnWidths = new int[] { 0, 0, 0 }; layout.rowHeights = new int[] { 0 }; layout.columnWeights = new double[] { 0.0, 0.0, 1.0 }; layout.rowWeights = new double[] { 1.0 }; cHorizontal.setLayout( layout ); getContentPane().add( cHorizontal, builder.position( 1, 0 ).fillHorizontal().build() ); cboxAllH = new JCheckBox( "Toggle All" ); cboxAllH.setEnabled( context.isHierarchyDataLoaded() ); cboxAllH.addItemListener( e -> { if ( cboxesHorizontal != null ) Arrays.stream( cboxesHorizontal ).forEach( cbox -> cbox.setSelected( cboxAllH.isSelected() ) ); } ); cHorizontal.add( cboxAllH, builder.position( 0, 0 ).anchorWest().build() ); cHorizontal.add( new JSeparator( SwingConstants.VERTICAL ), builder.position( 1, 0 ).fillVertical().build() ); cDimsH = new JPanel(); cDimsH.setLayout( new BoxLayout( cDimsH, BoxLayout.X_AXIS ) ); scrollPaneH = new JScrollPane( cDimsH ); scrollPaneH.setVerticalScrollBarPolicy( ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER ); scrollPaneH.setBorder( BorderFactory.createEmptyBorder() ); scrollPaneH.getHorizontalScrollBar().setUnitIncrement( 16 ); cHorizontal.add( scrollPaneH, builder.position( 2, 0 ).anchorWest().fill().build() ); // Vertical JPanel cVertical = new JPanel(); layout = new GridBagLayout(); layout.columnWidths = new int[] { 0 }; layout.rowHeights = new int[] { 0, 0, 0 }; layout.columnWeights = new double[] { 1.0 }; layout.rowWeights = new double[] { 0.0, 0.0, 1.0 }; cVertical.setLayout( layout ); getContentPane().add( cVertical, builder.position( 0, 1 ).fillVertical().build() ); cboxAllV = new JCheckBox( "Toggle All" ); cboxAllV.setEnabled( context.isHierarchyDataLoaded() ); cboxAllV.addItemListener( e -> { if ( cboxesVertical != null ) Arrays.stream( cboxesVertical ).forEach( cbox -> cbox.setSelected( cboxAllV.isSelected() ) ); } ); cVertical.add( cboxAllV, builder.position( 0, 0 ).anchorNorth().build() ); cVertical.add( new JSeparator( SwingConstants.HORIZONTAL ), builder.position( 0, 1 ).fillHorizontal().build() ); cDimsV = new JPanel(); cDimsV.setLayout( new BoxLayout( cDimsV, BoxLayout.Y_AXIS ) ); scrollPaneV = new JScrollPane( cDimsV ); scrollPaneV.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); scrollPaneV.setBorder( BorderFactory.createEmptyBorder() ); scrollPaneV.getVerticalScrollBar().setUnitIncrement( 16 ); cVertical.add( scrollPaneV, builder.position( 0, 2 ).anchorNorth().fill().build() ); } private void createVisualizationHolder() { scrollPane = new JScrollPane(); getContentPane().add( scrollPane, new GridBagConstraintsBuilder().position( 1, 1 ).fill().build() ); cViewport = new JPanel(); cViewport.setLayout( new GridBagLayout() ); scrollPane.setViewportView( cViewport ); cCols = new JPanel(); cRows = new JPanel(); scrollPane.setViewportBorder( UIManager.getBorder( "ScrollPane.border" ) ); scrollPane.setColumnHeaderView( cCols ); scrollPane.setRowHeaderView( cRows ); scrollPane.getColumnHeader().setScrollMode( JViewport.BACKINGSTORE_SCROLL_MODE ); scrollPane.getRowHeader().setScrollMode( JViewport.BACKINGSTORE_SCROLL_MODE ); scrollPane.getHorizontalScrollBar().setUnitIncrement( 16 ); scrollPane.getVerticalScrollBar().setUnitIncrement( 16 ); // Remove and replace the original listener to prevent the view from scrolling // when using control+scroll to resize all visible Displays scrollPane.removeMouseWheelListener( scrollPane.getMouseWheelListeners()[0] ); scrollPane.addMouseWheelListener( new MouseWheelListener() { @Override public void mouseWheelMoved( MouseWheelEvent e ) { if ( e.isControlDown() && displaysVisible() ) { Display dis = getFirstVisibleDisplay(); visWidth = Math.min( dis.getSize().width, dis.getSize().height ); visHeight = visWidth; visWidth -= e.getWheelRotation() * visZoomIncrement; visHeight -= e.getWheelRotation() * visZoomIncrement; visWidth = Utils.clamp( visWidthMin, visWidth, visWidthMax ); visHeight = Utils.clamp( visHeightMin, visHeight, visHeightMax ); // Update the zoom increment so that we don't have to scroll 10000 times when // the displays are already large. visZoomIncrement = getZoomIncrement( Math.min( visWidth, visHeight ) ); // Update the displays' preferred sizes so they can shrink to the new size Dimension d = new Dimension( visWidth, visHeight ); forEachDisplay( display -> display.setPreferredSize( d ) ); updateViewportLayout(); updateLabelLayout( true ); updateLabelLayout( false ); cCols.revalidate(); cRows.revalidate(); cViewport.revalidate(); repaint(); } else if ( e.isShiftDown() || !scrollPane.getVerticalScrollBar().isVisible() ) { // Horizontal scrolling Adjustable adj = scrollPane.getHorizontalScrollBar(); int scroll = e.getUnitsToScroll() * adj.getBlockIncrement(); adj.setValue( adj.getValue() + scroll ); } else { // Vertical scrolling Adjustable adj = scrollPane.getVerticalScrollBar(); int scroll = e.getUnitsToScroll() * adj.getBlockIncrement(); adj.setValue( adj.getValue() + scroll ); } } } ); } private int getZoomIncrement( int w ) { return w <= 300 ? 5 : w <= 500 ? 10 : 20; } /** * Recreates the UI, updating it to match the currently loaded hierarchy's data. */ private void recreateUI() { String[] dataNames = HierarchyProcessor.getFeatureNames( context.getHierarchy() ); recreateCheckboxes( dataNames ); recreateLabels( dataNames ); recreateViewportLayout( dataNames.length ); updateViewportLayout(); } private void recreateCheckboxes( String[] dataNames ) { cDimsH.removeAll(); cDimsV.removeAll(); int dims = dataNames.length; cboxesHorizontal = new JCheckBox[dims]; cboxesVertical = new JCheckBox[dims]; for ( int i = 0; i < dims; ++i ) { JCheckBox cboxH = new JCheckBox( dataNames[i] ); JCheckBox cboxV = new JCheckBox( dataNames[i] ); cboxH.setSelected( false ); cboxV.setSelected( false ); final int d = i; cboxH.addItemListener( e -> onDimensionVisibilityToggled( ImmutablePair.of( d, true ) ) ); cboxV.addItemListener( e -> onDimensionVisibilityToggled( ImmutablePair.of( d, false ) ) ); cDimsH.add( cboxH ); cDimsV.add( cboxV ); cboxesHorizontal[i] = cboxH; cboxesVertical[i] = cboxV; } updateCheckboxViewport(); revalidate(); repaint(); } private void updateCheckboxViewport() { // Find the widest checkbox's width int w = Arrays.stream( cboxesVertical ).mapToInt( cbox -> cbox.getPreferredSize().width ).max().getAsInt(); int h = cboxesHorizontal[0].getPreferredSize().height; w += scrollPaneV.getVerticalScrollBar().getPreferredSize().width; h += scrollPaneH.getHorizontalScrollBar().getPreferredSize().height; scrollPaneH.setPreferredSize( new Dimension( 0, h ) ); scrollPaneH.setMinimumSize( new Dimension( 0, h ) ); scrollPaneV.setPreferredSize( new Dimension( w, 0 ) ); scrollPaneV.setMinimumSize( new Dimension( w, 0 ) ); } private void recreateLabels( String[] dataNames ) { cCols.removeAll(); cRows.removeAll(); int dims = dataNames.length; cCols.setLayout( createLabelLayout( dims, true ) ); cRows.setLayout( createLabelLayout( dims, false ) ); Insets insetsH = new Insets( 0, 5, 0, 5 ); Insets insetsV = new Insets( 5, 0, 5, 0 ); GridBagConstraintsBuilder builder = new GridBagConstraintsBuilder(); BasicLabelUI verticalUI = new VerticalLabelUI( false ); for ( int i = 0; i < dims; ++i ) { JLabel lblH = new JLabel( dataNames[i] ); lblH.setHorizontalAlignment( SwingConstants.CENTER ); lblH.setVisible( false ); cCols.add( lblH, builder.position( i, 0 ).insets( insetsH ).build() ); JLabel lblV = new JLabel( dataNames[i] ); lblV.setUI( verticalUI ); lblV.setHorizontalAlignment( SwingConstants.CENTER ); lblV.setVisible( false ); cRows.add( lblV, builder.position( 0, i ).insets( insetsV ).build() ); } updateLabelLayout( true ); updateLabelLayout( false ); } // Helper methods for GUI creation /** * Recreates the layout of the scrollpane viewoprt. * * @param totalDims * total number of dimensions */ private void recreateViewportLayout( int totalDims ) { GridBagLayout layout = new GridBagLayout(); layout.columnWidths = new int[totalDims]; layout.rowHeights = new int[totalDims]; layout.columnWeights = new double[totalDims]; layout.rowWeights = new double[totalDims]; cViewport.setLayout( layout ); } /** * Updates the viewport layout so that the cells have the correct sizes */ private void updateViewportLayout() { GridBagLayout layout = (GridBagLayout)cViewport.getLayout(); for ( int i = 0; i < cboxesHorizontal.length; ++i ) { boolean visH = cboxesHorizontal[i].isSelected(); boolean visV = cboxesVertical[i].isSelected(); layout.columnWidths[i] = visH ? visWidth : 0; layout.rowHeights[i] = visV ? visHeight : 0; layout.columnWeights[i] = visH ? 1.0 : Double.MIN_VALUE; layout.rowWeights[i] = visV ? 1.0 : Double.MIN_VALUE; } } /** * Creates layout for a label holder. * * @param totalDims * total number of dimensions * @param horizontal * whether to update the horizontal or vertical labels * @return the layout */ private GridBagLayout createLabelLayout( int totalDims, boolean horizontal ) { GridBagLayout layout = new GridBagLayout(); if ( horizontal ) { layout.columnWidths = new int[totalDims]; layout.columnWeights = new double[totalDims]; layout.rowHeights = new int[] { defaultLabelHeight }; layout.rowWeights = new double[] { 0.0 }; } else { layout.rowHeights = new int[totalDims]; layout.rowWeights = new double[totalDims]; layout.columnWidths = new int[] { defaultLabelHeight }; layout.columnWeights = new double[] { 0.0 }; } return layout; } /** * Updates the label holder layout so that the cells have correct sizes. * * @param horizontal * whether to update the horizontal or vertical labels */ private void updateLabelLayout( boolean horizontal ) { JPanel panel = horizontal ? cCols : cRows; JCheckBox[] arr = horizontal ? cboxesHorizontal : cboxesVertical; GridBagLayout layout = (GridBagLayout)panel.getLayout(); for ( int i = 0; i < arr.length; ++i ) { boolean vis = arr[i].isSelected(); // Need to manually include insets in size calculation. // For some reason, the grid layout doesn't do it automatically... if ( horizontal ) { Insets insets = layout.getConstraints( cCols.getComponent( i ) ).insets; layout.columnWidths[i] = vis ? visWidth + insets.left + insets.right : 0; layout.columnWeights[i] = vis ? 1.0 : Double.MIN_VALUE; } else { Insets insets = layout.getConstraints( cRows.getComponent( i ) ).insets; layout.rowHeights[i] = vis ? visHeight + insets.top + insets.bottom : 0; layout.rowWeights[i] = vis ? 1.0 : Double.MIN_VALUE; } } } private Visualization createVisualizationFor( Node node, int dimX, int dimY ) { Visualization vis = null; if ( dimX == dimY ) { // TODO: Histogram vis = new Visualization(); } else { vis = HierarchyProcessor.createInstanceVisualization( context, node, context.getConfig().getPointSize(), dimX, dimY, true ); } return vis; } /** * Creates an instance display for the specified dimensions and the specified node * * @param node * node that is currently selected in the hierarchy view * @param dimX * dimension number on the X axis (0 based) * @param dimY * dimension number on the Y axis (0 based) * @return container serving as a holder for the display. */ private Display createInstanceDisplayFor( Node node, int dimX, int dimY ) { Visualization vis = createVisualizationFor( node, dimX, dimY ); Display display = createInstanceDisplayFor( vis ); GridBagConstraintsBuilder builder = new GridBagConstraintsBuilder(); cViewport.add( display, builder.position( dimX, dimY ).insets( displayInsets ).fill().build() ); vis.run( "draw" ); return display; } /** * Creates a properly configured, interactable display which can be used to show instance visualizations. * * @param vis * the visualization to create the display for. * @return the display */ private Display createInstanceDisplayFor( Visualization vis ) { Display display = new Display( vis ); display.setHighQuality( context.getHierarchy().getOverallNumberOfInstances() < HVConstants.INSTANCE_COUNT_MED ); display.setBackground( context.getConfig().getBackgroundColor() ); display.addControlListener( new PanControl( true ) ); display.addControlListener( new ToolTipControl( HVConstants.PREFUSE_INSTANCE_LABEL_COLUMN_NAME ) ); ZoomScrollControl zoomControl = new ZoomScrollControl(); zoomControl.setModifierControl( true ); display.addControlListener( zoomControl ); display.addMouseWheelListener( new MouseWheelEventBubbler( display, e -> !e.isControlDown() ) ); display.setPreferredSize( new Dimension( visWidth, visHeight ) ); display.addComponentListener( new ComponentAdapter() { public void componentResized( ComponentEvent e ) { redrawDisplayIfVisible( (Display)e.getComponent() ); } } ); Utils.unzoom( display, 0 ); return display; } /** * @param x * dimension number on the X axis (0 based) * @param y * dimension number on the Y axis (0 based) * @return whether x-th horizontal and y-th vertical checkboxes are both selected, * indicating that the display at { x, y } should be visible. */ private boolean shouldDisplayBeVisible( int x, int y ) { return cboxesHorizontal[x].isSelected() && cboxesVertical[y].isSelected(); } /** * @param dimX * dimension number on the X axis (0 based) * @param dimY * dimension number on the Y axis (0 based) * @return the display associated with the specified dimensions, or null if it wasn't created yet. */ private Display getDisplay( int dimX, int dimY ) { GridBagLayout layout = (GridBagLayout)cViewport.getLayout(); Component result = null; for ( Component c : cViewport.getComponents() ) { GridBagConstraints gbc = layout.getConstraints( c ); if ( gbc.gridx == dimX && gbc.gridy == dimY ) { result = c; break; } } return (Display)result; } /** * @return the first visible instance display, or null if none are visible */ private Display getFirstVisibleDisplay() { for ( Component c : cViewport.getComponents() ) { if ( c.isVisible() ) { return (Display)c; } } return null; } /** * @return true if any instance display is visible, false otherwise. */ private boolean displaysVisible() { return Arrays.stream( cViewport.getComponents() ).filter( c -> c.isVisible() ).count() > 0; } /** * Executes the specified function for each existing display in the grid. */ private void forEachDisplay( Consumer<Display> func ) { for ( Component c : cViewport.getComponents() ) { func.accept( (Display)c ); } } private void redrawDisplayIfVisible( Display d ) { if ( d.isVisible() ) { // Unzoom the display so that drawing is not botched. Utils.unzoom( d, 0 ); d.getVisualization().run( "draw" ); } } // Listeners private void onDimensionVisibilityToggled( Pair<Integer, Boolean> args ) { // Setting this to true will cause displays for inverted dimensions to also be created // ie. a square matrix of dimensions will be created // (as opposed to an upper triangle matrix when this constant is set to false) boolean includeFlippedDims = false; // Setting to to true will cause the displays to be shrunk to allow the newly added // displays to fit inside the viewport, if possible. boolean squishDisplays = false; // Unpack event arguments int dim = args.getLeft(); boolean horizontal = args.getRight(); Node node = context.findGroup( context.getSelectedRow() ); for ( int i = 0; i < cboxesVertical.length; ++i ) { int x = horizontal ? dim : i; int y = horizontal ? i : dim; boolean vis = shouldDisplayBeVisible( x, y ); Display display = getDisplay( x, y ); if ( display != null ) { display.setVisible( vis ); redrawDisplayIfVisible( display ); } else if ( vis ) { if ( includeFlippedDims || ( !includeFlippedDims && x >= y ) ) { // Lazily create the requested display. display = createInstanceDisplayFor( node, x, y ); } } } Component c = horizontal ? cCols.getComponent( dim ) : cRows.getComponent( dim ); c.setVisible( horizontal ? cboxesHorizontal[dim].isSelected() : cboxesVertical[dim].isSelected() ); if ( squishDisplays && displaysVisible() ) { int countH = (int)Arrays.stream( cboxesHorizontal ).filter( cbox -> cbox.isSelected() ).count(); int countV = (int)Arrays.stream( cboxesVertical ).filter( cbox -> cbox.isSelected() ).count(); Dimension viewportSize = scrollPane.getViewport().getSize(); Dimension newVisSize = new Dimension( ( viewportSize.width - countH * ( displayInsets.left + displayInsets.right ) ) / countH, ( viewportSize.height - countV * ( displayInsets.top + displayInsets.bottom ) ) / countV ); newVisSize.width = Utils.clamp( visWidthMin, newVisSize.width, visWidthMax ); newVisSize.height = Utils.clamp( visHeightMin, newVisSize.height, visHeightMax ); if ( ( newVisSize.width + displayInsets.left + displayInsets.right ) * countH <= viewportSize.width ) visWidth = newVisSize.width; if ( ( newVisSize.height + displayInsets.top + displayInsets.bottom ) * countV <= viewportSize.height ) visHeight = newVisSize.height; Dimension d = new Dimension( visWidth, visHeight ); forEachDisplay( display -> display.setPreferredSize( d ) ); } updateViewportLayout(); updateLabelLayout( horizontal ); cCols.revalidate(); cRows.revalidate(); revalidate(); repaint(); } private void onHierarchyChanging( Hierarchy h ) { cboxesHorizontal = null; cboxesVertical = null; cboxAllH.setSelected( false ); cboxAllV.setSelected( false ); cboxAllH.setEnabled( false ); cboxAllV.setEnabled( false ); cDimsH.removeAll(); cDimsV.removeAll(); cCols.removeAll(); cRows.removeAll(); cViewport.removeAll(); cDimsH.revalidate(); cDimsV.revalidate(); cCols.revalidate(); cRows.revalidate(); cViewport.revalidate(); repaint(); } private void onHierarchyChanged( Hierarchy h ) { recreateUI(); cboxAllH.setEnabled( true ); cboxAllV.setEnabled( true ); cDimsH.revalidate(); cDimsV.revalidate(); cCols.revalidate(); cRows.revalidate(); cViewport.revalidate(); repaint(); } private void onNodeSelectionChanged( int row ) { forEachDisplay( this::redrawDisplayIfVisible ); } private void onConfigChanged( HVConfig cfg ) { if ( !context.isHierarchyDataLoaded() ) return; GridBagLayout layout = (GridBagLayout)cViewport.getLayout(); Node node = context.findGroup( context.getSelectedRow() ); forEachDisplay( display -> { GridBagConstraints gbc = layout.getConstraints( display ); int dimX = gbc.gridx; int dimY = gbc.gridy; display.setVisualization( createVisualizationFor( node, dimX, dimY ) ); display.setBackground( cfg.getBackgroundColor() ); redrawDisplayIfVisible( display ); } ); } }
package net.savantly.graphite.query; import net.savantly.graphite.query.impl.FromImpl; import net.savantly.graphite.query.impl.TargetImpl; import net.savantly.graphite.query.impl.UntilImpl; public class GraphiteQueryBuilder<T> { private Target target; private From from = new FromImpl(); private Until until = new UntilImpl(); private final Formatter<T> format; private Template template; public GraphiteQueryBuilder(Formatter<T> format) { this.format = format; } public Target getTarget() { return target; } public GraphiteQueryBuilder<T> setTarget(Target target) { this.target = target; return this; } public GraphiteQueryBuilder<T> setTarget(String target) { this.target = new TargetImpl(target); return this; } public From getFrom() { return from; } public GraphiteQueryBuilder<T> setFrom(From from) { this.from = from; return this; } public GraphiteQueryBuilder<T> setFrom(String from) { this.from = new FromImpl(from); return this; } public GraphiteQueryBuilder<T> setFrom(int value, GraphiteTimeUnit unit) { this.from = new FromImpl(value, unit); return this; } public Until getUntil() { return until; } public GraphiteQueryBuilder<T> setUntil(Until until) { this.until = until; return this; } public GraphiteQueryBuilder<T> setUntil(String until) { this.until = new UntilImpl(until); return this; } public GraphiteQueryBuilder<T> setUntil(int value, GraphiteTimeUnit unit) { this.until = new UntilImpl(value, unit); return this; } public Formatter<T> getFormat() { return format; } public Template getTemplate() { return template; } public GraphiteQueryBuilder<T> setTemplate(Template template) { this.template = template; return this; } public GraphiteQuery<T> build() { if(target == null) { throw new AssertionError("target must not be null"); } return new GraphiteQuery<T>() { @Override public Target target() { return target; } @Override public From from() { return from; } @Override public Until until() { return until; } @Override public Formatter<T> format() { return format; } @Override public Template template() { return template; } }; } }
package org.andidev.webdriverextension.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.junit.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class BotUtils { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BotUtils.class); /* Read */ public static String textIn(WebElement webElement) { return webElement.getText(); } public static Double numberIn(WebElement webElement) { try { return NumberUtils.createDouble(webElement.getText()); } catch (NumberFormatException e) { return null; } } public static String url(WebDriver driver) { return driver.getCurrentUrl(); } public static String tagNameOf(WebElement webElement) { return webElement.getTagName(); } public static String attributeIn(String name, WebElement webElement) { return webElement.getAttribute(name); } public static String idIn(WebElement webElement) { return attributeIn("id", webElement); } public static String nameIn(WebElement webElement) { return attributeIn("name", webElement); } public static String classIn(WebElement webElement) { return attributeIn("class", webElement); } public static List<String> classesIn(WebElement webElement) { return Arrays.asList(StringUtils.split(classIn(webElement))); } public static String valueIn(WebElement webElement) { return attributeIn("value", webElement); } public static String hrefIn(WebElement webElement) { return attributeIn("href", webElement); } /* Count */ public static int sizeOf(Collection collection) { return collection.size(); } /* Clear */ public static void clear(WebElement webElement) { webElement.clear(); } /* Type */ public static void type(String text, WebElement webElement) { if (text == null) { return; } webElement.sendKeys(text); } public static void typeNumber(Double number, WebElement webElement) { if (number == null) { return; } type(toString(number), webElement); } /* Clear and Type */ public static void clearAndType(String text, WebElement webElement) { clear(webElement); type(text, webElement); } public static void clearAndTypeNumber(Double number, WebElement webElement) { clear(webElement); typeNumber(number, webElement); } /* Press */ public static void pressEnter(WebElement webElement) { pressKeys(webElement, Keys.ENTER); } public static void pressKeys(WebElement webElement, CharSequence... keys) { webElement.sendKeys(keys); } /* Click */ public static void click(WebElement webElement) { webElement.click(); } /* Select */ public static void select(WebElement webElement) { if (isDeselected(webElement)) { webElement.click(); } } public static void deselect(WebElement webElement) { if (isSelected(webElement)) { webElement.click(); } } /* Select Option */ public static void selectOption(String text, WebElement webElement) { new Select(webElement).selectByVisibleText(text); } public static void deselectOption(String text, WebElement webElement) { new Select(webElement).deselectByVisibleText(text); } public static void selectAllOptions(WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { select(webElement); } } public static void deselectAllOptions(WebElement webElement) { new Select(webElement).deselectAll(); } /* Select Option Value */ public static void selectOptionWithValue(String value, WebElement webElement) { new Select(webElement).selectByValue(value); } public static void deselectOptionWithValue(String value, WebElement webElement) { new Select(webElement).deselectByValue(value); } /* Select Option Index */ public static void selectOptionWithIndex(int index, WebElement webElement) { new Select(webElement).selectByIndex(index); } public static void deselectOptionWithIndex(int index, WebElement webElement) { new Select(webElement).selectByIndex(index); } /* Check */ public static void check(WebElement webElement) { if (isUnchecked(webElement)) { click(webElement); } } public static void uncheck(WebElement webElement) { if (isChecked(webElement)) { click(webElement); } } /* Open */ public static void open(String url, WebDriver driver) { driver.get(url); } public static void open(Openable openable) { openable.open(); } /* Wait */ public static void waitFor(double seconds) { long nanos = (long) (seconds * 1000000000); if (seconds > 0) { try { TimeUnit.NANOSECONDS.sleep(nanos); } catch (InterruptedException ex) { // Swallow exception ex.printStackTrace(); } } } public static void waitFor(double time, TimeUnit unit) { long nanos = 0; switch (unit) { case DAYS: nanos = (long) (time * 24 * 60 * 60 * 1000000000); break; case HOURS: nanos = (long) (time * 60 * 60 * 1000000000); break; case MINUTES: nanos = (long) (time * 60 * 1000000000); break; case SECONDS: nanos = (long) (time * 1000000000); break; case MILLISECONDS: nanos = (long) (time * 1000000); break; case MICROSECONDS: nanos = (long) (time * 1000); break; case NANOSECONDS: nanos = (long) (time); break; } if (time > 0) { try { TimeUnit.NANOSECONDS.sleep(nanos); } catch (InterruptedException ex) { // Swallow exception ex.printStackTrace(); } } } public static void waitForElementToDisplay(WebElement webElement, WebDriver driver) { waitForElementToDisplay(webElement, 30, driver); } public static void waitForElementToDisplay(WebElement webElement, long timeOutInSeconds, WebDriver driver) { WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds); wait.until(ExpectedConditions.visibilityOf(webElement)); } public static void waitForElementToDisplay(WebElement webElement, long timeOutInSeconds, long sleepInMillis, WebDriver driver) { WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds, sleepInMillis); wait.until(ExpectedConditions.visibilityOf(webElement)); } /* Debug */ public static void debug(String str) { log.debug(str); } public static void debug(WebElement webElement) { log.debug("Tag {} has text = \"{}\"", describeTag(webElement), textIn(webElement)); } public static void debug(List<? extends WebElement> webElements) { log.debug("List contains the following {} tags", sizeOf(webElements)); for (WebElement webElement : webElements) { debug(webElement); } } /* Tag Name */ public static boolean tagNameEquals(String value, WebElement webElement) { return equals(value, tagNameOf(webElement)); } public static boolean tagNameNotEquals(String value, WebElement webElement) { return notEquals(value, tagNameOf(webElement)); } public static void assertTagNameEquals(String value, WebElement webElement) { assertEquals("Tag name", value, tagNameOf(webElement)); } public static void assertTagNameNotEquals(String value, WebElement webElement) { assertNotEquals("Tag name", value, tagNameOf(webElement)); } /* Attribute */ public static boolean hasAttribute(String name, WebElement webElement) { return webElement.getAttribute(name) != null; } public static boolean hasNotAttribute(String name, WebElement webElement) { return !hasAttribute(name, webElement); } public static boolean attributeEquals(String name, String value, WebElement webElement) { return equals(value, attributeIn(name, webElement)); } public static boolean attributeNotEquals(String name, String value, WebElement webElement) { return notEquals(value, attributeIn(name, webElement)); } public static boolean attributeContains(String name, String searchText, WebElement webElement) { return contains(searchText, attributeIn(name, webElement)); } public static boolean attributeNotContains(String name, String searchText, WebElement webElement) { return notContains(searchText, attributeIn(name, webElement)); } public static boolean attributeStartsWith(String name, String prefix, WebElement webElement) { return startsWith(prefix, attributeIn(name, webElement)); } public static boolean attributeNotStartsWith(String name, String prefix, WebElement webElement) { return notStartsWith(prefix, attributeIn(name, webElement)); } public static boolean attributeEndsWith(String name, String suffix, WebElement webElement) { return endsWith(suffix, attributeIn(name, webElement)); } public static boolean attributeNotEndsWith(String name, String suffix, WebElement webElement) { return notEndsWith(suffix, attributeIn(name, webElement)); } public static void assertHasAttribute(String name, WebElement webElement) { if (hasNotAttribute(name, webElement)) { Assert.fail(describeTag(webElement, name) + " does not have the " + name + " attribute!"); } } public static void assertHasNotAttribute(String name, WebElement webElement) { if (hasAttribute(name, webElement)) { Assert.fail(describeTag(webElement, name) + " has the " + name + " attribute when it shouldn't!"); } } public static void assertAttributeEquals(String name, String value, WebElement webElement) { assertEquals(name, value, attributeIn(name, webElement)); } public static void assertAttributeNotEquals(String name, String value, WebElement webElement) { assertNotEquals(name, value, attributeIn(name, webElement)); } public static void assertAttributeContains(String name, String searchText, WebElement webElement) { assertContains(name, searchText, attributeIn(name, webElement)); } public static void assertAttributeNotContains(String name, String searchText, WebElement webElement) { assertNotContains(name, searchText, attributeIn(name, webElement)); } public static void assertAttributeStartsWith(String name, String prefix, WebElement webElement) { assertStartsWith(name, prefix, attributeIn(name, webElement)); } public static void assertAttributeNotStartsWith(String name, String prefix, WebElement webElement) { assertNotStartsWith(name, prefix, attributeIn(name, webElement)); } public static void assertAttributeEndsWith(String name, String suffix, WebElement webElement) { assertEndsWith(name, suffix, attributeIn(name, webElement)); } public static void assertAttributeNotEndsWith(String name, String suffix, WebElement webElement) { assertNotEndsWith(name, suffix, attributeIn(name, webElement)); } public static boolean hasId(WebElement webElement) { return hasAttribute("id", webElement); } public static boolean hasNotId(WebElement webElement) { return hasNotAttribute("id", webElement); } public static boolean idEquals(String value, WebElement webElement) { return equals(value, idIn(webElement)); } public static boolean idNotEquals(String value, WebElement webElement) { return notEquals(value, idIn(webElement)); } public static boolean idContains(String searchText, WebElement webElement) { return contains(searchText, idIn(webElement)); } public static boolean idNotContains(String searchText, WebElement webElement) { return contains(searchText, idIn(webElement)); } public static boolean idStartsWith(String prefix, WebElement webElement) { return startsWith(prefix, idIn(webElement)); } public static boolean idNotStartsWith(String prefix, WebElement webElement) { return notStartsWith(prefix, idIn(webElement)); } public static boolean idEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, idIn(webElement)); } public static boolean idNotEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, idIn(webElement)); } public static void assertHasId(WebElement webElement) { assertHasAttribute("id", webElement); } public static void assertHasNotId(WebElement webElement) { assertHasNotAttribute("id", webElement); } public static void assertIdEquals(String value, WebElement webElement) { assertEquals("id", value, idIn(webElement)); } public static void assertIdNotEquals(String value, WebElement webElement) { assertNotEquals("id", value, idIn(webElement)); } public static void assertIdContains(String searchText, WebElement webElement) { assertContains("id", searchText, idIn(webElement)); } public static void assertIdNotContains(String searchText, WebElement webElement) { assertNotContains("id", searchText, idIn(webElement)); } public static void assertIdStartsWith(String prefix, WebElement webElement) { assertStartsWith("id", prefix, idIn(webElement)); } public static void assertIdNotStartsWith(String prefix, WebElement webElement) { assertNotStartsWith("id", prefix, idIn(webElement)); } public static void assertIdEndsWith(String suffix, WebElement webElement) { assertEndsWith("id", suffix, idIn(webElement)); } public static void assertIdNotEndsWith(String suffix, WebElement webElement) { assertNotEndsWith("id", suffix, idIn(webElement)); } /* Name */ public static boolean hasName(WebElement webElement) { return hasAttribute("name", webElement); } public static boolean hasNotName(WebElement webElement) { return hasNotAttribute("name", webElement); } public static boolean nameEquals(String value, WebElement webElement) { return equals(value, nameIn(webElement)); } public static boolean nameNotEquals(String value, WebElement webElement) { return notEquals(value, nameIn(webElement)); } public static boolean nameContains(String searchText, WebElement webElement) { return contains(searchText, nameIn(webElement)); } public static boolean nameNotContains(String searchText, WebElement webElement) { return contains(searchText, nameIn(webElement)); } public static boolean nameStartsWith(String prefix, WebElement webElement) { return startsWith(prefix, nameIn(webElement)); } public static boolean nameNotStartsWith(String prefix, WebElement webElement) { return notStartsWith(prefix, nameIn(webElement)); } public static boolean nameEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, nameIn(webElement)); } public static boolean nameNotEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, nameIn(webElement)); } public static void assertHasName(WebElement webElement) { assertHasAttribute("name", webElement); } public static void assertHasNotName(WebElement webElement) { assertHasNotAttribute("name", webElement); } public static void assertNameEquals(String value, WebElement webElement) { assertEquals("name", value, nameIn(webElement)); } public static void assertNameNotEquals(String value, WebElement webElement) { assertNotEquals("name", value, nameIn(webElement)); } public static void assertNameContains(String searchText, WebElement webElement) { assertContains("name", searchText, nameIn(webElement)); } public static void assertNameNotContains(String searchText, WebElement webElement) { assertNotContains("name", searchText, nameIn(webElement)); } public static void assertNameStartsWith(String prefix, WebElement webElement) { assertStartsWith("name", prefix, nameIn(webElement)); } public static void assertNameNotStartsWith(String prefix, WebElement webElement) { assertNotStartsWith("name", prefix, nameIn(webElement)); } public static void assertNameEndsWith(String suffix, WebElement webElement) { assertEndsWith("name", suffix, nameIn(webElement)); } public static void assertNameNotEndsWith(String suffix, WebElement webElement) { assertNotEndsWith("name", suffix, nameIn(webElement)); } /* Class */ public static boolean hasClass(WebElement webElement) { return hasAttribute("class", webElement); } public static boolean hasNotClass(WebElement webElement) { return hasNotAttribute("class", webElement); } public static boolean hasClass(String className, WebElement webElement) { return classIn(webElement).matches("(\\\"|\\s)" + className.trim() + "(\\\"|\\s)"); } public static boolean hasNotClass(String className, WebElement webElement) { return !hasClass(className, webElement); } public static boolean hasClassContaining(String searchText, WebElement webElement) { List<String> classes = classesIn(webElement); for (String clazz : classes) { if (contains(searchText, clazz)) { return true; } } return false; } public static boolean hasNotClassContaining(String searchText, WebElement webElement) { return !hasClassContaining(searchText, webElement); } public static boolean hasClassStartingWith(String prefix, WebElement webElement) { List<String> classes = classesIn(webElement); for (String clazz : classes) { if (startsWith(prefix, clazz)) { return true; } } return false; } public static boolean hasNotClassStartingWith(String prefix, WebElement webElement) { return !hasClassStartingWith(prefix, webElement); } public static boolean hasClassEndingWith(String suffix, WebElement webElement) { List<String> classes = classesIn(webElement); for (String clazz : classes) { if (endsWith(suffix, clazz)) { return true; } } return false; } public static boolean hasNotClassEndingWith(String suffix, WebElement webElement) { return !hasClassEndingWith(suffix, webElement); } public static void assertHasClass(WebElement webElement) { assertHasAttribute("class", webElement); } public static void assertHasNotClass(WebElement webElement) { assertHasNotAttribute("class", webElement); } public static void assertHasClass(String className, WebElement webElement) { if (hasNotClass(className, webElement)) { Assert.fail(describeTag(webElement) + " does not have class " + className.trim() + "!"); } } public static void assertHasNotClass(String className, WebElement webElement) { if (hasClass(className, webElement)) { Assert.fail(describeTag(webElement) + " has class " + className.trim() + " when it shouldn't!"); } } public static void assertHasClassContaining(String searchText, WebElement webElement) { if (hasNotClassContaining(searchText, webElement)) { Assert.fail(describeTag(webElement) + " does not have class containing text " + searchText.trim() + "!"); } } public static void assertHasNotClassContaining(String searchText, WebElement webElement) { if (hasClassContaining(searchText, webElement)) { Assert.fail(describeTag(webElement) + " has class containing text " + searchText.trim() + " when it shouldn't!"); } } public static void assertHasClassStartingWith(String prefix, WebElement webElement) { if (hasNotClassStartingWith(prefix, webElement)) { Assert.fail(describeTag(webElement) + " does not have class containing prefix " + prefix.trim() + "!"); } } public static void assertHasNotClassStartingWith(String prefix, WebElement webElement) { if (hasClassStartingWith(prefix, webElement)) { Assert.fail(describeTag(webElement) + " has class containing prefix " + prefix.trim() + " when it shouldn't!"); } } public static void assertHasClassEndingWith(String suffix, WebElement webElement) { if (hasNotClassEndingWith(suffix, webElement)) { Assert.fail(describeTag(webElement) + " does not have class containing suffix " + suffix.trim() + "!"); } } public static void assertHasNotClassEndingWith(String suffix, WebElement webElement) { if (hasClassEndingWith(suffix, webElement)) { Assert.fail(describeTag(webElement) + " has class containing suffix " + suffix.trim() + " when it shouldn't!"); } } /* Value */ public static boolean hasValue(WebElement webElement) { return hasAttribute("value", webElement); } public static boolean hasNotValue(WebElement webElement) { return hasNotAttribute("value", webElement); } public static boolean valueEquals(String value, WebElement webElement) { return equals(value, valueIn(webElement)); } public static boolean valueNotEquals(String value, WebElement webElement) { return notEquals(value, valueIn(webElement)); } public static boolean valueContains(String searchText, WebElement webElement) { return contains(searchText, valueIn(webElement)); } public static boolean valueNotContains(String searchText, WebElement webElement) { return contains(searchText, valueIn(webElement)); } public static boolean valueStartsWith(String prefix, WebElement webElement) { return startsWith(prefix, valueIn(webElement)); } public static boolean valueNotStartsWith(String prefix, WebElement webElement) { return notStartsWith(prefix, valueIn(webElement)); } public static boolean valueEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, valueIn(webElement)); } public static boolean valueNotEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, valueIn(webElement)); } public static void assertHasValue(WebElement webElement) { assertHasAttribute("value", webElement); } public static void assertHasNotValue(WebElement webElement) { assertHasNotAttribute("value", webElement); } public static void assertValueEquals(String value, WebElement webElement) { assertEquals("value", value, valueIn(webElement)); } public static void assertValueNotEquals(String value, WebElement webElement) { assertNotEquals("value", value, valueIn(webElement)); } public static void assertValueContains(String searchText, WebElement webElement) { assertContains("value", searchText, valueIn(webElement)); } public static void assertValueNotContains(String searchText, WebElement webElement) { assertNotContains("value", searchText, valueIn(webElement)); } public static void assertValueStartsWith(String prefix, WebElement webElement) { assertStartsWith("value", prefix, valueIn(webElement)); } public static void assertValueNotStartsWith(String prefix, WebElement webElement) { assertNotStartsWith("value", prefix, valueIn(webElement)); } public static void assertValueEndsWith(String suffix, WebElement webElement) { assertEndsWith("value", suffix, valueIn(webElement)); } public static void assertValueNotEndsWith(String suffix, WebElement webElement) { assertNotEndsWith("value", suffix, valueIn(webElement)); } /* Href */ public static boolean hasHref(WebElement webElement) { return hasAttribute("href", webElement); } public static boolean hasNotHref(WebElement webElement) { return hasNotAttribute("href", webElement); } public static boolean hrefEquals(String value, WebElement webElement) { return equals(value, hrefIn(webElement)); } public static boolean hrefNotEquals(String value, WebElement webElement) { return notEquals(value, hrefIn(webElement)); } public static boolean hrefContains(String searchText, WebElement webElement) { return contains(searchText, hrefIn(webElement)); } public static boolean hrefNotContains(String searchText, WebElement webElement) { return contains(searchText, hrefIn(webElement)); } public static boolean hrefStartsWith(String prefix, WebElement webElement) { return startsWith(prefix, hrefIn(webElement)); } public static boolean hrefNotStartsWith(String prefix, WebElement webElement) { return notStartsWith(prefix, hrefIn(webElement)); } public static boolean hrefEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, hrefIn(webElement)); } public static boolean hrefNotEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, hrefIn(webElement)); } public static void assertHasHref(WebElement webElement) { assertHasAttribute("href", webElement); } public static void assertHasNotHref(WebElement webElement) { assertHasNotAttribute("href", webElement); } public static void assertHrefEquals(String value, WebElement webElement) { assertEquals("href", value, hrefIn(webElement)); } public static void assertHrefNotEquals(String value, WebElement webElement) { assertNotEquals("href", value, hrefIn(webElement)); } public static void assertHrefContains(String searchText, WebElement webElement) { assertContains("href", searchText, hrefIn(webElement)); } public static void assertHrefNotContains(String searchText, WebElement webElement) { assertNotContains("href", searchText, hrefIn(webElement)); } public static void assertHrefStartsWith(String prefix, WebElement webElement) { assertStartsWith("href", prefix, hrefIn(webElement)); } public static void assertHrefNotStartsWith(String prefix, WebElement webElement) { assertNotStartsWith("href", prefix, hrefIn(webElement)); } public static void assertHrefEndsWith(String suffix, WebElement webElement) { assertEndsWith("href", suffix, hrefIn(webElement)); } public static void assertHrefNotEndsWith(String suffix, WebElement webElement) { assertNotEndsWith("href", suffix, hrefIn(webElement)); } /* Text */ public static boolean textEquals(String text, WebElement webElement) { return equals(text, textIn(webElement)); } public static boolean textNotEquals(String text, WebElement webElement) { return notEquals(text, textIn(webElement)); } public static boolean textContains(String searchText, WebElement webElement) { return contains(searchText, textIn(webElement)); } public static boolean textNotContains(String searchText, WebElement webElement) { return contains(searchText, textIn(webElement)); } public static boolean textStartsWith(String prefix, WebElement webElement) { return startsWith(prefix, textIn(webElement)); } public static boolean textNotStartsWith(String prefix, WebElement webElement) { return notStartsWith(prefix, textIn(webElement)); } public static boolean textEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, textIn(webElement)); } public static boolean textNotEndsWith(String suffix, WebElement webElement) { return endsWith(suffix, textIn(webElement)); } public static void assertTextEquals(String text, WebElement webElement) { assertEquals("Text", text, textIn(webElement)); } public static void assertTextNotEquals(String text, WebElement webElement) { assertNotEquals("Text", text, textIn(webElement)); } public static void assertTextContains(String searchText, WebElement webElement) { assertContains("Text", searchText, textIn(webElement)); } public static void assertTextNotContains(String searchText, WebElement webElement) { assertNotContains("Text", searchText, textIn(webElement)); } public static void assertTextStartsWith(String prefix, WebElement webElement) { assertStartsWith("Text", prefix, textIn(webElement)); } public static void assertTextNotStartsWith(String prefix, WebElement webElement) { assertNotStartsWith("Text", prefix, textIn(webElement)); } public static void assertTextEndsWith(String suffix, WebElement webElement) { assertEndsWith("Text", suffix, textIn(webElement)); } public static void assertTextNotEndsWith(String suffix, WebElement webElement) { assertNotEndsWith("Text", suffix, textIn(webElement)); } /* Number */ public static boolean numberEquals(Double number, WebElement webElement) { return equals(number, numberIn(webElement)); } public static boolean numberNotEquals(Double number, WebElement webElement) { return notEquals(number, numberIn(webElement)); } public static boolean numberLessThan(Double number, WebElement webElement) { return lessThan(number, numberIn(webElement)); } public static boolean numberLessThanOrEquals(Double number, WebElement webElement) { return lessThanOrEquals(number, numberIn(webElement)); } public static boolean numberGreaterThan(Double number, WebElement webElement) { return greaterThan(number, numberIn(webElement)); } public static boolean numberGreaterThanOrEquals(Double number, WebElement webElement) { return greaterThanOrEquals(number, numberIn(webElement)); } public static void assertNumberEquals(Double number, WebElement webElement) { assertEquals("Number", number, numberIn(webElement)); } public static void assertNumberNotEquals(Double number, WebElement webElement) { assertNotEequals("Number", number, numberIn(webElement)); } public static void assertNumberLessThan(Double number, WebElement webElement) { assertLessThan("Number", number, numberIn(webElement)); } public static void assertNumberLessThanOrEquals(Double number, WebElement webElement) { assertLessThanOrEquals("Number", number, numberIn(webElement)); } public static void assertNumberGreaterThan(Double number, WebElement webElement) { assertGreaterThan("Number", number, numberIn(webElement)); } public static void assertNumberGreaterThanOrEquals(Double number, WebElement webElement) { assertGreaterThanOrEquals("Number", number, numberIn(webElement)); } /* Url */ public static boolean urlEquals(String url, WebDriver driver) { return equals(url, url(driver)); } public static boolean urlNotEquals(String url, WebDriver driver) { return notEquals(url, url(driver)); } public static boolean urlMatches(String regExp, WebDriver driver) { return matches(regExp, url(driver)); } public static boolean urlNotMatches(String regExp, WebDriver driver) { return notMatches(regExp, url(driver)); } public static boolean urlMatches(Openable openable, WebDriver driver) { return matches(openable.getUrl(), url(driver)); } public static boolean urlNotMatches(Openable openable, WebDriver driver) { return notMatches(openable.getUrl(), url(driver)); } public static boolean urlContains(String searchText, WebDriver driver) { return contains(searchText, url(driver)); } public static boolean urlNotContains(String searchText, WebDriver driver) { return notContains(searchText, url(driver)); } public static boolean urlStartsWith(String prefix, WebDriver driver) { return startsWith(prefix, url(driver)); } public static boolean urlNotStartsWith(String prefix, WebDriver driver) { return notStartsWith(prefix, url(driver)); } public static boolean urlEndsWith(String suffix, WebDriver driver) { return endsWith(suffix, url(driver)); } public static boolean urlNotEndsWith(String suffix, WebDriver driver) { return notEndsWith(suffix, url(driver)); } public static void assertUrlEquals(String url, WebDriver driver) { assertEquals("Url", url, url(driver)); } public static void assertUrlNotEquals(String url, WebDriver driver) { assertNotEquals("Url", url, url(driver)); } public static void assertUrlMatches(String regExp, WebDriver driver) { assertMatches("Url", regExp, url(driver)); } public static void assertUrlNotMatches(String regExp, WebDriver driver) { assertNotMatches("Url", regExp, url(driver)); } public static void assertUrlMatches(Openable openable, WebDriver driver) { assertMatches("Url", openable.getUrl(), url(driver)); } public static void assertUrlNotMatches(Openable openable, WebDriver driver) { assertNotMatches("Url", openable.getUrl(), url(driver)); } public static void assertUrlContains(String searchText, WebDriver driver) { assertContains("Url", searchText, url(driver)); } public static void assertUrlNotContains(String searchText, WebDriver driver) { assertNotContains("Url", searchText, url(driver)); } public static void assertUrlStartsWith(String prefix, WebDriver driver) { assertStartsWith("Url", prefix, url(driver)); } public static void assertUrlNotStartsWith(String prefix, WebDriver driver) { assertNotStartsWith("Url", prefix, url(driver)); } public static void assertUrlEndsWith(String suffix, WebDriver driver) { assertEndsWith("Url", suffix, url(driver)); } public static void assertUrlNotEndsWith(String suffix, WebDriver driver) { assertNotEndsWith("Url", suffix, url(driver)); } /* Open */ public static boolean isOpen(Openable openable) { return openable.isOpen(); } public static boolean isNotOpen(Openable openable) { return openable.isNotOpen(); } public static void assertIsOpen(Openable openable) { openable.assertIsOpen(); } public static void assertIsNotOpen(Openable openable) { openable.assertIsNotOpen(); } /* Selected */ public static boolean isSelected(WebElement webElement) { return webElement.isSelected(); } public static boolean isDeselected(WebElement webElement) { return !isSelected(webElement); } public static void assertIsSelected(WebElement webElement) { if (isDeselected(webElement)) { Assert.fail(describeTag(webElement) + " is not selected!"); } } public static void assertIsDeselected(WebElement webElement) { if (isSelected(webElement)) { Assert.fail(describeTag(webElement) + " is not deselected!"); } } /* Checked/Unchecked */ public static boolean isChecked(WebElement webElement) { return webElement.isSelected(); } public static boolean isUnchecked(WebElement webElement) { return !isChecked(webElement); } public static void assertIsChecked(WebElement webElement) { if (isUnchecked(webElement)) { Assert.fail(describeTag(webElement) + " is not checked!"); } } public static void assertIsUnchecked(WebElement webElement) { if (isChecked(webElement)) { Assert.fail(describeTag(webElement) + " is not unchecked!"); } } /* Enabled/Disabled */ public static boolean isEnabled(WebElement webElement) { return webElement.isEnabled(); } public static boolean isDisabled(WebElement webElement) { return !isEnabled(webElement); } public static void assertIsEnabled(WebElement webElement) { if (isDisabled(webElement)) { Assert.fail(describeTag(webElement) + " is not enabled!"); } } public static void assertIsDisabled(WebElement webElement) { if (isEnabled(webElement)) { Assert.fail(describeTag(webElement) + " is not disabled!"); } } /* Display */ public static boolean isDisplayed(WebElement webElement) { try { return webElement.isDisplayed(); } catch (NoSuchElementException e) { return false; } } public static boolean isNotDisplayed(WebElement webElement) { return !isDisplayed(webElement); } public static boolean isDisplayed(WebElement webElement, long secondsToWait, WebDriver driver) { WebElement foundWebElement = new WebDriverWait(driver, secondsToWait).until(ExpectedConditions.visibilityOf(webElement)); if (foundWebElement != null) { return true; } else { return false; } } public static boolean isNotDisplayed(WebElement webElement, long secondsToWait, WebDriver driver) { return !isDisplayed(webElement, secondsToWait, driver); } public static void assertIsDisplayed(WebElement webElement) { if (isNotDisplayed(webElement)) { Assert.fail("WebElement is not displayed!"); } } public static void assertIsNotDisplayed(WebElement webElement) { if (isDisplayed(webElement)) { Assert.fail("WebElement is displayed when it shouldn't!"); } } public static void assertIsDisplayed(WebElement webElement, long secondsToWait , WebDriver driver) { if (isNotDisplayed(webElement, secondsToWait , driver)) { Assert.fail("WebElement is not displayed within " + secondsToWait + " seconds!"); } } public static void assertIsNotDisplayed(WebElement webElement, long secondsToWait , WebDriver driver) { if (isDisplayed(webElement, secondsToWait , driver)) { Assert.fail("WebElement is displayed within " + secondsToWait + " seconds when it shouldn't!"); } } /* Number of */ public static boolean sizeEquals(int number, Collection collection) { return equals((double) number, (double) collection.size()); } public static boolean sizeNotEquals(int number, Collection collection) { return notEquals((double) number, (double) collection.size()); } public static boolean sizeLessThan(int number, Collection collection) { return lessThan((double) number, (double) collection.size()); } public static boolean sizeLessThanOrEquals(int number, Collection collection) { return lessThanOrEquals((double) number, (double) collection.size()); } public static boolean sizeGreaterThan(int number, Collection collection) { return greaterThan((double) number, (double) collection.size()); } public static boolean sizeGreaterThanOrEquals(int number, Collection collection) { return greaterThanOrEquals((double) number, (double) collection.size()); } public static void assertSizeEquals(int number, Collection collection) { assertEquals("Size", (double) number, (double) collection.size()); } public static void assertSizeNotEquals(int number, Collection collection) { assertNotEequals("Size", (double) number, (double) collection.size()); } public static void assertSizeLessThan(int number, Collection collection) { assertLessThan("Size", (double) number, (double) collection.size()); } public static void assertSizeLessThanOrEquals(int number, Collection collection) { assertLessThanOrEquals("Size", (double) number, (double) collection.size()); } public static void assertSizeGreaterThan(int number, Collection collection) { assertGreaterThan("Size", (double) number, (double) collection.size()); } public static void assertSizeGreaterThanOrEquals(int number, Collection collection) { assertGreaterThanOrEquals("Size", (double) number, (double) collection.size()); } /* Option */ public static boolean hasOption(String text, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (textEquals(text, option)) { return true; } } return false; } public static boolean hasNotOption(String text, WebElement webElement) { return !hasOption(text, webElement); } public static boolean isOptionEnabled(String text, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (textEquals(text, option) && isEnabled(option)) { return true; } } return false; } public static boolean isOptionDisabled(String text, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (textEquals(text, option) && isDisabled(option)) { return true; } } return false; } public static boolean isOptionSelected(String text, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (textEquals(text, option) && isSelected(option)) { return true; } } return false; } public static boolean isOptionDeselected(String text, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (textEquals(text, option) && isDeselected(option)) { return true; } } return false; } public static boolean isAllOptionsSelected(WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (isDeselected(option)) { return false; } } return true; } public static boolean isNoOptionsSelected(WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (isSelected(option)) { return false; } } return true; } public static void assertHasOption(String text, WebElement webElement) { if (hasNotOption(text, webElement)) { Assert.fail(describeTag(webElement) + "has no option \"" + text.trim() + "\"!"); } } public static void assertHasNotOption(String text, WebElement webElement) { if (hasOption(text, webElement)) { Assert.fail(describeTag(webElement) + "has option \"" + text.trim() + "\" when it shouldn't!"); } } public static void assertIsOptionEnabled(String text, WebElement webElement) { if (isOptionDisabled(text, webElement)) { Assert.fail("Option \"" + text.trim() + "\" is not enabled!"); } } public static void assertIsOptionDisabled(String text, WebElement webElement) { if (isOptionEnabled(text, webElement)) { Assert.fail("Option \"" + text.trim() + "\" is not disabled!"); } } public static void assertIsOptionSelected(String text, WebElement webElement) { if (isOptionDeselected(text, webElement)) { Assert.fail("Option \"" + text.trim() + "\" is not selected!"); } } public static void assertIsOptionDeselected(String text, WebElement webElement) { if (isOptionSelected(text, webElement)) { Assert.fail("Option \"" + text.trim() + "\" is not deselected!"); } } public static void assertIsAllOptionsSelected(WebElement webElement) { if (!isAllOptionsSelected(webElement)) { Assert.fail("All options are not selected!"); } } public static void assertIsNoOptionsSelected(WebElement webElement) { if (!isNoOptionsSelected(webElement)) { Assert.fail("All options are not deselected!"); } } /* Option Value */ public static boolean hasOptionWithValue(String value, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (valueEquals(value, option)) { return true; } } return false; } public static boolean hasNotOptionWithValue(String value, WebElement webElement) { return !hasOptionWithValue(value, webElement); } public static boolean isOptionWithValueEnabled(String value, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (valueEquals(value, option) && isEnabled(option)) { return true; } } return false; } public static boolean isOptionWithValueDisabled(String value, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (valueEquals(value, option) && isDisabled(option)) { return true; } } return false; } public static boolean isOptionWithValueSelected(String value, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (valueEquals(value, option) && isSelected(option)) { return true; } } return false; } public static boolean isOptionWithValueDeselected(String value, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); for (WebElement option : options) { if (valueEquals(value, option) && isDeselected(option)) { return true; } } return false; } public static void assertHasOptionWithValue(String value, WebElement webElement) { if (hasNotOptionWithValue(value, webElement)) { Assert.fail(describeTag(webElement) + "has no option with value \"" + value.trim() + "\"!"); } } public static void assertHasNotOptionWithValue(String value, WebElement webElement) { if (hasOptionWithValue(value, webElement)) { Assert.fail(describeTag(webElement) + "has option with value \"" + value.trim() + "\" when it shouldn't!"); } } public static void assertIsOptionWithValueEnabled(String value, WebElement webElement) { if (isOptionWithValueDisabled(value, webElement)) { Assert.fail("Option with value \"" + value.trim() + "\" is not enabled!"); } } public static void assertIsOptionWithValueDisabled(String value, WebElement webElement) { if (isOptionWithValueEnabled(value, webElement)) { Assert.fail("Option with value \"" + value.trim() + "\" is not disabled!"); } } public static void assertIsOptionWithValueSelected(String value, WebElement webElement) { if (isOptionWithValueDeselected(value, webElement)) { Assert.fail("Option with value \"" + value.trim() + "\" is not selected!"); } } public static void assertIsOptionWithValueDeselected(String value, WebElement webElement) { if (isOptionWithValueSelected(value, webElement)) { Assert.fail("Option with value \"" + value.trim() + "\" is not deselected!"); } } /* Option Index */ public static boolean hasOptionWithIndex(int index, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); try { return options.get(index) != null; } catch (IndexOutOfBoundsException e) { return false; } } public static boolean hasNotOptionWithIndex(int index, WebElement webElement) { return !hasNotOptionWithIndex(index, webElement); } public static boolean isOptionWithIndexEnabled(int index, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); try { return isEnabled(options.get(index)); } catch (IndexOutOfBoundsException e) { return false; } } public static boolean isOptionWithIndexDisabled(int index, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); try { return isDisabled(options.get(index)); } catch (IndexOutOfBoundsException e) { return false; } } public static boolean isOptionWithIndexSelected(int index, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); try { return isSelected(options.get(index)); } catch (IndexOutOfBoundsException e) { return false; } } public static boolean isOptionWithIndexDeselected(int index, WebElement webElement) { List<WebElement> options = new Select(webElement).getOptions(); try { return isDeselected(options.get(index)); } catch (IndexOutOfBoundsException e) { return false; } } public static void assertHasOptionWithIndex(int index, WebElement webElement) { if (hasNotOptionWithIndex(index, webElement)) { Assert.fail(describeTag(webElement) + "has no option with index \"" + index + "\"!"); } } public static void assertHasNotOptionWithIndex(int index, WebElement webElement) { if (hasOptionWithIndex(index, webElement)) { Assert.fail(describeTag(webElement) + "has option with index \"" + index + "\" when it shouldn't!"); } } public static void assertIsOptionWithIndexEnabled(int index, WebElement webElement) { if (isOptionWithIndexDisabled(index, webElement)) { Assert.fail("Option with index \"" + index + "\" is not enabled!"); } } public static void assertIsOptionWithIndexDisabled(int index, WebElement webElement) { if (isOptionWithIndexEnabled(index, webElement)) { Assert.fail("Option with index \"" + index + "\" is not disabled!"); } } public static void assertIsOptionWithIndexSelected(int index, WebElement webElement) { if (isOptionWithIndexDeselected(index, webElement)) { Assert.fail("Option with index \"" + index + "\" is not selected!"); } } public static void assertIsOptionWithIndexDeselected(int index, WebElement webElement) { if (isOptionWithIndexSelected(index, webElement)) { Assert.fail("Option with index \"" + index + "\" is not deselected!"); } } /* Has */ public static boolean has(String name, WebElement webElement) { return webElement.getAttribute(name) != null; } public static boolean hasNot(String name, WebElement webElement) { return !hasAttribute(name, webElement); } public static boolean equals(String text1, String text2) { return StringUtils.equals(text1, text2); } public static boolean notEquals(String text1, String text2) { return !StringUtils.equals(text1, text2); } public static boolean contains(String searchText, String text) { return StringUtils.contains(text, searchText); } public static boolean notContains(String searchText, String text) { return !StringUtils.contains(text, searchText); } public static boolean startsWith(String prefix, String text) { return StringUtils.startsWith(text, prefix); } public static boolean notStartsWith(String prefix, String text) { return !StringUtils.startsWith(text, prefix); } public static boolean endsWith(String suffix, String text) { return StringUtils.endsWith(text, suffix); } public static boolean notEndsWith(String suffix, String text) { return !StringUtils.endsWith(text, suffix); } public static boolean matches(String regularExpression, String text) { if (text == null || regularExpression == null) { return false; } return text.matches(regularExpression); } public static boolean notMatches(String regularExpression, String text) { if (text == null || regularExpression == null) { return true; } return !text.matches(regularExpression); } /* Is Any Of */ public static boolean equalsAnyOf(String[] anyOfTexts, String text) { for (String anyOfText : anyOfTexts) { if (StringUtils.equals(text, anyOfText)) { return true; } } return false; } public static boolean notEqualsAnyOf(String[] anyOfTexts, String text) { return !equalsAnyOf(anyOfTexts, text); } public static boolean containsAnyOf(String[] searchTexts, String text) { for (String searchText : searchTexts) { if (StringUtils.contains(text, searchText)) { return true; } } return false; } public static boolean notContainsAnyOf(String[] searchTexts, String text) { return !containsAnyOf(searchTexts, text); } public static boolean startsWithAnyOf(String[] prefixes, String text) { return StringUtils.startsWithAny(text, prefixes); } public static boolean notStartsWithAnyOf(String[] prefixes, String text) { return !startsWithAnyOf(prefixes, text); } public static boolean endsWithAnyOf(String[] suffix, String text) { return StringUtils.endsWithAny(text, suffix); } public static boolean notEndsWithAnyOf(String[] suffix, String text) { return !endsWithAnyOf(suffix, text); } public static boolean matchingAnyOf(String[] regularExpressions, String text) { for (String regularExpression : regularExpressions) { if (matches(regularExpression, text)) { return true; } } return false; } public static boolean notMatchingAnyOf(String[] regularExpressions, String text) { return !matchingAnyOf(regularExpressions, text); } /* Is Ignore Case */ public static boolean equalsIgnoreCase(String text1, String text2) { return StringUtils.equalsIgnoreCase(text1, text2); } public static boolean notEqualsIgnoreCase(String text1, String text2) { return !equalsIgnoreCase(text1, text2); } public static boolean containsIgnoreCase(String searchText, String text) { return StringUtils.containsIgnoreCase(text, searchText); } public static boolean notContainsIgnoreCase(String searchText, String text) { return !containsIgnoreCase(text, searchText); } public static boolean startsWithIgnoreCase(String prefix, String text) { return StringUtils.startsWithIgnoreCase(text, prefix); } public static boolean notStartsWithIgnoreCase(String prefix, String text) { return !startsWithIgnoreCase(prefix, text); } public static boolean endsWithIgnoreCase(String suffix, String text) { return StringUtils.endsWithIgnoreCase(text, suffix); } public static boolean notEndsWithIgnoreCase(String suffix, String text) { return !endsWithIgnoreCase(suffix, text); } /* Asserts */ public static void assertEquals(String name, String expected, String actual) { Assert.assertEquals(name + " is not equal to " + expected + "!", expected, actual); } public static void assertNotEquals(String name, String notExpected, String actual) { Assert.assertNotEquals(name + " is equal to" + notExpected + " when it shouldn't!", notExpected, actual); } public static void assertMatches(String name, String regExp, String actual) { if (notMatches(regExp, actual)) { Assert.fail(name + ": " + actual + " is not matching " + regExp + "!"); } } public static void assertNotMatches(String name, String regExp, String actual) { if (matches(regExp, actual)) { Assert.fail(name + ": " + actual + " is matching " + regExp + " when it shouldn't!"); } } public static void assertContains(String name, String searchText, String actual) { if (notContains(searchText, actual)) { Assert.fail(name + ": " + actual + " is not containing " + searchText); } } public static void assertNotContains(String name, String searchText, String actual) { if (contains(searchText, actual)) { Assert.fail(name + ": " + actual + " is containing " + searchText + " when it shouldn't!"); } } public static void assertStartsWith(String name, String prefix, String actual) { if (notStartsWith(prefix, actual)) { Assert.fail(name + ": " + actual + " is not starting with " + prefix); } } public static void assertNotStartsWith(String name, String prefix, String actual) { if (startsWith(prefix, actual)) { Assert.fail(name + ": " + actual + " is starting with " + prefix + " when it shouldn't!"); } } public static void assertEndsWith(String name, String suffix, String actual) { if (notEndsWith(suffix, actual)) { Assert.fail(name + ": " + actual + " is not ending with " + suffix); } } public static void assertNotEndsWith(String name, String suffix, String actual) { if (endsWith(suffix, actual)) { Assert.fail(name + ": " + actual + " is ending with " + suffix + " when it shouldn't!"); } } public static boolean equals(Double comparedTo, Double number) { return number == comparedTo; } public static boolean notEquals(double comparedTo, double number) { return number != comparedTo; } public static boolean lessThan(Double comparedTo, Double number) { return number < comparedTo; } public static boolean lessThanOrEquals(double comparedTo, double number) { return number <= comparedTo; } public static boolean greaterThan(double comparedTo, double number) { return number > comparedTo; } public static boolean greaterThanOrEquals(double comparedTo, double number) { return number >= comparedTo; } public static void assertEquals(String name, double comparedTo, double number) { if (notEquals(comparedTo, number)) { Assert.fail(name + ": " + number + " is not equal to " + comparedTo + " !"); } } public static void assertNotEequals(String name, double comparedTo, double number) { if (equals(comparedTo, number)) { Assert.fail(name + ": " + number + " is equal to " + comparedTo + " when it shouldn't!"); } } public static void assertLessThan(String name, double comparedTo, double number) { if (greaterThanOrEquals(comparedTo, number)) { Assert.fail(name + ": " + number + " is not less than " + comparedTo + " !"); } } public static void assertLessThanOrEquals(String name, double comparedTo, double number) { if (greaterThan(comparedTo, number)) { Assert.fail(name + ": " + number + " is not less than or equal to " + comparedTo + " !"); } } public static void assertGreaterThan(String name, double comparedTo, double number) { if (lessThanOrEquals(comparedTo, number)) { Assert.fail(name + ": " + number + " is not greater than " + comparedTo + " !"); } } public static void assertGreaterThanOrEquals(String name, double comparedTo, double number) { if (lessThan(comparedTo, number)) { Assert.fail(name + ": " + number + " is not greater than or equal to " + comparedTo + " !"); } } public static String describeTag(WebElement webElement) { return describeTag(webElement, null); } public static String describeTag(WebElement webElement, String extraAttribute) { if (webElement == null) { return "WebElement"; } boolean printExtraAttribute = extraAttribute != null && !ArrayUtils.contains(new String[]{"id", "name", "name", "class", "value", "disabled", "selected", "checked"}, extraAttribute); return "Tag <" + tagNameOf(webElement) + describeId(webElement) + describeName(webElement) + describeClass(webElement) + describeValue(webElement) + describeAttribute("disabled", webElement) + describeAttribute("selected", webElement) + describeAttribute("checked", webElement) + (printExtraAttribute ? describeAttribute(extraAttribute, webElement) : "") + ">"; } public static String describeAttribute(String attributeName, WebElement webElement) { return hasAttribute(attributeName, webElement) ? attributeName + " = '" + attributeIn(attributeName, webElement) + "' " : ""; } public static String describeId(WebElement webElement) { return hasId(webElement) ? "id = '" + idIn(webElement) + "' " : ""; } public static String describeName(WebElement webElement) { return hasName(webElement) ? "name = '" + nameIn(webElement) + "' " : ""; } public static String describeClass(WebElement webElement) { return hasClass(webElement) ? "class = '" + classIn(webElement) + "' " : ""; } public static String describeValue(WebElement webElement) { return hasValue(webElement) ? "value = '" + valueIn(webElement) + "' " : ""; } public static String toString(double number) { if (number == (int) number) { return String.format("%d", (int) number); } else { return String.format("%s", number); } } }
package org.dainst.gazetteer.search; import java.io.InputStream; import java.util.Scanner; import java.util.concurrent.ExecutionException; import org.dainst.gazetteer.dao.PlaceRepository; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.mapping.delete.DeleteMappingRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ElasticSearchService { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchService.class); @Autowired private Client client; @Autowired private PlaceRepository placeDao; public void deletePlaceFromIndex(long placeId) { DeleteResponse deleteResponse = client.prepareDelete("gazetteer", "place", String.valueOf(placeId)) .execute().actionGet(); LOGGER.info("deleted place from index: " + deleteResponse.getId()); } public void reindexAllPlaces() { LOGGER.info("reindexing all places"); try { // recreate es index client.admin().indices().delete(new DeleteIndexRequest("gazetteer")).get(); client.admin().indices().create(new CreateIndexRequest("gazetteer")).get(); } catch (Exception e) { throw new RuntimeException("Failed to reindex places", e); } // recreate corresponding mongodb river try { client.admin().indices().deleteMapping(new DeleteMappingRequest("_river").types("mongodb")).get(); client.admin().indices().create(new CreateIndexRequest("_river")).get(); } catch (InterruptedException e) { throw new RuntimeException("Failed to reindex places", e); } catch (ExecutionException e) { // eat exceptions if river is created for the first time } try { InputStream esRiverStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("es/mongodb_river.json"); Scanner s = new Scanner(esRiverStream); String esRiverJson = s.useDelimiter("\\A").next(); s.close(); esRiverStream.close(); LOGGER.debug("esRiverJson: {}", esRiverJson); IndexResponse indexResponse = client.index(Requests.indexRequest("_river").type("mongodb").id("_meta").source(esRiverJson)).get(); LOGGER.debug("created: {}", indexResponse.isCreated()); } catch (Exception e) { throw new RuntimeException("Failed to reindex places", e); } } }
package org.dasein.cloud.google.network; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.Tag; import org.dasein.cloud.ci.AbstractConvergedHttpLoadBalancer; import org.dasein.cloud.ci.ConvergedHttpLoadBalancer; import org.dasein.cloud.google.Google; import org.dasein.cloud.google.GoogleException; import org.dasein.cloud.google.GoogleMethod; import org.dasein.cloud.google.GoogleOperationType; import org.dasein.cloud.identity.ServiceAction; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.compute.Compute; import com.google.api.services.compute.model.Backend; import com.google.api.services.compute.model.BackendService; import com.google.api.services.compute.model.ForwardingRule; import com.google.api.services.compute.model.ForwardingRuleList; import com.google.api.services.compute.model.HostRule; import com.google.api.services.compute.model.HttpHealthCheck; import com.google.api.services.compute.model.Operation; import com.google.api.services.compute.model.PathMatcher; import com.google.api.services.compute.model.PathRule; import com.google.api.services.compute.model.TargetHttpProxy; import com.google.api.services.compute.model.TargetHttpProxyList; import com.google.api.services.compute.model.UrlMap; import com.google.api.services.compute.model.UrlMapList; public class HttpLoadBalancer extends AbstractConvergedHttpLoadBalancer<Google> { private Google provider; private ProviderContext ctx; public HttpLoadBalancer(Google provider) { super(provider); this.provider = provider; ctx = provider.getContext(); } @Override public String getProviderTermForConvergedHttpLoadBalancer(Locale locale) { return "HTTP load balancer"; } @Override public boolean isSubscribed() throws CloudException, InternalException { return true; // TODO punt! } @Override public Iterable<String> listConvergedHttpLoadBalancers() throws CloudException, InternalException { List<String> httpLoadBalancers = new ArrayList<String>(); Compute gce = provider.getGoogleCompute(); try { UrlMapList urlMaps = gce.urlMaps().list(ctx.getAccountNumber()).execute(); if (null != urlMaps) { for (UrlMap urlMap: urlMaps.getItems()) { httpLoadBalancers.add(urlMap.getName()); } } } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred listing convergedHttpLoadBalancers " + ex.getMessage()); } return httpLoadBalancers; } @Override public @Nullable ConvergedHttpLoadBalancer getConvergedHttpLoadBalancer(@Nonnull String convergedHttpLoadBalancerName) throws CloudException, InternalException { return toConvergedHttpLoadBalancer(convergedHttpLoadBalancerName); } private String flatten(List<String> items) { String flattened = ""; for (String item : items) { flattened += item + ", "; } return flattened.replaceFirst(", $", ""); } public ConvergedHttpLoadBalancer toConvergedHttpLoadBalancer(@Nonnull String urlMap) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); ConvergedHttpLoadBalancer convergedHttpLoadBalancer; urlMap = urlMap.replaceAll(".*/", ""); try { UrlMap um = gce.urlMaps().get(ctx.getAccountNumber(), urlMap).execute(); convergedHttpLoadBalancer = ConvergedHttpLoadBalancer.getInstance(um.getName(), um.getDescription(), um.getSelfLink(), um.getCreationTimestamp(), um.getDefaultService().replaceAll(".*/", "")); List<HostRule> hostRules = um.getHostRules(); Map<String, String> descriptionMap = new HashMap<String, String>(); Map<String, String> hostMatchPatternMap = new HashMap<String, String>(); for (HostRule hostRule: hostRules) { descriptionMap.put(hostRule.getPathMatcher(), hostRule.getDescription()); hostMatchPatternMap.put(hostRule.getPathMatcher(), flatten(hostRule.getHosts())); } List<PathMatcher> pathMatchers = um.getPathMatchers(); for (PathMatcher pathMatcher: pathMatchers) { Map<String, String> pathMap = new HashMap<String, String>(); String defaultService = pathMatcher.getDefaultService().replaceAll(".*/", ""); pathMap.put("/*", defaultService); if (null != pathMatcher.getPathRules()) { for (PathRule pathRule: pathMatcher.getPathRules()) { pathMap.put(flatten(pathRule.getPaths()), pathRule.getService().replaceAll(".*/", "")); convergedHttpLoadBalancer = convergedHttpLoadBalancer.withUrlSet(pathMatcher.getName(), descriptionMap.get(pathMatcher.getName()), hostMatchPatternMap.get(pathMatcher.getName()), pathMap); } } } //um.getTests() List object unknown TargetHttpProxyList targetHttpProxyList = gce.targetHttpProxies().list(ctx.getAccountNumber()).execute(); for (TargetHttpProxy targetProxy: targetHttpProxyList.getItems()) { if (targetProxy.getUrlMap().endsWith(urlMap)) { convergedHttpLoadBalancer = convergedHttpLoadBalancer.withTargetHttpProxy(targetProxy.getName(), targetProxy.getDescription(), targetProxy.getCreationTimestamp(), targetProxy.getSelfLink()); ForwardingRuleList forwardingRuleList = gce.globalForwardingRules().list(ctx.getAccountNumber()).execute(); for (ForwardingRule forwardingRule: forwardingRuleList.getItems()) { if (forwardingRule.getTarget().endsWith(targetProxy.getName())) { convergedHttpLoadBalancer = convergedHttpLoadBalancer.withForwardingRule(forwardingRule.getName(), forwardingRule.getDescription(), forwardingRule.getCreationTimestamp(), forwardingRule.getIPAddress(), forwardingRule.getIPProtocol(), forwardingRule.getPortRange(), forwardingRule.getSelfLink(), forwardingRule.getTarget().replaceAll(".*/", "")); } } } } List<String> backendServices = new ArrayList<String>(); backendServices.add(um.getDefaultService().replaceAll(".*/", "")); List<String> allHealthChecks = new ArrayList<String>(); for (String backendService : new HashSet<String>(backendServices)) { // use HashSet to make it unique list BackendService bes = gce.backendServices().get(ctx.getAccountNumber(), backendService).execute(); List<String> healthChecks = bes.getHealthChecks(); List<String> instanceGroups = new ArrayList<String>(); for (Backend backend : bes.getBackends()) { instanceGroups.add(backend.getGroup().replaceAll(".*/", "")); convergedHttpLoadBalancer = convergedHttpLoadBalancer.withBackendServiceBackend(bes.getName(), backend.getDescription(), backend.getBalancingMode(), backend.getCapacityScaler(), backend.getGroup(), backend.getMaxRate(), backend.getMaxRatePerInstance(), backend.getMaxUtilization()); } convergedHttpLoadBalancer = convergedHttpLoadBalancer.withBackendService(bes.getName(), bes.getDescription(), bes.getCreationTimestamp(), bes.getPort(), bes.getPortName(), bes.getProtocol(), healthChecks.toArray(new String[healthChecks.size()]), instanceGroups.toArray(new String[instanceGroups.size()]), bes.getSelfLink(), bes.getTimeoutSec()); for (String healthCheck : bes.getHealthChecks()) { allHealthChecks.add(healthCheck.replaceAll(".*/", "")); } } for (String healthCheck : new HashSet<String>(allHealthChecks)) { // use HashSet to make it unique list HttpHealthCheck hc = gce.httpHealthChecks().get(ctx.getAccountNumber(), healthCheck).execute(); convergedHttpLoadBalancer = convergedHttpLoadBalancer.withHealthCheck(hc.getName(), hc.getDescription(), hc.getCreationTimestamp(), hc.getHost(), hc.getPort(), hc.getRequestPath(), hc.getCheckIntervalSec(), hc.getTimeoutSec(), hc.getHealthyThreshold(), hc.getUnhealthyThreshold(), hc.getSelfLink()); } } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred listing convergedHttpLoadBalancers " + ex.getMessage()); } catch (Exception ex) { throw new CloudException("Error removing Converged Http Load Balancer " + ex.getMessage()); } return convergedHttpLoadBalancer; } /* * takes either a globalForwardingRule name or url */ public void removeGlobalForwardingRule(@Nonnull String globalForwardingRule) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); try { Operation job = gce.globalForwardingRules().delete(ctx.getAccountNumber(), globalForwardingRule.replaceAll(".*/", "")).execute(); method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred removing global forwarding rule " + ex.getMessage()); } catch (Exception ex) { throw new CloudException("Error removing global forwarding rule " + ex.getMessage()); } } /* * takes either a targetHttpProxy name or url */ public void removeTargetHttpProxy(@Nonnull String targetHttpProxy) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); try { Operation job = gce.targetHttpProxies().delete(ctx.getAccountNumber(), targetHttpProxy.replaceAll(".*/", "")).execute(); method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred removing target http proxy " + ex.getMessage()); } catch (Exception ex) { throw new CloudException("Error removing target http proxy " + ex.getMessage()); } } /* * takes either a urlMap name or url */ public void removeUrlMap(@Nonnull String urlMap) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); try { Operation job = gce.urlMaps().delete(ctx.getAccountNumber(), urlMap.replaceAll(".*/", "")).execute(); method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred removing url map " + ex.getMessage()); } catch (Exception ex) { throw new CloudException("Error removing url map " + ex.getMessage()); } } /* * takes either a backendService name or url */ public void removeBackendService(@Nonnull String backendService) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); try { Operation job = gce.backendServices().delete(ctx.getAccountNumber(), backendService.replaceAll(".*/", "")).execute(); method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred removing backend service " + ex.getMessage()); } catch (Exception ex) { throw new CloudException("Error removing backend service " + ex.getMessage()); } } /* * takes either a httpHealthCheck name or url */ public void removeHttpHealthCheck(@Nonnull String httpHealthCheck) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); try { Operation job = gce.httpHealthChecks().delete(ctx.getAccountNumber(), httpHealthCheck.replaceAll(".*/", "")).execute(); method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred removing http health check " + ex.getMessage()); } catch (Exception ex) { throw new CloudException("Error removing http health check " + ex.getMessage()); } } @Override public void removeConvergedHttpLoadBalancers(@Nonnull String urlMap) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); urlMap = urlMap.replaceAll(".*/", ""); try { ForwardingRuleList forwardingRuleList = gce.globalForwardingRules().list(ctx.getAccountNumber()).execute(); TargetHttpProxyList targetHttpProxyList = gce.targetHttpProxies().list(ctx.getAccountNumber()).execute(); for (TargetHttpProxy targetProxy: targetHttpProxyList.getItems()) { if (targetProxy.getUrlMap().endsWith(urlMap)) { for (ForwardingRule forwardingRule: forwardingRuleList.getItems()) { if (forwardingRule.getTarget().endsWith(targetProxy.getName())) { removeGlobalForwardingRule(forwardingRule.getName()); } } removeTargetHttpProxy(targetProxy.getName()); } } UrlMap um = gce.urlMaps().get(ctx.getAccountNumber(), urlMap).execute(); List<String> backendServices = new ArrayList<String>(); backendServices.add(um.getDefaultService().replaceAll(".*/", "")); List<PathMatcher> pathMatchers = um.getPathMatchers(); for (PathMatcher pathMatcher: pathMatchers) { backendServices.add(pathMatcher.getDefaultService().replaceAll(".*/", "")); if (null != pathMatcher.getPathRules()) { for (PathRule pathRule: pathMatcher.getPathRules()) { backendServices.add(pathRule.getService().replaceAll(".*/", "")); } } } removeUrlMap(um.getName()); List<String> healthChecks = new ArrayList<String>(); for (String backendService : new HashSet<String>(backendServices)) { // use HashSet to make it unique list BackendService bes = gce.backendServices().get(ctx.getAccountNumber(), backendService).execute(); for (String healthCheck : bes.getHealthChecks()) { healthChecks.add(healthCheck); } removeBackendService(backendService); } for (String healthCheck : new HashSet<String>(healthChecks)) { // use HashSet to make it unique list removeHttpHealthCheck(healthCheck); } } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred removing convergedHttpLoadBalancer " + ex.getMessage()); } catch (Exception ex) { throw new CloudException("Error removing Converged Http Load Balancer " + ex.getMessage()); } } public void createBackendService(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); List<ConvergedHttpLoadBalancer.BackendService> backendServices = withConvergedHttpLoadBalancerOptions.getBackendServices(); //List<ConvergedHttpLoadBalancer.BackendServiceBackend> backendServiceBackends = withConvergedHttpLoadBalancerOptions.getBackendServiceBackends(); for (ConvergedHttpLoadBalancer.BackendService backendService : backendServices) { BackendService beContent = new BackendService(); beContent.setName(backendService.getName()); beContent.setDescription(backendService.getDescription()); beContent.setPort(backendService.getPort()); beContent.setPortName(backendService.getPortName()); beContent.setTimeoutSec(backendService.getTimeoutSec()); List<String> healthCheckSelfUrls = new ArrayList<String>(); for (String healthCheckName : backendService.getHealthChecks()) { healthCheckSelfUrls.add(withConvergedHttpLoadBalancerOptions.getHealthCheckSelfUrl(healthCheckName)); } beContent.setHealthChecks(healthCheckSelfUrls); List<Backend> backends = new ArrayList<Backend>(); String[] backendServiceBackends = backendService.getBackendServiceBackends(); //[instance-group-1] list requires zone, same with get. for (String backendServiceInstranceGroupSelfUrl : backendService.getBackendServiceBackends()) { Backend backend = new Backend(); backend.setGroup(backendServiceInstranceGroupSelfUrl); backends.add(backend); } beContent.setBackends(backends); try { Operation foo = gce.backendServices().insert(ctx.getAccountNumber(), beContent ).execute(); method.getOperationComplete(provider.getContext(), foo, GoogleOperationType.GLOBAL_OPERATION, null, null); } catch ( IOException ex ) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred listing convergedHttpLoadBalancers " + ex.getMessage()); } catch ( Exception ex ) { throw new CloudException("Error removing Converged Http Load Balancer " + ex.getMessage()); } backendService.setServiceUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/backendServices/" + backendService.getName()); } } public void createURLMap(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); try { List<ConvergedHttpLoadBalancer.UrlSet> urlSets = withConvergedHttpLoadBalancerOptions.getUrlSets(); UrlMap urlMap = new UrlMap(); List<PathMatcher> pathMatchers = new ArrayList<PathMatcher>(); List<HostRule> hostRules = new ArrayList<HostRule>(); for (ConvergedHttpLoadBalancer.UrlSet urlSet : urlSets) { HostRule hostRule = new HostRule(); List<String> hosts = new ArrayList<String>(); String hostMatchPatterns = urlSet.getHostMatchPatterns(); if (hostMatchPatterns.contains(",")) { for (String hostMatchPattern : hostMatchPatterns.split(", ?")) { hosts.add(hostMatchPattern); } } else { hosts.add(hostMatchPatterns); } hostRule.setHosts(hosts); hostRule.setPathMatcher(urlSet.getName()); hostRules.add(hostRule); PathMatcher pathMatcher = new PathMatcher(); pathMatcher.setName(urlSet.getName()); pathMatcher.setDescription(urlSet.getDescription()); List<PathRule> pathRules = new ArrayList<PathRule>(); Map<String, String> pathMap = urlSet.getPathMap(); for (String key : pathMap.keySet()) { PathRule pathRule = new PathRule(); List<String> paths = new ArrayList<String>();